From 827f23ca6585b238f13e6a208e2fe2cc02643eec Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 12 Sep 2026 00:38:14 +0700 Subject: [PATCH 1/3] fix(onboard): accept canonical N1x vLLM routes Signed-off-by: San Dang --- .../sandbox/n1x-managed-vllm-rebuild.test.ts | 58 +++++++++++--- .../sandbox/n1x-managed-vllm-rebuild.ts | 15 +++- .../created-sandbox-n1x-finalization.test.ts | 56 +++++++++++++- src/lib/state/registry-normalization.test.ts | 76 +++++++++++-------- 4 files changed, 154 insertions(+), 51 deletions(-) diff --git a/src/lib/domain/sandbox/n1x-managed-vllm-rebuild.test.ts b/src/lib/domain/sandbox/n1x-managed-vllm-rebuild.test.ts index f50e239bb41..0fdab0070be 100644 --- a/src/lib/domain/sandbox/n1x-managed-vllm-rebuild.test.ts +++ b/src/lib/domain/sandbox/n1x-managed-vllm-rebuild.test.ts @@ -21,7 +21,7 @@ describe("Deferred N1x managed-vLLM acceptance route", () => { const accepted = { provider: "vllm-local", model: "nvidia/Qwen3.6-35B-A3B-NVFP4", - endpointUrl: null, + endpointUrl: "http://host.openshell.internal:8000/v1", endpointSource: null, nimContainer: null, openshellDriver: "docker", @@ -29,6 +29,8 @@ describe("Deferred N1x managed-vLLM acceptance route", () => { it.each([ ["the exact route", accepted, true], + ["a derived legacy endpoint", { ...accepted, endpointUrl: null }, true], + ["another provider", { ...accepted, provider: "compatible-endpoint" }, false], ["another model", { ...accepted, model: "other" }, false], ["a recorded endpoint", { ...accepted, endpointUrl: "http://localhost:8000/v1" }, false], ["another endpoint source", { ...accepted, endpointSource: "inference-set" }, false], @@ -37,6 +39,35 @@ describe("Deferred N1x managed-vLLM acceptance route", () => { ])("classifies %s", (_case, route, expected) => { expect(isDeferredN1xManagedVllmAcceptanceRoute(route)).toBe(expected); }); + + it.each([1024, 8000, 18000, 65535])( + "accepts the canonical endpoint on port %s (#11510)", + (port) => { + expect( + isDeferredN1xManagedVllmAcceptanceRoute({ + ...accepted, + endpointUrl: `http://host.openshell.internal:${port}/v1`, + }), + ).toBe(true); + }, + ); + + it.each([ + undefined, + "", + "http://host.openshell.internal:1023/v1", + "http://host.openshell.internal:65536/v1", + "http://host.openshell.internal:08000/v1", + "http://host.openshell.internal.example:8000/v1", + "http://user:password@host.openshell.internal:8000/v1", + "https://host.openshell.internal:8000/v1", + "http://host.openshell.internal:8000/v1/", + "http://host.openshell.internal:8000/v1?target=other", + "http://host.openshell.internal:8000/v1#other", + "http://host.openshell.internal:8000/v1\n", + ])("rejects noncanonical endpoint %s (#11510)", (endpointUrl) => { + expect(isDeferredN1xManagedVllmAcceptanceRoute({ ...accepted, endpointUrl })).toBe(false); + }); }); describe("recorded N1x managed-vLLM rebuild eligibility", () => { @@ -84,15 +115,19 @@ describe("recorded N1x managed-vLLM rebuild eligibility", () => { expect(eligible(sandboxEntry)).toBe(true); }); - it("accepts normalized N1x Express intent with a derived endpoint (#10959)", () => { - expect( - eligible({ - ...n1xExpressEntry, - endpointSource: null, - deferredN1xManagedVllmAccepted: true, - }), - ).toBe(true); - }); + it.each([null, "http://host.openshell.internal:8000/v1"])( + "accepts recorded N1x preview intent with endpoint %s (#11510)", + (endpointUrl) => { + expect( + eligible({ + ...n1xExpressEntry, + endpointUrl, + endpointSource: null, + deferredN1xManagedVllmAccepted: true, + }), + ).toBe(true); + }, + ); it("accepts an explicit preview retry for a normalized legacy record (#10959)", () => { expect( @@ -175,12 +210,11 @@ describe("recorded N1x managed-vLLM rebuild eligibility", () => { rebuildSelection: n1xExpressSelection, }, { - caseName: "normalized source with a recorded endpoint", + caseName: "recorded endpoint without preview provenance", sandboxEntry: { ...n1xExpressEntry, endpointUrl: "http://host.openshell.internal:8000/v1", endpointSource: null, - deferredN1xManagedVllmAccepted: true, }, rebuildSelection: n1xExpressSelection, }, diff --git a/src/lib/domain/sandbox/n1x-managed-vllm-rebuild.ts b/src/lib/domain/sandbox/n1x-managed-vllm-rebuild.ts index 629543567fd..a2ece474e43 100644 --- a/src/lib/domain/sandbox/n1x-managed-vllm-rebuild.ts +++ b/src/lib/domain/sandbox/n1x-managed-vllm-rebuild.ts @@ -45,9 +45,19 @@ export interface DeferredN1xManagedVllmAcceptanceRoute { export function isDeferredN1xManagedVllmAcceptanceRoute( route: DeferredN1xManagedVllmAcceptanceRoute, ): boolean { + // Persisted acceptance must remain readable without the original shell's vLLM port setting. + const endpointMatch = + typeof route.endpointUrl === "string" + ? /^http:\/\/host\.openshell\.internal:([1-9][0-9]{3,4})\/v1$/u.exec(route.endpointUrl) + : null; + const canonicalEndpoint = + endpointMatch !== null && + endpointMatch[0] === route.endpointUrl && + Number(endpointMatch[1]) >= 1024 && + Number(endpointMatch[1]) <= 65535; return ( isN1xManagedVllmProviderModel(route.provider, route.model) && - route.endpointUrl === null && + (route.endpointUrl === null || canonicalEndpoint) && route.endpointSource === null && route.nimContainer == null && route.openshellDriver === "docker" @@ -94,9 +104,8 @@ export function isRecordedN1xManagedVllmRebuildEligible( const recordedSourceIsEligible = sandboxEntry.endpointSource === "onboard" || (sandboxEntry.endpointSource === null && - sandboxEntry.endpointUrl === null && (sandboxEntry.deferredN1xManagedVllmAccepted === true || - options.explicitPreviewIntent === true)); + (sandboxEntry.endpointUrl === null && options.explicitPreviewIntent === true))); if ( !isN1xManagedVllmProviderModel(sandboxEntry.provider, sandboxEntry.model) || !recordedEndpointUsesCanonicalLocalRoute || diff --git a/src/lib/onboard/created-sandbox-n1x-finalization.test.ts b/src/lib/onboard/created-sandbox-n1x-finalization.test.ts index 5981ca2fc15..5eef5c855b1 100644 --- a/src/lib/onboard/created-sandbox-n1x-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-n1x-finalization.test.ts @@ -5,8 +5,10 @@ import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; -import { afterEach, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { requireValue } from "../core/require-value"; +import { isRecordedN1xManagedVllmRebuildEligible } from "../domain/sandbox/n1x-managed-vllm-rebuild"; import { createSession, type Session } from "../state/onboard-session"; import type { SandboxEntry } from "../state/registry"; import { @@ -21,6 +23,9 @@ import { type InitialOnboardFlowContext, } from "./machine/initial-flow-phases"; import type { SandboxGpuCreateFlowResult } from "./sandbox-gpu-create-flow"; +import { parseHostLocalInferenceReceipt } from "./runtime-provider/host-local-inference"; +import type { SetupNimSelectionState } from "./setup-nim-flow"; +import { createSetupNimVllmHandler } from "./setup-nim-vllm"; const sandboxName = "n1x-preview"; const model = "nvidia/Qwen3.6-35B-A3B-NVFP4"; @@ -32,18 +37,54 @@ afterEach(async () => { vi.resetModules(); await Promise.all(homes.splice(0).map((home) => fs.rm(home, { recursive: true, force: true }))); }); -const inferenceSelection = { +const inferenceSelection: SetupNimSelectionState & { + model: string; + endpointSource: null; + compatibleEndpointReasoning: null; + compatibleEndpointReasoningEffort: null; +} = { provider, model, endpointUrl: null, endpointSource: null, credentialEnv: null, hermesAuthMethod: null, + hermesToolGateways: [], preferredInferenceApi: "openai-completions", compatibleEndpointReasoning: null, compatibleEndpointReasoningEffort: null, nimContainer: null, -} as const; + allowToolsIncompatible: false, +}; + +beforeEach(async () => { + inferenceSelection.endpointUrl = null; + const handler = createSetupNimVllmHandler({ + VLLM_PORT: 8000, + getLocalProviderBaseUrl: () => "http://host.openshell.internal:8000/v1", + getLocalProviderValidationBaseUrl: () => "http://127.0.0.1:8000/v1", + getManagedVllmProviderBinding: () => ({ + baseUrl: "http://host.openshell.internal:8000/v1", + validationBaseUrl: "http://127.0.0.1:8000/v1", + apiKey: "test-key", + }), + runCapture: vi.fn(() => { + throw new Error("Unexpected unauthenticated vLLM query"); + }), + queryVllmModels: () => JSON.stringify({ data: [{ id: model }] }), + isSafeModelId: () => true, + requireValue, + validateOpenAiLikeSelection: async () => ({ ok: true, api: "openai-completions" }), + applyVllmRuntimeContextWindow: vi.fn(), + persistConfiguredManagedVllmRuntimeReceipt: async () => ({ ok: true, persisted: true }), + exitProcess: (code) => { + throw new Error(`Unexpected vLLM setup exit ${code}`); + }, + }); + expect(await handler(inferenceSelection, { managedInstall: true, sparkHost: false })).toBe( + "selected", + ); +}); type Gpu = { type: "nvidia"; platform: "n1x" | "spark" }; type GpuConfig = { @@ -341,6 +382,15 @@ it.each([ }); const registration = await completeRegistration(flow.createIntent); + expect(registration.endpointUrl).toBe("http://host.openshell.internal:8000/v1"); + expect( + isRecordedN1xManagedVllmRebuildEligible( + registration, + { provider, model, pinEndpoint: true, endpointUrl: null }, + parseHostLocalInferenceReceipt, + ), + ).toBe(expected); + expect([ flow.accepted, flow.createIntent.deferredN1xManagedVllmPreviewIntent, diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index cd33eb800f8..16c594977dd 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -245,43 +245,53 @@ describe("sandbox registry normalization", () => { ); }); - it("round-trips only valid Deferred N1x preview acceptance (#10959)", async () => { - const registry = await loadRegistryWith({ legacy: { name: "legacy" } }); - registry.registerSandbox({ - name: "preview", - provider: "vllm-local", - model: "nvidia/Qwen3.6-35B-A3B-NVFP4", - endpointUrl: null, - endpointSource: null, - openshellDriver: "docker", - deferredN1xManagedVllmAccepted: true, - }); - vi.resetModules(); - const reloadedRegistry = await import("./registry"); - - expect(reloadedRegistry.getSandbox("preview")?.deferredN1xManagedVllmAccepted).toBe(true); - const malformed = await loadRegistryWith({ - malformed: { - name: "malformed", - deferredN1xManagedVllmAccepted: "true", - }, - }); - expect(() => malformed.getSandbox("malformed")).toThrow("invalid N1x preview acceptance"); - const mismatchedRoute = await loadRegistryWith({ - mismatched: { - name: "mismatched", + it.each([ + null, + "http://host.openshell.internal:8000/v1", + "http://host.openshell.internal:18000/v1", + ])( + "round-trips valid Deferred N1x preview acceptance with endpoint %s (#11510)", + async (endpointUrl) => { + const registry = await loadRegistryWith({ legacy: { name: "legacy" } }); + registry.registerSandbox({ + name: "preview", provider: "vllm-local", model: "nvidia/Qwen3.6-35B-A3B-NVFP4", - endpointUrl: null, - endpointSource: "inference-set", + endpointUrl, + endpointSource: null, openshellDriver: "docker", deferredN1xManagedVllmAccepted: true, - }, - }); - expect(() => mismatchedRoute.getSandbox("mismatched")).toThrow( - "invalid N1x preview acceptance", - ); - }); + }); + vi.resetModules(); + const reloadedRegistry = await import("./registry"); + + expect(reloadedRegistry.getSandbox("preview")).toMatchObject({ + endpointUrl, + deferredN1xManagedVllmAccepted: true, + }); + const malformed = await loadRegistryWith({ + malformed: { + name: "malformed", + deferredN1xManagedVllmAccepted: "true", + }, + }); + expect(() => malformed.getSandbox("malformed")).toThrow("invalid N1x preview acceptance"); + const mismatchedRoute = await loadRegistryWith({ + mismatched: { + name: "mismatched", + provider: "vllm-local", + model: "nvidia/Qwen3.6-35B-A3B-NVFP4", + endpointUrl, + endpointSource: "inference-set", + openshellDriver: "docker", + deferredN1xManagedVllmAccepted: true, + }, + }); + expect(() => mismatchedRoute.getSandbox("mismatched")).toThrow( + "invalid N1x preview acceptance", + ); + }, + ); it("clears Deferred N1x acceptance when route authority changes (#10959)", async () => { const registry = await loadRegistryWith({}); From 545cd8295753bd9b8c9da4bc336802470bf7c46a Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 12 Sep 2026 01:30:06 +0700 Subject: [PATCH 2/3] fix(onboard): reconcile absent retained N1x sandbox before retry Signed-off-by: San Dang --- src/lib/actions/onboard.test.ts | 35 +- src/lib/actions/onboard.ts | 11 +- .../actions/onboard/retained-recovery.test.ts | 335 ++++++++++++++++++ src/lib/actions/onboard/retained-recovery.ts | 156 ++++++++ src/lib/gateway-runtime-action.test.ts | 55 +++ src/lib/gateway-runtime-action.ts | 17 +- src/lib/onboard.ts | 22 +- src/lib/onboard/lifecycle-contracts.md | 9 + 8 files changed, 621 insertions(+), 19 deletions(-) create mode 100644 src/lib/actions/onboard/retained-recovery.test.ts create mode 100644 src/lib/actions/onboard/retained-recovery.ts diff --git a/src/lib/actions/onboard.test.ts b/src/lib/actions/onboard.test.ts index 4085f1e87ff..1ca8aea9e4f 100644 --- a/src/lib/actions/onboard.test.ts +++ b/src/lib/actions/onboard.test.ts @@ -7,10 +7,17 @@ const mocks = vi.hoisted(() => ({ listAgents: vi.fn(() => ["openclaw"]), onboard: vi.fn().mockResolvedValue(undefined), runOnboardCommand: vi.fn(), + reconcileRetainedOnboard: vi.fn(), })); vi.mock("../agent/defs", () => ({ listAgents: mocks.listAgents })); -vi.mock("../onboard", () => ({ onboard: mocks.onboard })); +vi.mock("../onboard", () => ({ + onboard: mocks.onboard, + retainedOnboardRecoveryHost: {}, +})); +vi.mock("./onboard/retained-recovery", () => ({ + createRetainedOnboardRecovery: () => mocks.reconcileRetainedOnboard, +})); vi.mock("../onboard/command", () => ({ runOnboardCommand: mocks.runOnboardCommand })); import { runOnboardAction } from "./onboard"; @@ -18,6 +25,7 @@ import { runOnboardAction } from "./onboard"; describe("onboard action runtime composition", () => { beforeEach(() => { vi.clearAllMocks(); + mocks.reconcileRetainedOnboard.mockResolvedValue(null); mocks.runOnboardCommand.mockImplementation( async (deps: { runOnboard(options: unknown): Promise }) => { await deps.runOnboard({ nonInteractive: true, resume: false }); @@ -39,4 +47,29 @@ describe("onboard action runtime composition", () => { googlechatTunnelRuntime, }); }); + + it("restarts the default name fresh only after retained recovery completes (#11510)", async () => { + mocks.reconcileRetainedOnboard.mockResolvedValue("my-assistant"); + + await runOnboardAction({ "non-interactive": true }); + + expect(mocks.onboard).toHaveBeenCalledExactlyOnceWith({ + nonInteractive: true, + resume: false, + fresh: true, + sandboxName: "my-assistant", + googlechatTunnelRuntime: undefined, + }); + expect(mocks.reconcileRetainedOnboard).toHaveBeenCalledBefore(mocks.onboard); + }); + + it("does not enter onboarding when recovery fails", async () => { + mocks.reconcileRetainedOnboard.mockRejectedValue(new Error("Recovery preserved")); + + await expect(runOnboardAction({ "non-interactive": true })).rejects.toThrow( + "Recovery preserved", + ); + + expect(mocks.onboard).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/actions/onboard.ts b/src/lib/actions/onboard.ts index 9beb40d57d8..b4a5f641845 100644 --- a/src/lib/actions/onboard.ts +++ b/src/lib/actions/onboard.ts @@ -19,10 +19,17 @@ async function runOnboard( ): Promise { // Keep the monolithic legacy onboarding graph lazy so command metadata/help // imports do not execute it. Resolve it only when the user invokes onboard. - const { onboard } = (await import("../onboard")) as unknown as { + const { createRetainedOnboardRecovery } = await import("./onboard/retained-recovery"); + const { onboard, retainedOnboardRecoveryHost } = (await import("../onboard")) as unknown as { onboard: (onboardOptions?: OnboardOptions) => Promise; + retainedOnboardRecoveryHost: Parameters[0]; }; - await onboard({ ...options, googlechatTunnelRuntime: runtimeDeps.googlechatTunnelRuntime }); + const recoveredName = await createRetainedOnboardRecovery(retainedOnboardRecoveryHost)(options); + await onboard({ + ...options, + ...(recoveredName ? { sandboxName: recoveredName, fresh: true, resume: false } : {}), + googlechatTunnelRuntime: runtimeDeps.googlechatTunnelRuntime, + }); } function buildOnboardCommandDeps(flags: OnboardFlags, runtimeDeps: OnboardActionRuntimeDeps) { diff --git a/src/lib/actions/onboard/retained-recovery.test.ts b/src/lib/actions/onboard/retained-recovery.test.ts new file mode 100644 index 00000000000..ac96d1fd626 --- /dev/null +++ b/src/lib/actions/onboard/retained-recovery.test.ts @@ -0,0 +1,335 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { classifyOpenShellSandboxPresence } from "../../adapters/openshell/sandbox-presence"; +import { resolveOnboardEntryOptions } from "../../onboard/entry-options"; +import type { RetainedSandboxRecoveryRecord } from "../../state/onboard-session/retained-sandbox-recovery"; +import type { SandboxEntry } from "../../state/registry"; +import * as gatewayRuntime from "../../gateway-runtime-action"; +import * as destroyRuntime from "../sandbox/destroy"; +import { + createRetainedOnboardRecovery, + reconcileRetainedN1xOnboard, + type RetainedOnboardRecoveryDeps, +} from "./retained-recovery"; + +vi.mock("../../state/mcp-lifecycle-lock-acquisition", () => ({ + withMcpLifecycleLock: async (_name: string, operation: () => Promise) => operation(), +})); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +const options = { + sandboxName: null, + resume: false, + agent: null, + experimentalProfile: null, + apfInterceptorRequested: null, +}; + +function harness(name = "my-assistant") { + const record: RetainedSandboxRecoveryRecord = { + schemaVersion: 1, + recordId: "a".repeat(64), + sandboxName: name, + sandboxIdentityFingerprint: "b".repeat(64), + identityWasUnavailable: false, + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "failed-generation", + createAttemptNonce: "c".repeat(62), + resources: { + sharedInferenceProviders: ["vllm-local"], + sandboxScopedProviders: [], + credentialEnvironmentVariables: [], + }, + reason: "retained_after_sandbox_creation_failure", + recordedAt: "2026-09-11T16:54:47.903Z", + }; + const entry: SandboxEntry = { + name, + provider: "vllm-local", + model: "nvidia/Qwen3.6-35B-A3B-NVFP4", + endpointUrl: "http://host.openshell.internal:8000/v1", + endpointSource: null, + pendingRouteReservation: true, + openshellDriver: null, + gatewayName: record.gatewayName, + gatewayPort: record.gatewayPort, + }; + const state = { + records: [record] as readonly RetainedSandboxRecoveryRecord[], + entry: entry as SandboxEntry | null, + gatewayAvailable: false, + response: { status: 0, stdout: "[]", stderr: "" }, + }; + const deps: RetainedOnboardRecoveryDeps = { + gatewayPort: 8080, + validateName: (name) => name, + env: {}, + loadSession: () => null, + listRecords: () => state.records, + getSandbox: () => state.entry, + withLock: vi.fn(async (_name, operation) => operation()), + recoverGateway: vi.fn(async () => { + state.gatewayAvailable = true; + return true; + }), + observeSandbox: vi.fn(() => + classifyOpenShellSandboxPresence( + name, + state.gatewayAvailable + ? state.response + : { status: 1, stderr: "Unknown gateway 'nemoclaw'" }, + ), + ), + confirm: vi.fn(async () => true), + destroy: vi.fn(async () => { + state.entry = null; + state.records = []; + }), + }; + return { state, deps, record, entry }; +} + +describe("retrying a retained N1x onboarding name", () => { + it("scopes production recovery to its recorded gateway and requires a cleanup answer", async () => { + const h = harness(); + vi.stubEnv("OPENSHELL_GATEWAY", "another-gateway"); + vi.stubEnv("OPENSHELL_WORKSPACE", undefined); + vi.stubEnv("NEMOCLAW_YES", "1"); + vi.stubEnv("NEMOCLAW_NON_INTERACTIVE", "1"); + vi.spyOn(process, "stdin", "get").mockReturnValue({ + isTTY: true, + fd: 0, + } as typeof process.stdin); + vi.spyOn(gatewayRuntime.gatewayRuntimeDependencies, "captureOpenshell").mockImplementation( + (args) => { + const output = args[0] === "sandbox" ? "[]" : "Status: Connected\nGateway: nemoclaw\n"; + return { status: 0, output, stdout: output, stderr: "" }; + }, + ); + const destroy = vi.spyOn(destroyRuntime, "destroySandbox").mockImplementation(h.deps.destroy); + const prompt = vi.fn(async () => { + expect(process.env.OPENSHELL_GATEWAY).toBe("nemoclaw"); + expect(process.env.OPENSHELL_WORKSPACE).toBe("default"); + expect(destroy).not.toHaveBeenCalled(); + return "yes"; + }); + + await expect(createRetainedOnboardRecovery({ ...h.deps, prompt })(options)).resolves.toBe( + "my-assistant", + ); + + expect(prompt).toHaveBeenCalledOnce(); + expect(destroy).toHaveBeenCalledExactlyOnceWith("my-assistant", { + yes: true, + cleanupGateway: false, + }); + expect(process.env.OPENSHELL_GATEWAY).toBe("another-gateway"); + expect(process.env.OPENSHELL_WORKSPACE).toBeUndefined(); + }); + + it("does not authorize production cleanup from installer auto-yes without a terminal", async () => { + const h = harness(); + vi.stubEnv("OPENSHELL_WORKSPACE", undefined); + vi.stubEnv("NEMOCLAW_YES", "1"); + vi.spyOn(process, "stdin", "get").mockReturnValue({ + isTTY: false, + fd: 0, + } as typeof process.stdin); + vi.spyOn(gatewayRuntime.gatewayRuntimeDependencies, "captureOpenshell").mockImplementation( + (args) => { + const output = args[0] === "sandbox" ? "[]" : "Status: Connected\nGateway: nemoclaw\n"; + return { status: 0, output, stdout: output, stderr: "" }; + }, + ); + const destroy = vi.spyOn(destroyRuntime, "destroySandbox").mockImplementation(h.deps.destroy); + const prompt = vi.fn(); + + await expect(createRetainedOnboardRecovery({ ...h.deps, prompt })(options)).rejects.toThrow( + "authorize cleanup", + ); + + expect(prompt).not.toHaveBeenCalled(); + expect(destroy).not.toHaveBeenCalled(); + expect(h.state.records).toEqual([h.record]); + }); + + it.each([null, "my-assistant", "custom-assistant"])( + "restores the missing gateway and admits the same name %s after confirmed cleanup (#11510)", + async (sandboxName) => { + const h = harness(sandboxName ?? "my-assistant"); + const recoveredName = await reconcileRetainedN1xOnboard({ ...options, sandboxName }, h.deps); + + expect(h.state.gatewayAvailable).toBe(true); + expect(recoveredName).toBe(h.record.sandboxName); + expect(h.deps.destroy).toHaveBeenCalledExactlyOnceWith(h.record.sandboxName); + expect(h.state.records).toEqual([]); + const admitted = resolveOnboardEntryOptions( + { + opts: { sandboxName: recoveredName, fresh: true }, + env: {}, + stdinIsTty: true, + stdoutIsTty: true, + retainedRecoverySandboxNames: h.state.records.map((record) => record.sandboxName), + }, + { + isNonInteractive: () => false, + validateName: (name) => name, + reservedSandboxNames: new Set(), + cliDisplayName: () => "nemoclaw", + getNameValidationGuidance: () => [], + error: vi.fn(), + exitProcess: () => { + throw new Error("Onboarding remained blocked"); + }, + }, + ); + expect(admitted).toMatchObject({ requestedSandboxName: h.record.sandboxName, fresh: true }); + }, + ); + + it("uses the installer-selected name without requiring an active session", async () => { + const h = harness("installer-name"); + h.deps.env.NEMOCLAW_SANDBOX_NAME = "installer-name"; + await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBe("installer-name"); + }); + + it.each([ + { status: 1, stdout: "", stderr: "Unknown gateway 'nemoclaw'" }, + { status: 0, stdout: "not-json", stderr: "" }, + { + status: 0, + stdout: JSON.stringify([ + { + id: "retained-sandbox", + name: "my-assistant", + labels: {}, + resource_version: 1, + created_at: "2026-09-11T16:54:47Z", + phase: "Ready", + current_policy_version: 1, + }, + ]), + stderr: "", + }, + ])("preserves recovery when absence is unproven: %j", async (response) => { + const h = harness(); + h.state.response = response; + await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); + expect(h.deps.confirm).not.toHaveBeenCalled(); + expect(h.deps.destroy).not.toHaveBeenCalled(); + expect(h.state.records).toEqual([h.record]); + }); + + it("does not clear recovery when gateway restoration fails", async () => { + const h = harness(); + h.deps.recoverGateway = vi.fn(async () => false); + await expect(reconcileRetainedN1xOnboard(options, h.deps)).rejects.toThrow("Could not restore"); + expect(h.deps.observeSandbox).not.toHaveBeenCalled(); + expect(h.deps.destroy).not.toHaveBeenCalled(); + expect(h.state.records).toEqual([h.record]); + }); + + it("preserves the record when cleanup is declined despite installer auto-yes", async () => { + const h = harness(); + h.deps.env.NEMOCLAW_YES = "1"; + h.deps.env.NEMOCLAW_NON_INTERACTIVE = "1"; + h.deps.confirm = vi.fn(async () => false); + await expect(reconcileRetainedN1xOnboard(options, h.deps)).rejects.toThrow("authorize cleanup"); + expect(h.deps.destroy).not.toHaveBeenCalled(); + expect(h.state.entry).toEqual(h.entry); + }); + + it("refuses a recovery record replaced during confirmation", async () => { + const h = harness(); + h.deps.confirm = async () => { + h.state.records = [{ ...h.record, createAttemptNonce: "d".repeat(62) }]; + return true; + }; + await expect(reconcileRetainedN1xOnboard(options, h.deps)).rejects.toThrow("authority"); + expect(h.deps.destroy).not.toHaveBeenCalled(); + }); + + it("refuses registry authority changed during gateway restoration", async () => { + const h = harness(); + h.deps.recoverGateway = async () => { + h.state.entry = { ...h.entry, lifecycleGeneration: "replacement" }; + return true; + }; + await expect(reconcileRetainedN1xOnboard(options, h.deps)).rejects.toThrow("authority"); + expect(h.deps.observeSandbox).not.toHaveBeenCalled(); + expect(h.deps.destroy).not.toHaveBeenCalled(); + }); + + it("does not admit the name when destroy leaves unresolved recovery", async () => { + const h = harness(); + h.deps.destroy = async () => {}; + await expect(reconcileRetainedN1xOnboard(options, h.deps)).rejects.toThrow("not confirmed"); + expect(h.state.records).toEqual([h.record]); + }); + + it.each([ + { resume: true }, + { agent: "hermes" }, + { apfInterceptorRequested: true }, + { sandboxName: "another-name" }, + ])("preserves other onboarding intent %j", async (override) => { + const h = harness(); + await expect( + reconcileRetainedN1xOnboard({ ...options, ...override }, h.deps), + ).resolves.toBeNull(); + expect(h.deps.recoverGateway).not.toHaveBeenCalled(); + expect(h.deps.destroy).not.toHaveBeenCalled(); + }); + + it.each([ + { provider: "compatible-endpoint" }, + { model: "another-model" }, + { pendingRouteReservation: undefined }, + { openshellDriver: "podman" }, + { gatewayName: "another-gateway" }, + { gatewayPort: 18080 }, + { endpointUrl: "https://external.example/v1" }, + { endpointSource: "inference-set" as const }, + { nimContainer: "nemoclaw-nim" }, + ])("preserves routes outside the failed N1x attempt: %j", async (override) => { + const h = harness(); + h.state.entry = { ...h.entry, ...override }; + await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); + expect(h.deps.recoverGateway).not.toHaveBeenCalled(); + expect(h.deps.destroy).not.toHaveBeenCalled(); + }); + + it("preserves a cancelled attempt and multiple matching recovery records", async () => { + const h = harness(); + h.state.records = [{ ...h.record, reason: "cancelled_after_sandbox_creation" }]; + await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); + h.state.records = [h.record, { ...h.record, recordId: "d".repeat(64) }]; + await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); + expect(h.deps.recoverGateway).not.toHaveBeenCalled(); + expect(h.deps.destroy).not.toHaveBeenCalled(); + }); + + it("preserves recovery under another workspace selection", async () => { + const h = harness(); + h.deps.env.OPENSHELL_WORKSPACE = "other"; + await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); + expect(h.deps.recoverGateway).not.toHaveBeenCalled(); + expect(h.deps.destroy).not.toHaveBeenCalled(); + }); + + it("preserves recovery when the environment selects another agent", async () => { + const h = harness(); + h.deps.env.NEMOCLAW_AGENT = "hermes"; + await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); + expect(h.deps.recoverGateway).not.toHaveBeenCalled(); + expect(h.deps.destroy).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/onboard/retained-recovery.ts b/src/lib/actions/onboard/retained-recovery.ts new file mode 100644 index 00000000000..6e6ad33d938 --- /dev/null +++ b/src/lib/actions/onboard/retained-recovery.ts @@ -0,0 +1,156 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isDeepStrictEqual } from "node:util"; + +import type { OpenShellSandboxPresence } from "../../adapters/openshell/sandbox-presence"; +import { isDeferredN1xManagedVllmAcceptanceRoute } from "../../domain/sandbox/n1x-managed-vllm-rebuild"; +import { + observeNamedGatewaySandboxPresence, + recoverNamedGatewayRuntime, + replaceOpenShellRuntimeSelectionEnv, + snapshotOpenShellEnv, + resolveGatewayName, +} from "../../gateway-runtime-action"; +import type { OnboardCommandOptions } from "../../onboard/command"; +import { RESERVED_SANDBOX_NAMES } from "../../onboard/sandbox-agent"; +import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock-acquisition"; +import type { RetainedSandboxRecoveryRecord } from "../../state/onboard-session/retained-sandbox-recovery"; +import type { SandboxEntry } from "../../state/registry/types"; +import { destroySandbox } from "../../actions/sandbox/destroy"; + +type RecoveryOptions = Pick< + OnboardCommandOptions, + "sandboxName" | "resume" | "agent" | "experimentalProfile" | "apfInterceptorRequested" +>; + +export interface RetainedOnboardRecoveryDeps { + readonly gatewayPort: number; + readonly env: NodeJS.ProcessEnv; + validateName(name: string, kind: string): string; + loadSession(): { sandboxName?: string | null } | null; + listRecords(): readonly RetainedSandboxRecoveryRecord[]; + getSandbox(name: string): SandboxEntry | null; + withLock(name: string, operation: () => Promise): Promise; + recoverGateway(record: RetainedSandboxRecoveryRecord): Promise; + observeSandbox(record: RetainedSandboxRecoveryRecord): OpenShellSandboxPresence; + confirm(name: string): Promise; + destroy(name: string): Promise; +} + +type RecoveryHostDeps = Pick< + RetainedOnboardRecoveryDeps, + "gatewayPort" | "loadSession" | "listRecords" | "getSandbox" | "validateName" +> & { prompt(question: string): Promise }; + +export function createRetainedOnboardRecovery(host: RecoveryHostDeps) { + const deps: RetainedOnboardRecoveryDeps = { + ...host, + env: process.env, + withLock: (name, operation) => + withMcpLifecycleLock(name, async () => { + const restore = snapshotOpenShellEnv(); + replaceOpenShellRuntimeSelectionEnv(process.env, { + gatewayName: resolveGatewayName(host.gatewayPort), + workspace: "default", + }); + try { + return await operation(); + } finally { + restore(); + } + }), + recoverGateway: async (record) => + ( + await recoverNamedGatewayRuntime({ + gatewayName: record.gatewayName, + ignoreProbeErrors: true, + }) + ).recovered, + observeSandbox: (record) => + observeNamedGatewaySandboxPresence(record.sandboxName, record.gatewayName), + confirm: async (name) => { + if (!process.stdin.isTTY) return false; + const answer = await host.prompt( + ` Sandbox '${name}' is absent after an earlier failed setup. Remove its verified leftovers and retry this name? [y/N]: `, + ); + return /^(?:y|yes)$/iu.test(answer.trim()); + }, + destroy: (name) => destroySandbox(name, { yes: true, cleanupGateway: false }), + }; + return (options: RecoveryOptions) => reconcileRetainedN1xOnboard(options, deps); +} + +/** Reconcile an absent failed N1x attempt before normal same-name admission. */ +export async function reconcileRetainedN1xOnboard( + options: RecoveryOptions, + deps: RetainedOnboardRecoveryDeps, +): Promise { + if ( + options.resume || + options.experimentalProfile || + options.apfInterceptorRequested || + (options.agent || deps.env.NEMOCLAW_AGENT?.trim() || "openclaw") !== "openclaw" || + (deps.env.OPENSHELL_WORKSPACE && deps.env.OPENSHELL_WORKSPACE !== "default") + ) { + return null; + } + const name = deps.validateName( + options.sandboxName || + deps.env.NEMOCLAW_SANDBOX_NAME?.trim() || + deps.loadSession()?.sandboxName || + "my-assistant", + "sandbox name", + ); + if (RESERVED_SANDBOX_NAMES.has(name)) return null; + const matching = deps.listRecords().filter((record) => record.sandboxName === name); + if (matching.length !== 1) return null; + const record = matching[0]; + const entry = deps.getSandbox(name); + if ( + record.reason !== "retained_after_sandbox_creation_failure" || + record.gatewayPort !== deps.gatewayPort || + record.gatewayName !== resolveGatewayName(deps.gatewayPort) || + !entry?.pendingRouteReservation || + !isDeferredN1xManagedVllmAcceptanceRoute({ + ...entry, + openshellDriver: entry.openshellDriver ?? "docker", + }) || + (entry.agent != null && entry.agent !== "openclaw") || + entry.gatewayName !== record.gatewayName || + entry.gatewayPort !== record.gatewayPort + ) { + return null; + } + return deps.withLock(name, async () => { + const assertCurrent = () => { + const current = deps.listRecords().filter((candidate) => candidate.sandboxName === name); + if ( + !isDeepStrictEqual(current, [record]) || + !isDeepStrictEqual(deps.getSandbox(name), entry) + ) { + throw new Error(`Recovery authority for sandbox '${name}' changed; retry stopped.`); + } + }; + assertCurrent(); + if (!(await deps.recoverGateway(record))) { + throw new Error(`Could not restore gateway '${record.gatewayName}'; recovery was preserved.`); + } + assertCurrent(); + if (deps.observeSandbox(record) !== "absent") return null; + if (!(await deps.confirm(name))) { + throw new Error( + `Recovery for '${name}' was preserved. Run 'nemoclaw ${name} destroy --yes' to authorize cleanup, then retry onboarding.`, + ); + } + assertCurrent(); + await deps.destroy(name); + if ( + deps.listRecords().some((candidate) => candidate.sandboxName === name) || + deps.getSandbox(name) + ) { + throw new Error(`Cleanup for sandbox '${name}' was not confirmed; retry stopped.`); + } + return name; + }); +} diff --git a/src/lib/gateway-runtime-action.test.ts b/src/lib/gateway-runtime-action.test.ts index 6424581c233..25f912a81da 100644 --- a/src/lib/gateway-runtime-action.test.ts +++ b/src/lib/gateway-runtime-action.test.ts @@ -156,6 +156,61 @@ describe("gateway-runtime-action per-sandbox gateway routing", () => { }); describe("recoverNamedGatewayRuntime", () => { + it.each([ + { status: 0, stdout: "[]", stderr: "", expected: "absent" }, + { status: 1, stdout: "", stderr: "Unknown gateway 'nemoclaw'", expected: "unknown" }, + { status: 0, stdout: "not-json", stderr: "", expected: "unknown" }, + ])("observes named sandbox presence conservatively: $expected", (result) => { + captureSpy.mockReturnValue({ ...result, output: result.stdout }); + + expect(gatewayRuntime.observeNamedGatewaySandboxPresence("my-assistant", "nemoclaw")).toBe( + result.expected, + ); + expect(captureSpy).toHaveBeenCalledWith( + ["sandbox", "list", "-g", "nemoclaw", "-o", "json"], + expect.objectContaining({ ignoreError: true, includeStreams: true }), + ); + }); + + it("restores an unknown gateway when recovery opts into non-fatal probes (#11510)", async () => { + let started = false; + captureSpy.mockImplementation((_args, opts) => { + expect(opts?.ignoreError).toBe(true); + return started + ? { status: 0, output: "Status: Connected\nGateway: nemoclaw\n" } + : { status: 1, output: "Unknown gateway 'nemoclaw'" }; + }); + runSpy.mockReturnValue({ status: 0 } as never); + startGatewaySpy.mockImplementation(async () => { + started = true; + }); + + const result = await gatewayRuntime.recoverNamedGatewayRuntime({ + gatewayName: "nemoclaw", + ignoreProbeErrors: true, + }); + + expect(result).toMatchObject({ recovered: true, via: "start" }); + expect(startGatewaySpy).toHaveBeenCalledExactlyOnceWith({ + gatewayName: "nemoclaw", + gatewayPort: 8080, + }); + expect(captureSpy.mock.calls.every(([, opts]) => opts?.includeStderr === true)).toBe(true); + }); + + it("keeps authentication failures blocking with non-fatal recovery probes (#11510)", async () => { + captureSpy.mockReturnValue({ status: 1, output: "gateway info requires admin privileges" }); + + const result = await gatewayRuntime.recoverNamedGatewayRuntime({ + gatewayName: "nemoclaw", + ignoreProbeErrors: true, + }); + + expect(result).toMatchObject({ recovered: false, attempted: false }); + expect(startGatewaySpy).not.toHaveBeenCalled(); + expect(runSpy).not.toHaveBeenCalled(); + }); + it.each([ { label: "authentication", status: 1, output: "gateway info requires admin privileges" }, { label: "schema validation", status: 1, output: "protobuf decode error: invalid wire type" }, diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index a7790b34676..b869e96d85d 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -20,6 +20,7 @@ import { } from "./onboard/gateway-binding"; import type { GatewayRecoveryOutput } from "./onboard/gateway-recovery"; import { sanitizeReadinessText } from "./readiness/sanitize"; +import { classifyOpenShellSandboxPresence } from "./adapters/openshell/sandbox-presence"; export { resolveGatewayName, resolveSandboxGatewayName }; @@ -56,6 +57,14 @@ export const gatewayRuntimeDependencies = { }, }; +export function observeNamedGatewaySandboxPresence(sandboxName: string, gatewayName: string) { + const result = gatewayRuntimeDependencies.captureOpenshell( + ["sandbox", "list", "-g", gatewayName, "-o", "json"], + { ignoreError: true, includeStreams: true, timeout: OPENSHELL_PROBE_TIMEOUT_MS }, + ); + return classifyOpenShellSandboxPresence(sandboxName, result); +} + /** Whether `gateway info` output names the given NemoClaw gateway. */ function hasNamedGateway(output = "", gatewayName = "nemoclaw"): boolean { return stripAnsi(output).includes(`Gateway: ${gatewayName}`); @@ -189,6 +198,7 @@ export function getNamedGatewayLifecycleState( type NamedGatewayLifecycleStateName = NamedGatewayLifecycleState["state"]; export type RecoverNamedGatewayRuntimeOptions = { + ignoreProbeErrors?: boolean; recoverableStates?: readonly NamedGatewayLifecycleStateName[]; gatewayName?: string; output?: GatewayRecoveryOutput; @@ -203,9 +213,10 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun `Gateway recovery target '${gatewayName}' does not match runtime selection '${options.runtimeSelection.gatewayName}'`, ); } - const lifecycleOptions = options.runtimeSelection - ? { runtimeSelection: options.runtimeSelection } - : {}; + const lifecycleOptions = { + ignoreProbeErrors: options.ignoreProbeErrors, + ...(options.runtimeSelection ? { runtimeSelection: options.runtimeSelection } : {}), + }; const recoverableStates = new Set( options.recoverableStates ?? [ "missing_named", diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 4509f814893..50e983d48ab 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -648,19 +648,7 @@ async function promptOrDefault( ): Promise { return onboardPromptHelpers.promptOrDefault(promptHelperDeps, question, envVar, defaultValue); } - -async function promptYesNoOrDefault( - question: string, - envVar: string | null, - defaultIsYes: boolean, -): Promise { - return onboardPromptHelpers.promptYesNoOrDefault( - promptHelperDeps, - question, - envVar, - defaultIsYes, - ); -} +const promptYesNoOrDefault = onboardPromptHelpers.promptYesNoOrDefault.bind(null, promptHelperDeps); // ── Helpers ────────────────────────────────────────────────────── @@ -3380,6 +3368,14 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { preserveIncompleteSession = true; } module.exports = { + retainedOnboardRecoveryHost: { + gatewayPort: DEFAULT_GATEWAY_PORT, + loadSession: onboardSession.loadSession, + listRecords: onboardSession.listRetainedSandboxRecoveryRecords, + getSandbox: registry.getSandbox, + validateName, + prompt, + }, buildOrphanedSandboxRollbackMessage, buildGatewayBootstrapSecretsScript, buildCompatibleEndpointSandboxSmokeCommand, diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index e86bbfe12b1..0ccb96ac11f 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -121,6 +121,15 @@ runtime mutation ## Journey matrix +The CLI action can reconcile an absent failed N1x managed-vLLM attempt before entry admission, +including the default `my-assistant` name. It requires one retained failed-create record and its +pending registry route on the current gateway port and default workspace. Under the lifecycle lock, +it restores the recorded gateway, requires OpenShell to confirm absence, and asks for explicit cleanup +consent. The existing destroy path rechecks authority and removes verified residual resources. +Only confirmed retirement of both the recovery record and registry row permits fresh onboarding +under the same name. A live sandbox, an inconclusive lookup, changed authority, or declined cleanup +keeps recovery unresolved. Installer auto-yes does not authorize this cleanup. + | Journey and entry | Desired state, planning, and assembly | Visible and destructive boundaries | Checkpoint and secret boundary | Compensation, coverage, and gaps | |---|---|---|---|---| | **New interactive or non-interactive onboard** — `onboard()` and `resolveOnboardEntryOptions` | Current flags, environment, and prompts. `MessagingWorkflowPlanner.buildPlan`, `prepareSandboxMessagingPreflight`, resource-profile selection, `resolveSandboxCreateIntent`, and `materializeSandboxCreatePlan` assemble policy, provider, package, resource, host-forward, and runtime-setup contributions. Non-interactive mode replaces prompts with defaults or hard aborts. | Consent/session/lock setup and preflight can persist local state, install OpenShell, or clean stale gateway artifacts before the gateway handler. Gateway reuse/recovery/start is the first provider-routing effect; inference-provider upserts follow. For OpenClaw, messaging selection and plan reconciliation complete before web-search or messaging provider registration. Each validated provider group is then created or updated and checkpointed before resource selection. A name with no live sandbox has no sandbox-destructive boundary; an existing target enters the recreate contract below. | Whole-step session plus machine snapshot. OpenClaw adds narrow checkpoints after each completed secret-free sandbox prompt group; sandbox registry registration is deferred until readiness and live validation. The session stores credential environment names, redacted endpoint metadata, legacy-value digests, and non-secret names of web-search and messaging providers registered for resume; real values remain process- or gateway-bound. | Readiness, post-create policy verification, dashboard forwarding, and cancellation failures preserve the live sandbox and an independent identity-bound recovery record. A later `destroy` refuses mutable-name deletion while that sandbox is live. Recovery remains blocked while the sandbox is present or its presence is unknown. After OpenShell authoritatively reports absence, destroy uses the record to qualify immutable runtime identity and, for Docker-backed sandboxes, exact container identities before residual cleanup and record retirement. A different explicit sandbox name starts a fresh session without changing the retained record. Exact provider-owned GPU cleanup can proceed through its owner receipt. NemoClaw attempts to remove temporary policy and build-context sources and reports cleanup failures with the onboarding error; post-create failures retain recovery state. Cancellation before sandbox creation can leave the session resumable. Shared inference providers remain gateway configuration and are not sandbox cleanup targets. Coverage: `transition-traces.test.ts`, `sandbox-create-intent-boundary.test.ts`, `sandbox-create-plan.test.ts`, and the focused cancellation, readiness, GPU cleanup, dashboard, policy-authority, destroy, and retained-recovery tests. Gap: gateway upserts can outlive a failed or interrupted create. | From 54e4e328cde3b571ee6f80154997f022cbca3866 Mon Sep 17 00:00:00 2001 From: San Dang Date: Mon, 14 Sep 2026 10:57:45 +0700 Subject: [PATCH 3/3] refactor(onboard): remove N1x recovery extension --- src/lib/actions/onboard.test.ts | 35 +- src/lib/actions/onboard.ts | 11 +- .../actions/onboard/retained-recovery.test.ts | 339 ------------------ src/lib/actions/onboard/retained-recovery.ts | 155 -------- .../openshell/gateway-observer-cli.test.ts | 30 -- .../openshell/gateway-observer-cli.ts | 23 +- src/lib/gateway-runtime-action.test.ts | 23 +- src/lib/gateway-runtime-action.ts | 13 - src/lib/onboard.ts | 22 +- .../created-sandbox-n1x-finalization.test.ts | 4 +- src/lib/onboard/lifecycle-contracts.md | 9 - src/lib/state/registry-normalization.test.ts | 45 +-- .../onboard/invalid-nvidia-key.test.ts | 1 - 13 files changed, 45 insertions(+), 665 deletions(-) delete mode 100644 src/lib/actions/onboard/retained-recovery.test.ts delete mode 100644 src/lib/actions/onboard/retained-recovery.ts diff --git a/src/lib/actions/onboard.test.ts b/src/lib/actions/onboard.test.ts index 1ca8aea9e4f..4085f1e87ff 100644 --- a/src/lib/actions/onboard.test.ts +++ b/src/lib/actions/onboard.test.ts @@ -7,17 +7,10 @@ const mocks = vi.hoisted(() => ({ listAgents: vi.fn(() => ["openclaw"]), onboard: vi.fn().mockResolvedValue(undefined), runOnboardCommand: vi.fn(), - reconcileRetainedOnboard: vi.fn(), })); vi.mock("../agent/defs", () => ({ listAgents: mocks.listAgents })); -vi.mock("../onboard", () => ({ - onboard: mocks.onboard, - retainedOnboardRecoveryHost: {}, -})); -vi.mock("./onboard/retained-recovery", () => ({ - createRetainedOnboardRecovery: () => mocks.reconcileRetainedOnboard, -})); +vi.mock("../onboard", () => ({ onboard: mocks.onboard })); vi.mock("../onboard/command", () => ({ runOnboardCommand: mocks.runOnboardCommand })); import { runOnboardAction } from "./onboard"; @@ -25,7 +18,6 @@ import { runOnboardAction } from "./onboard"; describe("onboard action runtime composition", () => { beforeEach(() => { vi.clearAllMocks(); - mocks.reconcileRetainedOnboard.mockResolvedValue(null); mocks.runOnboardCommand.mockImplementation( async (deps: { runOnboard(options: unknown): Promise }) => { await deps.runOnboard({ nonInteractive: true, resume: false }); @@ -47,29 +39,4 @@ describe("onboard action runtime composition", () => { googlechatTunnelRuntime, }); }); - - it("restarts the default name fresh only after retained recovery completes (#11510)", async () => { - mocks.reconcileRetainedOnboard.mockResolvedValue("my-assistant"); - - await runOnboardAction({ "non-interactive": true }); - - expect(mocks.onboard).toHaveBeenCalledExactlyOnceWith({ - nonInteractive: true, - resume: false, - fresh: true, - sandboxName: "my-assistant", - googlechatTunnelRuntime: undefined, - }); - expect(mocks.reconcileRetainedOnboard).toHaveBeenCalledBefore(mocks.onboard); - }); - - it("does not enter onboarding when recovery fails", async () => { - mocks.reconcileRetainedOnboard.mockRejectedValue(new Error("Recovery preserved")); - - await expect(runOnboardAction({ "non-interactive": true })).rejects.toThrow( - "Recovery preserved", - ); - - expect(mocks.onboard).not.toHaveBeenCalled(); - }); }); diff --git a/src/lib/actions/onboard.ts b/src/lib/actions/onboard.ts index b4a5f641845..9beb40d57d8 100644 --- a/src/lib/actions/onboard.ts +++ b/src/lib/actions/onboard.ts @@ -19,17 +19,10 @@ async function runOnboard( ): Promise { // Keep the monolithic legacy onboarding graph lazy so command metadata/help // imports do not execute it. Resolve it only when the user invokes onboard. - const { createRetainedOnboardRecovery } = await import("./onboard/retained-recovery"); - const { onboard, retainedOnboardRecoveryHost } = (await import("../onboard")) as unknown as { + const { onboard } = (await import("../onboard")) as unknown as { onboard: (onboardOptions?: OnboardOptions) => Promise; - retainedOnboardRecoveryHost: Parameters[0]; }; - const recoveredName = await createRetainedOnboardRecovery(retainedOnboardRecoveryHost)(options); - await onboard({ - ...options, - ...(recoveredName ? { sandboxName: recoveredName, fresh: true, resume: false } : {}), - googlechatTunnelRuntime: runtimeDeps.googlechatTunnelRuntime, - }); + await onboard({ ...options, googlechatTunnelRuntime: runtimeDeps.googlechatTunnelRuntime }); } function buildOnboardCommandDeps(flags: OnboardFlags, runtimeDeps: OnboardActionRuntimeDeps) { diff --git a/src/lib/actions/onboard/retained-recovery.test.ts b/src/lib/actions/onboard/retained-recovery.test.ts deleted file mode 100644 index cb1a1d2d519..00000000000 --- a/src/lib/actions/onboard/retained-recovery.test.ts +++ /dev/null @@ -1,339 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { afterEach, describe, expect, it, vi } from "vitest"; - -import { classifyOpenShellSandboxPresence } from "../../adapters/openshell/sandbox-presence"; -import { resolveOnboardEntryOptions } from "../../onboard/entry-options"; -import type { RetainedSandboxRecoveryRecord } from "../../state/onboard-session/retained-sandbox-recovery"; -import type { SandboxEntry } from "../../state/registry"; -import * as gatewayRuntime from "../../gateway-runtime-action"; -import * as destroyRuntime from "../sandbox/destroy"; -import { - createRetainedOnboardRecovery, - reconcileRetainedN1xOnboard, - type RetainedOnboardRecoveryDeps, -} from "./retained-recovery"; - -vi.mock("../../state/mcp-lifecycle-lock-acquisition", () => ({ - withMcpLifecycleLock: async (_name: string, operation: () => Promise) => operation(), -})); - -afterEach(() => { - vi.restoreAllMocks(); - vi.unstubAllEnvs(); -}); - -const options = { - sandboxName: null, - resume: false, - agent: null, - experimentalProfile: null, - apfInterceptorRequested: null, -}; - -function harness(name = "my-assistant") { - const record: RetainedSandboxRecoveryRecord = { - schemaVersion: 1, - recordId: "a".repeat(64), - sandboxName: name, - sandboxIdentityFingerprint: "b".repeat(64), - identityWasUnavailable: false, - gatewayName: "nemoclaw", - gatewayPort: 8080, - lifecycleGeneration: "failed-generation", - createAttemptNonce: "c".repeat(62), - resources: { - sharedInferenceProviders: ["vllm-local"], - sandboxScopedProviders: [], - credentialEnvironmentVariables: [], - }, - reason: "retained_after_sandbox_creation_failure", - recordedAt: "2026-09-11T16:54:47.903Z", - }; - const entry: SandboxEntry = { - name, - provider: "vllm-local", - model: "nvidia/Qwen3.6-35B-A3B-NVFP4", - endpointUrl: "http://host.openshell.internal:8000/v1", - endpointSource: null, - pendingRouteReservation: true, - openshellDriver: null, - gatewayName: record.gatewayName, - gatewayPort: record.gatewayPort, - }; - const state = { - records: [record] as readonly RetainedSandboxRecoveryRecord[], - entry: entry as SandboxEntry | null, - gatewayAvailable: false, - response: { status: 0, stdout: "[]", stderr: "" }, - }; - const deps: RetainedOnboardRecoveryDeps = { - gatewayPort: 8080, - validateName: (name) => name, - env: {}, - loadSession: () => null, - listRecords: () => state.records, - getSandbox: () => state.entry, - withLock: vi.fn(async (_name, operation) => operation()), - recoverGateway: vi.fn(async () => { - state.gatewayAvailable = true; - return true; - }), - observeSandbox: vi.fn(() => - classifyOpenShellSandboxPresence( - name, - state.gatewayAvailable - ? state.response - : { status: 1, stderr: "Unknown gateway 'nemoclaw'" }, - ), - ), - confirm: vi.fn(async () => true), - destroy: vi.fn(async () => { - state.entry = null; - state.records = []; - }), - }; - return { state, deps, record, entry }; -} - -describe("retrying a retained N1x onboarding name", () => { - it("scopes production recovery to its recorded gateway and requires a cleanup answer", async () => { - const h = harness(); - vi.stubEnv("OPENSHELL_GATEWAY", "another-gateway"); - vi.stubEnv("OPENSHELL_WORKSPACE", undefined); - vi.stubEnv("NEMOCLAW_YES", "1"); - vi.stubEnv("NEMOCLAW_NON_INTERACTIVE", "1"); - vi.spyOn(process, "stdin", "get").mockReturnValue({ - isTTY: true, - fd: 0, - } as typeof process.stdin); - vi.spyOn(gatewayRuntime.gatewayRuntimeDependencies, "observeGateway").mockResolvedValue({ - state: "healthy_named", - activeGateway: "nemoclaw", - recoveryBlocked: false, - unavailable: false, - diagnostic: "Connected", - }); - vi.spyOn(gatewayRuntime, "observeNamedGatewaySandboxPresence").mockReturnValue("absent"); - const destroy = vi.spyOn(destroyRuntime, "destroySandbox").mockImplementation(h.deps.destroy); - const prompt = vi.fn(async () => { - expect(process.env.OPENSHELL_GATEWAY).toBe("nemoclaw"); - expect(process.env.OPENSHELL_WORKSPACE).toBe("default"); - expect(destroy).not.toHaveBeenCalled(); - return "yes"; - }); - - await expect(createRetainedOnboardRecovery({ ...h.deps, prompt })(options)).resolves.toBe( - "my-assistant", - ); - - expect(prompt).toHaveBeenCalledOnce(); - expect(destroy).toHaveBeenCalledExactlyOnceWith("my-assistant", { - yes: true, - cleanupGateway: false, - }); - expect(process.env.OPENSHELL_GATEWAY).toBe("another-gateway"); - expect(process.env.OPENSHELL_WORKSPACE).toBeUndefined(); - }); - - it("does not authorize production cleanup from installer auto-yes without a terminal", async () => { - const h = harness(); - vi.stubEnv("OPENSHELL_WORKSPACE", undefined); - vi.stubEnv("NEMOCLAW_YES", "1"); - vi.spyOn(process, "stdin", "get").mockReturnValue({ - isTTY: false, - fd: 0, - } as typeof process.stdin); - vi.spyOn(gatewayRuntime.gatewayRuntimeDependencies, "observeGateway").mockResolvedValue({ - state: "healthy_named", - activeGateway: "nemoclaw", - recoveryBlocked: false, - unavailable: false, - diagnostic: "Connected", - }); - vi.spyOn(gatewayRuntime, "observeNamedGatewaySandboxPresence").mockReturnValue("absent"); - const destroy = vi.spyOn(destroyRuntime, "destroySandbox").mockImplementation(h.deps.destroy); - const prompt = vi.fn(); - - await expect(createRetainedOnboardRecovery({ ...h.deps, prompt })(options)).rejects.toThrow( - "authorize cleanup", - ); - - expect(prompt).not.toHaveBeenCalled(); - expect(destroy).not.toHaveBeenCalled(); - expect(h.state.records).toEqual([h.record]); - }); - - it.each([null, "my-assistant", "custom-assistant"])( - "restores the missing gateway and admits the same name %s after confirmed cleanup (#11510)", - async (sandboxName) => { - const h = harness(sandboxName ?? "my-assistant"); - const recoveredName = await reconcileRetainedN1xOnboard({ ...options, sandboxName }, h.deps); - - expect(h.state.gatewayAvailable).toBe(true); - expect(recoveredName).toBe(h.record.sandboxName); - expect(h.deps.destroy).toHaveBeenCalledExactlyOnceWith(h.record.sandboxName); - expect(h.state.records).toEqual([]); - const admitted = resolveOnboardEntryOptions( - { - opts: { sandboxName: recoveredName, fresh: true }, - env: {}, - stdinIsTty: true, - stdoutIsTty: true, - retainedRecoverySandboxNames: h.state.records.map((record) => record.sandboxName), - }, - { - isNonInteractive: () => false, - validateName: (name) => name, - reservedSandboxNames: new Set(), - cliDisplayName: () => "nemoclaw", - getNameValidationGuidance: () => [], - error: vi.fn(), - exitProcess: () => { - throw new Error("Onboarding remained blocked"); - }, - }, - ); - expect(admitted).toMatchObject({ requestedSandboxName: h.record.sandboxName, fresh: true }); - }, - ); - - it("uses the installer-selected name without requiring an active session", async () => { - const h = harness("installer-name"); - h.deps.env.NEMOCLAW_SANDBOX_NAME = "installer-name"; - await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBe("installer-name"); - }); - - it.each([ - { status: 1, stdout: "", stderr: "Unknown gateway 'nemoclaw'" }, - { status: 0, stdout: "not-json", stderr: "" }, - { - status: 0, - stdout: JSON.stringify([ - { - id: "retained-sandbox", - name: "my-assistant", - labels: {}, - resource_version: 1, - created_at: "2026-09-11T16:54:47Z", - phase: "Ready", - current_policy_version: 1, - }, - ]), - stderr: "", - }, - ])("preserves recovery when absence is unproven: %j", async (response) => { - const h = harness(); - h.state.response = response; - await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); - expect(h.deps.confirm).not.toHaveBeenCalled(); - expect(h.deps.destroy).not.toHaveBeenCalled(); - expect(h.state.records).toEqual([h.record]); - }); - - it("does not clear recovery when gateway restoration fails", async () => { - const h = harness(); - h.deps.recoverGateway = vi.fn(async () => false); - await expect(reconcileRetainedN1xOnboard(options, h.deps)).rejects.toThrow("Could not restore"); - expect(h.deps.observeSandbox).not.toHaveBeenCalled(); - expect(h.deps.destroy).not.toHaveBeenCalled(); - expect(h.state.records).toEqual([h.record]); - }); - - it("preserves the record when cleanup is declined despite installer auto-yes", async () => { - const h = harness(); - h.deps.env.NEMOCLAW_YES = "1"; - h.deps.env.NEMOCLAW_NON_INTERACTIVE = "1"; - h.deps.confirm = vi.fn(async () => false); - await expect(reconcileRetainedN1xOnboard(options, h.deps)).rejects.toThrow("authorize cleanup"); - expect(h.deps.destroy).not.toHaveBeenCalled(); - expect(h.state.entry).toEqual(h.entry); - }); - - it("refuses a recovery record replaced during confirmation", async () => { - const h = harness(); - h.deps.confirm = async () => { - h.state.records = [{ ...h.record, createAttemptNonce: "d".repeat(62) }]; - return true; - }; - await expect(reconcileRetainedN1xOnboard(options, h.deps)).rejects.toThrow("authority"); - expect(h.deps.destroy).not.toHaveBeenCalled(); - }); - - it("refuses registry authority changed during gateway restoration", async () => { - const h = harness(); - h.deps.recoverGateway = async () => { - h.state.entry = { ...h.entry, lifecycleGeneration: "replacement" }; - return true; - }; - await expect(reconcileRetainedN1xOnboard(options, h.deps)).rejects.toThrow("authority"); - expect(h.deps.observeSandbox).not.toHaveBeenCalled(); - expect(h.deps.destroy).not.toHaveBeenCalled(); - }); - - it("does not admit the name when destroy leaves unresolved recovery", async () => { - const h = harness(); - h.deps.destroy = async () => {}; - await expect(reconcileRetainedN1xOnboard(options, h.deps)).rejects.toThrow("not confirmed"); - expect(h.state.records).toEqual([h.record]); - }); - - it.each([ - { resume: true }, - { agent: "hermes" }, - { apfInterceptorRequested: true }, - { sandboxName: "another-name" }, - ])("preserves other onboarding intent %j", async (override) => { - const h = harness(); - await expect( - reconcileRetainedN1xOnboard({ ...options, ...override }, h.deps), - ).resolves.toBeNull(); - expect(h.deps.recoverGateway).not.toHaveBeenCalled(); - expect(h.deps.destroy).not.toHaveBeenCalled(); - }); - - it.each([ - { provider: "compatible-endpoint" }, - { model: "another-model" }, - { pendingRouteReservation: undefined }, - { openshellDriver: "podman" }, - { gatewayName: "another-gateway" }, - { gatewayPort: 18080 }, - { endpointUrl: "https://external.example/v1" }, - { endpointSource: "inference-set" as const }, - { nimContainer: "nemoclaw-nim" }, - ])("preserves routes outside the failed N1x attempt: %j", async (override) => { - const h = harness(); - h.state.entry = { ...h.entry, ...override }; - await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); - expect(h.deps.recoverGateway).not.toHaveBeenCalled(); - expect(h.deps.destroy).not.toHaveBeenCalled(); - }); - - it("preserves a cancelled attempt and multiple matching recovery records", async () => { - const h = harness(); - h.state.records = [{ ...h.record, reason: "cancelled_after_sandbox_creation" }]; - await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); - h.state.records = [h.record, { ...h.record, recordId: "d".repeat(64) }]; - await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); - expect(h.deps.recoverGateway).not.toHaveBeenCalled(); - expect(h.deps.destroy).not.toHaveBeenCalled(); - }); - - it("preserves recovery under another workspace selection", async () => { - const h = harness(); - h.deps.env.OPENSHELL_WORKSPACE = "other"; - await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); - expect(h.deps.recoverGateway).not.toHaveBeenCalled(); - expect(h.deps.destroy).not.toHaveBeenCalled(); - }); - - it("preserves recovery when the environment selects another agent", async () => { - const h = harness(); - h.deps.env.NEMOCLAW_AGENT = "hermes"; - await expect(reconcileRetainedN1xOnboard(options, h.deps)).resolves.toBeNull(); - expect(h.deps.recoverGateway).not.toHaveBeenCalled(); - expect(h.deps.destroy).not.toHaveBeenCalled(); - }); -}); diff --git a/src/lib/actions/onboard/retained-recovery.ts b/src/lib/actions/onboard/retained-recovery.ts deleted file mode 100644 index eeb5b6ef2a2..00000000000 --- a/src/lib/actions/onboard/retained-recovery.ts +++ /dev/null @@ -1,155 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { isDeepStrictEqual } from "node:util"; - -import type { OpenShellSandboxPresence } from "../../adapters/openshell/sandbox-presence"; -import { isDeferredN1xManagedVllmAcceptanceRoute } from "../../domain/sandbox/n1x-managed-vllm-rebuild"; -import { - observeNamedGatewaySandboxPresence, - recoverNamedGatewayRuntime, - replaceOpenShellRuntimeSelectionEnv, - snapshotOpenShellEnv, - resolveGatewayName, -} from "../../gateway-runtime-action"; -import type { OnboardCommandOptions } from "../../onboard/command"; -import { RESERVED_SANDBOX_NAMES } from "../../onboard/sandbox-agent"; -import { withMcpLifecycleLock } from "../../state/mcp-lifecycle-lock-acquisition"; -import type { RetainedSandboxRecoveryRecord } from "../../state/onboard-session/retained-sandbox-recovery"; -import type { SandboxEntry } from "../../state/registry/types"; -import { destroySandbox } from "../../actions/sandbox/destroy"; - -type RecoveryOptions = Pick< - OnboardCommandOptions, - "sandboxName" | "resume" | "agent" | "experimentalProfile" | "apfInterceptorRequested" ->; - -export interface RetainedOnboardRecoveryDeps { - readonly gatewayPort: number; - readonly env: NodeJS.ProcessEnv; - validateName(name: string, kind: string): string; - loadSession(): { sandboxName?: string | null } | null; - listRecords(): readonly RetainedSandboxRecoveryRecord[]; - getSandbox(name: string): SandboxEntry | null; - withLock(name: string, operation: () => Promise): Promise; - recoverGateway(record: RetainedSandboxRecoveryRecord): Promise; - observeSandbox(record: RetainedSandboxRecoveryRecord): OpenShellSandboxPresence; - confirm(name: string): Promise; - destroy(name: string): Promise; -} - -type RecoveryHostDeps = Pick< - RetainedOnboardRecoveryDeps, - "gatewayPort" | "loadSession" | "listRecords" | "getSandbox" | "validateName" -> & { prompt(question: string): Promise }; - -export function createRetainedOnboardRecovery(host: RecoveryHostDeps) { - const deps: RetainedOnboardRecoveryDeps = { - ...host, - env: process.env, - withLock: (name, operation) => - withMcpLifecycleLock(name, async () => { - const restore = snapshotOpenShellEnv(); - replaceOpenShellRuntimeSelectionEnv(process.env, { - gatewayName: resolveGatewayName(host.gatewayPort), - workspace: "default", - }); - try { - return await operation(); - } finally { - restore(); - } - }), - recoverGateway: async (record) => - ( - await recoverNamedGatewayRuntime({ - gatewayName: record.gatewayName, - }) - ).recovered, - observeSandbox: (record) => - observeNamedGatewaySandboxPresence(record.sandboxName, record.gatewayName), - confirm: async (name) => { - if (!process.stdin.isTTY) return false; - const answer = await host.prompt( - ` Sandbox '${name}' is absent after an earlier failed setup. Remove its verified leftovers and retry this name? [y/N]: `, - ); - return /^(?:y|yes)$/iu.test(answer.trim()); - }, - destroy: (name) => destroySandbox(name, { yes: true, cleanupGateway: false }), - }; - return (options: RecoveryOptions) => reconcileRetainedN1xOnboard(options, deps); -} - -/** Reconcile an absent failed N1x attempt before normal same-name admission. */ -export async function reconcileRetainedN1xOnboard( - options: RecoveryOptions, - deps: RetainedOnboardRecoveryDeps, -): Promise { - if ( - options.resume || - options.experimentalProfile || - options.apfInterceptorRequested || - (options.agent || deps.env.NEMOCLAW_AGENT?.trim() || "openclaw") !== "openclaw" || - (deps.env.OPENSHELL_WORKSPACE && deps.env.OPENSHELL_WORKSPACE !== "default") - ) { - return null; - } - const name = deps.validateName( - options.sandboxName || - deps.env.NEMOCLAW_SANDBOX_NAME?.trim() || - deps.loadSession()?.sandboxName || - "my-assistant", - "sandbox name", - ); - if (RESERVED_SANDBOX_NAMES.has(name)) return null; - const matching = deps.listRecords().filter((record) => record.sandboxName === name); - if (matching.length !== 1) return null; - const record = matching[0]; - const entry = deps.getSandbox(name); - if ( - record.reason !== "retained_after_sandbox_creation_failure" || - record.gatewayPort !== deps.gatewayPort || - record.gatewayName !== resolveGatewayName(deps.gatewayPort) || - !entry?.pendingRouteReservation || - !isDeferredN1xManagedVllmAcceptanceRoute({ - ...entry, - openshellDriver: entry.openshellDriver ?? "docker", - }) || - (entry.agent != null && entry.agent !== "openclaw") || - entry.gatewayName !== record.gatewayName || - entry.gatewayPort !== record.gatewayPort - ) { - return null; - } - return deps.withLock(name, async () => { - const assertCurrent = () => { - const current = deps.listRecords().filter((candidate) => candidate.sandboxName === name); - if ( - !isDeepStrictEqual(current, [record]) || - !isDeepStrictEqual(deps.getSandbox(name), entry) - ) { - throw new Error(`Recovery authority for sandbox '${name}' changed; retry stopped.`); - } - }; - assertCurrent(); - if (!(await deps.recoverGateway(record))) { - throw new Error(`Could not restore gateway '${record.gatewayName}'; recovery was preserved.`); - } - assertCurrent(); - if (deps.observeSandbox(record) !== "absent") return null; - if (!(await deps.confirm(name))) { - throw new Error( - `Recovery for '${name}' was preserved. Run 'nemoclaw ${name} destroy --yes' to authorize cleanup, then retry onboarding.`, - ); - } - assertCurrent(); - await deps.destroy(name); - if ( - deps.listRecords().some((candidate) => candidate.sandboxName === name) || - deps.getSandbox(name) - ) { - throw new Error(`Cleanup for sandbox '${name}' was not confirmed; retry stopped.`); - } - return name; - }); -} diff --git a/src/lib/adapters/openshell/gateway-observer-cli.test.ts b/src/lib/adapters/openshell/gateway-observer-cli.test.ts index 379760d9ceb..1b4c9cad2c1 100644 --- a/src/lib/adapters/openshell/gateway-observer-cli.test.ts +++ b/src/lib/adapters/openshell/gateway-observer-cli.test.ts @@ -16,36 +16,6 @@ function captureFor(status: string, metadata: string, statusCode = 0, infoCode = afterEach(() => vi.unstubAllEnvs()); describe("CLI gateway observation", () => { - it.each(["No gateway configured", "Error: × Unknown gateway 'nemoclaw-8090'."])( - "recognizes an unknown named gateway after status %s (#11510)", - async (status) => { - const capture = captureFor( - status, - "Error: × Unknown gateway 'nemoclaw-8090'.\n │ Register it first.", - 1, - 1, - ); - expect( - await createCliOpenShellGatewayObserver(capture).observeGateway(request), - ).toMatchObject({ - state: "missing_named", - recoveryBlocked: false, - }); - }, - ); - - it.each([ - "Error: × Unknown gateway 'another-gateway'.", - "Error: unexpected text Unknown gateway 'nemoclaw-8090'.", - "Error: × Unknown gateway 'nemoclaw-8090'.\nError: authentication failed", - ])("does not authorize recovery from misleading absence: %s", async (metadata) => { - const capture = captureFor("No gateway configured", metadata, 1, 1); - expect(await createCliOpenShellGatewayObserver(capture).observeGateway(request)).toMatchObject({ - state: "observation_failed", - recoveryBlocked: true, - }); - }); - it.each([ [ connected, diff --git a/src/lib/adapters/openshell/gateway-observer-cli.ts b/src/lib/adapters/openshell/gateway-observer-cli.ts index ce22688aba3..7e62d87ef1a 100644 --- a/src/lib/adapters/openshell/gateway-observer-cli.ts +++ b/src/lib/adapters/openshell/gateway-observer-cli.ts @@ -35,15 +35,6 @@ function gatewayName(output: string): string | null { return names.length === 1 && isValidName(names[0]) ? names[0] : null; } -function reportsUnknownNamedGateway(output: string, name: string): boolean { - return output - .split(/\r?\n/u) - .some( - (line) => - line.trim().replace(/^(?:Error:\s*)?(?:×\s*)?/u, "") === `Unknown gateway '${name}'.`, - ); -} - function failed( error: OpenShellSandboxError, activeGateway: string | null = null, @@ -102,9 +93,8 @@ export function createCliOpenShellGatewayObserver( const missing = /\bNo (?:active )?gateway(?: configured)?\b|No gateway metadata found/i; const statusError = gatewayError(status); const infoError = gatewayError(info); - const absentInfo = missing.test(infoText) || reportsUnknownNamedGateway(infoText, name); - const absentStatus = - missing.test(statusText) || reportsUnknownNamedGateway(statusText, name); + const absentInfo = missing.test(infoText); + const absentStatus = missing.test(statusText); // Only known absence and unreachable responses describe resource state. Other failures are not absence. for (const [error, absent, legacy] of [ [statusError, absentStatus, false], @@ -117,15 +107,6 @@ export function createCliOpenShellGatewayObserver( ) return failed(error, activeGateway); } - if (/\bunknown gateway\b/iu.test(infoText) && !reportsUnknownNamedGateway(infoText, name)) { - return failed( - infoError ?? { - kind: "schema", - message: "OpenShell returned an unrecognized gateway target.", - }, - activeGateway, - ); - } if (connected && activeGateway === name && absentInfo) { return failed( { kind: "schema", message: "OpenShell gateway selection and metadata disagree." }, diff --git a/src/lib/gateway-runtime-action.test.ts b/src/lib/gateway-runtime-action.test.ts index 18438e94692..c99b66a9d98 100644 --- a/src/lib/gateway-runtime-action.test.ts +++ b/src/lib/gateway-runtime-action.test.ts @@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { OpenShellGatewayObservation } from "./adapters/openshell/gateway-observer"; -import * as openshellRuntime from "./adapters/openshell/runtime"; import * as gatewayRuntime from "./gateway-runtime-action"; function observation(state: OpenShellGatewayObservation["state"]): OpenShellGatewayObservation { @@ -29,27 +28,7 @@ describe("gateway observations and recovery", () => { start.mockReset().mockResolvedValue(undefined); vi.stubEnv("OPENSHELL_GATEWAY", "foreign"); }); - afterEach(() => { - vi.unstubAllEnvs(); - vi.restoreAllMocks(); - }); - - it.each([ - { status: 0, stdout: "[]", stderr: "", expected: "absent" }, - { status: 1, stdout: "", stderr: "Unknown gateway 'nemoclaw'", expected: "unknown" }, - { status: 0, stdout: "not-json", stderr: "", expected: "unknown" }, - ])("observes named sandbox presence conservatively: $expected", (result) => { - const capture = vi - .spyOn(openshellRuntime, "captureResolvedOpenshell") - .mockReturnValue({ ...result, output: result.stdout }); - expect(gatewayRuntime.observeNamedGatewaySandboxPresence("my-assistant", "nemoclaw")).toBe( - result.expected, - ); - expect(capture).toHaveBeenCalledWith( - ["sandbox", "list", "-g", "nemoclaw", "-o", "json"], - expect.objectContaining({ ignoreError: true, includeStreams: true }), - ); - }); + afterEach(() => vi.unstubAllEnvs()); it("passes the default gateway to the observer without mutating selection", async () => { await gatewayRuntime.getNamedGatewayLifecycleState(); diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index fed14b14f33..f67463811af 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -11,7 +11,6 @@ import { resolveSandboxGatewayName, } from "./onboard/gateway-binding"; import type { GatewayRecoveryOutput } from "./onboard/gateway-recovery"; -import { classifyOpenShellSandboxPresence } from "./adapters/openshell/sandbox-presence"; import { sanitizeReadinessText } from "./readiness/sanitize"; export { resolveGatewayName, resolveSandboxGatewayName }; @@ -49,18 +48,6 @@ export const gatewayRuntimeDependencies = { }, }; -export function observeNamedGatewaySandboxPresence(sandboxName: string, gatewayName: string) { - const result = openshellRuntime.captureResolvedOpenshell( - ["sandbox", "list", "-g", gatewayName, "-o", "json"], - { - ignoreError: true, - includeStreams: true, - timeout: openshellRuntime.OPENSHELL_PROBE_TIMEOUT_MS, - }, - ); - return classifyOpenShellSandboxPresence(sandboxName, result); -} - export type NamedGatewayLifecycleState = OpenShellGatewayObservation; /** Read gateway identity and selection through the typed observation boundary. */ diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 1266a8fc4f3..5e825044e6c 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -622,7 +622,19 @@ async function promptOrDefault( ): Promise { return onboardPromptHelpers.promptOrDefault(promptHelperDeps, question, envVar, defaultValue); } -const promptYesNoOrDefault = onboardPromptHelpers.promptYesNoOrDefault.bind(null, promptHelperDeps); + +async function promptYesNoOrDefault( + question: string, + envVar: string | null, + defaultIsYes: boolean, +): Promise { + return onboardPromptHelpers.promptYesNoOrDefault( + promptHelperDeps, + question, + envVar, + defaultIsYes, + ); +} // ── Helpers ────────────────────────────────────────────────────── @@ -3335,14 +3347,6 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { preserveIncompleteSession = true; } module.exports = { - retainedOnboardRecoveryHost: { - gatewayPort: DEFAULT_GATEWAY_PORT, - loadSession: onboardSession.loadSession, - listRecords: onboardSession.listRetainedSandboxRecoveryRecords, - getSandbox: registry.getSandbox, - validateName, - prompt, - }, buildOrphanedSandboxRollbackMessage, buildGatewayBootstrapSecretsScript, buildCompatibleEndpointSandboxSmokeCommand, diff --git a/src/lib/onboard/created-sandbox-n1x-finalization.test.ts b/src/lib/onboard/created-sandbox-n1x-finalization.test.ts index 37ea8649c75..694585e7759 100644 --- a/src/lib/onboard/created-sandbox-n1x-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-n1x-finalization.test.ts @@ -27,7 +27,7 @@ import { parseHostLocalInferenceReceipt } from "./runtime-provider/host-local-in import type { SetupNimSelectionState } from "./setup-nim-flow"; import { createSetupNimVllmHandler } from "./setup-nim-vllm"; -const sandboxName = "n1x-preview"; +const sandboxName = "my-assistant"; const model = "nvidia/Qwen3.6-35B-A3B-NVFP4"; const provider = "vllm-local"; const previewEnv = { NEMOCLAW_PROVIDER: "install-vllm" }; @@ -371,7 +371,7 @@ it.each([ ["explicit rebuild denial", true, "n1x", false, previewEnv, false, false], ["ordinary N1x opt-out", false, "n1x", undefined, { NEMOCLAW_NO_EXPRESS: "1" }, false, false], ] as const)( - "carries %s preview acceptance through final registration (#10959)", + "carries %s preview acceptance through default-name registration (#11510)", async (_case, resume, platform, allow, environment, legacyOnboardRoute, expected) => { const flow = await createIntentThroughOnboardFlow({ resume, diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 6f5c79df450..41fcb6f2eee 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -121,15 +121,6 @@ runtime mutation ## Journey matrix -The CLI action can reconcile an absent failed N1x managed-vLLM attempt before entry admission, -including the default `my-assistant` name. It requires one retained failed-create record and its -pending registry route on the current gateway port and default workspace. Under the lifecycle lock, -it restores the recorded gateway, requires OpenShell to confirm absence, and asks for explicit cleanup -consent. The existing destroy path rechecks authority and removes verified residual resources. -Only confirmed retirement of both the recovery record and registry row permits fresh onboarding -under the same name. A live sandbox, an inconclusive lookup, changed authority, or declined cleanup -keeps recovery unresolved. Installer auto-yes does not authorize this cleanup. - | Journey and entry | Desired state, planning, and assembly | Visible and destructive boundaries | Checkpoint and secret boundary | Compensation, coverage, and gaps | |---|---|---|---|---| | **New interactive or non-interactive onboard** — `onboard()` and `resolveOnboardEntryOptions` | Current flags, environment, and prompts. `MessagingWorkflowPlanner.buildPlan`, `prepareSandboxMessagingPreflight`, resource-profile selection, `resolveSandboxCreateIntent`, and `materializeSandboxCreatePlan` assemble policy, provider, package, resource, host-forward, and runtime-setup contributions. Non-interactive mode replaces prompts with defaults or hard aborts. | Consent/session/lock setup and preflight can persist local state, install OpenShell, or clean stale gateway artifacts before the gateway handler. Gateway reuse/recovery/start is the first provider-routing effect; inference-provider upserts follow. For OpenClaw, messaging selection and plan reconciliation complete before web-search or messaging provider registration. Each validated provider group is then created or updated and checkpointed before resource selection. A name with no live sandbox has no sandbox-destructive boundary; an existing target enters the recreate contract below. | Whole-step session plus machine snapshot. OpenClaw adds narrow checkpoints after each completed secret-free sandbox prompt group; sandbox registry registration is deferred until readiness and live validation. The session stores credential environment names, redacted endpoint metadata, legacy-value digests, and non-secret names of web-search and messaging providers registered for resume; real values remain process- or gateway-bound. | Readiness, post-create policy verification, dashboard forwarding, and cancellation failures preserve the live sandbox and an independent identity-bound recovery record. A later `destroy` refuses mutable-name deletion while that sandbox is live. Recovery remains blocked while the sandbox is present or its presence is unknown. After OpenShell authoritatively reports absence, destroy uses the record to qualify immutable runtime identity and, for Docker-backed sandboxes, exact container identities before residual cleanup and record retirement. A different explicit sandbox name starts a fresh session without changing the retained record. Exact provider-owned GPU cleanup can proceed through its owner receipt. NemoClaw attempts to remove temporary policy and build-context sources and reports cleanup failures with the onboarding error; post-create failures retain recovery state. Cancellation before sandbox creation can leave the session resumable. Shared inference providers remain gateway configuration and are not sandbox cleanup targets. Coverage: `transition-traces.test.ts`, `sandbox-create-intent-boundary.test.ts`, `sandbox-create-plan.test.ts`, and the focused cancellation, readiness, GPU cleanup, dashboard, policy-authority, destroy, and retained-recovery tests. Gap: gateway upserts can outlive a failed or interrupted create. | diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index 5c272f986e2..b7edf12a108 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -225,30 +225,33 @@ describe("sandbox registry normalization", () => { endpointUrl, deferredN1xManagedVllmAccepted: true, }); - const malformed = await loadRegistryWith({ - malformed: { - name: "malformed", - deferredN1xManagedVllmAccepted: "true", - }, - }); - expect(() => malformed.getSandbox("malformed")).toThrow("invalid N1x preview acceptance"); - const mismatchedRoute = await loadRegistryWith({ - mismatched: { - name: "mismatched", - provider: "vllm-local", - model: "nvidia/Qwen3.6-35B-A3B-NVFP4", - endpointUrl, - endpointSource: "inference-set", - openshellDriver: "docker", - deferredN1xManagedVllmAccepted: true, - }, - }); - expect(() => mismatchedRoute.getSandbox("mismatched")).toThrow( - "invalid N1x preview acceptance", - ); }, ); + it("rejects malformed Deferred N1x preview acceptance (#10959)", async () => { + const malformed = await loadRegistryWith({ + malformed: { + name: "malformed", + deferredN1xManagedVllmAccepted: "true", + }, + }); + expect(() => malformed.getSandbox("malformed")).toThrow("invalid N1x preview acceptance"); + const mismatchedRoute = await loadRegistryWith({ + mismatched: { + name: "mismatched", + provider: "vllm-local", + model: "nvidia/Qwen3.6-35B-A3B-NVFP4", + endpointUrl: null, + endpointSource: "inference-set", + openshellDriver: "docker", + deferredN1xManagedVllmAccepted: true, + }, + }); + expect(() => mismatchedRoute.getSandbox("mismatched")).toThrow( + "invalid N1x preview acceptance", + ); + }); + it("clears Deferred N1x acceptance when route authority changes (#10959)", async () => { const registry = await loadRegistryWith({}); registry.registerSandbox({ diff --git a/test/package-contract/onboard/invalid-nvidia-key.test.ts b/test/package-contract/onboard/invalid-nvidia-key.test.ts index c8686f1065a..1cc653197e5 100644 --- a/test/package-contract/onboard/invalid-nvidia-key.test.ts +++ b/test/package-contract/onboard/invalid-nvidia-key.test.ts @@ -54,7 +54,6 @@ require.cache[onboardPath] = { filename: onboardPath, loaded: true, exports: { - ...require(onboardPath), onboard: async () => { resolveNonInteractiveBuildCredential({ provider: "nvidia-prod",