diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index e7dc132aee8..b465222b12a 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -31,7 +31,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/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index c043a97d6ac..b7fc0183ba7 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -44,14 +44,17 @@ $$nemoclaw start ``` This path preserves the sandbox workspace and leaves lifecycle ownership with OpenShell. `start` -and `recover` reconcile a sandbox that OpenShell still reports as `Stopped`; neither command -directly restarts or unpauses the underlying provider container. Before destructive replacement, -run `$$nemoclaw status`. If the owning gateway reports the registered sandbox -missing, NemoClaw leaves any provider container untouched. Preserve any separate snapshot, use -`$$nemoclaw destroy --yes` to retire the stale registered sandbox when the command -can prove the OpenShell resource absent, then onboard a clean replacement. Restore the snapshot -afterward if one is available; rebuild cannot recover a workspace or live OpenShell policy that no -longer exists. +and `recover` reconcile a sandbox that OpenShell still reports as `Stopped`, including when its +provider container is already running. Neither command directly restarts or unpauses the provider +container. If the container is paused, follow the printed provider guidance instead. + +Before destructive replacement, run `$$nemoclaw status`. If the owning gateway +reports the registered sandbox missing, NemoClaw leaves any provider container and registry entry +untouched. Retry after the gateway reconnects. If the sandbox was intentionally deleted, preserve +any separate snapshot and use `$$nemoclaw destroy --yes` to retire the stale entry +when the command can prove the OpenShell resource absent. Then onboard a clean replacement and +restore the snapshot 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. @@ -251,6 +254,10 @@ It does not report a successful rebuild. If the sandbox is stopped (for example, an out-of-band runtime failure left it in `Phase: Error`), rebuild asks OpenShell to start that exact sandbox for the duration of the pre-recreate state backup and asks OpenShell to return it to `Stopped` afterward, the same lifecycle path `$$nemoclaw backup-all` uses. If OpenShell cannot start 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 succeeds but OpenShell cannot return the sandbox to `Stopped`, rebuild also aborts and reports the failed transition. +If OpenShell still reports the sandbox in `Phase: Error` but its Docker-driver container is missing, +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. + 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/commands/sandbox/rebuild.test.ts b/src/commands/sandbox/rebuild.test.ts index ab5d6e11f1b..b6fc0e7177b 100644 --- a/src/commands/sandbox/rebuild.test.ts +++ b/src/commands/sandbox/rebuild.test.ts @@ -1,9 +1,18 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { beforeEach, describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, 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", @@ -13,14 +22,30 @@ 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, +})); +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-")); + vi.stubEnv("HOME", home); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + fs.rmSync(home, { force: true, recursive: true }); }); it("routes exact confirmed recovery retirement without starting a rebuild", async () => { @@ -36,12 +61,52 @@ 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("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"], @@ -63,4 +128,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..0cb35fffc86 100644 --- a/src/commands/sandbox/rebuild.ts +++ b/src/commands/sandbox/rebuild.ts @@ -2,15 +2,42 @@ // 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, + 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"; import { DCODE_AUTO_APPROVAL_MODES, 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: { + "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 +81,36 @@ export default class RebuildCliCommand extends NemoClawCommand { }), }; + protected override async runBeforeLifecycleBoundary(): Promise { + const parsed = await this.parse(RebuildCliCommand); + this.retainLifecycleParserOutput(parsed); + const { args, flags } = parsed; + const recoveryTransactionId = flags["retire-recovery"]; + if (recoveryTransactionId) { + enforceRemovedImmutabilityMigrationBoundary(args.sandboxName, { + allowStateRecord: true, + }); + 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, + 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 +125,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-flow.test.ts b/src/lib/actions/sandbox/connect-flow.test.ts index 832f9e30534..4e75eac502d 100644 --- a/src/lib/actions/sandbox/connect-flow.test.ts +++ b/src/lib/actions/sandbox/connect-flow.test.ts @@ -1084,7 +1084,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"); @@ -1103,13 +1103,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; @@ -1154,7 +1157,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]!, @@ -1164,7 +1167,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-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/connect.ts b/src/lib/actions/sandbox/connect.ts index 4c023eafb09..621c7aeb9fc 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -177,6 +177,18 @@ 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); +} + +function getConnectSessionAgent(sandboxName: string): AgentDefinition | null { + return agentRuntime.resolveRegisteredSandboxAgent( + sandboxName, + agentRuntime.getSessionAgent(sandboxName), + ); +} + export type SandboxStartupRecoveryResult = Awaited< ReturnType > & { @@ -385,7 +397,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"); @@ -682,10 +694,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[], @@ -724,13 +746,14 @@ function hermesPortableLaunchReadinessDeps( ); return { ...createBoundLaunchReadinessDeps(capture, commandExecutor), + getSandbox: readConnectSandbox, ...probeTimingLaunchReadinessDeps(probeTiming), }; } function portableAgentLifecycleAuthorityDeps() { return { - readRegistry: registry.getSandbox, + readRegistry: readConnectSandbox, stateDir: defaultPortableDemoStateDir(process.env), }; } @@ -889,7 +912,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()); @@ -1087,7 +1110,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 @@ -1271,7 +1294,11 @@ function failConnectReadinessDockerRuntimeDown(sandboxName: string): never { } async function failIfGatewayBlocksConnectReadiness(sandboxName: string): Promise { - const lifecycle = await getNamedGatewayLifecycleState(getSandboxTargetGatewayName(sandboxName)); + const sb = readConnectSandbox(sandboxName); + const gatewayName = sb + ? getPersistedSandboxTargetGatewayName(sb) + : getSandboxTargetGatewayName(sandboxName); + const lifecycle = await getNamedGatewayLifecycleState(gatewayName); if (lifecycle.error) failConnectReadinessObservation(sandboxName, lifecycle.error); if (isBlockingGatewayLifecycle(lifecycle)) { failConnectReadinessGatewayUnavailable(sandboxName, lifecycle.diagnostic, lifecycle); @@ -1643,7 +1670,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); @@ -1794,13 +1821,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 = getPersistedSandboxTargetGatewayName(snapshot); return withGatewayRouteMutationLock(gatewayName, () => { - const lockedSnapshot = registry.getSandbox(sandboxName); + const lockedSnapshot = readConnectSandbox(sandboxName); if ( lockedSnapshot && registry.getSandboxEntryInference(lockedSnapshot).kind === "configured" && @@ -2110,7 +2137,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.`, @@ -2301,7 +2328,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)) { @@ -2379,9 +2406,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 = @@ -2393,9 +2418,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, @@ -2419,7 +2442,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; @@ -2761,7 +2784,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 && @@ -2794,7 +2817,7 @@ async function prepareConnectSandboxWithinLifecycleFence( sandboxName, entry: retainedAuthority.active.entry, operatingReceipt: retainedAuthority.command.receipt, - readRegistry: registry.getSandbox, + readRegistry: readConnectSandbox, assertCallerCurrent: assertBaseCurrent, env: retainedAuthority.command.env, }), @@ -2812,7 +2835,7 @@ async function prepareConnectSandboxWithinLifecycleFence( intent: "connect-probe-only", sandboxName, authority: retainedAuthority.active, - readRegistry: registry.getSandbox, + readRegistry: readConnectSandbox, commandAuthority: retainedAuthority.command, }), ); @@ -2879,7 +2902,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/destroy-cross-root.test.ts b/src/lib/actions/sandbox/destroy-cross-root.test.ts new file mode 100644 index 00000000000..9c9cba8a7a8 --- /dev/null +++ b/src/lib/actions/sandbox/destroy-cross-root.test.ts @@ -0,0 +1,116 @@ +// 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(); + }); + + 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-flow.test.ts b/src/lib/actions/sandbox/destroy-flow.test.ts index 52ceae5e560..a96bca2e0d9 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 1be88a07afd..68ed2ba0570 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 c1c0d8ad64b..42e1670a104 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -79,6 +79,7 @@ import { } from "./destroy-presence"; import { prepareSandboxDestroy, + resolveSandboxDestroyRegistryAuthority, resolveSandboxDestroyGatewayName, resolveSandboxDestroyRuntimeSelection, stopModelRouterForDestroyedSandbox, @@ -685,7 +686,10 @@ async function destroySandboxUnlocked( } = {}, ): 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) { @@ -744,7 +748,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, @@ -760,7 +764,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), @@ -839,6 +843,7 @@ async function destroySandboxUnlocked( let destroyPreflight: Awaited>; try { destroyPreflight = await prepareSandboxDestroy(sandboxName, { + getSandbox: getRegisteredSandbox, retainedRecoveryGatewayName: retainedRecoveryAuthority?.gatewayName, operationRuntimeSelection, }); @@ -916,8 +921,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 } : {}), @@ -1096,8 +1101,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, @@ -1108,6 +1113,8 @@ async function destroySandboxUnlocked( : {}), }, { + getSandbox: getRegisteredSandbox, + listSandboxes: listRegisteredSandboxes, runOpenshell: cleanupRunOpenshell, }, ); @@ -1155,15 +1162,19 @@ 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. const registryEntryAbsent = - removalOutcome.status === "complete" || removalOutcome.status === "not-found"; + removalOutcome.status === "complete" || + (removalOutcome.status === "not-found" && !getRegisteredSandbox(sandboxName)); 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 ` + @@ -1198,7 +1209,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) { @@ -1209,7 +1220,9 @@ async function destroySandboxUnlocked( } } if (deleteSucceededOrAlreadyGone && removed && priorHttpsPinRouteId) { - await revokeDestroyedSandboxHttpsPinRoute(cleanupGatewayName, priorHttpsPinRouteId); + await revokeDestroyedSandboxHttpsPinRoute(cleanupGatewayName, priorHttpsPinRouteId, { + listSandboxes: listRegisteredSandboxes, + }); } let routedSessionCleanupHandled = false; if (deleteSucceededOrAlreadyGone && removed) { @@ -1292,7 +1305,7 @@ async function destroySandboxUnlocked( const cleanupDecision = deleteSucceededOrAlreadyGone && registryEntryAbsent && - registry.listSandboxes().sandboxes.length === 0 + listRegisteredSandboxes().sandboxes.length === 0 ? resolveDestroyGatewayCleanupDecision(normalized, { nonInteractive: isDestroyNonInteractiveEnv(), platform: process.platform, @@ -1311,6 +1324,7 @@ async function destroySandboxUnlocked( }, { ...deps.finalGatewayCleanup, + listSandboxes: listRegisteredSandboxes, ...(cleanupCaptureOpenshell ? { captureOpenshell: cleanupCaptureOpenshell } : {}), }, ); diff --git a/src/lib/actions/sandbox/docker-health.test.ts b/src/lib/actions/sandbox/docker-health.test.ts index 1d00828961f..23815e326b5 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,39 @@ 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", + containerAbsenceConfirmed: false, + }); + } 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", @@ -208,6 +258,7 @@ describe("getSandboxDockerRuntime (#4495)", () => { paused: false, running: false, containerName: null, + containerAbsenceConfirmed: true, }); }); @@ -222,6 +273,7 @@ describe("getSandboxDockerRuntime (#4495)", () => { paused: true, running: true, containerName: "openshell-my-assistant-live", + containerAbsenceConfirmed: false, }); }); @@ -236,6 +288,7 @@ describe("getSandboxDockerRuntime (#4495)", () => { paused: false, running: false, containerName: "openshell-my-assistant-12ab", + containerAbsenceConfirmed: false, }); }); @@ -246,6 +299,7 @@ describe("getSandboxDockerRuntime (#4495)", () => { paused: true, running: true, containerName: "openshell-my-assistant-12ab", + containerAbsenceConfirmed: false, }); }); @@ -291,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 45367390842..3f2cbbd553b 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-container-observation"; 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"; @@ -26,10 +31,12 @@ 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 { - getSandbox: (name: string) => registry.SandboxEntry | null; + getSandbox: (name: string) => SandboxEntry | null; listSandboxNames: () => string[]; dockerPsNames: () => string; findLabeledSandboxContainers: typeof findLabeledSandboxContainers; @@ -37,15 +44,29 @@ interface ResolveDeps { dockerInspectPaused: (containerName: string) => string; } +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) => 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), + findLabeledSandboxContainers: (sandboxName) => + findLabeledSandboxContainers(sandboxName, { ignoreError: false }), dockerInspectHealth: (containerName) => dockerContainerInspectFormat( "{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}", @@ -129,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) @@ -155,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, @@ -172,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/forward-recovery.ts b/src/lib/actions/sandbox/forward-recovery.ts index 933c58875b9..4b106016f50 100644 --- a/src/lib/actions/sandbox/forward-recovery.ts +++ b/src/lib/actions/sandbox/forward-recovery.ts @@ -66,6 +66,20 @@ 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); +} + +function getForwardSessionAgent( + sandboxName: string, +): ReturnType { + return agentRuntime.resolveRegisteredSandboxAgent( + sandboxName, + agentRuntime.getSessionAgent(sandboxName), + ); +} + export interface HermesPortableForwardCommandAuthority { readonly env: NodeJS.ProcessEnv; readonly executablePath: string; @@ -314,7 +328,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"); } @@ -451,13 +465,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; @@ -474,11 +488,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`; @@ -499,7 +513,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; @@ -555,7 +569,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, @@ -573,7 +587,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, }); @@ -605,7 +619,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 }), }); @@ -688,7 +702,7 @@ async function inspectSandboxPortForwardListener( forwardAdapterForAuthority: OpenShellForwardObservationAdapterFactory = createOpenShellForwardAdapterForAuthority, expectedListenerPid?: number, ): Promise { - const sandbox = registry.getSandbox(sandboxName); + const sandbox = readForwardSandbox(sandboxName); if (!sandbox) return "absent"; try { const gatewayName = runtimeSelection?.gatewayName ?? resolveSandboxGatewayName(sandbox); @@ -760,7 +774,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); @@ -804,6 +818,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) => @@ -813,7 +828,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; @@ -892,10 +907,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, @@ -945,12 +960,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, @@ -962,11 +977,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, @@ -1014,7 +1029,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(), }); @@ -1048,9 +1063,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/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 527d98d5b8f..64f72af62a0 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; @@ -63,6 +63,52 @@ export type SandboxContainerFailureRunners = { portProbe: (port: number) => Promise; }; +export type SandboxPhaseRecoveryAction = "replace_missing_docker_container" | "start" | "rebuild"; + +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 === "docker" && !dockerContainerName && dockerContainerAbsenceConfirmed) { + return "replace_missing_docker_container"; + } + 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; } @@ -117,7 +163,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.`, @@ -280,12 +326,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 @@ -330,7 +376,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(); diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index 6ce49ad13ca..3688cf46de8 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -31,7 +31,11 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { let getNamedGatewayLifecycleStateSpy: MockInstance; let getSandboxSpy: MockInstance; let findSandboxAcrossGatewayRootsSpy: MockInstance; + let listPublishedSandboxNamesAcrossGatewayRootsSpy: MockInstance; + let getSandboxDockerRuntimeSpy: MockInstance; + let listPublishedSandboxNamesForDockerRuntime: () => string[]; let recoverNamedGatewayRuntimeSpy: MockInstance; + let dockerInfoSpy: MockInstance; function mockSandboxPhase(phase: string): void { captureOpenshellSpy.mockImplementation((args: string[]) => @@ -49,9 +53,13 @@ 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"); + 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); @@ -63,6 +71,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", @@ -76,6 +85,16 @@ 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, + running: true, + containerName: "openshell-instance-a-abc", + containerAbsenceConfirmed: false, + }); vi.spyOn(gatewaySelect, "selectSandboxOwningGateway").mockReturnValue({ outcome: "selected", gatewayName: "nemoclaw", @@ -258,6 +277,377 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { expect(exitSpy).toHaveBeenCalledWith(1); }); + it("uses stopped guidance when a Docker container is not running during Error", async () => { + mockSandboxPhase("Error"); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: false, + running: false, + containerName: "openshell-instance-a-abc", + 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("Sandbox 'instance-a' is stopped."); + expect(output).toContain("Workspace state is preserved."); + expect(output).toContain("nemoclaw instance-a start"); + expect(output).not.toContain("rebuild --yes"); + expect(output).not.toContain("process crash"); + expect(output).not.toContain("stuck in 'Error'"); + expect(exitSpy).toHaveBeenCalledWith(1); + }); + + it("steers a non-paused Error sandbox to the workspace-preserving start path (#7222)", async () => { + mockSandboxPhase("Error"); + 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).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", { + 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", + containerAbsenceConfirmed: false, + }); + 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({ + name: "instance-a", + gatewayName: "nemoclaw", + gatewayPort: 8080, + openshellDriver: "docker", + }); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: false, + running: false, + containerName: null, + containerAbsenceConfirmed: true, + }); + 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("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); + }); + + 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, + containerAbsenceConfirmed: false, + }); + 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("keeps recovery guidance when Docker driver metadata is missing", async () => { + mockSandboxPhase("Error"); + getSandboxSpy.mockReturnValue({ + name: "instance-a", + gatewayName: "nemoclaw", + gatewayPort: 8080, + openshellDriver: undefined, + }); + 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); + }); + + 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); + }); + + 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, + 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(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, + running: true, + 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).toContain("restart the sandbox through OpenShell"); + expect(output).not.toContain("Run `nemoclaw instance-a rebuild --yes` to recreate"); + expect(exitSpy).toHaveBeenCalledWith(1); + }); + + it("keeps rebuild guidance for a paused container in a terminal phase other than Error", async () => { + mockSandboxPhase("Failed"); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: true, + running: true, + containerName: "openshell-instance-a-abc", + 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 rebuild --yes"); + expect(output).not.toContain("nemoclaw instance-a start"); + expect(output).not.toContain("docker unpause"); + expect(getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("instance-a", { + getSandbox: expect.any(Function), + listSandboxNames: listPublishedSandboxNamesForDockerRuntime, + }); + expect(exitSpy).toHaveBeenCalledWith(1); + }); + + it("preserves docker-unpause recovery for a paused Error sandbox (#4495)", async () => { + mockSandboxPhase("Error"); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: true, + running: true, + containerName: "openshell-instance-a-abc", + 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("docker unpause openshell-instance-a-abc"); + expect(output).not.toContain("nemoclaw instance-a start"); + expect(output).not.toContain("rebuild --yes"); + expect(exitSpy).toHaveBeenCalledWith(1); + }); + it.each([ { lifecycle: gatewayObservation("named_unreachable", "Gateway is unreachable."), diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 49917906bd9..aa3fa27eb5d 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -96,7 +96,16 @@ import { usesLegacyRuntimeLifecycleCompatibility, } from "../../state/registry/lifecycle-generation"; import type { SandboxEntry } from "../../state/registry/types"; -import { isDockerRuntimeDown, printDockerRuntimeDownGuidance } from "./gateway-failure-classifier"; +import { + getSandboxDockerRuntime, + listPublishedSandboxNamesForDockerRuntime, +} from "./docker-health"; +import { + classifySandboxPhaseRecoveryAction, + getSandboxPhaseRecoveryGuidance, + isDockerRuntimeDown, + printDockerRuntimeDownGuidance, +} from "./gateway-failure-classifier"; import { mutateRegisteredStandardSandboxLifecycle, type RegisteredStandardLifecycleDeps, @@ -1047,6 +1056,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 @@ -1057,7 +1067,7 @@ export async function ensureLiveSandboxOrExit( phase !== "Running" && !sandboxPhaseNeedsLifecycleStart(phase) && !isTerminalSandboxPhase(phase) && - isDockerRuntimeDown(sandboxName) + isDockerRuntimeDown(sandboxName, { getSandbox: () => sandboxEntry }) ) { printDockerRuntimeDownGuidance(sandboxName); exit(1); @@ -1067,28 +1077,55 @@ export async function ensureLiveSandboxOrExit( exit(1); } if (!allowNonReadyPhase && phase && phase !== "Ready" && phase !== "Running") { - if (phase === "Stopped") { + const dockerRuntime = getSandboxDockerRuntime(sandboxName, { + getSandbox: () => sandboxEntry, + listSandboxNames: listPublishedSandboxNamesForDockerRuntime, + }); + if ( + phase === "Stopped" || + (dockerRuntime.containerName && !dockerRuntime.running && !dockerRuntime.paused) + ) { console.error(` Sandbox '${sandboxName}' is stopped.`); console.error(" Workspace state is preserved."); console.error(` Start it again with \`${CLI_NAME} ${sandboxName} start\`.`); exit(1); } + if (phase === "Error" && dockerRuntime.paused && dockerRuntime.containerName) { + console.error(` Sandbox '${sandboxName}' is stuck in '${phase}' phase.`); + console.error(""); + console.error( + ` The Docker-driver container for '${sandboxName}' is paused: ${dockerRuntime.containerName}`, + ); + console.error( + " A paused container can report 'Phase: Error' even though the sandbox is intact.", + ); + console.error(" Resume it to restore the running phase:"); + console.error(` docker unpause ${dockerRuntime.containerName}`); + exit(1); + } console.error(` Sandbox '${sandboxName}' is stuck in '${phase}' phase.`); console.error( " This usually happens when a process crash inside the sandbox prevented clean startup.", ); console.error(""); - 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.)`, - ); - } else { - console.error( - ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the sandbox (--yes skips the confirmation prompt; workspace state will be preserved).`, - ); + const openshellDriver = sandboxEntry?.openshellDriver; + const recoveryAction = classifySandboxPhaseRecoveryAction({ + phase, + openshellDriver, + dockerContainerName: dockerRuntime.containerName, + dockerContainerAbsenceConfirmed: dockerRuntime.containerAbsenceConfirmed, + }); + if ( + !dockerRuntime.containerName && + isDockerRuntimeDown(sandboxName, { + getSandbox: () => ({ openshellDriver }), + }) + ) { + printDockerRuntimeDownGuidance(sandboxName); + exit(1); + } + for (const line of getSandboxPhaseRecoveryGuidance(sandboxName, recoveryAction)) { + console.error(line); } exit(1); } 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 a74bbc5125d..f6bb6f2f6f2 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -111,6 +111,21 @@ 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); +} + +function getRecoverySessionAgent( + sandboxName?: string, +): ReturnType { + if (!sandboxName) return agentRuntime.getSessionAgent(); + return agentRuntime.resolveRegisteredSandboxAgent( + sandboxName, + agentRuntime.getSessionAgent(sandboxName), + ); +} + export type { GatewayRestartDeps, GatewayRestartFailureLayer, @@ -123,6 +138,7 @@ export type RestartSandboxGatewayOptions = BaseRestartSandboxGatewayOptions & { }; export { buildSandboxExecMarkedCommand } from "./sandbox-exec-output"; +export { buildSubprocessEnv as buildSandboxSubprocessEnv }; export type { SandboxCommandResult, SandboxExecCommandOptions }; @@ -1345,7 +1361,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); @@ -1581,7 +1597,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"; @@ -1589,7 +1605,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; @@ -1633,7 +1649,7 @@ export async function isSandboxGatewayRunningForStatus( getHealthProbeUrl?: typeof getSandboxHealthProbeUrl; } = {}, ): Promise { - const agent = (options.getSessionAgent ?? agentRuntime.getSessionAgent)(sandboxName); + const agent = (options.getSessionAgent ?? getRecoverySessionAgent)(sandboxName); if (agent && !agentRuntime.hasGatewayRuntime(agent)) return null; return isSandboxGatewayHttpReachableForStatus(sandboxName, gatewayName, options); } @@ -1769,11 +1785,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() @@ -1782,7 +1798,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 ( @@ -1857,8 +1873,8 @@ export async function restartSandboxGateway( restartSandboxGatewayWithDeps(sandboxName, { quiet, deps: { - getSessionAgent: agentRuntime.getSessionAgent, - getSandbox: registry.getSandbox, + getSessionAgent: getRecoverySessionAgent, + getSandbox: readRecoverySandbox, resolveSandboxDashboardPort, buildOpenClawReadinessProbeCommand: (name) => { // OpenClaw 2026.3.11+ exposes { ready: boolean } here: @@ -1882,7 +1898,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) => @@ -2249,7 +2265,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. } @@ -2272,7 +2288,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 @@ -2498,7 +2514,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/rebuild-flow-helpers.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.ts index bde8c66ee5e..692944820d7 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 8c122106773..f757df83ccb 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"; @@ -16,6 +20,13 @@ import { checkRebuildGatewaySchemaPreflight, runRebuildGatewayIntentPreflight, } from "./rebuild-preflight-guards"; +import { + delegateRecoveryRetirementToOwningRegistry, + delegateRebuildToOwningRegistry, + findRebuildRecoveryStorageRoot, + rebuildOwningRegistryDependencies, +} from "./rebuild/owning-registry"; +import { rebuildSandbox } from "./rebuild"; const driftIssue: gatewayDrift.OpenShellStateRpcIssue = { kind: "image_drift", @@ -353,3 +364,310 @@ 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), + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + }; + 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({ operation: "rebuild", ...input }, 9000, { + credentialEnvNames: ["NVIDIA_INFERENCE_API_KEY"], + }); + 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(); + }); + + 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, + gatewayPort: 9000, + registryGatewayPort: 9000, + registryFile: "/home/test/.nemoclaw/gateways/9000/sandboxes.json", + }); + vi.spyOn(rebuildOwningRegistryDependencies, "isHostFenceHeld").mockReturnValue(false); + const confirmInteractiveRebuild = vi + .spyOn(rebuildOwningRegistryDependencies, "confirmInteractiveRebuild") + .mockResolvedValue(true); + const runWorker = vi + .spyOn(rebuildOwningRegistryDependencies, "runWorker") + .mockResolvedValue(undefined); + + await expect( + delegateRebuildToOwningRegistry( + { sandboxName: "alpha", options: {}, executionOptions: {} }, + "/home/test", + "/home/test/.nemoclaw/sandboxes.json", + ), + ).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(); + }); + + 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 }); + } + }); + + 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, + ); + 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"); + + 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-pipeline.ts b/src/lib/actions/sandbox/rebuild-pipeline.ts index c8127191640..9645be47023 100644 --- a/src/lib/actions/sandbox/rebuild-pipeline.ts +++ b/src/lib/actions/sandbox/rebuild-pipeline.ts @@ -47,6 +47,7 @@ import { serializeHermesOperatorConfigSnapshot, } from "./rebuild-durable-config"; import { + delegateRebuildToOwningRegistry, disposeRebuildAgentBaseImagePreflight, removeStaleRebuildDockerOrphan, snapshotOpenShellEnv, @@ -124,6 +125,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( { @@ -154,7 +165,7 @@ export async function rebuildSandbox( try { await rebuildSandboxUnlocked( sandboxName, - options, + normalizedOptions, opts, removedImmutabilityMigration.stateRecord !== null, ); diff --git a/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts b/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts index d7372094365..e20a15511ce 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, @@ -19,9 +20,47 @@ import { afterEach(() => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); }); 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("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 b1a0f78088a..384d4b33323 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 }, @@ -150,6 +159,42 @@ 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 { + 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.", + ); + return false; + } + 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-recreate-journal.ts b/src/lib/actions/sandbox/rebuild-recreate-journal.ts index ebfb937198b..e16935ba950 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 new file mode 100644 index 00000000000..5ca3253e2ab --- /dev/null +++ b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts @@ -0,0 +1,112 @@ +// 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 { enforceRemovedImmutabilityMigrationBoundary } from "../../../state/migrations/removed-immutability"; +import { withSandboxLifecycleLock } from "../lifecycle/lock"; +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, OwningRegistryWorkerResult } from "./owning-registry"; + +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(): OwningRegistryWorkerInput { + 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") { + throw new Error("Rebuild worker input is invalid."); + } + if ( + parsed.operation === "rebuild" && + isRecord(parsed.options) && + isRecord(parsed.executionOptions) + ) { + 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, + }; + } + throw new Error("Rebuild worker input is invalid."); +} + +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 = 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}.`, + ); + return; + } + const executionOptions = { + ...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 { + await run(input); + writeResult({ ok: true, ...identity }); + } catch (error) { + const detail = redactBoundedRebuildFailure(error); + writeResult({ ok: false, ...identity, ...(detail ? { message: detail } : {}) }); + process.exitCode = 1; + } +} + +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..c3f4fa7b7a1 --- /dev/null +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -0,0 +1,504 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +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 type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; +import { resolveGatewayName } from "../../../gateway-runtime-action"; +import { webSearchEnvFor } from "../../../inference/web-search"; +import { snapshotCredentialEnv } from "../../../onboard/credential-env"; +import { + assertGatewayStatePathSafe, + isValidName, + 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 { 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"; + +export interface RebuildOwningRegistryInput { + readonly sandboxName: string; + readonly options: RebuildSandboxOptions; + 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 type OwningRegistryWorkerResult = Readonly<{ + ok: boolean; + operation: OwningRegistryWorkerInput["operation"]; + sandboxName: string; + gatewayPort: number; + 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; + confirmInteractiveRebuild: typeof confirmDelegatedRebuildIntent; + findSandbox: typeof findSandboxAcrossGatewayRoots; + findRecoveryRoot: typeof findRebuildRecoveryStorageRoot; + isHostFenceHeld: typeof isCurrentPortableHostFenceHeld; + runWorker( + input: OwningRegistryWorkerInput, + gatewayPort: 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; +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", + "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, + credentialEnvNames: readonly string[], +): Record { + const extra: Record = { + ...snapshotCredentialEnv(credentialEnvNames), + 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); +} + +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; + for await (const chunk of stream) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string); + bytes += buffer.length; + if (bytes > MAX_WORKER_RESULT_BYTES) { + throw new Error("Rebuild worker result is too large."); + } + chunks.push(buffer); + } + 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).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") + ) { + return null; + } + return parsed as OwningRegistryWorkerResult; +} + +function workerProcessGroupIsRunning(child: ChildProcess, dedicatedProcessGroup: boolean): boolean { + if (!dedicatedProcessGroup || typeof child.pid !== "number") { + return child.exitCode === null && child.signalCode === null; + } + try { + process.kill(-child.pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "EPERM"; + } +} + +function signalWorkerProcessGroup( + child: ChildProcess, + dedicatedProcessGroup: boolean, + signal: NodeJS.Signals, +): void { + if (dedicatedProcessGroup && typeof child.pid === "number") { + try { + process.kill(-child.pid, signal); + return; + } catch { + // Fall back to the leader when the group is already gone or unavailable. + } + } + try { + child.kill(signal); + } catch { + // The leader already exited. + } +} + +async function waitForWorkerProcessGroupExit( + child: ChildProcess, + dedicatedProcessGroup: boolean, + timeoutMs: number, +): 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 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, + options: RebuildWorkerOptions = {}, +): 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."); + } + assertWorkerPlatformSupported(process.platform); + const dedicatedProcessGroup = true; + 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); + try { + const child = spawn(process.execPath, [WORKER_PATH], { + detached: dedicatedProcessGroup, + env: rebuildWorkerEnv(gatewayPort, options.credentialEnvNames ?? []), + 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 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, + ]); + } catch (error) { + await terminateWorkerProcessGroup(child, dedicatedProcessGroup, terminationGraceMs); + await settleWorkerPromises([inputWritten, exited, result], REBUILD_WORKER_REAP_TIMEOUT_MS); + throw error; + } 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"; + 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.`, + ); + } + 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); + } +} + +export const rebuildOwningRegistryDependencies: RebuildOwningRegistryDependencies = { + assertWorkerPlatformSupported, + confirmInteractiveRebuild: confirmDelegatedRebuildIntent, + 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 { + if (!isValidName(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); + 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); + 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}'.`, + ); + } + 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, + 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 + * 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.`, + ); + } + let workerInput = input; + if (!input.options.yes && !input.options.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", ...workerInput }, + hit.registryGatewayPort, + { credentialEnvNames: rebuildCredentialEnvNames(hit.entry) }, + ); + 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/src/lib/actions/sandbox/start.test.ts b/src/lib/actions/sandbox/start.test.ts index 945ab7627d2..8ab39882cde 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 { afterEach, describe, expect, it, vi } from "vitest"; import * as sandboxCommandCli from "../../adapters/openshell/sandbox-command-cli"; @@ -139,6 +143,44 @@ function providerRegistry(providerId: "docker" | "podman") { } 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, + lifecycleLiveIdentityFingerprint: fingerprintOpenShellSandboxId("sandbox-alpha"), + openshellDriver: "docker", + 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.each(["docker", "podman"] as const)( "dispatches standard %s lifecycle through the shared OpenShell adapter", async (providerId) => { diff --git a/src/lib/actions/sandbox/start.ts b/src/lib/actions/sandbox/start.ts index 94df83510a6..301d559feb7 100644 --- a/src/lib/actions/sandbox/start.ts +++ b/src/lib/actions/sandbox/start.ts @@ -19,6 +19,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, @@ -205,7 +210,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, @@ -215,7 +222,7 @@ async function startSandboxWithinLifecycleFence( if (!resolved.ok) return resolved.result; const input = { - readRegistry: deps.getSandbox ?? registry.getSandbox, + readRegistry: readSandbox, environment: deps.environment ?? process.env, gatewayName: getPersistedSandboxTargetGatewayName(resolved.sandbox), log, @@ -273,14 +280,13 @@ async function startSandboxWithinLifecycleFence( } 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/status-flow.test.ts b/src/lib/actions/sandbox/status-flow.test.ts index dbe32139ec4..88fcf35e5de 100644 --- a/src/lib/actions/sandbox/status-flow.test.ts +++ b/src/lib/actions/sandbox/status-flow.test.ts @@ -2,6 +2,7 @@ // 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"; @@ -23,8 +24,11 @@ function hermesPortableDisposition(phase: "pending" | "configuring" | "active") describe("showSandboxStatus flow", () => { let exitSpy: MockInstance; + let testHome: string; beforeEach(() => { + testHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-status-flow-")); + vi.stubEnv("HOME", testHome); process.exitCode = undefined; exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number | string | null) => { throw new Error(`process.exit(${code ?? 0})`); @@ -33,8 +37,10 @@ describe("showSandboxStatus flow", () => { afterEach(() => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); process.exitCode = undefined; resetStatusFlowModuleCache(); + fs.rmSync(testHome, { force: true, recursive: true }); }); it.each(["pending", "configuring", "active"] as const)( @@ -122,10 +128,147 @@ 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)); }); + it.each([ + { + label: "Docker", + openshellDriver: "docker", + expected: "nemoclaw alpha destroy --yes", + unexpected: "nemoclaw alpha start", + containerAbsenceConfirmed: true, + registryEntry: "present" as const, + publishedAcrossGatewayRoots: false, + }, + { + label: "native", + openshellDriver: "mxc", + expected: "nemoclaw alpha start", + unexpected: "nemoclaw alpha destroy --yes", + containerAbsenceConfirmed: false, + registryEntry: "present" as const, + publishedAcrossGatewayRoots: false, + }, + { + label: "cross-root native", + openshellDriver: "mxc", + expected: "nemoclaw alpha start", + unexpected: "nemoclaw alpha destroy --yes", + containerAbsenceConfirmed: false, + registryEntry: "missing" as const, + publishedAcrossGatewayRoots: true, + }, + ])( + "passes the $label driver to missing-container Error recovery guidance", + async ({ + openshellDriver, + expected, + unexpected, + containerAbsenceConfirmed, + 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", + phase: "Error", + recoveredGateway: true, + recoveryVia: "gateway reattach", + }, + }); + harness.getSandboxDockerRuntimeSpy.mockReturnValue({ + containerName: null, + health: "none", + paused: false, + running: false, + containerAbsenceConfirmed, + }); + + 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); + expect(harness.collectSandboxStatusSnapshotSpy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + sandboxEntry: expect.objectContaining({ openshellDriver }), + }), + ); + }, + ); + + 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, + containerAbsenceConfirmed: false, + }); + + 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" }, + 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, + containerAbsenceConfirmed: 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", @@ -271,7 +414,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(); }); @@ -512,6 +655,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(); @@ -628,14 +773,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 () => { @@ -663,9 +811,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-inference.test.ts b/src/lib/actions/sandbox/status-inference.test.ts index df259b5d481..c6f72d5a9ae 100644 --- a/src/lib/actions/sandbox/status-inference.test.ts +++ b/src/lib/actions/sandbox/status-inference.test.ts @@ -1,7 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { buildSandboxInferenceInvocationCommand } from "./inference-invocation-probe"; import { collectSandboxStatusSnapshot, @@ -11,6 +15,18 @@ import { } from "./status"; describe("sandbox status inference.local route health (#6192)", () => { + let testHome: string; + + beforeEach(() => { + testHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-status-inference-")); + vi.stubEnv("HOME", testHome); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + fs.rmSync(testHome, { force: true, recursive: true }); + }); + function snapshotDeps(options: { agent?: string; confirmedStopped?: boolean; @@ -43,9 +59,9 @@ 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 }; + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + recordSandboxStopIntent: vi.fn((_name: string, stopped: boolean) => { + sandbox = { ...sandbox, stopped }; return true; }), reconcile: vi.fn(async () => @@ -92,6 +108,12 @@ describe("sandbox status inference.local route health (#6192)", () => { async (_input: Parameters[0]) => ({ ok: true }) as const, ), + recoverSandboxProcesses: vi.fn(async () => ({ + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + })) as never, probeTerminalRuntimeHealth: vi.fn(() => ({ kind: "ok" as const, oomKillCount: 0 as const })), reportInferenceProbeError, }; @@ -205,7 +227,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({ @@ -229,7 +251,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.test.ts b/src/lib/actions/sandbox/status-lookup-rendering.test.ts index d8d46a891cb..873fb4b78ff 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.test.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.test.ts @@ -16,13 +16,18 @@ function captureConsoleLog(): { lines: () => string; restore: () => void } { async function printGuidance({ phase, dockerRuntime, + openshellDriver = "docker", + dockerRuntimeDown = false, }: { phase: string; + openshellDriver?: string | null; + dockerRuntimeDown?: boolean; dockerRuntime: { health: "none"; paused: boolean; running: boolean; containerName: string | null; + containerAbsenceConfirmed?: boolean; } | null; }): Promise { await printSandboxGatewayLookupStatus({ @@ -30,12 +35,19 @@ async function printGuidance({ registered: true, lookup: { state: "present", output: `Sandbox:\n Name: beta\n Phase: ${phase}` }, phase, - dockerRuntime, + openshellDriver, + dockerRuntime: dockerRuntime + ? { + ...dockerRuntime, + containerAbsenceConfirmed: dockerRuntime.containerAbsenceConfirmed === true, + } + : null, + dockerRuntimeDown, effectivePreflight: { failure: null, - failureLayer: null, - suppressInferenceProbe: false, - exitCode: 0, + failureLayer: dockerRuntimeDown ? "docker_unreachable" : null, + suppressInferenceProbe: dockerRuntimeDown, + exitCode: dockerRuntimeDown ? 1 : 0, }, }); } @@ -61,13 +73,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 () => { @@ -116,7 +127,9 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { registered: true, lookup: { state: "missing", output: "sandbox beta not found" }, phase: "Stopped", + openshellDriver: "docker", dockerRuntime: null, + dockerRuntimeDown: false, effectivePreflight: { failure: null, failureLayer: null, @@ -143,7 +156,9 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { registered: true, lookup: { state: "gateway_schema_mismatch", output: "gateway schema mismatch" }, phase: "Stopped", + openshellDriver: "docker", dockerRuntime: null, + dockerRuntimeDown: false, effectivePreflight: { failure: null, failureLayer: null, @@ -173,7 +188,9 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { " Sandbox 'beta' is running, but NemoClaw could not clear its stale intentional-stop record.", }, phase: "Running", + openshellDriver: "docker", dockerRuntime: null, + dockerRuntimeDown: false, effectivePreflight: { failure: null, failureLayer: null, @@ -212,24 +229,112 @@ 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 Docker-driver sandbox without its container to clean replacement", async () => { + const cap = captureConsoleLog(); + await printGuidance({ + phase: "Error", + dockerRuntime: { + health: "none", + paused: false, + running: false, + containerName: null, + containerAbsenceConfirmed: true, + }, + }); + 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).toContain("separately created snapshot"); + expect(text).not.toContain("nemoclaw beta rebuild --yes"); + 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("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("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 () => { + 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(); + 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"); + }); + + 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..8b0bf673bf7 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -7,7 +7,12 @@ 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, + getSandboxPhaseRecoveryGuidance, + isDockerRuntimeDown, + printDockerRuntimeDownGuidance, +} from "./gateway-failure-classifier"; import type { SandboxGatewayState } from "./gateway-state"; import { printSandboxGatewayStateHint, printWrongGatewayActiveGuidance } from "./gateway-state"; import { getSandboxTargetGatewayName } from "./gateway-target"; @@ -22,7 +27,9 @@ type SandboxGatewayLookupStatusContext = { registered: boolean; lookup: SandboxGatewayState; phase: string | null; + openshellDriver: string | null; dockerRuntime: ReturnType | null; + dockerRuntimeDown: boolean; effectivePreflight: SandboxStatusPreflightResult; }; @@ -133,7 +140,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.`, ); } @@ -141,7 +148,9 @@ function printPresentSandboxGatewayLookupStatus({ sandboxName, lookup, phase, + openshellDriver, dockerRuntime, + dockerRuntimeDown, }: SandboxGatewayLookupStatusContext): void { console.log(""); if ("recoveredGateway" in lookup && lookup.recoveredGateway) { @@ -166,7 +175,13 @@ 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, + dockerRuntimeDown, + }); } function printWrongGatewayActiveLookupStatus({ @@ -262,11 +277,15 @@ async function printUnknownGatewayLookupStatus({ function printNonReadySandboxPhaseGuidance({ sandboxName, phase, + openshellDriver, dockerRuntime, + dockerRuntimeDown, }: { sandboxName: string; phase: string | null; + openshellDriver: string | null; dockerRuntime: ReturnType | null; + dockerRuntimeDown: boolean; }): void { if (!phase || phase === "Ready") return; if ( @@ -285,8 +304,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,16 +337,17 @@ function printNonReadySandboxPhaseGuidance({ " This usually happens when a process crash inside the sandbox prevented clean startup.", ); console.log(""); - if (phase === "Error" && dockerRuntime?.containerName) { - 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.)`, - ); - return; + const recoveryAction = classifySandboxPhaseRecoveryAction({ + phase, + openshellDriver, + dockerContainerName: dockerRuntime?.containerName, + dockerContainerAbsenceConfirmed: dockerRuntime?.containerAbsenceConfirmed === true, + }); + if (!dockerRuntime?.containerName && dockerRuntimeDown) { + printDockerRuntimeDownGuidance(sandboxName, { writer: console.log }); + deferSandboxLifecycleExit(1); + } + for (const line of getSandboxPhaseRecoveryGuidance(sandboxName, recoveryAction)) { + console.log(line); } - 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-inference-health.test.ts b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts index 1c80b904c9b..d3d21967af5 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 a9887d4178c..866d63ea01a 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"; @@ -72,7 +76,8 @@ 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, inferenceRouteObserver: { observeInferenceRoute: async () => { @@ -87,6 +92,91 @@ 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("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("leaves agent delivery recovery to the native image runtime", async () => { const deps = { ...snapshotDeps({ @@ -300,7 +390,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-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index a7dd0b9c712..ac2ece386ac 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,83 @@ 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 }); + }); + + 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)", () => { @@ -336,7 +401,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 f3c82b0dab2..45384e9faf9 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -30,15 +30,19 @@ import { type ProviderHealthStatus, probeProviderHealth, } from "../../inference/health"; -import type { ServingProfileProvenance } from "../../inference/serving/types"; import { type DcodeAutoApprovalMode, 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, + recordSandboxStopIntentAcrossGatewayRoots, +} from "../../state/registry/cross-port"; import { canSandboxGatewayRouteRealign } from "./connect-inference-gateway"; import { getSandboxDockerRuntime } from "./docker-health"; import type { SandboxGatewayState } from "./gateway-state"; @@ -76,6 +80,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; @@ -169,7 +174,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; @@ -301,9 +306,12 @@ 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; + recordSandboxStopIntent?: typeof recordSandboxStopIntentAcrossGatewayRoots; + captureOpenshellForStatusImpl?: typeof captureOpenshellForStatus; inferenceRouteObserver?: OpenShellInferenceRouteObserver; probeProviderHealthImpl?: ProbeProviderHealth; probeSandboxInferenceGatewayHealthImpl?: ProbeSandboxInferenceGatewayHealth; @@ -315,7 +323,7 @@ interface CollectSandboxStatusSnapshotDeps { recoverSandboxProcesses?: RecoverSandboxProcesses; reconcile?: ReconcileSandboxGatewayState; getSandboxStatusPreflightImpl?: typeof getSandboxStatusPreflight; - getGatewayPresets?: typeof getGatewayPresets; + getGatewayPresets?: GetGatewayPresets; inspectManagedLlamaCppOwnership?: typeof inspectManagedLlamaCppOwnership; } @@ -431,6 +439,7 @@ function reportInferenceProbeRetry( export async function collectSandboxStatusSnapshot( sandboxName: string, opts: { + sandboxEntry?: registry.SandboxEntry | null; suppressInferenceProbe?: boolean; preflight?: SandboxStatusPreflightResult; deps?: CollectSandboxStatusSnapshotDeps; @@ -442,7 +451,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 @@ -473,10 +484,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 = { @@ -605,7 +615,10 @@ export async function collectSandboxStatusSnapshot( sandboxName, sb, gatewayName, - (opts.deps?.listSandboxes ?? registry.listSandboxes)().sandboxes, + ( + opts.deps?.listPublishedSandboxesAcrossGatewayRoots ?? + listPublishedSandboxesAcrossGatewayRoots + )(), ), ), } @@ -790,14 +803,17 @@ async function buildSandboxStatusReport( const getSandbox = deps.getSandbox ?? ((name: string) => { - const entry = registry.getSandbox(name); + const entry = + (deps.findSandboxAcrossGatewayRoots ?? 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 { @@ -815,7 +831,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( @@ -828,7 +849,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, undefined, sb) : []; const agent = resolveSandboxStatusAgent(sb?.agent || "openclaw"); return { schemaVersion: 1, @@ -863,7 +888,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 dc755d4d87b..7f5bd59e36b 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -8,7 +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 } from "../../state/registry/cross-port"; +import { + findSandboxAcrossGatewayRoots, + listPublishedSandboxNamesAcrossGatewayRoots, +} from "../../state/registry/cross-port"; import { getSandboxDockerRuntime } from "./docker-health"; import { qualifyPortableAgentLifecycleAuthority, @@ -134,7 +137,7 @@ export async function getSandboxStatusReport( deps.getGatewayPresets ?? getGatewayPresets, ); } - return getLegacySandboxStatusReport(sandboxName, deps); + return getLegacySandboxStatusReport(sandboxName, { getGatewayPresets, ...deps }); }); } @@ -177,7 +180,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 +189,7 @@ async function showLegacySandboxStatus(sandboxName: string): Promise { // synthesized fallback keeps the user-visible contract intact. const snapshot = await collectSandboxStatusSnapshot(sandboxName, { preflight, + sandboxEntry, }); const { sb, @@ -200,16 +205,18 @@ 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 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) { @@ -250,7 +257,9 @@ async function showLegacySandboxStatus(sandboxName: string): Promise { registered: sb !== null, lookup, phase, + openshellDriver: sb?.openshellDriver ?? null, dockerRuntime, + dockerRuntimeDown, effectivePreflight, }); diff --git a/src/lib/actions/sandbox/stop.test.ts b/src/lib/actions/sandbox/stop.test.ts index 942a54ef132..ee9b381287b 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"; @@ -318,6 +322,88 @@ 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", + dashboardPort: 19443, + gatewayName: "nemoclaw-8245", + gatewayPort: 8245, + lifecycleLiveIdentityFingerprint: fingerprintOpenShellSandboxId("sandbox-alpha"), + openshellDriver: "docker", + }, + }, + }), + ); + vi.stubEnv("HOME", home); + try { + 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, + 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 }); + 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 }); + } + }); + it("gracefully stops in-sandbox channels before stopping through OpenShell (#6026)", async () => { const h = harness(); h.getSandbox.mockReturnValue(sandbox({ lifecycleGeneration: "standard-generation" })); diff --git a/src/lib/actions/sandbox/stop.ts b/src/lib/actions/sandbox/stop.ts index 30951ab5cd4..eae1b4a318f 100644 --- a/src/lib/actions/sandbox/stop.ts +++ b/src/lib/actions/sandbox/stop.ts @@ -20,6 +20,12 @@ import { } from "../../onboard/experimental/portable-agent-lifecycle"; 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 { @@ -79,6 +85,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; @@ -173,7 +186,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, @@ -297,7 +310,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, @@ -307,7 +322,7 @@ async function stopSandboxWithinLifecycleFence( if (!resolved.ok) return resolved.result; const input = { - readRegistry: deps.getSandbox ?? registry.getSandbox, + readRegistry: readSandbox, environment: deps.environment ?? process.env, gatewayName: resolvePersistedSandboxOwnershipGateway(resolved.sandbox), log, @@ -391,13 +406,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/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..61d8797f5d0 100644 --- a/src/lib/onboard/credential-env.test.ts +++ b/src/lib/onboard/credential-env.test.ts @@ -1,18 +1,39 @@ // 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, + snapshotCredentialEnv, + 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("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", () => { @@ -23,7 +44,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..d7c3d154b5a 100644 --- a/src/lib/onboard/credential-env.ts +++ b/src/lib/onboard/credential-env.ts @@ -1,7 +1,28 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { 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 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/src/lib/onboard/runtime-provider/contract.ts b/src/lib/onboard/runtime-provider/contract.ts index 541c1994d12..0a780a65b41 100644 --- a/src/lib/onboard/runtime-provider/contract.ts +++ b/src/lib/onboard/runtime-provider/contract.ts @@ -44,6 +44,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 0ca6a12eb30..c4e419350ec 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, @@ -21,6 +22,7 @@ import { type RuntimeProviderSnapshotRestoreReceipt, type RuntimeProviderSnapshotRestoreSource, } from "./contract"; +export { normalizeRuntimeProviderIdentity } from "./contract"; import type { HostLocalInferenceOperation, HostLocalInferenceOperationInput, @@ -727,11 +729,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, diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index 0ffa894e487..18a41d983d3 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") @@ -2742,8 +2751,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 []; @@ -2788,11 +2797,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 { @@ -2809,7 +2819,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({ @@ -2820,7 +2830,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/src/lib/state/gateway-registry.ts b/src/lib/state/gateway-registry.ts index 656fd5e045d..8c451ad54ef 100644 --- a/src/lib/state/gateway-registry.ts +++ b/src/lib/state/gateway-registry.ts @@ -13,6 +13,7 @@ import { GATEWAYS_SUBDIR, nemoclawStateRoot } from "./state-root"; export { GATEWAYS_SUBDIR, resolveHome } from "./state-root"; export { DEFAULT_GATEWAY_PORT } from "../core/ports"; +export { isValidName } from "../name-validation"; export { releaseManagedGatewayStateLifecycleLock, tryAcquireManagedGatewayStateLifecycleLock, @@ -35,6 +36,7 @@ export interface GatewayRegistryEntry extends Record { export interface GatewayRegistryDocument extends Record { defaultSandbox: string | null; + defaultSelectionRevision?: number; sandboxes: Record; } @@ -93,6 +95,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/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.ts b/src/lib/state/registry.ts index a47da53429e..cffbb3f121d 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/src/lib/state/registry/cross-port.test.ts b/src/lib/state/registry/cross-port.test.ts index 383bc634605..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("", { @@ -122,20 +173,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..a86ccbec78c 100644 --- a/src/lib/state/registry/cross-port.ts +++ b/src/lib/state/registry/cross-port.ts @@ -10,13 +10,18 @@ import { registryEntryGatewayPort, resolveHome, type GatewayRegistryEntry, + withRegistryLockAt, } from "../gateway-registry"; +import { writeConfigFile } from "../config-io"; +import { removeSandboxFromRegistry } from "../registry-reversible-removal"; import type { SandboxEntry } from "./types"; 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; } @@ -62,6 +67,7 @@ function listSandboxHitsAcrossGatewayRoots(home: string): CrossPortSandboxHit[] state.gatewayPort === DEFAULT_GATEWAY_PORT && !hasRecordedGatewayIdentity ? null : gatewayPort, + registryGatewayPort: state.gatewayPort, registryFile, }); } @@ -92,11 +98,96 @@ export function findSandboxAcrossGatewayRoots( return matches[0]; } +/** 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 sandboxName = hit.entry.name; + 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; + } +} + +/** 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) + .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 +195,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(), 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/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 }); } diff --git a/test/cli/rebuild-recovery-routing.test.ts b/test/cli/rebuild-recovery-routing.test.ts new file mode 100644 index 00000000000..6aec878e27a --- /dev/null +++ b/test/cli/rebuild-recovery-routing.test.ts @@ -0,0 +1,298 @@ +// 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"; + +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 }; +} + +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, + stopped: true, + }, + }, + })}\n`, + { mode: 0o600 }, + ); + return registryPath; +} + +function writeSuccessfulRebuildWorkerPreload(home: string): { + markerPath: string; + preloadPath: string; +} { + const siblingStateRoot = path.join(home, ".nemoclaw", "gateways", "9000"); + const markerPath = path.join(siblingStateRoot, "rebuild-worker-success.json"); + const preloadPath = path.join(home, "successful-rebuild-worker.cjs"); + fs.writeFileSync( + preloadPath, + [ + 'const childProcess = require("node:child_process");', + 'const fs = require("node:fs");', + 'const path = require("node:path");', + 'const Module = require("node:module");', + "const originalSpawn = childProcess.spawn;", + "childProcess.spawn = function spawnWithWorkerPreload(command, args, options) {", + ' const isOwningRegistryWorker = Array.isArray(args) && args.some((arg) => String(arg).endsWith("owning-registry-worker.js"));', + " if (isOwningRegistryWorker) {", + " options = {", + " ...options,", + ` env: { ...options.env, NODE_OPTIONS: ${JSON.stringify(`--require=${preloadPath}`)} },`, + " };", + " }", + " return originalSpawn.call(this, command, args, options);", + "};", + "const originalLoad = Module._load;", + "Module._load = function loadSuccessfulRebuildFixture(request, parent, isMain) {", + ' if (process.env.NEMOCLAW_GATEWAY_PORT === "9000" && request === "../rebuild-pipeline") {', + " return {", + " rebuildSandbox: async (sandboxName, options, executionOptions) => {", + ' if (sandboxName !== "gw1-sb" || options?.yes !== true || executionOptions?.throwOnError !== true) {', + ' throw new Error("compiled worker received an invalid rebuild descriptor");', + " }", + ' const stateRoot = path.join(process.env.HOME, ".nemoclaw", "gateways", process.env.NEMOCLAW_GATEWAY_PORT);', + ' const registryPath = path.join(stateRoot, "sandboxes.json");', + ' const registry = JSON.parse(fs.readFileSync(registryPath, "utf8"));', + " registry.sandboxes[sandboxName].stopped = false;", + " fs.writeFileSync(registryPath, `${JSON.stringify(registry)}\\n`, { mode: 0o600 });", + ` fs.writeFileSync(${JSON.stringify(markerPath)}, JSON.stringify({`, + " sandboxName,", + " gatewayPort: Number(process.env.NEMOCLAW_GATEWAY_PORT),", + " yes: options.yes,", + " throwOnError: executionOptions.throwOnError,", + " }), { mode: 0o600 });", + " },", + " };", + " }", + " return originalLoad.call(this, request, parent, isMain);", + "};", + ].join("\n"), + { mode: 0o600 }, + ); + return { markerPath, preloadPath }; +} + +describe("CLI rebuild recovery routing", () => { + it( + "completes a 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 { markerPath, preloadPath } = writeSuccessfulRebuildWorkerPreload(home); + + const result = runWithEnv( + "gw1-sb rebuild --yes", + { + HOME: home, + NODE_OPTIONS: `--require=${preloadPath}`, + }, + 30_000, + ); + + expect(result.code, result.out).toBe(0); + expect(JSON.parse(fs.readFileSync(markerPath, "utf8"))).toEqual({ + sandboxName: "gw1-sb", + gatewayPort: 9000, + yes: true, + throwOnError: true, + }); + expect(JSON.parse(fs.readFileSync(registryPath, "utf8")).sandboxes["gw1-sb"].stopped).toBe( + false, + ); + 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), + () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-retire-recovery-ok-")); + try { + const openshellLog = writeOpenShellStub(home, false); + const { backupPath, handoffPath, manifestPath, recordPath, retainedPath } = + 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.out).toContain( + `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([ + "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 }); + } + }, + ); + + 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 }); + } + }, + ); + + 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 }); + } + }, + ); +}); 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/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index 39ed0fa3749..2624b762811 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -273,6 +273,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"); 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..6745bf83242 --- /dev/null +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -0,0 +1,495 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// 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"; + +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"; +const TIMESTAMP = "2026-09-17T00-00-00-000Z"; + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +function writeRecoveryFixture(home: string) { + 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 }); + 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({ + schemaVersion: 3, + transactionId: TRANSACTION_ID, + sandboxName: "alpha", + backupTimestamp: TIMESTAMP, + gatewayName: "nemoclaw-9000", + gatewayPort: 9000, + phase: "restore", + })}\n`, + { mode: 0o600 }, + ); + return manifest; +} + +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 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 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> = {}, +): 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", + dashboardPort: 18_789, + gatewayName: "nemoclaw-9000", + gatewayPort: 9000, + ...entryOverrides, + }, + }, + })}\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."; + let failure: unknown; + + try { + await rebuildOwningRegistryDependencies.runWorker( + { + operation: "rebuild", + sandboxName: "alpha", + options: { yes: true, toolDisclosure: "invalid" } as never, + executionOptions: {}, + }, + 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", + gatewayPort: 9000, + message: expectedMessage, + }); + }); + + 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, + ), + ).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("OPENAI_API_KEY", "openai-unrelated-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, + { + credentialEnvNames: ["NVIDIA_INFERENCE_API_KEY"], + 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("OPENAI_API_KEY=openai-unrelated-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 { + writeSiblingRegistry(home); + const recoveryManifest = writeRecoveryFixture(home); + vi.stubEnv("HOME", home); + vi.stubEnv("NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", "1"); + let failure: unknown; + + try { + await rebuildOwningRegistryDependencies.runWorker( + { + operation: "rebuild", + sandboxName: "alpha", + options: { yes: true }, + executionOptions: { recoveryManifest }, + }, + 9000, + ); + } catch (error) { + failure = error; + } + + expect(failure).toBeInstanceOf(Error); + 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: "Recovery registry entry has no NemoClaw-managed image fingerprint.", + }), + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + 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( + { + 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.", + ); + }); + + 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 }); + } + }); + + 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) => + pid < 0 && signal === 0 ? true : 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\./, + ); + }); +}); 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. diff --git a/test/runtime/policy/policy-channel-agent-resolution.test.ts b/test/runtime/policy/policy-channel-agent-resolution.test.ts index 7efc000d05c..e2c944e035a 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 = (await import(${POLICIES_PATH})).default; +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 }, + }); + expect(result.status, result.stderr).toBe(0); + const calls = fs.readFileSync(openshellLog, "utf8"); + fs.rmSync(tmpDir, { recursive: true, force: true }); + + 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` diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 7cfc5e963f3..a65f13251d4 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -755,6 +755,16 @@ 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, + ); vi.spyOn(registry, "listSandboxes").mockReturnValue({ sandboxes: registryEntries, defaultSandbox: primaryRegistryEntry.name, diff --git a/test/support/status-flow-test-harness.ts b/test/support/status-flow-test-harness.ts index 33de1e088dd..7f00f0e97ec 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 ?? { @@ -250,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")