diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index b3b8656f5f3..e6a47984d01 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -463,6 +463,16 @@ Use `$$nemoclaw rebuild` when you want NemoClaw to recreate the s #### `--apf-interceptor` Use this option to request a policyless sandbox creation for an APF-interceptor flow. +This option currently supports providerless sandbox creation only. +APF onboarding with an inference provider and model is not yet supported. +APF onboarding with an OpenShell provider for a Model Context Protocol (MCP) server is also not yet supported. +OpenShell cannot bind provider attachment to the new sandbox's verified immutable ID. +If the prepared plan contains any provider, NemoClaw exits before it: + +- Creates the sandbox. +- Registers or changes credentials. +- Creates, updates, or deletes providers. + The option requires these conditions: - Start a new onboarding session. @@ -488,8 +498,8 @@ Do not destroy that sandbox by name. Retain the reported sandbox name, create-attempt label, and durable identity fingerprint for comparison only. If OpenShell did not return the fingerprint, recovery remains blocked until an administrator resolves the create-attempt label to one exact sandbox. Ask an OpenShell administrator to obtain the exact live durable ID, verify it against the fingerprint, and use an identity-bound removal procedure. -After the administrator confirms removal, start a fresh onboarding attempt. -`--resume` and `--recreate-sandbox` cannot recover the incomplete attempt. +This onboarding mode does not support `--resume` or `--recreate-sandbox`, regardless of whether sandbox creation began. +After the administrator confirms identity-bound removal, repeat the original command with `--fresh` and a new name. #### `--tool-disclosure ` @@ -886,8 +896,21 @@ Pairing and `TELEGRAM_ALLOWED_IDS` still govern direct messages. -If you cancel a brand-new onboarding run at the policy preset step, NemoClaw rolls back the sandbox, registry entry, and onboarding session instead of leaving a default sandbox with unfinished policy state. -Existing live sandboxes are not deleted by this cancel rollback path. +If you cancel a brand-new onboarding run at the policy-tier selector or either policy-preset selector after sandbox creation, NemoClaw preserves the incomplete sandbox, registry entry, and onboarding session for identity-bound recovery. +NemoClaw reports the durable sandbox identity fingerprint when it is available. +It does not run OpenShell's mutable-name deletion command because the name may now identify a replacement sandbox. +Do not delete the sandbox by mutable name. +Shared inference providers are gateway configuration, not sandbox cleanup targets. +Sandbox-scoped provider registrations or gateway-bound credentials may remain when the durable recovery record lists them. +Ask an OpenShell administrator to inspect the exact sandbox identity and remove only sandbox-scoped resources whose ownership is confirmed for the retained sandbox. +A credential environment name in the recovery record does not prove that its value was exposed. +Rotate a credential only when identity-bound inspection proves that it was exposed or attached to a retained sandbox-scoped resource. +NemoClaw stores the recovery record independently from the active onboarding session. +A fresh run with a different name can proceed without clearing that record, but automatic resume, explicit `--resume`, reuse, recreation, and fresh onboarding with the retained name remain blocked. +NemoClaw has no supported operation in this release to clear the recovery record, so the retained name remains unavailable even after external recovery or removal. +Preserve the record as evidence. +Start fresh onboarding with `--fresh` and another available sandbox name. +Select the required provider, model, agent, policy, and environment inputs again because `--fresh` does not retain them. If you run onboarding again with the same sandbox name and choose a different inference provider or model, NemoClaw detects the drift and recreates the sandbox so the running agent config matches your selection. In interactive mode, the wizard asks for confirmation before delete and recreate. diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index fea999dc076..a4725751394 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -347,6 +347,7 @@ const { resolveSandboxImageTagFromCreateOutput } = require("./domain/sandbox/image-tag") as typeof import("./domain/sandbox/image-tag"); const nim: typeof import("./inference/nim") = require("./inference/nim"); const onboardSession: typeof import("./state/onboard-session") = require("./state/onboard-session"); +const { markCancellationRecovery: recordRecovery } = onboardSession; const portableRetirementAuthority: typeof import("./onboard/portable-retirement-authority") = require("./onboard/portable-retirement-authority"); const { registerIncompleteOnboardExitHandlerForSession, @@ -458,6 +459,7 @@ const { }: typeof import("./onboard/cancel-rollback") = require("./onboard/cancel-rollback"); const { createCoreOnboardFlowPhases, + isCoreFlowCompleteBeforeFinalization, prepareCoreOnboardFlowContext, prepareFinalOnboardFlowContext, runCoreOnboardFlowSlice, @@ -2634,9 +2636,7 @@ const onboardRuntimeBoundary = new OnboardRuntimeBoundary({ toSessionUpdates(updates as Parameters[0]), maybeForceE2eStepFailure, }); - -const sandboxCancelRollback = installSandboxCancelRollback({ cliName: cliName() }); // #4614, #9833 - +const sandboxCancelRollback = installSandboxCancelRollback({ recordRecovery }); // #4614 const { arePolicyPresetsApplied, computeSetupPresetSuggestions, @@ -2749,29 +2749,17 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { ); setOnboardBrandingAgent(opts.agent || process.env.NEMOCLAW_AGENT || null); AUTO_YES = opts.autoYes === true || process.env.NEMOCLAW_YES === "1"; - const entryOptions = onboardEntryOptions.resolveDefaultRunEntryOptions( - opts, - onboardSession.loadSession()?.status ?? null, - validateName, - ); - const { fresh, nonInteractive, cannotPrompt, resume } = entryOptions; - const { requestedFromDockerfile, requestedSandboxName } = entryOptions; - NON_INTERACTIVE = nonInteractive; - const validatePolicyTierBeforeRuntime = - isNonInteractive() && !resume && opts.experimentalProfile !== "portable"; - if (validatePolicyTierBeforeRuntime) validatePolicyTierEnvEarly(); + const resolveEntryOptions = () => + onboardEntryOptions.resolveDefaultRunEntryOptionsFromState(opts, validateName, onboardSession); + const initialEntryOptions = resolveEntryOptions(); + NON_INTERACTIVE = initialEntryOptions.nonInteractive; RECREATE_SANDBOX = opts.recreateSandbox || process.env.NEMOCLAW_RECREATE_SANDBOX === "1"; _preflightDashboardPort = opts.controlUiPort ?? (process.env.NEMOCLAW_DASHBOARD_PORT != null ? DASHBOARD_PORT : null); onboardRuntimeBoundary.reset(); - const baseImageResolutionContext = baseImageResolutionFlow.createBaseImageResolutionContext({ - fresh, - initialHint: opts.baseImageResolutionHint, - initialPreResolvedMetadata: opts.preResolvedBaseImageMetadata, - }); const portableRetirementEntry = portableRetirementAuthority.beginPortableOnboardRetirementEntry({ alreadyHeld: opts.onboardLockAlreadyHeld === true, - command: `nemoclaw onboard${resume ? " --resume" : ""}${fresh ? " --fresh" : ""}${isNonInteractive() ? " --non-interactive" : ""}${requestedFromDockerfile ? ` --from ${requestedFromDockerfile}` : ""}`, + command: `nemoclaw onboard${initialEntryOptions.resume ? " --resume" : ""}${initialEntryOptions.fresh ? " --fresh" : ""}${initialEntryOptions.nonInteractive ? " --non-interactive" : ""}${initialEntryOptions.requestedFromDockerfile ? ` --from ${initialEntryOptions.requestedFromDockerfile}` : ""}`, displayName: cliDisplayName(), homeDir: process.env.HOME || os.homedir(), loadRegistry: registry.load, @@ -2779,14 +2767,12 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { sessionFile: onboardSession.SESSION_FILE, withLifecycleLock: sandboxMutationLock.withMcpLifecycleLock, }); - let portableEnvScope: | import("./onboard/session-bootstrap").PortableOnboardEnvironmentScope | null = null; const restorePortableEnvScope = () => portableEnvScope?.restore(); // Secure removal remains gated on successful migration of every staged legacy credential. let stagedLegacyKeys: string[] = []; - let onboardTrace: ReturnType = { collector: null, span: null, @@ -2796,6 +2782,18 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { preserveIncompleteSession = false; try { await portableRetirementEntry.run(async () => { + const entryOptions = resolveEntryOptions(); + const { fresh, nonInteractive, cannotPrompt, resume } = entryOptions; + const { requestedFromDockerfile, requestedSandboxName } = entryOptions; + NON_INTERACTIVE = nonInteractive; + const validatePolicyTierBeforeRuntime = + isNonInteractive() && !resume && opts.experimentalProfile !== "portable"; + if (validatePolicyTierBeforeRuntime) validatePolicyTierEnvEarly(); + const baseImageResolutionContext = baseImageResolutionFlow.createBaseImageResolutionContext({ + fresh, + initialHint: opts.baseImageResolutionHint, + initialPreResolvedMetadata: opts.preResolvedBaseImageMetadata, + }); const lockedRuntime = await resumeRuntime.prepare( opts, resume, @@ -2965,13 +2963,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { onboardSessionBootstrap.reportReadOnlyHostMounts(effectiveHostMounts, note); const explicitSandboxGpuFlag = resolveSandboxGpuFlagFromOptions(opts); const recordedGpuPassthroughBeforePreflight = session?.gpuPassthrough === true; - type InitialOnboardFlowContext = - import("./onboard/machine/initial-flow-composition").InitialOnboardFlowContext< - typeof agent, - ReturnType, - ReturnType - >; - const initialFlowContext: InitialOnboardFlowContext = { + const initialFlowContext = { resume, fresh, session, @@ -2992,12 +2984,13 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { webSearchConfig: session?.webSearchConfig || null, webSearchSupported: false, selectedMessagingChannels, - gpu: null, - sandboxGpuConfig: null, + gpu: null as ReturnType | null, + sandboxGpuConfig: null as ReturnType | null, gpuPassthrough: false, resumeHasResolvedGpuIntent: false, requestedGpuPassthrough: opts.gpu === true, }; + type InitialOnboardFlowContext = typeof initialFlowContext; const policyAuthorityBindings = sandboxCreateOrchestration.createOnboardPolicyAuthorityBindings( sandboxCreateOrchestrationRuntime, @@ -3123,6 +3116,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { }, providerInference: { gatewayName: GATEWAY_NAME, + inspectSandboxForCreate, forceProviderSelection: forceProviderSelectionForAgentChange, ...authoritativeRebuildTarget.rebuildProviderFlowOptions(opts, coreFlowContext), endpointProvenance, @@ -3317,6 +3311,13 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { resume, recordRepairEvent, }); + if (isCoreFlowCompleteBeforeFinalization(coreFlowResult)) { + sandboxCancelRollback.disarm(); + await portableRetirementEntry.supersede(lockedRuntime.checkpointProfile); + completed = true; + process.exitCode = 0; + return; + } setupInferenceFactory.selectGatewayForFollowupOrExit(GATEWAY_NAME, runOpenshell); const finalFlowContext = prepareFinalOnboardFlowContext(coreFlowResult); let liveFinalFlowContext: InitialOnboardFlowContext = finalFlowContext; @@ -3574,7 +3575,6 @@ module.exports = { recoverGatewayRuntime, buildChain, buildControlUiUrls, - startGateway, startDockerDriverGateway, findAvailableDashboardPort, diff --git a/src/lib/onboard/cancel-rollback.test.ts b/src/lib/onboard/cancel-rollback.test.ts index c1def71ab3b..6fd504321cb 100644 --- a/src/lib/onboard/cancel-rollback.test.ts +++ b/src/lib/onboard/cancel-rollback.test.ts @@ -9,107 +9,276 @@ import { installSandboxCancelRollback, makeOnboardCancelExit, } from "./cancel-rollback"; -import { completeOrdinaryOnboardSandboxCreation } from "./created-sandbox-finalization"; -function createGuard() { +const SANDBOX_FINGERPRINT = "a".repeat(64); + +function createHarness() { const log = vi.fn(); - return { guard: createSandboxCancelRollback({ cliName: "nemohermes", log }), log }; + return { log, rollback: createSandboxCancelRollback({ log }) }; } describe("createSandboxCancelRollback", () => { - it("preserves the sandbox and recovery state when armed and cancelled (#9833)", () => { - const { guard, log } = createGuard(); - guard.arm("new-sb"); - guard.markCancelled(); - guard.runIfArmed(); + it("preserves an armed cancelled sandbox and reports its captured identity (#9833)", () => { + const { rollback, log } = createHarness(); + + rollback.arm("new-sb", SANDBOX_FINGERPRINT); + rollback.markCancelled(); + rollback.runIfArmed(); + const guidance = log.mock.calls.flat().join("\n"); expect(guidance).toContain("preserved incomplete sandbox 'new-sb'"); - expect(guidance).toContain("sandbox registry entry and onboarding session"); - expect(guidance).toContain("nemohermes onboard --resume"); - expect(guidance).toContain("Do not destroy this sandbox by mutable sandbox name"); + expect(guidance).toContain(SANDBOX_FINGERPRINT); + expect(guidance).toContain("OpenShell administrator"); + expect(guidance).toContain("did not run OpenShell's mutable-name deletion command"); + expect(guidance).toContain("Do not delete the sandbox by mutable sandbox name"); + expect(guidance).toContain("Shared inference providers are gateway configuration"); + expect(guidance).toContain("not sandbox cleanup targets"); + expect(guidance).toContain("sandbox-scoped resources whose ownership is confirmed"); + expect(guidance).toContain("no supported operation to clear this recovery record"); + expect(guidance).toContain("credential environment name alone does not prove exposure"); + expect(guidance).toContain("rotate a credential only when identity-bound inspection proves"); + expect(guidance).not.toContain("rotate any credential"); }); - it("does not report recovery on a non-cancel exit (#9833)", () => { - const { guard, log } = createGuard(); - guard.arm("new-sb"); - guard.runIfArmed(); - expect(log).not.toHaveBeenCalled(); + it.each([ + ["missing", undefined], + ["invalid", "not-a-fingerprint"], + ])("preserves registry and session recovery guidance when identity is %s", (_case, identity) => { + const { rollback, log } = createHarness(); + + rollback.arm("new-sb", identity); + rollback.markCancelled(); + rollback.runIfArmed(); + + const guidance = log.mock.calls.flat().join("\n"); + expect(guidance).toContain("preserved incomplete sandbox 'new-sb'"); + expect(guidance).toContain("identity fingerprint is unavailable"); + expect(guidance).toContain("preserve the registry and onboarding recovery state"); }); - it("does not report recovery when cancelled before a sandbox is armed (#9833)", () => { - const { guard, log } = createGuard(); - guard.markCancelled(); - guard.runIfArmed(); + it("does not run on a non-cancel exit", () => { + const { rollback, log } = createHarness(); + + rollback.arm("new-sb", SANDBOX_FINGERPRINT); + rollback.runIfArmed(); + expect(log).not.toHaveBeenCalled(); }); - it("does not report recovery after the sandbox is disarmed (#9833)", () => { - const { guard, log } = createGuard(); - guard.arm("new-sb"); - guard.disarm(); - guard.markCancelled(); - guard.runIfArmed(); + it("does not run when cancelled before any sandbox was armed", () => { + const { rollback, log } = createHarness(); + + rollback.markCancelled(); + rollback.runIfArmed(); + expect(log).not.toHaveBeenCalled(); }); - it("reports recovery at most once (#9833)", () => { - const { guard, log } = createGuard(); - guard.arm("new-sb"); - guard.markCancelled(); - guard.runIfArmed(); - guard.runIfArmed(); - guard.runIfArmed(); - expect(log).toHaveBeenCalledTimes(buildCancelRollbackMessage("new-sb", "nemohermes").length); + it("does not run after disarm", () => { + const { rollback, log } = createHarness(); + + rollback.arm("new-sb", SANDBOX_FINGERPRINT); + rollback.disarm(); + rollback.markCancelled(); + rollback.runIfArmed(); + + expect(log).not.toHaveBeenCalled(); }); - it("reports whether a sandbox is armed", () => { - const { guard } = createGuard(); - expect(guard.isArmed()).toBe(false); - guard.arm("new-sb"); - expect(guard.isArmed()).toBe(true); - guard.disarm(); - expect(guard.isArmed()).toBe(false); + it("runs at most once", () => { + const { rollback, log } = createHarness(); + + rollback.arm("new-sb", SANDBOX_FINGERPRINT); + rollback.markCancelled(); + rollback.runIfArmed(); + const callCount = log.mock.calls.length; + rollback.runIfArmed(); + + expect(log).toHaveBeenCalledTimes(callCount); }); - it("uses the latest sandbox name after rearming (#9833)", () => { - const { guard, log } = createGuard(); - guard.arm("first"); - guard.arm("second"); - guard.markCancelled(); - guard.runIfArmed(); + it("tracks the latest armed sandbox and identity", () => { + const { rollback, log } = createHarness(); + + expect(rollback.isArmed()).toBe(false); + rollback.arm("first", "b".repeat(64)); + rollback.arm("second", SANDBOX_FINGERPRINT); + expect(rollback.isArmed()).toBe(true); + rollback.markCancelled(); + rollback.runIfArmed(); + const guidance = log.mock.calls.flat().join("\n"); - expect(guidance).toContain("'second'"); - expect(guidance).not.toContain("'first'"); + expect(guidance).toContain("second"); + expect(guidance).toContain(SANDBOX_FINGERPRINT); + expect(guidance).not.toContain("b".repeat(64)); + expect(rollback.isArmed()).toBe(false); }); }); describe("installSandboxCancelRollback", () => { - it("registers preservation-only cancellation recovery (#9833)", () => { + it("registers a non-destructive exit handler that retains external recovery state (#9833)", () => { const log = vi.fn(); + const recordRecovery = vi.fn(); const exitHandlers: Array<() => void> = []; - const guard = installSandboxCancelRollback({ - cliName: "nemohermes", + const rollback = installSandboxCancelRollback({ log, + recordRecovery, registerExitHandler: (handler) => exitHandlers.push(handler), }); expect(exitHandlers).toHaveLength(1); - guard.arm("new-sb"); - guard.markCancelled(); + rollback.arm("new-sb", SANDBOX_FINGERPRINT); + rollback.markCancelled(); + exitHandlers[0](); + + expect(recordRecovery).toHaveBeenCalledWith("new-sb", SANDBOX_FINGERPRINT, undefined); + expect(log.mock.calls.flat().join("\n")).toContain(SANDBOX_FINGERPRINT); + }); + + it("forwards the full verified tuple from cancellation to durable state (#9833)", () => { + const recordRecovery = vi.fn(); + const recoveryContext = { + gatewayName: "nemoclaw-18080", + gatewayPort: 18080, + lifecycleGeneration: "00000000-0000-4000-8000-000000000004", + verifiedEffectivePolicyIdentity: { hash: "sha256:policy-4", activeVersion: 4 }, + } as const; + const rollback = createSandboxCancelRollback({ log: vi.fn(), recordRecovery }); + const armWithContext = rollback.arm as ( + sandboxName: string, + sandboxIdentityFingerprint: string, + context: typeof recoveryContext, + ) => void; + + armWithContext("new-sb", SANDBOX_FINGERPRINT, recoveryContext); + rollback.markCancelled(); + + expect(recordRecovery).toHaveBeenCalledWith("new-sb", SANDBOX_FINGERPRINT, recoveryContext); + }); + + it("persists recovery before a deferred process exit and records it once (#9833)", () => { + const log = vi.fn(); + const recordRecovery = vi.fn(); + const exitHandlers: Array<() => void> = []; + const rollback = installSandboxCancelRollback({ + log, + recordRecovery, + registerExitHandler: (handler) => exitHandlers.push(handler), + }); + const deferredExit = new Error("deferred exit"); + const cancel = makeOnboardCancelExit(rollback, vi.fn(), () => { + throw deferredExit; + }); + + rollback.arm("new-sb", SANDBOX_FINGERPRINT); + expect(() => cancel()).toThrow(deferredExit); + expect(recordRecovery).toHaveBeenCalledOnce(); + expect(recordRecovery).toHaveBeenCalledWith("new-sb", SANDBOX_FINGERPRINT, undefined); + exitHandlers[0](); - expect(log.mock.calls.flat().join("\n")).toContain("preserved incomplete sandbox 'new-sb'"); + expect(recordRecovery).toHaveBeenCalledOnce(); + expect(log.mock.calls.flat().join("\n")).toContain(SANDBOX_FINGERPRINT); }); - it("does not run recovery for an ordinary process exit (#9833)", () => { + it("retries recovery from the exit handler after the immediate durable write fails (#9833)", () => { const log = vi.fn(); + const recordRecovery = vi + .fn() + .mockImplementationOnce(() => { + throw new Error("recovery write failed"); + }) + .mockImplementationOnce(() => undefined); const exitHandlers: Array<() => void> = []; - const guard = installSandboxCancelRollback({ - cliName: "nemohermes", + const rollback = installSandboxCancelRollback({ log, + recordRecovery, registerExitHandler: (handler) => exitHandlers.push(handler), }); - guard.arm("new-sb"); + + rollback.arm("new-sb", SANDBOX_FINGERPRINT); + expect(() => rollback.markCancelled()).not.toThrow(); + expect(recordRecovery).toHaveBeenCalledOnce(); + exitHandlers[0](); - expect(log).not.toHaveBeenCalled(); + expect(recordRecovery).toHaveBeenCalledTimes(2); + expect(recordRecovery).toHaveBeenLastCalledWith("new-sb", SANDBOX_FINGERPRINT, undefined); + const guidance = log.mock.calls.flat().join("\n"); + expect(guidance).toContain(SANDBOX_FINGERPRINT); + expect(guidance).not.toContain("could not save the onboarding recovery record"); + }); + + it("exits and reports identity recovery when both durable writes fail (#9833)", () => { + const log = vi.fn(); + const recordRecovery = vi.fn(() => { + throw new Error("recovery write failed"); + }); + const exitHandlers: Array<() => void> = []; + const rollback = installSandboxCancelRollback({ + log, + recordRecovery, + registerExitHandler: (handler) => exitHandlers.push(handler), + }); + const exit = vi.fn(); + + rollback.arm("new-sb", SANDBOX_FINGERPRINT); + expect(() => makeOnboardCancelExit(rollback, vi.fn(), exit)()).not.toThrow(); + expect(exit).toHaveBeenCalledWith(1); + + expect(() => exitHandlers[0]()).not.toThrow(); + expect(recordRecovery).toHaveBeenCalledTimes(2); + const guidance = log.mock.calls.flat().join("\n"); + expect(guidance).toContain(SANDBOX_FINGERPRINT); + expect(guidance).toContain("could not save the onboarding recovery record"); + }); + + it("retries recovery on a repeated exit callback after two durable writer failures (#9833)", () => { + const log = vi.fn(); + const recordRecovery = vi + .fn() + .mockImplementationOnce(() => { + throw new Error("immediate recovery write failed"); + }) + .mockImplementationOnce(() => { + throw new Error("first exit recovery write failed"); + }) + .mockImplementationOnce(() => undefined); + const exitHandlers: Array<() => void> = []; + const rollback = installSandboxCancelRollback({ + log, + recordRecovery, + registerExitHandler: (handler) => exitHandlers.push(handler), + }); + + rollback.arm("new-sb", SANDBOX_FINGERPRINT); + rollback.markCancelled(); + exitHandlers[0](); + exitHandlers[0](); + + expect(recordRecovery).toHaveBeenCalledTimes(3); + expect(recordRecovery).toHaveBeenNthCalledWith(3, "new-sb", SANDBOX_FINGERPRINT, undefined); + const guidanceCalls = log.mock.calls.filter(([message]) => + String(message).includes("preserved incomplete sandbox"), + ); + expect(guidanceCalls).toHaveLength(1); + + exitHandlers[0](); + expect(recordRecovery).toHaveBeenCalledTimes(3); + }); + + it("preserves missing-checkpoint recovery state without a mutable-name fallback (#9833)", () => { + const log = vi.fn(); + const exitHandlers: Array<() => void> = []; + const rollback = installSandboxCancelRollback({ + log, + registerExitHandler: (handler) => exitHandlers.push(handler), + }); + + rollback.arm("new-sb"); + rollback.markCancelled(); + exitHandlers[0](); + + const guidance = log.mock.calls.flat().join("\n"); + expect(guidance).toContain("identity fingerprint is unavailable"); + expect(guidance).toContain("OpenShell administrator"); }); }); @@ -126,47 +295,13 @@ describe("makeOnboardCancelExit", () => { }); describe("buildCancelRollbackMessage", () => { - it("reports the agent-specific resume command without name-only destruction (#9833)", () => { - const guidance = buildCancelRollbackMessage("sb", "nemohermes").join("\n"); - expect(guidance).toContain("preserved incomplete sandbox 'sb'"); - expect(guidance).toContain("identity-bound recovery"); - expect(guidance).toContain("nemohermes onboard --resume"); - expect(guidance).toContain("Do not destroy this sandbox by mutable sandbox name"); - expect(guidance).not.toContain("removed incomplete sandbox"); - expect(guidance).not.toContain("openshell sandbox delete"); - }); -}); - -describe("ordinary sandbox creation cancellation recovery", () => { - it("arms recovery after a fresh create and reports it on policy-selection cancellation (#9833)", () => { - const { guard, log } = createGuard(); - const exit = vi.fn(); - - completeOrdinaryOnboardSandboxCreation( - { - sandboxName: "new-sb", - sandboxWasLiveDefault: false, - runtimeFields: {} as never, - messagingProviders: [], - liveExists: false, - }, - { - setDefault: vi.fn(), - runFile: vi.fn(), - scriptsDir: "/tmp", - gatewayName: "nemoclaw", - providerExistsInGateway: () => true, - armCancelRollback: guard.arm, - dockerInfoFormat: () => "", - runCapture: () => "", - revalidatePolicyAuthority: vi.fn(), - applyVmDnsMonkeypatch: vi.fn(), - }, - ); - makeOnboardCancelExit(guard, vi.fn(), exit)(); - guard.runIfArmed(); + it("preserves identity-bound recovery guidance", () => { + const message = buildCancelRollbackMessage("sb", SANDBOX_FINGERPRINT).join("\n"); - expect(exit).toHaveBeenCalledExactlyOnceWith(1); - expect(log.mock.calls.flat().join("\n")).toContain("nemohermes onboard --resume"); + expect(message).toContain("preserved incomplete sandbox 'sb'"); + expect(message).toContain(SANDBOX_FINGERPRINT); + expect(message).toContain("identity-bound inspection, recovery, or removal"); + expect(message).not.toContain("openshell sandbox delete"); + expect(message).not.toContain("cannot delete it by immutable identity"); }); }); diff --git a/src/lib/onboard/cancel-rollback.ts b/src/lib/onboard/cancel-rollback.ts index 36a6f19db24..f2d72f81afb 100644 --- a/src/lib/onboard/cancel-rollback.ts +++ b/src/lib/onboard/cancel-rollback.ts @@ -1,77 +1,103 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { RetainedSandboxRecoveryContext } from "../state/onboard-session"; + // Re-exported so the onboard entrypoint imports its sandbox default/cancel // lifecycle helpers from a single module. export { restoreDefaultAfterRecreate, wasSandboxDefault } from "./default-preservation"; /** - * Recovery guard for a sandbox that was created during onboarding but whose - * onboarding was cancelled before the policy-preset step was confirmed. + * Preservation guard for a sandbox whose onboarding is cancelled before the + * policy tier and preset selection window is confirmed. * - * OpenShell can destroy a sandbox only by mutable name. Cancellation therefore - * preserves the sandbox, registry entry, and onboarding session for - * identity-bound recovery (#9833). + * Cancellation preserves the incomplete sandbox, registry entry, and onboarding + * session. The guard emits identity-bound recovery guidance and never deletes a + * sandbox by mutable name (#4614). * - * The guard is deliberately a two-key gate — it only fires when BOTH: - * - a freshly-created sandbox is `arm()`ed (set after createSandbox succeeds), AND - * - the operator actually cancelled via `markCancelled()` (the policy-step - * prompts call this on Ctrl+C / SIGTERM before exiting). + * The guard activates only when both conditions are true: + * - `arm()` records a newly created sandbox after `createSandbox` succeeds. + * - `markCancelled()` records Ctrl+C or SIGTERM at the policy-tier or either + * policy-preset selector. * - * This keeps every other `process.exit(1)` failure path untouched. A genuine - * build or verification failure exits without `markCancelled()`. + * Other `process.exit(1)` failure paths do not call `markCancelled()`. Their + * existing preservation behavior remains unchanged. */ export interface SandboxCancelRollbackDeps { /** Emit an operator-facing line (stderr). */ log(message: string): void; - /** Agent-specific CLI name used for the recovery command. */ - cliName: string; + /** Persist the recovery-only session before process exit completes. */ + recordRecovery?( + sandboxName: string, + sandboxIdentityFingerprint?: string, + context?: RetainedSandboxRecoveryContext, + ): void; } export interface SandboxCancelRollback { - /** Arm rollback for a just-created sandbox. */ - arm(sandboxName: string): void; - /** Disarm once the sandbox is past the cancellable window (policies confirmed). */ + /** Arm cancellation recovery guidance for a just-created sandbox. */ + arm( + sandboxName: string, + sandboxIdentityFingerprint?: string, + context?: RetainedSandboxRecoveryContext, + ): void; + /** Disarm once the sandbox is past the cancellable policy-selection window. */ disarm(): void; /** Record that the operator cancelled at a cancellable step. */ markCancelled(): void; - /** Run the rollback iff armed AND cancelled. Idempotent. */ + /** Report preservation guidance iff armed AND cancelled. Idempotent. */ runIfArmed(): void; /** Test/introspection helper. */ isArmed(): boolean; } -export function buildCancelRollbackMessage(sandboxName: string, cliName: string): string[] { +export function buildCancelRollbackMessage( + sandboxName: string, + sandboxIdentityFingerprint?: string, +): string[] { return [ "", - ` Onboarding cancelled — preserved incomplete sandbox '${sandboxName}' because OpenShell cannot bind sandbox destruction to its durable identity.`, - " Preserve its sandbox registry entry and onboarding session for identity-bound recovery.", - ` Run \`${cliName} onboard --resume\` to continue the saved onboarding session.`, - " Do not destroy this sandbox by mutable sandbox name.", + ` Onboarding cancelled — preserved incomplete sandbox '${sandboxName}'.`, + ...(sandboxIdentityFingerprint + ? [ + ` Durable sandbox identity fingerprint: ${sandboxIdentityFingerprint}`, + " Preserve this fingerprint for identity-bound inspection, recovery, or removal.", + ] + : [ + " Its durable identity fingerprint is unavailable; preserve the registry and onboarding recovery state.", + " Ask an OpenShell administrator to establish the exact sandbox identity before recovery or removal.", + ]), + " NemoClaw did not run OpenShell's mutable-name deletion command because the name may now identify a replacement sandbox.", + " Do not delete the sandbox by mutable sandbox name.", + " Shared inference providers are gateway configuration and are not sandbox cleanup targets.", + " Sandbox-scoped provider registrations or gateway-bound credentials may remain when the durable recovery record lists them.", + " Ask an OpenShell administrator to inspect the exact sandbox identity and remove only sandbox-scoped resources whose ownership is confirmed for this retained sandbox.", + " A recorded credential environment name alone does not prove exposure; rotate a credential only when identity-bound inspection proves that it was exposed or attached to a retained sandbox-scoped resource.", + " NemoClaw has no supported operation to clear this recovery record; use a different sandbox name for later onboarding.", ]; } export interface InstallSandboxCancelRollbackOptions { - cliName?: string; log?: (message: string) => void; + recordRecovery?: SandboxCancelRollbackDeps["recordRecovery"]; /** Override for tests; defaults to `process.on("exit", ...)`. */ registerExitHandler?: (handler: () => void) => void; } /** - * Register the process-exit hook for sandbox cancellation recovery. Kept here - * so the orchestration lives in a focused module rather than the onboard - * entrypoint. + * Register the process-exit hook that emits cancellation recovery guidance. + * Keep this orchestration outside the onboard entrypoint. * - * `process.exit()` synchronously emits `exit`. The handler records recovery - * guidance only when the guard is armed and the operator cancelled. + * Policy-step prompts use `process.exit()` for Ctrl+C. It synchronously emits + * `exit`, so the handler reports the recovery guidance before exit completes. + * The handler does nothing unless it is armed and the operator cancels. */ export function installSandboxCancelRollback( opts: InstallSandboxCancelRollbackOptions = {}, ): SandboxCancelRollback { const rollback = createSandboxCancelRollback({ - cliName: opts.cliName ?? "nemoclaw", log: opts.log ?? ((message) => console.error(message)), + recordRecovery: opts.recordRecovery, }); const register = opts.registerExitHandler ?? @@ -83,7 +109,7 @@ export function installSandboxCancelRollback( } /** - * Build the cancel handler the policy-step prompts run on Ctrl+C / SIGTERM: + * Build the cancel handler the policy-selection prompts run on Ctrl+C / SIGTERM: * restore the terminal (`cleanup`), record the cancel, then exit non-zero. * Shared so both the tier and preset selectors stay in sync. */ @@ -102,32 +128,85 @@ export function makeOnboardCancelExit( export function createSandboxCancelRollback( deps: SandboxCancelRollbackDeps, ): SandboxCancelRollback { - let armedSandboxName: string | null = null; + let armedSandbox: { + readonly name: string; + readonly identityFingerprint: string | null; + readonly context: RetainedSandboxRecoveryContext | undefined; + } | null = null; let cancelRequested = false; + let recoveryRecorded = false; + let recoveryPersistenceFailed = false; + let guidanceReported = false; let done = false; + const recordArmedRecovery = (): boolean => { + if (recoveryRecorded) return true; + if (armedSandbox === null) return false; + try { + deps.recordRecovery?.( + armedSandbox.name, + armedSandbox.identityFingerprint ?? undefined, + armedSandbox.context, + ); + recoveryRecorded = true; + recoveryPersistenceFailed = false; + return true; + } catch { + recoveryPersistenceFailed = true; + return false; + } + }; + return { - arm(sandboxName: string): void { - armedSandboxName = sandboxName; + arm( + sandboxName: string, + sandboxIdentityFingerprint?: string, + context?: RetainedSandboxRecoveryContext, + ): void { + armedSandbox = { + name: sandboxName, + identityFingerprint: + typeof sandboxIdentityFingerprint === "string" && + /^[0-9a-f]{64}$/u.test(sandboxIdentityFingerprint) + ? sandboxIdentityFingerprint + : null, + context, + }; }, disarm(): void { - armedSandboxName = null; + armedSandbox = null; }, markCancelled(): void { cancelRequested = true; + // Persist before requesting process exit. This also covers callers that + // defer the real exit and prevents later exit handlers from replacing + // the recovery-only marker with an ordinary resumable failure. + recordArmedRecovery(); }, isArmed(): boolean { - return armedSandboxName !== null; + return armedSandbox !== null; }, runIfArmed(): void { - if (done || !cancelRequested || armedSandboxName === null) return; - done = true; - const sandboxName = armedSandboxName; - armedSandboxName = null; - - for (const line of buildCancelRollbackMessage(sandboxName, deps.cliName)) { - deps.log(line); + if (done || !cancelRequested || armedSandbox === null) return; + const { name: sandboxName, identityFingerprint } = armedSandbox; + const persisted = recordArmedRecovery(); + if (!guidanceReported) { + guidanceReported = true; + if (recoveryPersistenceFailed) { + deps.log( + " NemoClaw could not save the onboarding recovery record; preserve the registry entry and exact sandbox identity for administrator recovery.", + ); + } + for (const line of buildCancelRollbackMessage( + sandboxName, + identityFingerprint ?? undefined, + )) { + deps.log(line); + } } + if (!persisted) return; + done = true; + armedSandbox = null; }, }; } diff --git a/src/lib/onboard/command-support.test.ts b/src/lib/onboard/command-support.test.ts index 36a7ddd7c8f..fcef7cae4b8 100644 --- a/src/lib/onboard/command-support.test.ts +++ b/src/lib/onboard/command-support.test.ts @@ -48,6 +48,7 @@ describe("buildOnboardFlags --apf-interceptor help", () => { expect(flags["apf-interceptor"].hidden).not.toBe(true); expect(flags["apf-interceptor"].allowNo).not.toBe(true); + expect(flags["apf-interceptor"].description).toContain("providerless sandbox"); expect(flags["apf-interceptor"].description).toContain("contained sandbox-scoped policy"); expect(flags["apf-interceptor"].description).toContain("without claiming its provenance"); expect(flags["apf-interceptor"].exclusive).toEqual(["resume", "recreate-sandbox"]); diff --git a/src/lib/onboard/command-support.ts b/src/lib/onboard/command-support.ts index be031cf81ee..806ea45d057 100644 --- a/src/lib/onboard/command-support.ts +++ b/src/lib/onboard/command-support.ts @@ -109,7 +109,7 @@ export function buildOnboardFlags(options: { includeEvents?: boolean } = {}): Re "recreate-sandbox": Flags.boolean({ description: "Delete and recreate an existing sandbox" }), "apf-interceptor": Flags.boolean({ description: - "Create without a caller policy and require a contained sandbox-scoped policy without claiming its provenance", + "Create a providerless sandbox without a caller policy and require a contained sandbox-scoped policy without claiming its provenance", exclusive: ["resume", "recreate-sandbox"], }), gpu: Flags.boolean({ diff --git a/src/lib/onboard/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index ea77fcc6408..4cb05e7a478 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -12,6 +12,7 @@ import type { SandboxEntry } from "../state/registry"; import type { QualifiedSandboxInferenceRouteReservation } from "../state/registry/route-reservation"; import * as sandboxState from "../state/sandbox"; import { + completeOrdinaryOnboardSandboxCreation, createCreatedSandboxCompletionActions, createOnboardCreatedSandboxCompletion, createOnboardCreatedSandboxRegistration, @@ -58,6 +59,51 @@ describe("created sandbox registration authority", () => { }); }); +describe("new sandbox cancellation recovery", () => { + it("preserves recovery guidance when the durable identity is unavailable (#9833)", () => { + const error = vi.spyOn(console, "error").mockImplementation(() => undefined); + const runFile = vi.fn(); + const armCancelRollback = vi.fn(); + const markCancellationRecovery = vi.fn(); + + expect(() => + completeOrdinaryOnboardSandboxCreation( + { + sandboxName: "new-sandbox", + sandboxWasLiveDefault: false, + runtimeFields: { openshellDriver: "docker" } as never, + messagingProviders: [], + liveExists: false, + }, + { + setDefault: vi.fn(), + runFile, + scriptsDir: "/repo/scripts", + gatewayName: "nemoclaw", + providerExistsInGateway: () => true, + armCancelRollback, + markCancellationRecovery, + dockerInfoFormat: () => "", + runCapture: () => "", + revalidatePolicyAuthority: vi.fn(), + applyVmDnsMonkeypatch: vi.fn(), + }, + ), + ).toThrow("Sandbox 'new-sandbox' has no exact identity for cancel recovery."); + + const guidance = error.mock.calls.flat().join("\n"); + expect(guidance).toContain("Sandbox 'new-sandbox' was created on gateway 'nemoclaw'"); + expect(guidance).toContain("registry entry and onboarding session were preserved"); + expect(guidance).toContain("Do not delete the sandbox by mutable sandbox name"); + expect(guidance).toContain("establish the exact live durable identity before removal"); + expect(guidance).toContain("add --fresh, and use a new sandbox name"); + expect(runFile).not.toHaveBeenCalled(); + expect(armCancelRollback).not.toHaveBeenCalled(); + expect(markCancellationRecovery).toHaveBeenCalledOnce(); + expect(markCancellationRecovery).toHaveBeenCalledWith("new-sandbox"); + }); +}); + function executable(file: string, contents: string): void { fs.writeFileSync(file, contents, { mode: 0o755 }); } diff --git a/src/lib/onboard/created-sandbox-finalization.ts b/src/lib/onboard/created-sandbox-finalization.ts index bdc02c6137a..d1e5a23b0f8 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -29,14 +29,9 @@ import type { HermesPortableConfiguredReceipt } from "./experimental/hermes-port import { warnIfLandlockUnsupported } from "./landlock-warning"; import * as managedWorkloadOnboard from "./managed-workload/onboard-orchestration"; import { printMessagingProviderMissing } from "./preflight-messages"; -import { - pendingSandboxPolicyVerificationForBoundary, -} from "./sandbox-create/policy-creation-receipt"; +import { pendingSandboxPolicyVerificationForBoundary } from "./sandbox-create/policy-creation-receipt"; import type { SandboxGpuCreateFlowResult } from "./sandbox-gpu-create-flow"; -import type { - VerifiedSandboxPolicyBoundary, - VerifiedSandboxPolicyRegistration, -} from "./types"; +import type { VerifiedSandboxPolicyBoundary, VerifiedSandboxPolicyRegistration } from "./types"; import type { SelectionDrift } from "./selection-drift"; import { applyOnboardVmDnsMonkeypatch } from "./vm-dns-monkeypatch"; import { @@ -250,6 +245,7 @@ export function completeOrdinaryOnboardSandboxCreation( readonly runtimeFields: RegistrationSeed["runtimeFields"]; readonly messagingProviders: readonly string[]; readonly liveExists: boolean; + readonly lifecycleLiveIdentityFingerprint?: string; }, deps: { readonly setDefault: (sandboxName: string) => void; @@ -257,7 +253,8 @@ export function completeOrdinaryOnboardSandboxCreation( readonly scriptsDir: string; readonly gatewayName: string; readonly providerExistsInGateway: (providerName: string) => boolean; - readonly armCancelRollback: (sandboxName: string) => void; + readonly armCancelRollback: (sandboxName: string, sandboxIdentityFingerprint: string) => void; + readonly markCancellationRecovery: (sandboxName: string) => unknown; readonly dockerInfoFormat: Parameters[0]["dockerInfoFormat"]; readonly runCapture: Parameters[0]["runCapture"]; readonly revalidatePolicyAuthority: (operation: string) => void; @@ -287,7 +284,27 @@ export function completeOrdinaryOnboardSandboxCreation( deps.revalidatePolicyAuthority(`reporting sandbox '${input.sandboxName}' creation success`); console.log(` ✓ Sandbox '${input.sandboxName}' created`); warnIfLandlockUnsupported(deps); - if (!input.liveExists) deps.armCancelRollback(input.sandboxName); + if (!input.liveExists) { + const lifecycleLiveIdentityFingerprint = input.lifecycleLiveIdentityFingerprint; + if ( + !lifecycleLiveIdentityFingerprint || + !/^[0-9a-f]{64}$/u.test(lifecycleLiveIdentityFingerprint) + ) { + deps.markCancellationRecovery(input.sandboxName); + for (const line of [ + "", + ` Sandbox '${input.sandboxName}' was created on gateway '${deps.gatewayName}', but NemoClaw could not verify its durable identity.`, + " The sandbox registry entry and onboarding session were preserved for recovery.", + " Do not delete the sandbox by mutable sandbox name.", + " Ask an OpenShell administrator to establish the exact live durable identity before removal.", + " After confirmed identity-bound removal, rerun the original onboarding command with the same required inputs, add --fresh, and use a new sandbox name.", + ]) { + console.error(line); + } + throw new Error(`Sandbox '${input.sandboxName}' has no exact identity for cancel recovery.`); + } + deps.armCancelRollback(input.sandboxName, lifecycleLiveIdentityFingerprint); + } return input.sandboxName; } @@ -491,8 +508,7 @@ export function createCreatedSandboxCompletionActions( policyAuthority: verifiedPolicyRegistration.policyAuthority, ...(verifiedPolicyRegistration.policyAuthority === "nemoclaw-managed" ? { - policyCreationReceipt: - verifiedPolicyRegistration.policyCreationReceipt, + policyCreationReceipt: verifiedPolicyRegistration.policyCreationReceipt, } : {}), inferenceRouteReservation: verifiedInferenceRouteReservation, @@ -583,8 +599,8 @@ type OnboardGatewayBinding = { }; type OnboardPreparedPolicy = Omit< Pick< - managedWorkloadOnboard.PreparedOnboardSandboxWorkloadLaunch, - "initialSandboxPolicy" | "policyTier" | "policyAuthority" | "dashboardRemoteBindPrepared" + managedWorkloadOnboard.PreparedOnboardSandboxWorkloadLaunch, + "initialSandboxPolicy" | "policyTier" | "policyAuthority" | "dashboardRemoteBindPrepared" >, "policyAuthority" > & { diff --git a/src/lib/onboard/entry-options.test.ts b/src/lib/onboard/entry-options.test.ts index 93292f2882f..ae40e6f3bc9 100644 --- a/src/lib/onboard/entry-options.test.ts +++ b/src/lib/onboard/entry-options.test.ts @@ -213,6 +213,147 @@ describe("resolveOnboardEntryOptions", () => { expect(result.resume).toBe(false); }); + it.each([ + ["automatic", {}], + ["explicit", { resume: true }], + ])("rejects %s recovery-only continuation before onboarding effects", (_label, opts) => { + const deps = createDeps(); + + expect(() => + resolveOnboardEntryOptions( + { + opts, + env: {}, + stdinIsTty: true, + stdoutIsTty: true, + persistedSessionStatus: "recovery_required", + persistedRecoverySandboxName: "retained-sb", + persistedSessionSandboxName: "retained-sb", + retainedRecoverySandboxNames: ["retained-sb"], + }, + deps, + ), + ).toThrow(ExitError); + expect(deps.error).toHaveBeenCalledWith( + expect.stringContaining("cannot use retained sandbox 'retained-sb'"), + ); + expect(deps.error).toHaveBeenCalledWith( + expect.stringContaining("resume, reuse, recreation, and same-name fresh onboarding"), + ); + }); + + it.each([ + ["a missing name", null], + ["the retained name", "retained-sb"], + ])("rejects recovery-only --fresh with %s", (_label, sandboxName) => { + const deps = createDeps(); + + expect(() => + resolveOnboardEntryOptions( + { + opts: { fresh: true, sandboxName }, + env: {}, + stdinIsTty: true, + stdoutIsTty: true, + persistedSessionStatus: "recovery_required", + persistedRecoverySandboxName: "retained-sb", + }, + deps, + ), + ).toThrow(ExitError); + expect(deps.error).toHaveBeenCalledWith( + expect.stringContaining("--fresh with an explicit sandbox name different"), + ); + }); + + it("allows recovery-only --fresh with a different explicit name", () => { + const deps = createDeps(); + + const result = resolveOnboardEntryOptions( + { + opts: { fresh: true, sandboxName: "replacement-sb" }, + env: {}, + stdinIsTty: true, + stdoutIsTty: true, + persistedSessionStatus: "recovery_required", + persistedRecoverySandboxName: "retained-sb", + retainedRecoverySandboxNames: ["retained-sb"], + }, + deps, + ); + + expect(result).toMatchObject({ + fresh: true, + resume: false, + requestedSandboxName: "replacement-sb", + }); + expect(deps.error).not.toHaveBeenCalled(); + }); + + it("rejects a different fresh name when recovery has no independent durable record", () => { + const deps = createDeps(); + + expect(() => + resolveOnboardEntryOptions( + { + opts: { fresh: true, sandboxName: "replacement-sb" }, + env: {}, + stdinIsTty: true, + stdoutIsTty: true, + persistedSessionStatus: "recovery_required", + persistedRecoverySandboxName: "retained-sb", + retainedRecoverySandboxNames: [], + }, + deps, + ), + ).toThrow(ExitError); + expect(deps.error).toHaveBeenCalledWith( + expect.stringContaining("independent retained sandbox recovery record"), + ); + }); + + it("blocks a retained name after a different fresh session replaced the active session", () => { + const deps = createDeps(); + + expect(() => + resolveOnboardEntryOptions( + { + opts: { fresh: true, sandboxName: "retained-sb" }, + env: {}, + stdinIsTty: true, + stdoutIsTty: true, + persistedSessionStatus: "in_progress", + persistedRecoverySandboxName: null, + retainedRecoverySandboxNames: ["retained-sb"], + }, + deps, + ), + ).toThrow(ExitError); + expect(deps.error).toHaveBeenCalledWith( + expect.stringContaining("retained sandbox 'retained-sb'"), + ); + }); + + it("allows a different fresh name without clearing an independent recovery record", () => { + const deps = createDeps(); + + const result = resolveOnboardEntryOptions( + { + opts: { fresh: true, sandboxName: "replacement-sb" }, + env: {}, + stdinIsTty: true, + stdoutIsTty: true, + persistedSessionStatus: "recovery_required", + persistedRecoverySandboxName: "retained-sb", + retainedRecoverySandboxNames: ["retained-sb"], + }, + deps, + ); + + expect(result.requestedSandboxName).toBe("replacement-sb"); + expect(deps.error).not.toHaveBeenCalled(); + }); + it("does not auto-resume when --fresh is set even with an in_progress session (#5470)", () => { const deps = createDeps(); diff --git a/src/lib/onboard/entry-options.ts b/src/lib/onboard/entry-options.ts index c3b5e1b8ed4..b8f707b0ca1 100644 --- a/src/lib/onboard/entry-options.ts +++ b/src/lib/onboard/entry-options.ts @@ -4,6 +4,11 @@ import { isNonInteractiveEnv } from "../core/non-interactive"; import { getNameValidationGuidance } from "../name-validation"; import { cliDisplayName } from "./branding"; +import { + canonicalPlaceholderKeys, + EXTRA_PLACEHOLDER_KEYS_ENV, + parseExtraPlaceholderKeys, +} from "./extra-placeholder-keys"; import { RESERVED_SANDBOX_NAMES } from "./sandbox-agent"; import { requireStationExpressResumeIntent, @@ -29,6 +34,9 @@ export interface OnboardEntryOptionsInput { * flag-only behavior for callers that don't load the session. */ persistedSessionStatus?: string | null; + persistedRecoverySandboxName?: string | null; + persistedSessionSandboxName?: string | null; + retainedRecoverySandboxNames?: readonly string[]; } export interface OnboardEntryOptionsDeps { @@ -53,8 +61,54 @@ export interface ResolvedOnboardEntryOptions { cannotPrompt: boolean; } +type PersistedOnboardEntrySession = { + readonly status: string; + readonly sandboxName?: string | null; + readonly cancellationRecovery?: { readonly sandboxName: string } | null; +}; + +interface DefaultRunEntryState { + loadSession(): PersistedOnboardEntrySession | null; + listRetainedSandboxRecoveryRecords(): readonly { readonly sandboxName: string }[]; +} + type NonInteractiveEntryOptions = { nonInteractive?: boolean }; -type ResumableEntryOptions = NonInteractiveEntryOptions & { resume?: boolean; fresh?: boolean }; +type ResumableEntryOptions = NonInteractiveEntryOptions & { + resume?: boolean; + fresh?: boolean; + apfInterceptorRequested?: boolean | null; +}; + +const PROVIDER_INTENT_ENV_KEYS = [ + "NEMOCLAW_PROVIDER", + "NEMOCLAW_MODEL", + "NEMOCLAW_PROVIDER_MODEL", + "NEMOCLAW_SERVING_PRESET", + "NEMOCLAW_MESSAGING_PLAN_B64", +] as const; + +const PROVIDERLESS_WEB_SEARCH_ENV_VALUES = new Set(["", "none", "off", "disabled", "no", "0"]); + +/** Reject ambient provider intent before onboarding records or external effects. */ +export function assertProviderlessInterceptorEnvironment( + interceptorRequested: boolean, + env: NodeJS.ProcessEnv, +): void { + if (!interceptorRequested) return; + const hasProviderIntent = + PROVIDER_INTENT_ENV_KEYS.some((key) => String(env[key] ?? "").trim().length > 0) || + parseExtraPlaceholderKeys(env[EXTRA_PLACEHOLDER_KEYS_ENV], canonicalPlaceholderKeys()).keys + .length > 0 || + !PROVIDERLESS_WEB_SEARCH_ENV_VALUES.has( + String(env.NEMOCLAW_WEB_SEARCH_PROVIDER ?? "") + .trim() + .toLowerCase(), + ); + if (!hasProviderIntent) return; + throw new Error( + "Interceptor onboarding supports providerless sandbox creation only. No sandbox or provider was created.", + ); +} export function resolveOnboardRunOptions( options: OnboardEntryOptionsInput["opts"] & { autoYes?: boolean; nonInteractive?: boolean }, @@ -65,6 +119,9 @@ export function resolveOnboardRunOptions( stdinIsTty: Boolean(process.stdin?.isTTY), stdoutIsTty: Boolean(process.stdout?.isTTY), }, + persistedRecoverySandboxName: string | null = null, + persistedSessionSandboxName: string | null = null, + retainedRecoverySandboxNames: readonly string[] = [], ) { const resume = options.resume === true || (options.fresh !== true && persistedSessionStatus === "in_progress"); @@ -75,7 +132,15 @@ export function resolveOnboardRunOptions( return { resume, nonInteractive, - entryOptionsInput: { opts: options, env, ...terminal, persistedSessionStatus }, + entryOptionsInput: { + opts: options, + env, + ...terminal, + persistedSessionStatus, + persistedRecoverySandboxName, + persistedSessionSandboxName, + retainedRecoverySandboxNames, + }, }; } @@ -85,12 +150,19 @@ export function resolveOnboardRunEntryOptions( persistedSessionStatus: string | null, isNonInteractiveEnv: () => boolean, deps: Omit, + persistedRecoverySandboxName: string | null = null, + persistedSessionSandboxName: string | null = null, + retainedRecoverySandboxNames: readonly string[] = [], ) { const context = resolveOnboardRunOptions( options, env, persistedSessionStatus, isNonInteractiveEnv, + undefined, + persistedRecoverySandboxName, + persistedSessionSandboxName, + retainedRecoverySandboxNames, ); return { ...context, @@ -103,18 +175,43 @@ export function resolveOnboardRunEntryOptions( export function resolveDefaultRunEntryOptions( options: OnboardEntryOptionsInput["opts"] & { autoYes?: boolean; nonInteractive?: boolean }, - persistedSessionStatus: string | null, + persistedSession: PersistedOnboardEntrySession | null, validateSandboxName: OnboardEntryOptionsDeps["validateName"], env: NodeJS.ProcessEnv = process.env, + retainedRecoverySandboxNames: readonly string[] = [], ) { - return resolveOnboardRunEntryOptions(options, env, persistedSessionStatus, isNonInteractiveEnv, { - validateName: validateSandboxName, - reservedSandboxNames: RESERVED_SANDBOX_NAMES, - cliDisplayName, - getNameValidationGuidance, - error: (message) => console.error(message), - exitProcess: (code) => process.exit(code), - }); + return resolveOnboardRunEntryOptions( + options, + env, + persistedSession?.status ?? null, + isNonInteractiveEnv, + { + validateName: validateSandboxName, + reservedSandboxNames: RESERVED_SANDBOX_NAMES, + cliDisplayName, + getNameValidationGuidance, + error: (message) => console.error(message), + exitProcess: (code) => process.exit(code), + }, + persistedSession?.cancellationRecovery?.sandboxName ?? null, + persistedSession?.sandboxName ?? null, + retainedRecoverySandboxNames, + ); +} + +export function resolveDefaultRunEntryOptionsFromState( + options: OnboardEntryOptionsInput["opts"] & { autoYes?: boolean; nonInteractive?: boolean }, + validateSandboxName: OnboardEntryOptionsDeps["validateName"], + state: DefaultRunEntryState, + env: NodeJS.ProcessEnv = process.env, +) { + return resolveDefaultRunEntryOptions( + options, + state.loadSession(), + validateSandboxName, + env, + state.listRetainedSandboxRecoveryRecords().map((record) => record.sandboxName), + ); } export function assertDefaultSandboxNameAllowed(sandboxName: string): void { @@ -153,8 +250,15 @@ export function wrapOnboard( run: (options?: Options) => Promise, session: StationExpressSessionLifecycle, ): (options?: Options) => Promise { + const guardProviderlessInput = async (options?: Options): Promise => { + assertProviderlessInterceptorEnvironment( + options?.apfInterceptorRequested === true, + process.env, + ); + await run(options); + }; return wrapStationExpressOnboard( - withNonInteractiveEnvironment(run), + withNonInteractiveEnvironment(guardProviderlessInput), session.loadSession, session.reconcileStationExpressReceiptRetirement, ); @@ -233,6 +337,68 @@ export function resolveOnboardEntryOptions( } requestedSandboxName = validated; } + const retainedRecoverySandboxNames = new Set( + (input.retainedRecoverySandboxNames ?? []).map((name) => name.trim()).filter(Boolean), + ); + const recoveryEntryName = + requestedSandboxName ?? input.persistedSessionSandboxName?.trim() ?? null; + if (retainedRecoverySandboxNames.size > 0) { + if (!recoveryEntryName) { + deps.error( + " Onboarding cannot continue while a retained sandbox recovery record is unresolved without an explicit different sandbox name.", + ); + deps.error( + " Use --fresh --name ; the retained sandbox recovery record stays unresolved.", + ); + deps.exitProcess(1); + } + if (retainedRecoverySandboxNames.has(recoveryEntryName)) { + deps.error( + ` Onboarding cannot use retained sandbox '${recoveryEntryName}' while its identity-bound recovery record is unresolved.`, + ); + deps.error( + " Automatic and explicit resume, reuse, recreation, and same-name fresh onboarding remain disabled; NemoClaw has no supported operation to clear this recovery record.", + ); + deps.exitProcess(1); + } + } + if (input.persistedSessionStatus === "recovery_required") { + const recoverySandboxName = input.persistedRecoverySandboxName?.trim() || null; + if (!fresh) { + deps.error( + ` Onboarding cannot continue because cancellation preserved sandbox '${recoverySandboxName ?? "unknown"}' in recovery-only state.`, + ); + deps.error( + " Automatic and explicit resume, reuse, and recreation are disabled to protect the retained sandbox.", + ); + deps.error( + " Use --fresh --name ; the retained sandbox recovery record stays unresolved.", + ); + deps.exitProcess(1); + } + if ( + !recoverySandboxName || + !requestedSandboxName || + requestedSandboxName === recoverySandboxName + ) { + deps.error( + " Recovery-only onboarding state requires --fresh with an explicit sandbox name different from the retained sandbox.", + ); + deps.error( + " The retained sandbox recovery record stays unresolved when onboarding starts with another name.", + ); + deps.exitProcess(1); + } + if (!retainedRecoverySandboxNames.has(recoverySandboxName)) { + deps.error( + " Onboarding cannot replace the recovery-only session because its independent retained sandbox recovery record is unavailable.", + ); + deps.error( + " Preserve the session and registry state for identity-bound administrator recovery.", + ); + deps.exitProcess(1); + } + } if (cannotPrompt && !resume && requestedFromDockerfile && !requestedSandboxName) { deps.error( " --from requires --name (or NEMOCLAW_SANDBOX_NAME) when running without a TTY or with --non-interactive.", diff --git a/src/lib/onboard/exit-step-failure.test.ts b/src/lib/onboard/exit-step-failure.test.ts index 0f09145602f..bae8e2b353e 100644 --- a/src/lib/onboard/exit-step-failure.test.ts +++ b/src/lib/onboard/exit-step-failure.test.ts @@ -250,6 +250,20 @@ describe("incomplete-onboard --resume backstop (#6003)", () => { expect(runExitHandler(1)).not.toContain("--resume"); }); + it("preserves recovery-only cancellation through the later exit backstop (#9833)", () => { + const fingerprint = "a".repeat(64); + session.saveSession( + session.createSession({ lastStepStarted: "sandbox", sandboxName: "retained-sb" }), + ); + session.markCancellationRecovery("retained-sb", fingerprint); + const beforeExit = requireLoadedSession(); + + const output = runExitHandler(1); + + expect(output).not.toContain("--resume"); + expect(requireLoadedSession()).toEqual(beforeExit); + }); + it("stays silent when cancel cleanup clears the session before a signal is re-raised", async () => { const signalListeners = new Map<"SIGINT" | "SIGTERM", () => void>(); const kill = vi.fn(); diff --git a/src/lib/onboard/exit-step-failure.ts b/src/lib/onboard/exit-step-failure.ts index 19a18972a95..0977dae42fd 100644 --- a/src/lib/onboard/exit-step-failure.ts +++ b/src/lib/onboard/exit-step-failure.ts @@ -56,6 +56,7 @@ export function registerIncompleteOnboardExitFailureHandler( // printOnboardResumeHint also self-dedupes against tailored hints. const interrupted = markLastStartedStepFailed(deps, message, true); if (!interrupted) return; + if (interrupted.status === "recovery_required") return; printOnboardResumeHint(portable, undefined, interrupted.sandboxName); }; diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 00ca0efcf7c..8fa6669f487 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -125,7 +125,7 @@ runtime mutation | 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 because OpenShell cannot condition deletion on its durable identity. Exact provider-owned GPU cleanup can proceed through its owner receipt. Temporary policy and build-context cleanup remains best effort. Cancellation clears only the aborted session and leaves the registry row unchanged. Coverage: `transition-traces.test.ts`, `sandbox-create-intent-boundary.test.ts`, `sandbox-create-plan.test.ts`, and the focused cancellation, readiness, GPU cleanup, dashboard, and policy-authority tests. Gap: gateway upserts can outlive a failed or interrupted create. | +| **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 because NemoClaw refuses the available mutable-name deletion command when it could target a replacement. Exact provider-owned GPU cleanup can proceed through its owner receipt. Temporary policy and build-context cleanup remains best effort. Cancellation before sandbox creation can leave the session resumable. Cancellation after creation preserves the incomplete session, registry row, and an independent identity-bound recovery record. Shared inference providers remain gateway configuration and are not sandbox cleanup targets. Recovery removes only confirmed sandbox-scoped resources and rotates credentials only when inspection proves exposure or attachment to a retained resource; a recorded environment-variable name alone is not exposure evidence. Coverage: `transition-traces.test.ts`, `sandbox-create-intent-boundary.test.ts`, `sandbox-create-plan.test.ts`, and the focused cancellation, readiness, GPU cleanup, dashboard, and policy-authority tests. Gap: gateway upserts can outlive a failed or interrupted create. | | **`--fresh` onboard** — `resolveOnboardEntryOptions`, `prepareFreshSession`, `createBaseImageResolutionContext` | Current flags/environment/prompts replace resumable intent. `--fresh` disables auto-resume and forces base-image resolution; it does not prove that the selected sandbox name is unused. | The first destructive effect is local: the prior onboard session is cleared before a new session is saved. A matching live sandbox can later reuse or recreate through the normal sandbox decision; `--fresh` does not itself delete it. | The new session and machine snapshot replace the old resume checkpoint. Credential and effect boundaries then match new onboard or live recreate. | The discarded resume checkpoint is not restored on later failure. Covered by `entry-options.test.ts`, `session-bootstrap.test.ts`, and base-image resolution tests. | | **Resume, re-onboard, or recreate** — `onboard()`, `prepareOnboardSession`, `decideSandboxResume`, live-sandbox handling in `createSandbox` | For `--resume`, the recorded session is authoritative and conflicting current name/provider/model/image/tool-disclosure hints are rejected. A new re-onboard run takes current flags, environment, and prompts as intent while registry/gateway state provides drift evidence. The machine resolves a complete secret-free create intent, including policy, messaging/provider, GPU, resource, disabled-channel, and agent inputs, before repair/removal or live recreation. | Ordinary live recreation conditionally backs up before provider cleanup, **delete**, and image removal. The recreate journal preserves the source registry row after deletion. Replacement registration commits the new row after readiness and validation. A selected pre-upgrade backup suppresses a new one; an explicit override permits recreation without backup. Resume registry removal and `repair-and-recreate` occur only after complete intent validation. Temporary policy/build artifacts remain materialization effects after the delete boundary. | Resume continues the recorded session/machine snapshot; non-resume re-onboard writes a new session first. OpenClaw records completed sandbox name, web search, messaging, and resource choices with explicit progress markers, including explicit `null` choices, while the complete create intent stays process-local and is not persisted or emitted. Raw credential values remain outside the session. A missing process value can be rebound only when the same OpenClaw session recorded successfully registering that provider and its live provider name, provider type, and credential key still match; otherwise interactive resume requests it again and non-interactive resume exits with environment-variable guidance. Credentials are checked before mutation and again immediately before materialization. | A failed replacement keeps the source registry row. Restore failures warn and can still publish the replacement; managed-DCode live-selection failure leaves a running, unregistered sandbox with manual-delete guidance. Checkpoint replay reuses an exact live sandbox after an interrupted create and backfills missing create/register receipts. Cancel rollback is not armed and there is no rebuild-style receipt rollback. Coverage: transition traces, create-intent characterization, checkpoint replay and resume guards, and sandbox-handler crash recovery. Gaps: early backup asymmetry and no rebuild-style cross-effect rollback. | | **Rebuild or installer-driven upgrade** — `rebuildSandbox` in `rebuild-pipeline.ts`; `upgradeSandboxes` | Registry state is authoritative. A matching session may fill guarded legacy gaps only when its selection agrees; an unrelated/global session is never used. Ambient provider/model selection is quarantined by `isolateAmbientRecreateEnv`, apart from narrowly scoped legacy recovery. Legacy and custom-image rebuilds retain and fingerprint a prepared build context. Managed-image rebuilds instead stage an immutable image and startup-profile handoff, skip Dockerfile image preflight, and revalidate provider-bound workload authority before each deletion boundary. | Consent persistence, target-gateway selection/recovery, and target-preflight registry updates can precede disposable image build/probes. Backup is the first durable recovery checkpoint when available. Shields unlock, MCP detach/scrub, and NIM stop are destructive in-place effects before the **sandbox delete** boundary. Legacy and custom-image paths recheck prepared context and mutation-edge conditions before delete. Managed-image paths revalidate the exact provider-bound handoff before delete. | Durable checkpoints are the backup/recovery manifest when one exists and the rewritten recreate session; stale recovery can reach deletion without a manifest, making that session its first new durable checkpoint. Rollback receipts/snapshots are process-local. Credential metadata comes from the target or guarded fallback; raw credentials/providers are checked against current process/gateway state, while prepared installer recovery may reconstruct a missing gateway provider from a validated host credential. | In-process rollback best-effort restores registry/MCP retry metadata, but process death after non-MCP delete can still lose it. The inner onboarding consumes the exact managed-workload handoff or selects the legacy resource profile after deletion. Covered by rebuild, managed-workload authority, image-preflight, DCode, and messaging tests. Gaps: health-before-delete and atomic swap. Closed issue #5801 records the original gap; #6835 fixed only the printed recovery path. | diff --git a/src/lib/onboard/machine/core-flow-composition.ts b/src/lib/onboard/machine/core-flow-composition.ts index c3223d9e215..d371f2d4da8 100644 --- a/src/lib/onboard/machine/core-flow-composition.ts +++ b/src/lib/onboard/machine/core-flow-composition.ts @@ -13,6 +13,7 @@ import type { OnboardFlowContext } from "./flow-context"; import { createResumeProviderShim, type ResumeProviderShimDeps } from "./resume-provider-shim"; export { + isCoreFlowCompleteBeforeFinalization, prepareCoreOnboardFlowContext, prepareFinalOnboardFlowContext, runCoreOnboardFlowSlice, diff --git a/src/lib/onboard/machine/core-flow-phases.test.ts b/src/lib/onboard/machine/core-flow-phases.test.ts index 9d4ce379652..a76c7ec8f86 100644 --- a/src/lib/onboard/machine/core-flow-phases.test.ts +++ b/src/lib/onboard/machine/core-flow-phases.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; +import * as credentialStore from "../../credentials/store"; import { type InferenceEndpointSource, normalizeInferenceSelection, @@ -21,6 +22,7 @@ import { createProviderInferenceOnboardFlowPhase, createSandboxOnboardFlowPhase, type EndpointProvenanceOptions, + isCoreFlowCompleteBeforeFinalization, type ProviderInferenceOnboardFlowPhaseOptions, runCoreOnboardFlowSlice, type SandboxOnboardFlowPhaseOptions, @@ -96,6 +98,8 @@ function repairRecorder(events: string[] = []): OnboardPrerequisiteRepairEventRe function createPhases( overrides: { endpointProvenance?: Partial; + inspectSandboxForCreate?: ProviderOptions["inspectSandboxForCreate"]; + providerEnv?: NodeJS.ProcessEnv; providerDeps?: Partial; sandboxOptions?: Partial>; sandboxDeps?: Partial; @@ -119,8 +123,12 @@ function createPhases( const providerInference = createProviderInferenceOnboardFlowPhase({ gatewayName: "nemoclaw", forceProviderSelection: false, + inspectSandboxForCreate: + overrides.inspectSandboxForCreate ?? + (() => ({ existingEntry: null, preservedMcpState: undefined, liveExists: false })), + apfInterceptorRequested: overrides.sandboxOptions?.apfInterceptorRequested === true, endpointProvenance, - env: {}, + env: overrides.providerEnv ?? {}, constants: { hermesProviderName: "hermes", hermesApiKeyAuthMethod: "api_key", @@ -139,10 +147,8 @@ function createPhases( _gatewayName: string, operation: () => Promise | T, ) => await operation(), - withModelRouterPortLifecycleLock: async ( - _port: number, - operation: () => Promise | T, - ) => await operation(), + withModelRouterPortLifecycleLock: async (_port: number, operation: () => Promise | T) => + await operation(), getModelRouterPort: () => 4000, normalizeHermesAuthMethod: (value) => value === "oauth" || value === "api_key" ? value : null, @@ -336,8 +342,8 @@ describe("core onboard flow phases", () => { return durableSession; }); const createSandbox = vi.fn(async (...args: unknown[]) => { - const authority = args.at(-3) as InferenceRouteReservationAuthority | null; - const createIntent = args.at(-2) as { + const authority = args[14] as InferenceRouteReservationAuthority | null; + const createIntent = args[15] as { endpointSource?: InferenceEndpointSource | null; }; const reservation = getSandbox(sandboxName); @@ -423,8 +429,8 @@ describe("core onboard flow phases", () => { return durableSession; }); const createSandbox = vi.fn(async (...args: unknown[]) => { - const authority = args.at(-3) as InferenceRouteReservationAuthority | null; - const createIntent = args.at(-2) as { + const authority = args[14] as InferenceRouteReservationAuthority | null; + const createIntent = args[15] as { endpointSource?: InferenceEndpointSource | null; }; const reservation = getSandbox(sandboxName); @@ -596,15 +602,16 @@ describe("core onboard flow phases", () => { credentialEnv: "NVIDIA_INFERENCE_API_KEY", }), ); - expect(createSandbox.mock.calls[0]?.at(-2)).toMatchObject({ + const createIntent = (createSandbox.mock.calls[0] as unknown[] | undefined)?.[15]; + expect(createIntent).toMatchObject({ compatibleEndpointReasoning: "true", - deferSandboxEffectsUntilPolicyVerification: true, resolved: { inferenceProvider: "compatible-endpoint", extraProviders: ["current-provider"], staleExtraProviders: ["stale-provider"], }, }); + expect(createIntent).not.toHaveProperty("deferSandboxEffectsUntilPolicyVerification"); }); it("carries authoritative rebuild state into sandbox creation (#7803)", async () => { @@ -624,38 +631,35 @@ describe("core onboard flow phases", () => { const providerResult = await providerPhase.run(context({ agent: { name: "hermes" } })); await sandboxPhase.run(providerResult.context); - expect(createSandbox.mock.calls[0]?.at(-2)).toMatchObject({ + expect((createSandbox.mock.calls[0] as unknown[] | undefined)?.[15]).toMatchObject({ rebuildPreservedEnv, rebuildPolicyPresets, }); }); - it("defers normal-entry credential provider effects until policy verification and checkpoint publication", async () => { + it("keeps ordinary provider effects on the create-time path", async () => { const events: string[] = []; const stageSandboxCredentialProviders = vi.fn(async () => { events.push("credential-provider-effect"); return []; }); const createSandbox = vi.fn(async (...args: unknown[]) => { - const createIntent = args.at(-2) as { + const createIntent = args[15] as { deferSandboxEffectsUntilPolicyVerification?: boolean; resolved?: { policy?: { basePolicyPath?: string } }; }; - const runVerifiedEffects = args.at(-1) as + const runVerifiedEffects = args[16] as | ((context: { revalidatePolicyRequirements: (operation: string) => void; }) => Promise) | undefined; expect(createIntent).toMatchObject({ - deferSandboxEffectsUntilPolicyVerification: true, resolved: { policy: { basePolicyPath: "/repo/policy.yaml" } }, }); - expect(runVerifiedEffects).toEqual(expect.any(Function)); - expect(stageSandboxCredentialProviders).not.toHaveBeenCalled(); - events.push("policy-verified", "checkpoint-published"); - await runVerifiedEffects?.({ - revalidatePolicyRequirements: () => events.push("policy-checkpoint-revalidated"), - }); + expect(createIntent.deferSandboxEffectsUntilPolicyVerification).toBeUndefined(); + expect(runVerifiedEffects).toBeUndefined(); + expect(stageSandboxCredentialProviders).toHaveBeenCalledOnce(); + events.push("sandbox-create"); return "created-sandbox"; }); const { providerInference: providerPhase, sandbox: sandboxPhase } = createPhases({ @@ -665,34 +669,391 @@ describe("core onboard flow phases", () => { const providerResult = await providerPhase.run(context()); await sandboxPhase.run(providerResult.context); - expect(events).toEqual([ - "policy-verified", - "checkpoint-published", - "policy-checkpoint-revalidated", - "credential-provider-effect", + expect(events).toEqual(["credential-provider-effect", "sandbox-create"]); + }); + + it.each([ + ["provider-backed input", { model: "gpt-5.4", provider: "nvidia-prod" }], + ["a nondefault agent", { agent: { name: "hermes" }, model: null, provider: null }], + ])("rejects %s before provider inference or sandbox effects", async (_label, patch) => { + const setupInference = vi.fn(async () => ({ ok: true as const })); + const reserveSandboxInferenceRoute = vi.fn(() => true); + const createSandbox = vi.fn(async () => "created-sandbox"); + const { providerInference: providerPhase } = createPhases({ + providerDeps: { reserveSandboxInferenceRoute, setupInference }, + sandboxOptions: { apfInterceptorRequested: true }, + sandboxDeps: { createSandbox }, + }); + + await expect( + providerPhase.run( + context({ + fresh: true, + selectedMessagingChannels: [], + ...patch, + }), + ), + ).rejects.toThrow(/supports providerless sandbox creation only/u); + + expect(setupInference).not.toHaveBeenCalled(); + expect(reserveSandboxInferenceRoute).not.toHaveBeenCalled(); + expect(createSandbox).not.toHaveBeenCalled(); + }); + + it.each([ + "NEMOCLAW_PROVIDER", + "NEMOCLAW_MODEL", + "NEMOCLAW_PROVIDER_MODEL", + "NEMOCLAW_SERVING_PRESET", + "NEMOCLAW_MESSAGING_PLAN_B64", + ])("rejects APF when %s requests a provider plan", async (key) => { + const reserveSandboxInferenceRoute = vi.fn(() => true); + const checkpointSandboxIdentity = vi.fn(async () => undefined); + const { providerInference: providerPhase } = createPhases({ + providerEnv: { [key]: "requested" }, + providerDeps: { checkpointSandboxIdentity, reserveSandboxInferenceRoute }, + sandboxOptions: { apfInterceptorRequested: true }, + }); + + await expect( + providerPhase.run( + context({ fresh: true, model: null, provider: null, selectedMessagingChannels: [] }), + ), + ).rejects.toThrow(/supports providerless sandbox creation only/u); + + expect(checkpointSandboxIdentity).not.toHaveBeenCalled(); + expect(reserveSandboxInferenceRoute).not.toHaveBeenCalled(); + }); + + it("rejects an explicit APF web-search provider before route reservation", async () => { + const reserveSandboxInferenceRoute = vi.fn(() => true); + const checkpointSandboxIdentity = vi.fn(async () => undefined); + const { providerInference: providerPhase } = createPhases({ + providerEnv: { NEMOCLAW_WEB_SEARCH_PROVIDER: "brave", BRAVE_API_KEY: "secret-value" }, + providerDeps: { checkpointSandboxIdentity, reserveSandboxInferenceRoute }, + sandboxOptions: { apfInterceptorRequested: true }, + }); + + await expect( + providerPhase.run( + context({ fresh: true, model: null, provider: null, selectedMessagingChannels: [] }), + ), + ).rejects.toThrow(/supports providerless sandbox creation only/u); + + expect(checkpointSandboxIdentity).not.toHaveBeenCalled(); + expect(reserveSandboxInferenceRoute).not.toHaveBeenCalled(); + }); + + it("rejects an extra-placeholder provider before route, credential, provider, or sandbox effects", async () => { + const credentialRead = vi.spyOn(credentialStore, "getCredential").mockReturnValue(null); + const setupInference = vi.fn(async () => ({ ok: true as const })); + const reserveSandboxInferenceRoute = vi.fn(() => true); + const checkpointSandboxIdentity = vi.fn(async () => undefined); + const stageSandboxCredentialProviders = vi.fn(); + const createSandbox = vi.fn(async () => "created-sandbox"); + const { providerInference: providerPhase } = createPhases({ + providerEnv: { + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: "TELEGRAM_BOT_TOKEN_AGENT_A", + TELEGRAM_BOT_TOKEN_AGENT_A: "secret-canary", + }, + providerDeps: { + checkpointSandboxIdentity, + reserveSandboxInferenceRoute, + setupInference, + }, + sandboxOptions: { apfInterceptorRequested: true }, + sandboxDeps: { createSandbox, stageSandboxCredentialProviders }, + }); + + try { + await expect( + providerPhase.run( + context({ fresh: true, model: null, provider: null, selectedMessagingChannels: [] }), + ), + ).rejects.toThrow(/supports providerless sandbox creation only/u); + + expect(checkpointSandboxIdentity).not.toHaveBeenCalled(); + expect(reserveSandboxInferenceRoute).not.toHaveBeenCalled(); + expect(credentialRead).not.toHaveBeenCalled(); + expect(setupInference).not.toHaveBeenCalled(); + expect(stageSandboxCredentialProviders).not.toHaveBeenCalled(); + expect(createSandbox).not.toHaveBeenCalled(); + } finally { + credentialRead.mockRestore(); + } + }); + + it("rejects APF messaging intent before route reservation or external effects", async () => { + const setupInference = vi.fn(async () => ({ ok: true as const })); + const reserveSandboxInferenceRoute = vi.fn(() => true); + const checkpointSandboxIdentity = vi.fn(async () => undefined); + const { providerInference: providerPhase } = createPhases({ + providerDeps: { + checkpointSandboxIdentity, + reserveSandboxInferenceRoute, + setupInference, + }, + sandboxOptions: { apfInterceptorRequested: true }, + }); + + await expect( + providerPhase.run( + context({ + fresh: true, + model: null, + provider: null, + selectedMessagingChannels: ["telegram"], + }), + ), + ).rejects.toThrow(/supports providerless sandbox creation only/u); + + expect(checkpointSandboxIdentity).not.toHaveBeenCalled(); + expect(reserveSandboxInferenceRoute).not.toHaveBeenCalled(); + expect(setupInference).not.toHaveBeenCalled(); + }); + + it("rejects APF when a serving profile requests an inference plan", async () => { + const session = createSession({ apfInterceptorRequested: true }); + session.servingProfileProvenance = {} as never; + const reserveSandboxInferenceRoute = vi.fn(() => true); + const checkpointSandboxIdentity = vi.fn(async () => undefined); + const { providerInference: providerPhase } = createPhases({ + providerDeps: { checkpointSandboxIdentity, reserveSandboxInferenceRoute }, + sandboxOptions: { apfInterceptorRequested: true }, + }); + + await expect( + providerPhase.run( + context({ + fresh: true, + session, + model: null, + provider: null, + selectedMessagingChannels: [], + }), + ), + ).rejects.toThrow(/supports providerless sandbox creation only/u); + + expect(checkpointSandboxIdentity).not.toHaveBeenCalled(); + expect(reserveSandboxInferenceRoute).not.toHaveBeenCalled(); + }); + + it("completes providerless APF after the verified sandbox-create boundary", async () => { + const setupNim = vi.fn(); + const setupInference = vi.fn(async () => ({ ok: true as const })); + let providerlessReservation: { + name: string; + gatewayName: string; + pendingRouteReservation: true; + reservationSessionId?: string; + provider: string | null; + model: string | null; + endpointUrl: string | null; + endpointSource: InferenceEndpointSource | null; + credentialEnv: string | null; + preferredInferenceApi: string | null; + } | null = null; + const reserveRoute = vi.fn( + ( + name: string, + route: Parameters[1], + ) => { + providerlessReservation = { + name, + pendingRouteReservation: true, + ...route, + }; + return true; + }, + ); + const updateSandboxRegistry = vi.fn(); + const recordStepComplete = vi.fn(async (_stepName: string, updates: SessionUpdates = {}) => { + Object.assign(session, updates); + return session; + }); + const createSandbox = vi.fn(async (...args: unknown[]) => { + expect(args[1]).toBe(""); + expect(args[2]).toBe(""); + expect(args[15]).toMatchObject({ + apfInterceptorRequested: true, + deferSandboxEffectsUntilPolicyVerification: true, + }); + return "created-sandbox"; + }); + const session = createSession({ apfInterceptorRequested: true }); + const { providerInference: providerPhase, sandbox: sandboxPhase } = createPhases({ + providerEnv: { NEMOCLAW_WEB_SEARCH_PROVIDER: "none" }, + providerDeps: { + reserveSandboxInferenceRoute: reserveRoute, + setupInference, + setupNim, + }, + sandboxOptions: { apfInterceptorRequested: true }, + sandboxDeps: { + createSandbox, + getSandboxRegistryEntry: () => providerlessReservation, + recordStepComplete, + setupMessagingChannels: vi.fn(async () => []), + updateSandboxRegistry, + }, + }); + const initial = context({ + fresh: true, + session, + model: null, + provider: null, + selectedMessagingChannels: [], + }); + + const providerResult = await providerPhase.run(initial); + expect(providerResult.result).toEqual([ + advanceTo("inference", { + metadata: { state: "provider_selection", providerlessApf: true }, + }), + advanceTo("sandbox", { + metadata: { state: "inference", providerlessApf: true }, + }), ]); + expect(reserveRoute).toHaveBeenCalledWith( + "my-sandbox", + expect.objectContaining({ + provider: null, + model: null, + gatewayName: "nemoclaw", + reservationSessionId: session.sessionId, + }), + { requireAbsent: true }, + ); + const sandboxResult = await sandboxPhase.run(providerResult.context); + + expect(sandboxResult.result).toMatchObject({ type: "complete" }); + expect( + isCoreFlowCompleteBeforeFinalization({ + context: sandboxResult.context, + session: { machine: { state: "complete" } }, + }), + ).toBe(true); + expect(setupNim).not.toHaveBeenCalled(); + expect(setupInference).not.toHaveBeenCalled(); + expect(createSandbox).toHaveBeenCalledOnce(); + expect(updateSandboxRegistry).toHaveBeenCalledWith( + "created-sandbox", + expect.not.objectContaining({ model: expect.anything(), provider: expect.anything() }), + ); + const sandboxCompletion = recordStepComplete.mock.calls.find(([step]) => step === "sandbox"); + expect(sandboxCompletion?.[1]).not.toHaveProperty("model"); + expect(sandboxCompletion?.[1]).not.toHaveProperty("provider"); + }); + + it.each([ + ["registered", true, false], + ["live", false, true], + ] as const)( + "rejects a %s APF sandbox-name collision without changing registry or external state", + async (_label, registered, liveExists) => { + const existingEntry = registered + ? { + name: "my-sandbox", + provider: "nim", + model: "nvidia/test", + gatewayName: "nemoclaw", + } + : null; + const originalEntry = structuredClone(existingEntry); + const reserveRoute = vi.fn(() => true); + const checkpointSandboxIdentity = vi.fn(async () => undefined); + const createSandbox = vi.fn(async () => "created-sandbox"); + const stageSandboxCredentialProviders = vi.fn(async () => []); + const { providerInference: providerPhase } = createPhases({ + inspectSandboxForCreate: () => ({ + existingEntry, + preservedMcpState: undefined, + liveExists, + }), + providerDeps: { checkpointSandboxIdentity, reserveSandboxInferenceRoute: reserveRoute }, + sandboxOptions: { apfInterceptorRequested: true }, + sandboxDeps: { createSandbox, stageSandboxCredentialProviders }, + }); + + await expect( + providerPhase.run( + context({ + fresh: true, + session: createSession({ apfInterceptorRequested: true }), + selectedMessagingChannels: [], + }), + ), + ).rejects.toThrow(/cannot adopt existing sandbox/u); + + expect(existingEntry).toEqual(originalEntry); + expect(checkpointSandboxIdentity).not.toHaveBeenCalled(); + expect(reserveRoute).not.toHaveBeenCalled(); + expect(stageSandboxCredentialProviders).not.toHaveBeenCalled(); + expect(createSandbox).not.toHaveBeenCalled(); + }, + ); + + it("refuses an APF reservation race without sandbox, credential, or provider effects", async () => { + const reserveRoute = vi.fn(() => false); + const createSandbox = vi.fn(async () => "created-sandbox"); + const stageSandboxCredentialProviders = vi.fn(async () => []); + const { providerInference: providerPhase } = createPhases({ + providerDeps: { reserveSandboxInferenceRoute: reserveRoute }, + sandboxOptions: { apfInterceptorRequested: true }, + sandboxDeps: { createSandbox, stageSandboxCredentialProviders }, + }); + + await expect( + providerPhase.run( + context({ + fresh: true, + session: createSession({ apfInterceptorRequested: true }), + selectedMessagingChannels: [], + }), + ), + ).rejects.toThrow(/could not reserve sandbox/u); + + expect(reserveRoute).toHaveBeenCalledWith("my-sandbox", expect.any(Object), { + requireAbsent: true, + }); + expect(stageSandboxCredentialProviders).not.toHaveBeenCalled(); + expect(createSandbox).not.toHaveBeenCalled(); }); it.each([ ["post-create policy verification", "policy verification refused"], ["durable checkpoint publication", "checkpoint publication refused"], - ])("withholds normal-entry provider effects when %s fails", async (_boundary, failure) => { + ])("withholds APF provider effects when %s fails", async (_boundary, failure) => { const stageSandboxCredentialProviders = vi.fn(async () => []); const createSandbox = vi.fn(async (...args: unknown[]) => { - const createIntent = args.at(-2) as { + const createIntent = args[15] as { deferSandboxEffectsUntilPolicyVerification?: boolean; }; - const runVerifiedEffects = args.at(-1); + const runVerifiedEffects = args[16]; expect(createIntent.deferSandboxEffectsUntilPolicyVerification).toBe(true); expect(runVerifiedEffects).toEqual(expect.any(Function)); expect(stageSandboxCredentialProviders).not.toHaveBeenCalled(); throw new Error(failure); }); + const session = createSession({ apfInterceptorRequested: true }); const { providerInference: providerPhase, sandbox: sandboxPhase } = createPhases({ - sandboxDeps: { createSandbox, stageSandboxCredentialProviders }, + sandboxOptions: { apfInterceptorRequested: true }, + sandboxDeps: { + createSandbox, + getSandboxRegistryEntry: () => ({ + name: "my-sandbox", + gatewayName: "nemoclaw", + pendingRouteReservation: true, + reservationSessionId: session.sessionId, + }), + setupMessagingChannels: vi.fn(async () => []), + stageSandboxCredentialProviders, + }, }); - const providerResult = await providerPhase.run(context()); + const providerResult = await providerPhase.run( + context({ fresh: true, session, selectedMessagingChannels: [] }), + ); await expect(sandboxPhase.run(providerResult.context)).rejects.toThrow(failure); expect(stageSandboxCredentialProviders).not.toHaveBeenCalled(); @@ -825,155 +1186,172 @@ describe("core onboard flow phases", () => { false, ], ["provider-mismatched", "nvidia-prod", "https://persisted.example.test/v1", null, null, false], - ] as const)("binds %s persisted onboard provenance to its exact provider endpoint", async (_label, registeredProvider, registeredEndpointUrl, expectedSource, expectedOnboardEndpointUrl, expectTrustedUrl) => { - const setupInference = vi.fn(async () => ({ ok: true as const })); - const updateSandboxRegistry = vi.fn(); - const getSandboxRegistryEntry = vi.fn((_sandboxName: string) => ({ - name: "my-sandbox", - provider: registeredProvider, - model: "custom/model", - endpointUrl: registeredEndpointUrl, - endpointSource: "onboard" as const, - credentialEnv: "COMPATIBLE_API_KEY", - preferredInferenceApi: "openai-completions", - gatewayName: "nemoclaw", - gpuEnabled: false, - policies: [], - })); - const { providerInference: providerPhase, sandbox: sandboxPhase } = createPhases({ - providerDeps: { - setupInference, - hydrateCredentialEnv: vi.fn(() => "host-key"), - }, - endpointProvenance: { - getSandboxRegistryEntry, - }, - sandboxDeps: { updateSandboxRegistry }, - }); - const session = createSession({ - provider: "compatible-endpoint", - model: "custom/model", - endpointUrl: "https://persisted.example.test/v1", - credentialEnv: "COMPATIBLE_API_KEY", - preferredInferenceApi: "openai-completions", - steps: { provider_selection: completeStep() }, - }); - - const result = await providerPhase.run( - context({ - resume: true, - session, + ] as const)( + "binds %s persisted onboard provenance to its exact provider endpoint", + async ( + _label, + registeredProvider, + registeredEndpointUrl, + expectedSource, + expectedOnboardEndpointUrl, + expectTrustedUrl, + ) => { + const setupInference = vi.fn(async () => ({ ok: true as const })); + const updateSandboxRegistry = vi.fn(); + const getSandboxRegistryEntry = vi.fn((_sandboxName: string) => ({ + name: "my-sandbox", + provider: registeredProvider, + model: "custom/model", + endpointUrl: registeredEndpointUrl, + endpointSource: "onboard" as const, + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + gatewayName: "nemoclaw", + gpuEnabled: false, + policies: [], + })); + const { providerInference: providerPhase, sandbox: sandboxPhase } = createPhases({ + providerDeps: { + setupInference, + hydrateCredentialEnv: vi.fn(() => "host-key"), + }, + endpointProvenance: { + getSandboxRegistryEntry, + }, + sandboxDeps: { updateSandboxRegistry }, + }); + const session = createSession({ provider: "compatible-endpoint", model: "custom/model", endpointUrl: "https://persisted.example.test/v1", credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-completions", - }), - ); + steps: { provider_selection: completeStep() }, + }); + + const result = await providerPhase.run( + context({ + resume: true, + session, + provider: "compatible-endpoint", + model: "custom/model", + endpointUrl: "https://persisted.example.test/v1", + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + }), + ); - const inferenceOptions = setupInference.mock.calls[0]?.at(-1) as - | { endpointSource?: string | null; onboardEndpointUrl?: string } - | undefined; - expect(inferenceOptions).toMatchObject({ endpointSource: expectedSource }); - expect(inferenceOptions?.onboardEndpointUrl ?? null).toBe(expectedOnboardEndpointUrl); - expect(Object.hasOwn(inferenceOptions ?? {}, "onboardEndpointUrl")).toBe(expectTrustedUrl); - expect(result.context.endpointSource).toBe(expectedSource); - expect(result.context.onboardEndpointUrl ?? null).toBe(expectedOnboardEndpointUrl); - expect(getSandboxRegistryEntry).toHaveBeenCalledWith("my-sandbox"); + const inferenceOptions = setupInference.mock.calls[0]?.at(-1) as + | { endpointSource?: string | null; onboardEndpointUrl?: string } + | undefined; + expect(inferenceOptions).toMatchObject({ endpointSource: expectedSource }); + expect(inferenceOptions?.onboardEndpointUrl ?? null).toBe(expectedOnboardEndpointUrl); + expect(Object.hasOwn(inferenceOptions ?? {}, "onboardEndpointUrl")).toBe(expectTrustedUrl); + expect(result.context.endpointSource).toBe(expectedSource); + expect(result.context.onboardEndpointUrl ?? null).toBe(expectedOnboardEndpointUrl); + expect(getSandboxRegistryEntry).toHaveBeenCalledWith("my-sandbox"); - await sandboxPhase.run(result.context); + await sandboxPhase.run(result.context); - expect(updateSandboxRegistry).toHaveBeenCalledWith( - "created-sandbox", - expect.objectContaining({ endpointSource: expectedSource }), - ); - }); + expect(updateSandboxRegistry).toHaveBeenCalledWith( + "created-sandbox", + expect.objectContaining({ endpointSource: expectedSource }), + ); + }, + ); it.each([ ["fresh", false], ["resumed", true], - ] as const)("uses the strict runner for %s provider selection sessions", async (_label, resume) => { - const phaseCalls: string[] = []; - const appliedTransitions: string[] = []; - const sandboxEffect = vi.fn(); - let runtimeSession = createSession({ - machine: { - version: 1, - state: "provider_selection", - stateEnteredAt: "2026-06-09T00:00:00.000Z", - revision: 1, - }, - }); - const runProviderInference = vi.fn((ctx: CoreContext) => { - phaseCalls.push("provider_selection"); - return { - context: { ...ctx, endpointUrl: "https://example.test/v1" }, - result: [ - advanceTo("inference", { metadata: { state: "provider_selection" } }), - advanceTo("sandbox", { metadata: { state: "inference" } }), - ], - }; - }); - const runSandbox = vi.fn((ctx: CoreContext) => { - phaseCalls.push("sandbox"); - sandboxEffect(ctx); - return { - context: { ...ctx, sandboxName: "created-sandbox" }, - result: branchTo("openclaw", { metadata: { state: "sandbox" } }), + ] as const)( + "uses the strict runner for %s provider selection sessions", + async (_label, resume) => { + const phaseCalls: string[] = []; + const appliedTransitions: string[] = []; + const sandboxEffect = vi.fn(); + let runtimeSession = createSession({ + machine: { + version: 1, + state: "provider_selection", + stateEnteredAt: "2026-06-09T00:00:00.000Z", + revision: 1, + }, + }); + const runProviderInference = vi.fn((ctx: CoreContext) => { + phaseCalls.push("provider_selection"); + return { + context: { ...ctx, endpointUrl: "https://example.test/v1" }, + result: [ + advanceTo("inference", { metadata: { state: "provider_selection" } }), + advanceTo("sandbox", { metadata: { state: "inference" } }), + ], + }; + }); + const runSandbox = vi.fn((ctx: CoreContext) => { + phaseCalls.push("sandbox"); + sandboxEffect(ctx); + return { + context: { ...ctx, sandboxName: "created-sandbox" }, + result: branchTo("openclaw", { metadata: { state: "sandbox" } }), + }; + }); + const phases: CoreOnboardFlowPhases = { + providerInference: { + state: "provider_selection", + run: runProviderInference, + }, + sandbox: { + state: "sandbox", + run: runSandbox, + }, }; - }); - const phases: CoreOnboardFlowPhases = { - providerInference: { - state: "provider_selection", - run: runProviderInference, - }, - sandbox: { - state: "sandbox", - run: runSandbox, - }, - }; - const result = await runCoreOnboardFlowSlice({ - context: context({ + const result = await runCoreOnboardFlowSlice({ + context: context({ + resume, + fresh: !resume, + model: "nvidia/test", + provider: "nim", + }), + runtime: { + session: async () => runtimeSession, + applyResult: async (stateResult) => { + const transition = stateResult as ReturnType; + appliedTransitions.push(`${transition.transitionKind}:${transition.next}`); + runtimeSession = createSession({ + machine: { + version: 1, + state: transition.next, + stateEnteredAt: "2026-06-09T00:03:00.000Z", + revision: runtimeSession.machine.revision + 1, + }, + }); + return runtimeSession; + }, + }, + phases, resume, - fresh: !resume, - model: "nvidia/test", - provider: "nim", - }), - runtime: { - session: async () => runtimeSession, - applyResult: async (stateResult) => { - const transition = stateResult as ReturnType; - appliedTransitions.push(`${transition.transitionKind}:${transition.next}`); - runtimeSession = createSession({ - machine: { - version: 1, - state: transition.next, - stateEnteredAt: "2026-06-09T00:03:00.000Z", - revision: runtimeSession.machine.revision + 1, - }, - }); - return runtimeSession; + recordRepairEvent: async () => { + throw new Error("repair recorder should not run on the exact-entry path"); }, - }, - phases, - resume, - recordRepairEvent: async () => { - throw new Error("repair recorder should not run on the exact-entry path"); - }, - }); + }); - expect(phaseCalls).toEqual(["provider_selection", "sandbox"]); - expect(runProviderInference).toHaveBeenCalledOnce(); - expect(runSandbox).toHaveBeenCalledOnce(); - expect(sandboxEffect).toHaveBeenCalledOnce(); - expect(sandboxEffect).toHaveBeenCalledWith( - expect.objectContaining({ endpointUrl: "https://example.test/v1" }), - ); - expect(appliedTransitions).toEqual(["advance:inference", "advance:sandbox", "branch:openclaw"]); - expect(result.context.endpointUrl).toBe("https://example.test/v1"); - expect(result.context.sandboxName).toBe("created-sandbox"); - expect(result.session.machine.state).toBe("openclaw"); - }); + expect(phaseCalls).toEqual(["provider_selection", "sandbox"]); + expect(runProviderInference).toHaveBeenCalledOnce(); + expect(runSandbox).toHaveBeenCalledOnce(); + expect(sandboxEffect).toHaveBeenCalledOnce(); + expect(sandboxEffect).toHaveBeenCalledWith( + expect.objectContaining({ endpointUrl: "https://example.test/v1" }), + ); + expect(appliedTransitions).toEqual([ + "advance:inference", + "advance:sandbox", + "branch:openclaw", + ]); + expect(result.context.endpointUrl).toBe("https://example.test/v1"); + expect(result.context.sandboxName).toBe("created-sandbox"); + expect(result.session.machine.state).toBe("openclaw"); + }, + ); it("runs the sandbox effect once at exact sandbox entry", async () => { const createSandbox = vi.fn(async () => "created-sandbox"); @@ -1032,176 +1410,76 @@ describe("core onboard flow phases", () => { ["inference", true, ["advance:sandbox", "branch:openclaw"]], ["sandbox", true, ["branch:openclaw"]], ["sandbox", false, ["branch:openclaw"]], - ] as const)("repairs provider context before strict %s entry", async (state, resume, expected) => { - const calls: string[] = []; - const applied: string[] = []; - const repairEvents: string[] = []; - let runtimeSession = createSession({ - machine: { - version: 1, - state, - stateEnteredAt: "2026-06-09T00:02:00.000Z", - revision: 7, - }, - }); - const phases: CoreOnboardFlowPhases = { - providerInference: { - state: "provider_selection", - run: (ctx) => { - calls.push("provider_selection"); - return { - context: { ...ctx, endpointUrl: "https://example.test/v1" }, - result: [ - advanceTo("inference", { metadata: { state: "provider_selection" } }), - advanceTo("sandbox", { metadata: { state: "inference" } }), - ], - }; + ] as const)( + "repairs provider context before strict %s entry", + async (state, resume, expected) => { + const calls: string[] = []; + const applied: string[] = []; + const repairEvents: string[] = []; + let runtimeSession = createSession({ + machine: { + version: 1, + state, + stateEnteredAt: "2026-06-09T00:02:00.000Z", + revision: 7, }, - }, - sandbox: { - state: "sandbox", - run: (ctx) => { - calls.push("sandbox"); - return { - context: { ...ctx, sandboxName: "created-sandbox" }, - result: branchTo("openclaw", { metadata: { state: "sandbox" } }), - }; - }, - }, - }; - - const result = await runCoreOnboardFlowSlice({ - context: context({ resume }), - runtime: { - session: async () => runtimeSession, - applyResult: async (stateResult) => { - if (stateResult.type === "transition") { - applied.push(`${stateResult.transitionKind}:${stateResult.next}`); - runtimeSession.machine = { - ...runtimeSession.machine, - state: stateResult.next, - revision: runtimeSession.machine.revision + 1, + }); + const phases: CoreOnboardFlowPhases = { + providerInference: { + state: "provider_selection", + run: (ctx) => { + calls.push("provider_selection"); + return { + context: { ...ctx, endpointUrl: "https://example.test/v1" }, + result: [ + advanceTo("inference", { metadata: { state: "provider_selection" } }), + advanceTo("sandbox", { metadata: { state: "inference" } }), + ], }; - } - return runtimeSession; + }, }, - }, - phases, - resume, - recordRepairEvent: repairRecorder(repairEvents), - }); - - expect(calls).toEqual(["provider_selection", "sandbox"]); - expect(applied).toEqual(expected); - expect(repairEvents).toEqual([ - "state.repair.started:provider_selection", - "state.repair.completed:provider_selection", - ]); - expect(result.context.endpointUrl).toBe("https://example.test/v1"); - expect(result.context.sandboxName).toBe("created-sandbox"); - expect(result.session.machine.state).toBe("openclaw"); - }); - - it.each([ - "openclaw", - "agent_setup", - "policies", - "finalizing", - "post_verify", - ] as const)("repairs core prerequisites without changing resumed %s entry", async (state) => { - const repairEvents: string[] = []; - const branchState = state === "agent_setup" ? "agent_setup" : "openclaw"; - const session = createSession({ - machine: { - version: 1, - state, - stateEnteredAt: "2026-06-09T00:02:00.000Z", - revision: 7, - }, - }); - const phases: CoreOnboardFlowPhases = { - providerInference: { - state: "provider_selection", - run: (ctx) => ({ - context: { ...ctx, endpointUrl: "https://example.test/v1" }, - result: [ - advanceTo("inference", { metadata: { state: "provider_selection" } }), - advanceTo("sandbox", { metadata: { state: "inference" } }), - ], - }), - }, - sandbox: { - state: "sandbox", - run: (ctx) => ({ - context: { ...ctx, sandboxName: "created-sandbox" }, - result: branchTo(branchState, { metadata: { state: "sandbox" } }), - }), - }, - }; - - const result = await runCoreOnboardFlowSlice({ - context: context({ resume: true }), - runtime: { - session: async () => session, - applyResult: async () => { - throw new Error("prerequisite repair must not apply a machine result"); + sandbox: { + state: "sandbox", + run: (ctx) => { + calls.push("sandbox"); + return { + context: { ...ctx, sandboxName: "created-sandbox" }, + result: branchTo("openclaw", { metadata: { state: "sandbox" } }), + }; + }, }, - }, - phases, - resume: true, - recordRepairEvent: repairRecorder(repairEvents), - }); - - expect(repairEvents).toEqual([ - "state.repair.started:provider_selection", - "state.repair.completed:provider_selection", - "state.repair.started:sandbox", - "state.repair.completed:sandbox", - ]); - expect(result.session.machine.state).toBe(state); - expect(result.context.sandboxName).toBe("created-sandbox"); - }); - - it.each([ - "complete", - "failed", - ] as const)("rejects terminal %s sessions before core repair effects", async (state) => { - const providerInference: OnboardSequencePhase = { - state: "provider_selection", - run: vi.fn((ctx) => ({ - context: ctx, - result: advanceTo("sandbox", { metadata: { state: "inference" } }), - })), - }; - const sandbox: OnboardSequencePhase = { - state: "sandbox", - run: vi.fn((ctx) => ({ - context: ctx, - result: branchTo("openclaw", { metadata: { state: "sandbox" } }), - })), - }; + }; - await expect( - runCoreOnboardFlowSlice({ - context: context({ resume: true }), + const result = await runCoreOnboardFlowSlice({ + context: context({ resume }), runtime: { - session: async () => - createSession({ - machine: { - version: 1, - state, - stateEnteredAt: "2026-06-09T00:00:00.000Z", - revision: 7, - }, - }), - applyResult: async () => createSession(), + session: async () => runtimeSession, + applyResult: async (stateResult) => { + if (stateResult.type === "transition") { + applied.push(`${stateResult.transitionKind}:${stateResult.next}`); + runtimeSession.machine = { + ...runtimeSession.machine, + state: stateResult.next, + revision: runtimeSession.machine.revision + 1, + }; + } + return runtimeSession; + }, }, - phases: { providerInference, sandbox }, - resume: true, - recordRepairEvent: repairRecorder(), - }), - ).rejects.toThrow("Unexpected onboarding flow state before slice entry"); - expect(providerInference.run).not.toHaveBeenCalled(); - expect(sandbox.run).not.toHaveBeenCalled(); - }); + phases, + resume, + recordRepairEvent: repairRecorder(repairEvents), + }); + + expect(calls).toEqual(["provider_selection", "sandbox"]); + expect(applied).toEqual(expected); + expect(repairEvents).toEqual([ + "state.repair.started:provider_selection", + "state.repair.completed:provider_selection", + ]); + expect(result.context.endpointUrl).toBe("https://example.test/v1"); + expect(result.context.sandboxName).toBe("created-sandbox"); + expect(result.session.machine.state).toBe("openclaw"); + }, + ); }); diff --git a/src/lib/onboard/machine/core-flow-phases.ts b/src/lib/onboard/machine/core-flow-phases.ts index c6f94e514e6..556ef4e016f 100644 --- a/src/lib/onboard/machine/core-flow-phases.ts +++ b/src/lib/onboard/machine/core-flow-phases.ts @@ -7,6 +7,7 @@ import { } from "../../inference/selection"; import type { WebSearchConfig } from "../../inference/web-search"; import type { DcodeAutoApprovalMode } from "../dcode-auto-approval"; +import { assertProviderlessInterceptorEnvironment } from "../entry-options"; import type { createProviderRecoveryReceiptLedger, ProviderRecoveryReceipt, @@ -19,6 +20,7 @@ import { import { createProviderInferencePhase, createSandboxPhase } from "./flow-phases/provider-sandbox"; import { UnexpectedOnboardFlowSliceStateError } from "./flow-slice-error"; import { runCoreOnboardFlowSequence } from "./flow-slices"; +import { advanceTo } from "./result"; import { handleProviderInferenceState, type ProviderInferenceStateOptions, @@ -52,9 +54,11 @@ export interface ProviderInferenceOnboardFlowPhaseOptions< gatewayName: string; forceProviderSelection: boolean; forceInferenceSetup?: boolean; + apfInterceptorRequested?: boolean; authoritativeResumeConfig?: boolean; providerRecoveryReceipt?: ProviderRecoveryReceipt | null; providerRecoveryReceiptLedger?: ReturnType; + inspectSandboxForCreate: import("../sandbox-lifecycle").SandboxLifecycleHelpers["inspectSandboxForCreate"]; endpointProvenance: EndpointProvenanceOptions; env: NodeJS.ProcessEnv; constants: ProviderInferenceStateOptions["constants"]; @@ -105,6 +109,47 @@ interface EndpointProvenance { onboardEndpointUrl: string | null; } +export function isCoreFlowCompleteBeforeFinalization(result: { + readonly context: Pick; + readonly session: { readonly machine: { readonly state: string } }; +}): boolean { + return ( + result.context.providerlessApf === true && + result.session.machine.state === "complete" && + Boolean(result.context.sandboxName) + ); +} + +function hasProviderBackedApfIntent(context: OnboardFlowContext): boolean { + const requestedAgentName = (context.agent as { readonly name?: unknown } | null)?.name; + const requestsNondefaultAgent = + typeof requestedAgentName === "string" && + requestedAgentName.trim().toLowerCase() !== "openclaw"; + const routeValues = [ + context.provider, + context.model, + context.endpointUrl, + context.onboardEndpointUrl, + context.credentialEnv, + context.preferredInferenceApi, + context.compatibleEndpointReasoning, + context.compatibleEndpointReasoningEffort, + context.nimContainer, + ]; + return ( + requestsNondefaultAgent || + routeValues.some((value) => typeof value === "string" && value.trim().length > 0) || + context.endpointSource != null || + context.selectedMessagingChannels.length > 0 || + context.hermesToolGateways.length > 0 || + context.webSearchConfig !== null || + Boolean(context.session?.messagingPlan) || + context.hostLocalInferenceRouteOnly === true || + context.hostLocalInferenceSandboxProofAuthority != null || + context.session?.servingProfileProvenance != null + ); +} + function endpointProvenanceForPhase( context: Pick, options: EndpointProvenanceOptions, @@ -143,6 +188,64 @@ export function createProviderInferenceOnboardFlowPhase< Host = unknown, >(options: ProviderInferenceOnboardFlowPhaseOptions): OnboardSequencePhase { return createProviderInferencePhase(async (context) => { + if ( + options.apfInterceptorRequested === true || + context.session?.apfInterceptorRequested === true + ) { + assertProviderlessInterceptorEnvironment(true, options.env); + if (hasProviderBackedApfIntent(context)) { + throw new Error( + "Interceptor onboarding supports providerless sandbox creation only. No sandbox or provider was created.", + ); + } + const sandboxName = + context.sandboxName ?? (await options.deps.promptValidatedSandboxName(context.agent)); + const reservationSessionId = context.session?.sessionId; + if (!reservationSessionId) { + throw new Error( + "APF interceptor onboarding requires a durable session before providerless sandbox creation.", + ); + } + const observed = options.inspectSandboxForCreate(sandboxName); + if (observed.existingEntry || observed.liveExists) { + throw new Error( + `APF interceptor selection cannot adopt existing sandbox '${sandboxName}'. Choose a new sandbox name.`, + ); + } + await options.deps.checkpointSandboxIdentity(sandboxName, context.agent); + const reserved = await options.deps.withGatewayRouteMutationLock(options.gatewayName, () => + options.deps.reserveSandboxInferenceRoute( + sandboxName, + { + provider: null, + model: null, + endpointUrl: null, + endpointSource: null, + credentialEnv: null, + preferredInferenceApi: null, + gatewayName: options.gatewayName, + reservationSessionId, + }, + { requireAbsent: true }, + ), + ); + if (!reserved) { + throw new Error( + `APF interceptor onboarding could not reserve sandbox '${sandboxName}' for verified providerless creation.`, + ); + } + return { + context: { ...context, sandboxName, providerlessApf: true }, + result: [ + advanceTo("inference", { + metadata: { state: "provider_selection", providerlessApf: true }, + }), + advanceTo("sandbox", { + metadata: { state: "inference", providerlessApf: true }, + }), + ], + }; + } const endpointProvenance = endpointProvenanceForPhase(context, options.endpointProvenance); const providerInferenceResult = await handleProviderInferenceState({ gatewayName: options.gatewayName, @@ -232,7 +335,7 @@ export function createSandboxOnboardFlowPhase< apfInterceptorRequested: options.apfInterceptorRequested === true, authoritativeResumeConfig: options.authoritativeResumeConfig, authoritativePolicyTier: options.authoritativePolicyTier, - deferSandboxEffectsUntilPolicyVerification: true, + deferSandboxEffectsUntilPolicyVerification: options.apfInterceptorRequested === true, recreateJournalTargetIntentFingerprint: options.recreateJournalTargetIntentFingerprint, endpointSource: endpointProvenance.endpointSource, @@ -245,8 +348,8 @@ export function createSandboxOnboardFlowPhase< recreateSandbox: options.recreateSandbox, session: context.session, sandboxName: context.sandboxName, - model: context.model, - provider: context.provider, + model: context.model ?? "", + provider: context.provider ?? "", endpointUrl: context.endpointUrl, compatibleEndpointReasoning: context.compatibleEndpointReasoning, credentialEnv: context.credentialEnv, diff --git a/src/lib/onboard/machine/core-flow-prerequisite-repair.test.ts b/src/lib/onboard/machine/core-flow-prerequisite-repair.test.ts new file mode 100644 index 00000000000..92033bd73fa --- /dev/null +++ b/src/lib/onboard/machine/core-flow-prerequisite-repair.test.ts @@ -0,0 +1,154 @@ +// 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 { createSession } from "../../state/onboard-session"; +import { type CoreOnboardFlowPhases, runCoreOnboardFlowSlice } from "./core-flow-phases"; +import type { OnboardFlowContext } from "./flow-context"; +import type { OnboardPrerequisiteRepairEventRecorder } from "./prerequisite-repair"; +import { advanceTo, branchTo } from "./result"; +import type { OnboardSequencePhase } from "./sequence-runner"; + +type Agent = { name: string }; +type Gpu = { platform: string }; +type SandboxGpuConfig = { mode: string }; +type CoreContext = OnboardFlowContext; + +function context(patch: Partial = {}): CoreContext { + return { + resume: false, + fresh: false, + session: createSession(), + agent: { name: "openclaw" }, + recordedSandboxName: null, + requestedSandboxName: null, + sandboxName: "my-sandbox", + fromDockerfile: null, + model: null, + provider: null, + endpointUrl: null, + credentialEnv: null, + hermesAuthMethod: null, + hermesToolGateways: [], + preferredInferenceApi: null, + compatibleEndpointReasoning: null, + compatibleEndpointReasoningEffort: null, + nimContainer: null, + webSearchConfig: null, + webSearchSupported: false, + selectedMessagingChannels: ["slack"], + gpu: { platform: "linux" }, + sandboxGpuConfig: { mode: "cdi" }, + gpuPassthrough: true, + ...patch, + }; +} + +function repairRecorder(events: string[] = []): OnboardPrerequisiteRepairEventRecorder { + return async (type, options) => { + events.push(`${type}:${options.state ?? "unknown"}`); + }; +} + +describe("core onboard prerequisite repair", () => { + it.each(["openclaw", "agent_setup", "policies", "finalizing", "post_verify"] as const)( + "repairs core prerequisites without changing resumed %s entry", + async (state) => { + const repairEvents: string[] = []; + const branchState = state === "agent_setup" ? "agent_setup" : "openclaw"; + const session = createSession({ + machine: { + version: 1, + state, + stateEnteredAt: "2026-06-09T00:02:00.000Z", + revision: 7, + }, + }); + const phases: CoreOnboardFlowPhases = { + providerInference: { + state: "provider_selection", + run: (ctx) => ({ + context: { ...ctx, endpointUrl: "https://example.test/v1" }, + result: [ + advanceTo("inference", { metadata: { state: "provider_selection" } }), + advanceTo("sandbox", { metadata: { state: "inference" } }), + ], + }), + }, + sandbox: { + state: "sandbox", + run: (ctx) => ({ + context: { ...ctx, sandboxName: "created-sandbox" }, + result: branchTo(branchState, { metadata: { state: "sandbox" } }), + }), + }, + }; + + const result = await runCoreOnboardFlowSlice({ + context: context({ resume: true }), + runtime: { + session: async () => session, + applyResult: async () => { + throw new Error("prerequisite repair must not apply a machine result"); + }, + }, + phases, + resume: true, + recordRepairEvent: repairRecorder(repairEvents), + }); + + expect(repairEvents).toEqual([ + "state.repair.started:provider_selection", + "state.repair.completed:provider_selection", + "state.repair.started:sandbox", + "state.repair.completed:sandbox", + ]); + expect(result.session.machine.state).toBe(state); + expect(result.context.sandboxName).toBe("created-sandbox"); + }, + ); + + it.each(["complete", "failed"] as const)( + "rejects terminal %s sessions before core repair effects", + async (state) => { + const providerInference: OnboardSequencePhase = { + state: "provider_selection", + run: vi.fn((ctx) => ({ + context: ctx, + result: advanceTo("sandbox", { metadata: { state: "inference" } }), + })), + }; + const sandbox: OnboardSequencePhase = { + state: "sandbox", + run: vi.fn((ctx) => ({ + context: ctx, + result: branchTo("openclaw", { metadata: { state: "sandbox" } }), + })), + }; + + await expect( + runCoreOnboardFlowSlice({ + context: context({ resume: true }), + runtime: { + session: async () => + createSession({ + machine: { + version: 1, + state, + stateEnteredAt: "2026-06-09T00:00:00.000Z", + revision: 7, + }, + }), + applyResult: async () => createSession(), + }, + phases: { providerInference, sandbox }, + resume: true, + recordRepairEvent: repairRecorder(), + }), + ).rejects.toThrow("Unexpected onboarding flow state before slice entry"); + expect(providerInference.run).not.toHaveBeenCalled(); + expect(sandbox.run).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/src/lib/onboard/machine/flow-context.ts b/src/lib/onboard/machine/flow-context.ts index a1fab15c506..73df46ed8ae 100644 --- a/src/lib/onboard/machine/flow-context.ts +++ b/src/lib/onboard/machine/flow-context.ts @@ -33,6 +33,8 @@ export interface OnboardFlowContext( - context: ProviderModelSelectedOnboardFlowContext, + context: Context, patch: SandboxCreatedContextUpdate, -): SandboxCreatedOnboardFlowContext { +): Context & { sandboxName: string } { return { ...context, ...patch }; } diff --git a/src/lib/onboard/machine/flow-phases/provider-sandbox.ts b/src/lib/onboard/machine/flow-phases/provider-sandbox.ts index 739241adcbc..852cbb338fb 100644 --- a/src/lib/onboard/machine/flow-phases/provider-sandbox.ts +++ b/src/lib/onboard/machine/flow-phases/provider-sandbox.ts @@ -1,27 +1,19 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { - OnboardFlowContext, - OnboardFlowPhaseResult, - ProviderModelSelectedOnboardFlowContext, - ProviderSelectedOnboardFlowContext, - SandboxCreatedOnboardFlowContext, -} from "../flow-context"; +import type { OnboardFlowContext, OnboardFlowPhaseResult } from "../flow-context"; import { assertProviderSelectedContext, onboardFlowPhaseResult } from "../flow-context"; import type { OnboardSequencePhase } from "../sequence-runner"; type ProviderInferencePhaseHandler = ( context: Context, ) => Promise<{ - context: ProviderModelSelectedOnboardFlowContext; + context: Context; result: OnboardFlowPhaseResult["result"]; }>; -type SandboxPhaseHandler = ( - context: ProviderSelectedOnboardFlowContext, -) => Promise<{ - context: SandboxCreatedOnboardFlowContext; +type SandboxPhaseHandler = (context: Context) => Promise<{ + context: Context & { sandboxName: string }; result: OnboardFlowPhaseResult["result"]; }>; @@ -43,7 +35,9 @@ export function createSandboxPhase( return { state: "sandbox", async run(context) { - assertProviderSelectedContext(context, "sandbox setup"); + if (context.providerlessApf !== true) { + assertProviderSelectedContext(context, "sandbox setup"); + } const result = await runSandbox(context); return onboardFlowPhaseResult(result.context, result.result); }, diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 246ceb32fb7..882926f67b9 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -278,8 +278,8 @@ export interface ProviderInferenceStateOptions { reserveSandboxInferenceRoute( sandboxName: string, route: { - provider: string; - model: string; + provider: string | null; + model: string | null; endpointUrl: string | null; endpointSource: InferenceEndpointSource | null; credentialEnv: string | null; @@ -287,6 +287,7 @@ export interface ProviderInferenceStateOptions { gatewayName: string; reservationSessionId?: string; }, + options?: { requireAbsent?: boolean }, ): boolean; registryUpdateSandbox(sandboxName: string, updates: { nimContainer?: string | null }): void; checkpointSandboxIdentity(sandboxName: string, agent: Agent): Promise; diff --git a/src/lib/onboard/machine/handlers/sandbox-apf.test.ts b/src/lib/onboard/machine/handlers/sandbox-apf.test.ts index d23ac034f94..523f0ded467 100644 --- a/src/lib/onboard/machine/handlers/sandbox-apf.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-apf.test.ts @@ -21,7 +21,7 @@ describe("APF sandbox create selection", () => { expect(apfCreateFingerprintFields(true)).toEqual(["apf-interceptor"]); }); - it("defers fresh-create credentials behind the verified APF effect callback (#9833)", async () => { + it("defers providerless creation effects behind the verified APF callback (#9833)", async () => { const session = createSession({ apfInterceptorRequested: true }); const { deps, calls } = createDeps( { @@ -30,10 +30,6 @@ describe("APF sandbox create selection", () => { gatewayName: "nemoclaw", pendingRouteReservation: true, reservationSessionId: session.sessionId, - provider: "provider", - model: "model", - endpointUrl: null, - preferredInferenceApi: "openai-completions", webSearchEnabled: false, toolDisclosure: "progressive", fromDockerfile: null, @@ -51,9 +47,15 @@ describe("APF sandbox create selection", () => { ...baseOptions(deps, session), fresh: true, apfInterceptorRequested: true, + model: "", + provider: "", + preferredInferenceApi: null, }); expect(calls.stageCredentialProviders).not.toHaveBeenCalled(); + expect(calls.configureWebSearch).not.toHaveBeenCalled(); + expect(calls.validateBrave).not.toHaveBeenCalled(); + expect(calls.setupMessaging).not.toHaveBeenCalled(); expect(calls.createSandbox).toHaveBeenCalledOnce(); const createCall = calls.createSandbox.mock.calls[0] ?? []; expect(createCall.at(-2)).toMatchObject({ @@ -72,6 +74,73 @@ describe("APF sandbox create selection", () => { ); }); + it.each([ + [ + "an explicit web-search environment selection", + { env: { NEMOCLAW_WEB_SEARCH_PROVIDER: "brave", BRAVE_API_KEY: "secret-value" } }, + ], + ["a selected messaging channel", { selectedMessagingChannels: ["telegram"] }], + ])("rejects %s before credential, provider, or sandbox effects", async (_label, intent) => { + const session = createSession({ apfInterceptorRequested: true }); + const { deps, calls } = createDeps({}, session); + + await expect( + handleSandboxState({ + ...baseOptions(deps, session), + ...intent, + fresh: true, + apfInterceptorRequested: true, + model: "", + provider: "", + preferredInferenceApi: null, + }), + ).rejects.toThrow(/supports providerless sandbox creation only/u); + + expect(calls.configureWebSearch).not.toHaveBeenCalled(); + expect(calls.validateBrave).not.toHaveBeenCalled(); + expect(calls.setupMessaging).not.toHaveBeenCalled(); + expect(calls.stageCredentialProviders).not.toHaveBeenCalled(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + }); + + it("rejects a resolved APF provider plan before sandbox or provider effects (#9833)", async () => { + const session = createSession({ apfInterceptorRequested: true }); + const { deps, calls } = createDeps( + { + getSandboxRegistryEntry: (name) => ({ + name, + gatewayName: "nemoclaw", + pendingRouteReservation: true, + reservationSessionId: session.sessionId, + }), + getSandboxRecreateObservation: () => ({ + state: "missing" as const, + liveIdentityFingerprint: null, + }), + planRegisteredExtraProviders: () => ({ + extraProviders: [], + staleExtraProviders: ["stale-provider"], + }), + }, + session, + ); + + await expect( + handleSandboxState({ + ...baseOptions(deps, session), + fresh: true, + apfInterceptorRequested: true, + model: "", + provider: "", + preferredInferenceApi: null, + }), + ).rejects.toThrow(/supports providerless sandbox creation only/u); + + expect(calls.resolveCreateIntent).not.toHaveBeenCalled(); + expect(calls.stageCredentialProviders).not.toHaveBeenCalled(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + }); + it("rejects registered sandbox adoption before credential staging (#9833)", async () => { const session = createSession({ apfInterceptorRequested: true }); const { deps, calls } = createDeps({}, session); @@ -81,6 +150,9 @@ describe("APF sandbox create selection", () => { ...baseOptions(deps, session), fresh: true, apfInterceptorRequested: true, + model: "", + provider: "", + preferredInferenceApi: null, }), ).rejects.toThrow(/cannot adopt registered sandbox/u); @@ -106,6 +178,9 @@ describe("APF sandbox create selection", () => { ...baseOptions(deps, session), fresh: true, apfInterceptorRequested: true, + model: "", + provider: "", + preferredInferenceApi: null, }), ).rejects.toThrow(/cannot adopt live sandbox/u); diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 3fa70b89499..2e4f1951b81 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -105,7 +105,7 @@ import { import { withSandboxPhaseTrace } from "../../tracing"; import type { InferenceRouteReservationAuthority, SandboxCreateIntent } from "../../types"; -import { branchTo, type OnboardStateTransitionResult } from "../result"; +import { branchTo, completeOnboardMachine, type OnboardStateResult } from "../result"; import * as dcodeResume from "./sandbox-dcode-resume"; import { hasMessagingCredentialDrift, @@ -291,7 +291,7 @@ export interface SandboxStateOptions< ): Promise; startRecordedStep( stepName: string, - updates: { sandboxName?: string | null; provider: string; model: string }, + updates: { sandboxName?: string | null; provider?: string | null; model?: string | null }, ): Promise; getRecordedMessagingChannelsForResume( resume: boolean, @@ -409,7 +409,7 @@ export interface SandboxStateResult { selectedMessagingChannels: string[]; webSearchSupported: boolean; session: Session | null; - stateResult: OnboardStateTransitionResult; + stateResult: OnboardStateResult; } interface SandboxStepState { @@ -689,6 +689,25 @@ class SandboxStateFlow< return !agentName || agentName === "openclaw"; } + private assertProviderlessApfInput(): void { + if (this.options.apfInterceptorRequested !== true) return; + const explicitWebSearch = parseExplicitWebSearchProvider( + this.options.env[WEB_SEARCH_PROVIDER_ENV], + ).provider; + const hasProviderIntent = + this.options.provider.trim().length > 0 || + this.options.model.trim().length > 0 || + this.options.webSearchConfig !== null || + explicitWebSearch !== null || + this.options.selectedMessagingChannels.length > 0 || + this.options.hermesToolGateways.length > 0 || + Boolean(this.options.session?.messagingPlan); + if (!hasProviderIntent) return; + throw new Error( + "Interceptor onboarding supports providerless sandbox creation only. No sandbox or provider was created.", + ); + } + private prepareWebSearchSupport(): SandboxStepState { const probePath = this.options.fromDockerfile ? this.deps.resolvePath(this.options.fromDockerfile) @@ -1140,6 +1159,28 @@ class SandboxStateFlow< ` Error: sandbox route reservation '${sandboxName ?? "unknown"}' disappeared while onboarding was in progress. Retry onboarding.`, ); } + if (this.options.apfInterceptorRequested === true) { + const reservationSessionId = this.options.session?.sessionId; + const isExactProviderlessReservation = + typeof reservationSessionId === "string" && + reservationSessionId.length > 0 && + targetEntry.pendingRouteReservation === true && + targetEntry.reservationSessionId === reservationSessionId && + resolveSandboxGatewayName(targetEntry) === this.options.gatewayName && + (targetEntry.provider ?? null) === null && + (targetEntry.model ?? null) === null && + (targetEntry.endpointUrl ?? null) === null && + (targetEntry.endpointSource ?? null) === null && + (targetEntry.credentialEnv ?? null) === null && + (targetEntry.preferredInferenceApi ?? null) === null && + (targetEntry.compatibleEndpointReasoning ?? null) === null && + (targetEntry.compatibleEndpointReasoningEffort ?? null) === null && + (targetEntry.nimContainer ?? null) === null; + if (isExactProviderlessReservation) return; + this.failGatewayRouteCheck( + ` Error: providerless APF sandbox '${sandboxName}' lost its exact route reservation while onboarding was in progress. Retry onboarding.`, + ); + } if (getSandboxEntryInference(targetEntry).kind !== "configured") { this.failGatewayRouteCheck( ` Error: sandbox '${sandboxName}' has incomplete route metadata, so its shared-gateway compatibility cannot be proven. Remove and re-onboard that sandbox.`, @@ -1855,6 +1896,23 @@ class SandboxStateFlow< }; } + private assertProviderlessApfCreatePlan(createIntent: CompleteSandboxCreateIntent): void { + if (this.options.apfInterceptorRequested !== true) return; + const resolved = createIntent.resolved; + const hasProviderPlan = + Boolean(resolved.inferenceProvider?.trim()) || + resolved.activeMessagingChannels.length > 0 || + resolved.messagingProviderRequests.length > 0 || + resolved.reusableMessagingProviders.length > 0 || + resolved.extraProviders.length > 0 || + resolved.staleExtraProviders.length > 0 || + resolved.hermesToolGateways.length > 0; + if (!hasProviderPlan) return; + throw new Error( + "Interceptor onboarding supports providerless sandbox creation only. No sandbox or provider was created.", + ); + } + private assertApfFreshCreate(sandboxName: string, decision: SandboxCreationDecision): void { if (this.options.apfInterceptorRequested !== true) return; if (this.options.resume || this.options.recreateSandbox(false) || decision.kind !== "create") { @@ -1863,7 +1921,19 @@ class SandboxStateFlow< ); } const registered = this.deps.getSandboxRegistryEntry(sandboxName); - if (registered && registered.pendingRouteReservation !== true) { + const sessionId = this.options.session?.sessionId; + const ownsProviderlessReservation = + registered?.pendingRouteReservation === true && + typeof sessionId === "string" && + registered.reservationSessionId === sessionId && + registered.gatewayName === this.options.gatewayName && + registered.provider == null && + registered.model == null && + registered.endpointUrl == null && + registered.endpointSource == null && + registered.credentialEnv == null && + registered.preferredInferenceApi == null; + if (registered && !ownsProviderlessReservation) { throw new Error( `APF interceptor selection cannot adopt registered sandbox '${sandboxName}'. Choose a new sandbox name.`, ); @@ -2138,6 +2208,16 @@ class SandboxStateFlow< requestedSandboxName, registryMessagingAuthoritySnapshot, ); + if ( + this.options.apfInterceptorRequested === true && + (extraProviderPlan.extraProviders.length > 0 || + extraProviderPlan.staleExtraProviders.length > 0 || + effectiveHermesToolGateways.length > 0) + ) { + throw new Error( + "Interceptor onboarding supports providerless sandbox creation only. No sandbox or provider was created.", + ); + } // Build the complete create plan after acquiring the sandbox lock. A // baseline transaction may have started while onboarding waited, and a // pre-lock snapshot must never survive a destructive recreate. @@ -2151,6 +2231,11 @@ class SandboxStateFlow< effectiveHermesToolGateways, deferSandboxEffectsUntilPolicyVerification, ); + this.assertProviderlessApfCreatePlan(createIntent); + const providerlessApf = + this.options.apfInterceptorRequested === true && + this.options.provider.trim().length === 0 && + this.options.model.trim().length === 0; this.assertGatewayRouteCompatible(requestedSandboxName); this.assertCheckpointBindingsStillLive(state); this.assertCheckpointCreateInputsStillMatch( @@ -2160,8 +2245,7 @@ class SandboxStateFlow< ); await this.deps.startRecordedStep("sandbox", { sandboxName: requestedSandboxName, - provider: this.options.provider, - model: this.options.model, + ...(providerlessApf ? {} : { provider: this.options.provider, model: this.options.model }), }); this.deps.updateSession((current) => { current.messagingPlan = messagingPlan; @@ -2270,13 +2354,17 @@ class SandboxStateFlow< // Preserve the validated route and credential env-var name, never a credential value. revalidatePolicyRequirements("register the created sandbox"); this.deps.updateSandboxRegistry(sandboxName, { - model: this.options.model, - provider: this.options.provider, - endpointUrl: this.options.endpointUrl, - endpointSource: createIntent.endpointSource ?? null, - credentialEnv: this.options.credentialEnv, - nimContainer: this.options.nimContainer, - preferredInferenceApi: this.options.preferredInferenceApi, + ...(providerlessApf + ? {} + : { + model: this.options.model, + provider: this.options.provider, + endpointUrl: this.options.endpointUrl, + endpointSource: createIntent.endpointSource ?? null, + credentialEnv: this.options.credentialEnv, + nimContainer: this.options.nimContainer, + preferredInferenceApi: this.options.preferredInferenceApi, + }), ...agentRegistryFields, }); // Finalization marks the default so a cancelled onboarding cannot leave a @@ -2286,8 +2374,9 @@ class SandboxStateFlow< "sandbox", this.deps.toSessionUpdates({ sandboxName, - provider: this.options.provider, - model: this.options.model, + ...(providerlessApf + ? {} + : { provider: this.options.provider, model: this.options.model }), nimContainer: this.options.nimContainer, webSearchConfig: state.webSearchConfig, messagingPlan, @@ -2396,6 +2485,28 @@ class SandboxStateFlow< nextState = this.checkpointSandboxName(nextState, requestedSandboxName); } nextState = this.recordSandboxIdentityForCreate(nextState, requestedSandboxName); + if (this.options.apfInterceptorRequested === true) { + const registryMessagingAuthority = + this.deps.getRegistrySandboxMessagingAuthority(requestedSandboxName); + if (registryMessagingAuthority.plan !== null) { + throw new Error( + "Interceptor onboarding supports providerless sandbox creation only. No sandbox or provider was created.", + ); + } + return this.createAndRecordSandbox( + nextState, + requestedSandboxName, + null, + registryMessagingAuthority, + decision, + true, + async (state) => + this.checkpointMessaging(this.checkpointWebSearch(state, null), { + plan: null, + selectedChannels: [], + }), + ); + } const webSearchConfig = await this.resolveWebSearchForCreation(nextState); const webSearchConfigChanged = nextState.webSearchConfigChanged || @@ -2469,8 +2580,7 @@ class SandboxStateFlow< const hasCreateTimeCredentialBindings = webSearchProviderBindings.length > 0 || messagingProviderBindings.length > 0; const deferCredentialProviderEffects = - this.deferSandboxEffectsUntilPolicyVerification() && - (this.options.apfInterceptorRequested === true || !hasCreateTimeCredentialBindings); + this.deferSandboxEffectsUntilPolicyVerification() && !hasCreateTimeCredentialBindings; if (!deferCredentialProviderEffects) { nextState = await activateCredentialProviders(nextState); } @@ -2503,6 +2613,11 @@ class SandboxStateFlow< " Tavily Search replaces Hermes managed Web search/extract and removes the conflicting nous-web selection.", ); } + const metadata = { + state: "sandbox", + sandboxName: state.sandboxName, + agent: (this.options.agent as { name?: string } | null)?.name ?? "openclaw", + }; return { sandboxName: state.sandboxName, webSearchConfig: state.webSearchConfig, @@ -2511,17 +2626,15 @@ class SandboxStateFlow< selectedMessagingChannels: state.selectedMessagingChannels, webSearchSupported: state.webSearchSupported, session: state.session, - stateResult: branchTo(this.options.agent ? "agent_setup" : "openclaw", { - metadata: { - state: "sandbox", - sandboxName: state.sandboxName, - agent: (this.options.agent as { name?: string } | null)?.name ?? "openclaw", - }, - }), + stateResult: + this.options.apfInterceptorRequested === true + ? completeOnboardMachine({}, metadata) + : branchTo(this.options.agent ? "agent_setup" : "openclaw", { metadata }), }; } async run(): Promise> { + this.assertProviderlessApfInput(); if (this.options.session?.checkpoint) { this.replayableCheckpointProviderBindings(this.options.session.checkpoint); } diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts index 250b3bd0c5f..ecf2ffd0970 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts @@ -183,6 +183,16 @@ describe("managed workload onboard orchestration", () => { ).toBe(false); }); + it("keeps stock managed images required during providerless interceptor creation (#9833)", () => { + expect( + shouldActivateStockManagedRuntime({ + portableLifecycle: false, + hermesPortableLifecycle: false, + agentName: "openclaw", + }), + ).toBe(true); + }); + it("rejects an unavailable catalog for stock managed-image onboarding", async () => { const { runtime } = createFreshOnboardingRuntime( {}, diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index dc090945816..a45b7173268 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -133,8 +133,8 @@ export interface CreateManagedWorkloadOnboardRuntimeInput { readonly legacyDockerfilePath: string; readonly customDockerfilePath: string | null; readonly rootDir: string; - readonly model: string; - readonly provider: string; + readonly model: string | null; + readonly provider: string | null; readonly preferredInferenceApi: string | null; readonly endpointUrl: string | null; readonly startupProfile: ManagedProfileInput; @@ -301,25 +301,27 @@ export function createManagedWorkloadOnboardRuntime( return input.managedWorkloadRebuild.replacementProfile; } if (preparedProfile) return preparedProfile; + const selectedModel = input.model?.trim() || "unconfigured"; + const selectedProvider = input.provider?.trim() || null; const inferenceApi = input.agentName === "langchain-deepagents-code" ? "openai-completions" : dependencies.resolveAgentInferenceApi( input.agentName, - input.provider, + selectedProvider, input.preferredInferenceApi, ); const inference: SandboxInferenceConfig = dependencies.getSandboxInferenceConfig( - input.model, - input.provider, + selectedModel, + selectedProvider, inferenceApi, ); preparedProfile = buildManagedStartupOnboardProfile({ agentName: input.agentName, inference: { routeProvider: inference.providerKey, - upstreamProvider: input.provider.trim() ? input.provider : inference.providerKey, - model: input.model, + upstreamProvider: selectedProvider ?? inference.providerKey, + model: selectedModel, routedBaseUrl: inference.inferenceBaseUrl, upstreamEndpointUrl: input.agentName === "langchain-deepagents-code" ? input.endpointUrl : null, diff --git a/src/lib/onboard/messaging-prep.test.ts b/src/lib/onboard/messaging-prep.test.ts index 875e5303072..28f7b860508 100644 --- a/src/lib/onboard/messaging-prep.test.ts +++ b/src/lib/onboard/messaging-prep.test.ts @@ -43,6 +43,20 @@ function createInput( } describe("prepareCreateSandboxMessaging", () => { + it("does not read messaging credentials when no channel is enabled (#9833)", () => { + const getValidatedMessagingTokenByEnvKey = vi.fn(() => "secret-value"); + + const result = prepareCreateSandboxMessaging( + createInput({ + enabledChannels: [], + getValidatedMessagingTokenByEnvKey, + }), + ); + + expect(getValidatedMessagingTokenByEnvKey).not.toHaveBeenCalled(); + expect(result.messagingTokenDefs).toEqual([]); + }); + it("filters token definitions and reuses missing-token providers with matching bindings", () => { const registerExtraPlaceholderProviders = vi.fn(() => ["SLACK_BOT_TOKEN_AGENT_A"]); const providerMatchesGatewayCredential = vi.fn( diff --git a/src/lib/onboard/messaging-prep.ts b/src/lib/onboard/messaging-prep.ts index cdf40a51b00..cdd99d0530c 100644 --- a/src/lib/onboard/messaging-prep.ts +++ b/src/lib/onboard/messaging-prep.ts @@ -97,7 +97,6 @@ export function prepareCreateSandboxMessaging( return { name: credential.providerNameTemplate.replaceAll("{sandboxName}", input.sandboxName), envKey: credential.providerEnvKey, - token: input.getValidatedMessagingTokenByEnvKey(input.channels, credential.providerEnvKey), providerType: staticProviderType ?? MESSAGING_CREDENTIAL_PROVIDER_TYPE, retainWhileDisabled: staticProviderType !== null, }; @@ -107,7 +106,11 @@ export function prepareCreateSandboxMessaging( !enabledEnvKeys || enabledEnvKeys.has(envKey) || (retainWhileDisabled && disabledEnvKeys.has(envKey)), - ); + ) + .map((definition) => ({ + ...definition, + token: input.getValidatedMessagingTokenByEnvKey(input.channels, definition.envKey), + })); const messagingTokenDefs: MessagingTokenDef[] = messagingCredentialDefs .filter(({ envKey }) => !disabledEnvKeys.has(envKey)) .map(({ retainWhileDisabled: _retainWhileDisabled, ...definition }) => definition); diff --git a/src/lib/onboard/policy-selection-prompts.test.ts b/src/lib/onboard/policy-selection-prompts.test.ts index d5d863daca9..f07d2969460 100644 --- a/src/lib/onboard/policy-selection-prompts.test.ts +++ b/src/lib/onboard/policy-selection-prompts.test.ts @@ -156,6 +156,58 @@ describe("createPolicySelectionPromptHelpers", () => { expect(errorSpy).toHaveBeenCalledWith(" Unknown preset name ignored: missing"); }); + it.each([ + [ + "policy tier", + (helpers: ReturnType) => + helpers.selectPolicyTier(), + ], + [ + "tier presets", + (helpers: ReturnType) => + helpers.selectTierPresetsAndAccess("balanced", [{ name: "npm" }]), + ], + [ + "preset checkbox", + (helpers: ReturnType) => + helpers.presetsCheckboxSelector([{ name: "npm", description: "npm registry" }], []), + ], + ])( + "marks cancellation when SIGTERM interrupts the non-TTY %s selector", + async (_label, select) => { + vi.spyOn(console, "log").mockImplementation(() => undefined); + const { helpers, markCancelled, processEvents, prompt } = createHarness({ + stdinTTY: false, + stdoutTTY: false, + }); + prompt.mockImplementation(() => new Promise(() => undefined)); + + const selection = select(helpers); + expect(prompt).toHaveBeenCalledOnce(); + processEvents.emit("SIGTERM"); + + await expect(selection).rejects.toMatchObject({ code: 1 }); + expect(markCancelled).toHaveBeenCalledOnce(); + expect(processEvents.listenerCount("SIGINT")).toBe(0); + expect(processEvents.listenerCount("SIGTERM")).toBe(0); + }, + ); + + it("marks cancellation when a non-TTY prompt reports Ctrl-C", async () => { + vi.spyOn(console, "log").mockImplementation(() => undefined); + const { helpers, markCancelled, processEvents, prompt } = createHarness({ + stdinTTY: false, + stdoutTTY: false, + }); + prompt.mockRejectedValue(Object.assign(new Error("Prompt interrupted"), { code: "SIGINT" })); + + await expect(helpers.selectPolicyTier()).rejects.toMatchObject({ code: 1 }); + + expect(markCancelled).toHaveBeenCalledOnce(); + expect(processEvents.listenerCount("SIGINT")).toBe(0); + expect(processEvents.listenerCount("SIGTERM")).toBe(0); + }); + it("selectTierPresetsAndAccess returns raw-mode access toggles on Enter", async () => { const { helpers, markCancelled, stdin } = createHarness(); const result = helpers.selectTierPresetsAndAccess("balanced", [ diff --git a/src/lib/onboard/policy-selection-prompts.ts b/src/lib/onboard/policy-selection-prompts.ts index b6d06873a7b..bf9ff28d0be 100644 --- a/src/lib/onboard/policy-selection-prompts.ts +++ b/src/lib/onboard/policy-selection-prompts.ts @@ -23,8 +23,8 @@ type PolicyPromptOutput = { write(chunk: string): unknown; }; type PolicyPromptProcessEvents = { - once(event: "SIGTERM", listener: () => void): unknown; - removeListener(event: "SIGTERM", listener: () => void): unknown; + once(event: "SIGINT" | "SIGTERM", listener: () => void): unknown; + removeListener(event: "SIGINT" | "SIGTERM", listener: () => void): unknown; }; export interface PolicySelectionPromptDeps { @@ -78,6 +78,48 @@ export function createPolicySelectionPromptHelpers(deps: PolicySelectionPromptDe const stdout = deps.stdout ?? process.stdout; const processEvents = deps.processEvents ?? process; + function promptWithOnboardCancel(question: string): Promise { + return new Promise((resolve, reject) => { + let cancelled = false; + const cleanup = () => { + processEvents.removeListener("SIGINT", onCancel); + processEvents.removeListener("SIGTERM", onCancel); + }; + const cancelExit = makeOnboardCancelExit(sandboxCancelRollback, cleanup, (code) => + reject(new OnboardDeferredExitError(code)), + ); + const onCancel = () => { + if (cancelled) return; + cancelled = true; + cancelExit(); + }; + processEvents.once("SIGINT", onCancel); + processEvents.once("SIGTERM", onCancel); + let answer: Promise; + try { + answer = prompt(question); + } catch (error) { + cleanup(); + reject(error); + return; + } + void answer.then( + (value) => { + cleanup(); + resolve(value); + }, + (error: unknown) => { + if ((error as NodeJS.ErrnoException)?.code === "SIGINT") { + onCancel(); + return; + } + cleanup(); + reject(error); + }, + ); + }); + } + /** * Prompt the user to select a policy tier (restricted / balanced / open / personal). * Uses the same radio-style TUI as presetsCheckboxSelector (single-select). @@ -110,7 +152,7 @@ export function createPolicySelectionPromptHelpers(deps: PolicySelectionPromptDe console.log(` ${marker} ${tier.label}`); }); console.log(""); - const answer = await prompt( + const answer = await promptWithOnboardCancel( ` Select tier [1-${allTiers.length}] (default: ${allTiers.indexOf(defaultTier) + 1} ${defaultTier.name}): `, ); const chosen = selectFromNumberedMenuOrExit( @@ -283,7 +325,7 @@ export function createPolicySelectionPromptHelpers(deps: PolicySelectionPromptDe console.log(` ${check} ${badge} ${preset.name}`); }); console.log(""); - const rawInclude = await prompt( + const rawInclude = await promptWithOnboardCancel( " Include presets (comma-separated names, Enter to keep defaults): ", ); if (rawInclude.trim()) { @@ -433,7 +475,9 @@ export function createPolicySelectionPromptHelpers(deps: PolicySelectionPromptDe console.log(` ${marker} ${preset.name.padEnd(14)} — ${preset.description}`); }); console.log(""); - const raw = await prompt(" Select presets (comma-separated names, Enter to skip): "); + const raw = await promptWithOnboardCancel( + " Select presets (comma-separated names, Enter to skip): ", + ); if (!raw.trim()) { console.log(" Skipping policy presets."); return []; diff --git a/src/lib/onboard/portable-resume-lock-boundary.test.ts b/src/lib/onboard/portable-resume-lock-boundary.test.ts index 5e6fcdd110c..86ee2edcd78 100644 --- a/src/lib/onboard/portable-resume-lock-boundary.test.ts +++ b/src/lib/onboard/portable-resume-lock-boundary.test.ts @@ -526,13 +526,14 @@ describe("portable resume command lock boundary", () => { return directory; }) as typeof fs.mkdtempSync); const harnessModule = await import("../../../test/helpers/rebuild-flow-generic-harness"); - const { rebuildOnboardDependencies } = + const { onboardSession: rebuildOnboardSession, rebuildOnboardDependencies } = await import("../../../test/helpers/rebuild-flow-harness"); const actualOnboard = rebuildOnboardDependencies.onboard.bind(rebuildOnboardDependencies) as ( options: import("./types").OnboardOptions, ) => Promise; const { retirement } = boundaryModules; let innerObserved = false; + let innerError = ""; const harness = harnessModule.createRebuildFlowHarness({ onboard: async (_session, options) => { const lockPath = retirement.portableHostFencePath(tempHome); @@ -545,16 +546,19 @@ describe("portable resume command lock boundary", () => { try { await actualOnboard(options); } catch (error) { + innerError = String(error); innerObserved = String(error).includes("retirement record"); expect(fs.lstatSync(lockPath, { bigint: true }).ino).toBe(outerInode); throw error; } }, }); + vi.mocked(rebuildOnboardSession.acquireOnboardLock).mockRestore(); + vi.mocked(rebuildOnboardSession.releaseOnboardLock).mockRestore(); try { await harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }).catch(() => {}); - expect(innerObserved).toBe(true); + expect(innerObserved, innerError).toBe(true); expect(fs.existsSync(retirement.portableHostFencePath(tempHome))).toBe(false); } finally { mkdtemp.mockRestore(); diff --git a/src/lib/onboard/portable-retirement-authority.ts b/src/lib/onboard/portable-retirement-authority.ts index 4f94a679e69..8c6cac002e0 100644 --- a/src/lib/onboard/portable-retirement-authority.ts +++ b/src/lib/onboard/portable-retirement-authority.ts @@ -6,7 +6,12 @@ import fs from "node:fs"; import path from "node:path"; import { isDeepStrictEqual, TextDecoder } from "node:util"; -import { acquireOnboardLock, normalizeSession, releaseOnboardLock } from "../state/onboard-session"; +import { + acquireOnboardLock, + assertOnboardLockOwned, + normalizeSession, + releaseOnboardLock, +} from "../state/onboard-session"; import { assertHermesPortableUninstallCompleteForOnboarding } from "../state/hermes-portable-uninstall/journal"; import { inspectPortableOnboardSupersession, @@ -550,6 +555,7 @@ export function beginPortableOnboardRetirementEntry( options: PortableOnboardRetirementEntryOptions, ) { const ownsOnboardLock = !options.alreadyHeld; + if (!ownsOnboardLock) assertOnboardLockOwned(); const lockResult = ownsOnboardLock ? acquireOnboardLock(options.command) : { acquired: true as const }; diff --git a/src/lib/onboard/sandbox-create-plan-materialization.ts b/src/lib/onboard/sandbox-create-plan-materialization.ts index c5973920503..c52afcbca1f 100644 --- a/src/lib/onboard/sandbox-create-plan-materialization.ts +++ b/src/lib/onboard/sandbox-create-plan-materialization.ts @@ -266,6 +266,23 @@ function buildCreateProviderSet( ); } +function assertDeferredProviderPlanSupported( + intent: SandboxCreateIntent, + messagingProviders: readonly string[], + initialSandboxPolicy: InitialSandboxPolicy, +): void { + const requiresProviderAttachment = + Boolean(intent.inferenceProvider) || + messagingProviders.length > 0 || + intent.extraProviders.length > 0 || + intent.hermesToolGateways.length > 0; + if (!requiresProviderAttachment) return; + initialSandboxPolicy.cleanup?.(); + throw new Error( + `Cannot create sandbox '${intent.sandboxName}' with deferred providers because OpenShell cannot bind provider attachment to a verified immutable sandbox identity. No sandbox was created; use an OpenShell release with identity-bound provider attachment before retrying.`, + ); +} + /** Materialize policy, route metadata, resources, and providers from a secretless intent. */ export function materializeSandboxCreatePlan({ intent, @@ -332,6 +349,9 @@ export function materializeSandboxCreatePlan({ intent.policy.activeMessagingChannels, intent.disabledChannelNames, ); + if (deferSandboxEffectsUntilPolicyVerification) { + assertDeferredProviderPlanSupported(intent, plannedMessagingProviders, initialSandboxPolicy); + } if (policyAuthority === "nemoclaw-managed") { assertCredentialBindingProvidersAttached( initialSandboxPolicy, diff --git a/src/lib/onboard/sandbox-create-plan.test.ts b/src/lib/onboard/sandbox-create-plan.test.ts index 603f21ded87..e203212efef 100644 --- a/src/lib/onboard/sandbox-create-plan.test.ts +++ b/src/lib/onboard/sandbox-create-plan.test.ts @@ -632,7 +632,7 @@ describe("resolveSandboxCreateIntent", () => { expect(JSON.stringify(intent)).toBe(serializedIntent); }); - it("defers every provider effect and create attachment until activation (#9833)", () => { + it("rejects deferred provider plans before provider effects or sandbox creation (#9833)", () => { const tokenDefs = [ { name: "sandbox-telegram-bridge", @@ -664,62 +664,50 @@ describe("resolveSandboxCreateIntent", () => { policyTier: null, }); const events: string[] = []; - const revalidatePolicyRequirements = vi.fn((operation: string) => - events.push(`revalidate:${operation}`), - ); - const plan = materializeSandboxCreatePlan({ - intent, - fromRef: "example.invalid/image@sha256:abc", - policyAuthority: "externally-managed", - deferSandboxEffectsUntilPolicyVerification: true, - messagingTokenDefs: tokenDefs, - prepareInitialSandboxCreatePolicy: () => ({ - policyPath: "/tmp/policy.yaml", - appliedPresets: ["telegram"], - }), - runProviderPreDeleteCleanup: (revalidate) => { - expect(revalidate).toBe(revalidatePolicyRequirements); - revalidate?.("cleaning up providers"); - events.push("cleanup"); - }, - upsertMessagingProviders: vi.fn((_tokenDefs, options) => { - expect(options.revalidatePolicyRequirements).toBe(revalidatePolicyRequirements); - events.push("upsert"); - return ["sandbox-telegram-bridge"]; - }), - getHermesToolGatewayProviderName: () => { - events.push("hermes"); - return "sandbox-hermes-tools"; - }, + const cleanupPolicy = vi.fn(() => { + events.push("policy-cleanup"); + return true; + }); + const runProviderPreDeleteCleanup = vi.fn(() => events.push("provider-cleanup")); + const upsertMessagingProviders = vi.fn(() => { + events.push("upsert"); + return ["sandbox-telegram-bridge"]; + }); + const getHermesToolGatewayProviderName = vi.fn(() => { + events.push("hermes"); + return "sandbox-hermes-tools"; }); - expect(events).toEqual([]); - expect(plan.createArgs).not.toContain("--provider"); - expect(plan.messagingProviders).toEqual([ - "sandbox-telegram-bridge", - "sandbox-existing-discord", - ]); + expect(() => + materializeSandboxCreatePlan({ + intent, + fromRef: "example.invalid/image@sha256:abc", + policyAuthority: "externally-managed", + deferSandboxEffectsUntilPolicyVerification: true, + messagingTokenDefs: tokenDefs, + prepareInitialSandboxCreatePolicy: () => ({ + policyPath: "/tmp/policy.yaml", + appliedPresets: ["telegram"], + cleanup: cleanupPolicy, + }), + runProviderPreDeleteCleanup, + upsertMessagingProviders, + getHermesToolGatewayProviderName, + }), + ).toThrow("No sandbox was created"); - expect(plan.activateDeferredProviderEffects?.(revalidatePolicyRequirements)).toEqual([ - "nvidia-prod", - "sandbox-telegram-bridge", - "sandbox-existing-discord", - "sandbox-hermes-tools", - "custom-provider", - ]); - expect(events).toEqual([ - "revalidate:cleaning up providers", - "cleanup", - "upsert", - "hermes", - ]); + expect(events).toEqual(["policy-cleanup"]); + expect(cleanupPolicy).toHaveBeenCalledOnce(); + expect(runProviderPreDeleteCleanup).not.toHaveBeenCalled(); + expect(upsertMessagingProviders).not.toHaveBeenCalled(); + expect(getHermesToolGatewayProviderName).not.toHaveBeenCalled(); }); it("keeps the NemoClaw policy on a managed create when effects are deferred (#9833)", () => { const intent = resolveSandboxCreateIntent({ basePolicyPath: "/repo/policy.yaml", sandboxName: "sandbox", - inferenceProvider: "nvidia-prod", + inferenceProvider: null, channels, enabledChannels: [], disabledChannelNames: new Set(), @@ -751,9 +739,7 @@ describe("resolveSandboxCreateIntent", () => { getHermesToolGatewayProviderName: vi.fn(), }); - expect(plan.createArgs).toEqual( - expect.arrayContaining(["--policy", "/tmp/policy.yaml"]), - ); + expect(plan.createArgs).toEqual(expect.arrayContaining(["--policy", "/tmp/policy.yaml"])); expect(plan.createArgs).not.toContain("--provider"); }); diff --git a/src/lib/onboard/sandbox-create/orchestration.test.ts b/src/lib/onboard/sandbox-create/orchestration.test.ts index 5e15813858b..6cbeb038aa0 100644 --- a/src/lib/onboard/sandbox-create/orchestration.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration.test.ts @@ -17,14 +17,25 @@ import { createProviderEffectBoundary, finalizeCreatedSandboxBeforeHermesCredentialReconciliation, hasManagedMcpRebuildHandoff, + installPostCreateRecoveryRetryOwner, + persistPostCreateRecovery, persistRetainedSandboxRecoveryMessage, readManagedDcodeCreateSelectionDrift, readSandboxRecreateRegistryEntry, reconcileCreatedHermesCredentialEnvironment, resolveSandboxCreatePolicyAuthority, + runAsyncWithPostCreateRecovery, runSandboxCreateWithPolicyAuthorityChecks, + runWithPostCreateRecovery, } from "./orchestration"; +const UNVERIFIED_RECOVERY_CONTEXT = { + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "generation-1", + verifiedEffectivePolicyIdentity: null, +} as const; + describe("created Hermes credential environment reconciliation", () => { const plan = { agent: "hermes" } as never; @@ -73,6 +84,7 @@ describe("created Hermes credential environment reconciliation", () => { return true; }, }, + vi.fn(), ); expect(events).toEqual([ @@ -99,6 +111,7 @@ describe("created Hermes credential environment reconciliation", () => { parseRestartCompletion: vi.fn(), waitForGateway, }, + vi.fn(), ); expect(restartGateway).not.toHaveBeenCalled(); @@ -106,6 +119,7 @@ describe("created Hermes credential environment reconciliation", () => { }); it("fails onboarding when the changed gateway cannot prove restart completion", () => { + const recordRecovery = vi.fn(); expect(() => reconcileCreatedHermesCredentialEnvironment( { sandboxName: "alpha", plan }, @@ -116,8 +130,10 @@ describe("created Hermes credential environment reconciliation", () => { parseRestartCompletion: () => null, waitForGateway: vi.fn(), }, + recordRecovery, ), ).toThrow("managed gateway restart did not complete"); + expect(recordRecovery).toHaveBeenCalledOnce(); }); }); @@ -144,12 +160,26 @@ describe("retained create recovery persistence", () => { session.saveSession(session.createSession({ sandboxName: "alpha" })); expect( - persistRetainedSandboxRecoveryMessage(message, session.finalizeIncompleteOnboardStep), + persistRetainedSandboxRecoveryMessage( + { + sandboxName: "alpha", + message, + ...(fingerprint ? { sandboxIdentityFingerprint: fingerprint } : {}), + recoveryContext: UNVERIFIED_RECOVERY_CONTEXT, + }, + session.markRetainedSandboxRecovery, + ), ).toBe(true); const stored = session.loadSession(); - expect(stored?.machine.state).toBe("failed"); - expect(stored?.steps.sandbox?.status).toBe("failed"); + expect(stored?.status).toBe("recovery_required"); + expect(stored?.resumable).toBe(false); + expect(stored?.cancellationRecovery?.reason).toBe( + "retained_after_sandbox_creation_failure", + ); + expect(stored?.cancellationRecovery?.sandboxName).toBe("alpha"); + expect(stored?.machine.state).not.toBe("failed"); + expect(stored?.steps.sandbox?.status).not.toBe("failed"); expect(stored?.failure?.message).toContain(createAttemptLabel); expect(stored?.steps.sandbox?.error).toContain(createAttemptLabel); const fingerprintExpectation = fingerprint @@ -165,35 +195,52 @@ describe("retained create recovery persistence", () => { }, ); + it("forwards the full verified recovery tuple to durable state (#9833)", () => { + const recoveryContext = { + gatewayName: "nemoclaw-18080", + gatewayPort: 18080, + lifecycleGeneration: "00000000-0000-4000-8000-000000000004", + verifiedEffectivePolicyIdentity: { hash: "sha256:policy-4", activeVersion: 4 }, + } as const; + const markRetainedSandboxRecovery = vi.fn(() => true); + const input = { + stage: "registry publication" as const, + sandboxName: "alpha", + gatewayName: recoveryContext.gatewayName, + lifecycleGeneration: recoveryContext.lifecycleGeneration, + exactIdentity: "f".repeat(64), + recoveryContext, + markRetainedSandboxRecovery, + }; + + persistPostCreateRecovery(input); + + expect(markRetainedSandboxRecovery).toHaveBeenCalledWith( + "alpha", + expect.stringContaining(recoveryContext.lifecycleGeneration), + "f".repeat(64), + recoveryContext, + ); + }); + it("reports persistence failure when no onboard session owns the recovery (#9211)", () => { const finalizeIncompleteOnboardStep = vi.fn(() => null); expect( persistRetainedSandboxRecoveryMessage( - "Create-attempt label: ai.nvidia.nemoclaw.create-attempt=authority", + { + sandboxName: "alpha", + message: "Create-attempt label: ai.nvidia.nemoclaw.create-attempt=authority", + recoveryContext: UNVERIFIED_RECOVERY_CONTEXT, + }, finalizeIncompleteOnboardStep, ), ).toBe(false); expect(finalizeIncompleteOnboardStep).toHaveBeenCalledExactlyOnceWith( - "sandbox", + "alpha", "Create-attempt label: ai.nvidia.nemoclaw.create-attempt=authority", - ); - }); - - it("reports persistence failure when the saved recovery readback differs (#9833)", () => { - const message = `Create-attempt label: ai.nvidia.nemoclaw.create-attempt=${"a".repeat(62)}`; - const changedMessage = `Create-attempt label: ai.nvidia.nemoclaw.create-attempt=${"b".repeat(62)}`; - const finalizeIncompleteOnboardStep = vi.fn(() => ({ - failure: { message: changedMessage }, - steps: { sandbox: { error: changedMessage } }, - })); - - expect( - persistRetainedSandboxRecoveryMessage(message, finalizeIncompleteOnboardStep), - ).toBe(false); - expect(finalizeIncompleteOnboardStep).toHaveBeenCalledExactlyOnceWith( - "sandbox", - message, + undefined, + UNVERIFIED_RECOVERY_CONTEXT, ); }); @@ -209,20 +256,138 @@ describe("retained create recovery persistence", () => { expect( persistRetainedSandboxRecoveryMessage( - "Create-attempt label: ai.nvidia.nemoclaw.create-attempt=unpersisted", - session.finalizeIncompleteOnboardStep, + { + sandboxName: "alpha", + message: "Create-attempt label: ai.nvidia.nemoclaw.create-attempt=unpersisted", + recoveryContext: UNVERIFIED_RECOVERY_CONTEXT, + }, + session.markRetainedSandboxRecovery, ), - ).toBe(false); + ).toBe(true); const stored = session.loadSession(); - expect(stored?.failure?.message).toBe("Earlier sandbox failure"); - expect(stored?.steps.sandbox?.error).toBe("Earlier sandbox failure"); + expect(stored?.status).toBe("recovery_required"); + expect(stored?.failure?.message).toContain("create-attempt=unpersisted"); + expect(stored?.steps.sandbox?.error).toContain("create-attempt=unpersisted"); } finally { vi.resetModules(); fs.rmSync(tempHome, { force: true, recursive: true }); vi.unstubAllEnvs(); } }); + + it.each([ + ["registry publication", "false"], + ["registry publication", "throw"], + ["registry publication", "journal readback mismatch"], + ["onboarding finalization", "false"], + ["onboarding finalization", "throw"], + ["onboarding finalization", "journal readback mismatch"], + ] as const)( + "keeps the original %s error when recovery persistence returns %s (#9833)", + async (stage, failureMode) => { + const operationError = new Error(`${stage} failed`); + const recoveryFailures = { + false: () => false, + throw: () => { + throw new Error("retained sandbox recovery writer threw"); + }, + "journal readback mismatch": () => { + throw new Error("Retained sandbox recovery record did not survive durable readback."); + }, + } satisfies Record false | never>; + const markRetainedSandboxRecovery = vi.fn(recoveryFailures[failureMode]); + const recordRecovery = () => + persistPostCreateRecovery({ + stage, + sandboxName: "alpha", + gatewayName: "nemoclaw", + lifecycleGeneration: "generation-1", + exactIdentity: "f".repeat(64), + recoveryContext: UNVERIFIED_RECOVERY_CONTEXT, + markRetainedSandboxRecovery, + }); + + const caught = + stage === "registry publication" + ? await runAsyncWithPostCreateRecovery( + async () => Promise.reject(operationError), + recordRecovery, + ).catch((error: unknown) => error) + : (() => { + try { + return runWithPostCreateRecovery(() => { + throw operationError; + }, recordRecovery); + } catch (error) { + return error; + } + })(); + + expect(caught).toBeInstanceOf(AggregateError); + expect((caught as AggregateError).errors).toEqual( + expect.arrayContaining([ + operationError, + expect.objectContaining({ + message: expect.stringContaining("could not save the retained sandbox recovery"), + }), + ]), + ); + expect(((caught as AggregateError).errors[1] as Error).cause).toEqual( + failureMode === "false" + ? undefined + : expect.objectContaining({ + message: expect.stringMatching(/writer threw|did not survive durable readback/u), + }), + ); + }, + ); + + it.each(["registry publication", "onboarding finalization"] as const)( + "retries %s recovery at exit without rerunning the failed operation (#9833)", + async (stage) => { + const exitHandlers: Array<() => void> = []; + const owner = installPostCreateRecoveryRetryOwner({ + log: vi.fn(), + registerExitHandler: (handler) => exitHandlers.push(handler), + }); + const operationError = new Error(`${stage} failed`); + const operation = vi.fn(() => { + throw operationError; + }); + const recordRecovery = vi + .fn() + .mockImplementationOnce(() => { + throw new Error("retained recovery write failed"); + }) + .mockImplementationOnce(() => undefined); + const recordWithOwner = () => owner.record(recordRecovery); + + const caught = + stage === "registry publication" + ? await runAsyncWithPostCreateRecovery(async () => operation(), recordWithOwner).catch( + (error: unknown) => error, + ) + : (() => { + try { + return runWithPostCreateRecovery(operation, recordWithOwner); + } catch (error) { + return error; + } + })(); + + expect(caught).toBeInstanceOf(AggregateError); + expect(operation).toHaveBeenCalledOnce(); + expect(recordRecovery).toHaveBeenCalledOnce(); + + exitHandlers[0](); + expect(recordRecovery).toHaveBeenCalledTimes(2); + expect(operation).toHaveBeenCalledOnce(); + + exitHandlers[0](); + expect(recordRecovery).toHaveBeenCalledTimes(2); + }, + ); }); describe("APF create policy selection", () => { @@ -259,25 +424,9 @@ describe("APF create policy selection", () => { }); describe("deferred provider effect authority", () => { - it("refuses a second provider attachment after policy authority changes (#9833)", async () => { - const events: string[] = []; - const recordPolicyCheck = (operation: string) => { - events.push(`policy: ${operation}`); - }; - const revalidatePolicyRequirements = vi.fn(recordPolicyCheck); - const runOpenshell = vi.fn((args: string[]) => { - events.push(args.join(" ")); - revalidatePolicyRequirements - .mockImplementationOnce(recordPolicyCheck) - .mockImplementationOnce((operation) => { - recordPolicyCheck(operation); - throw new Error("policy authority changed after the first provider attachment"); - }); - return { status: 0 }; - }); - const revalidateSandboxIdentity = vi.fn((_exactIdentity: string, operation: string) => { - events.push(`identity: ${operation}`); - }); + it("refuses every deferred provider attachment before a same-name replacement can receive credentials (#9833)", async () => { + const revalidatePolicyRequirements = vi.fn(); + const runOpenshell = vi.fn(() => ({ status: 0 })); const boundary = createProviderEffectBoundary({ deferred: true, sandboxName: "alpha", @@ -301,8 +450,6 @@ describe("deferred provider effect authority", () => { return ["first", "second"]; }, revalidatePolicyAuthorityBeforeCreate: vi.fn(), - runOpenshell: runOpenshell as never, - revalidateSandboxIdentity, }); const runAfterVerifiedCreate = boundary.runAfterVerifiedCreate; expect(runAfterVerifiedCreate).toBeTypeOf("function"); @@ -323,19 +470,15 @@ describe("deferred provider effect authority", () => { route: "direct" as never, revalidatePolicyRequirements, }), - ).rejects.toThrow("policy authority changed after the first provider attachment"); + ).rejects.toThrow("OpenShell cannot attach providers to the immutable identity"); - expect(runOpenshell).toHaveBeenCalledExactlyOnceWith( - ["sandbox", "provider", "attach", "-g", "nemoclaw", "alpha", "first"], - { ignoreError: true, suppressOutput: true }, + expect(runOpenshell).not.toHaveBeenCalledWith( + expect.arrayContaining(["sandbox", "provider", "attach"]), + expect.anything(), ); - expect(revalidateSandboxIdentity).toHaveBeenCalledWith( - "a".repeat(64), - "attaching provider 'second' to sandbox 'alpha'", + expect(revalidatePolicyRequirements).toHaveBeenCalledWith( + "attaching deferred providers to sandbox 'alpha'", ); - expect(events).toContain("policy: attaching provider 'second' to sandbox 'alpha'"); - expect(events).toContain("policy: cleaning up providers for sandbox 'alpha'"); - expect(events).not.toContain("sandbox provider attach -g nemoclaw alpha second"); }); }); @@ -678,12 +821,18 @@ describe("sandbox create policy authority checks", () => { }).catch((caught: unknown) => caught); expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).message).toMatch( + new RegExp( + `left sandbox 'alpha' in place.*identity fingerprint: ${exactIdentity}.*did not run OpenShell's mutable-name deletion command.*Do not delete the sandbox by mutable sandbox name.*OpenShell administrator.*identity-bound recovery or removal procedure`, + "u", + ), + ); expect((error as AggregateError).errors).toEqual( expect.arrayContaining([ expect.objectContaining({ message: expect.stringMatching( new RegExp( - `left sandbox 'alpha' in place.*identity fingerprint: ${exactIdentity}.*Do not delete the sandbox by name, even after this comparison.*Contact the OpenShell administrator for an identity-bound recovery or removal procedure`, + `left sandbox 'alpha' in place.*identity fingerprint: ${exactIdentity}.*did not run OpenShell's mutable-name deletion command.*Do not delete the sandbox by mutable sandbox name.*OpenShell administrator.*identity-bound recovery or removal procedure`, "u", ), ), @@ -693,6 +842,137 @@ describe("sandbox create policy authority checks", () => { expect(events).toEqual(["create-check", "create", "ready-check", "cleanup-sources"]); }); + it("records recovery before returning a post-create authority failure (#9833)", async () => { + const persistRetainedSandboxRecovery = vi.fn(() => true); + + await expect( + runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate: vi.fn(), + create: async (verifyCreatedSandbox) => { + await verifyCreatedSandbox("created"); + return "created"; + }, + ...exactIdentityBoundary(), + revalidateVerifiedPolicy: () => { + throw new Error("external policy authority changed"); + }, + persistRetainedSandboxRecovery, + cleanupTemporarySources: vi.fn(), + }), + ).rejects.toThrow("automatic sandbox cleanup was not safe"); + + expect(persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining("left sandbox 'alpha' in place"), + exactIdentity, + "verified", + ); + }); + + it("retains verified policy evidence when checkpoint persistence fails (#9833)", async () => { + const verifiedEvidence = { policyHash: "sha256:policy-4", policyVersion: 4 } as const; + const persistRetainedSandboxRecovery = vi.fn(() => true); + + await expect( + runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate: vi.fn(), + create: async (verifyCreatedSandbox) => { + await verifyCreatedSandbox("created"); + return "created"; + }, + ...exactIdentityBoundary(), + verifyCreatedPolicy: () => verifiedEvidence, + persistVerifiedPolicy: () => { + throw new Error("checkpoint write failed"); + }, + persistRetainedSandboxRecovery, + cleanupTemporarySources: vi.fn(), + }), + ).rejects.toThrow("automatic sandbox cleanup was not safe"); + + expect(persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining("left sandbox 'alpha' in place"), + exactIdentity, + verifiedEvidence, + ); + }); + + it("records recovery when the create runner fails after verification (#9833)", async () => { + const createFailure = new Error("runtime patch failed after verification"); + const persistRetainedSandboxRecovery = vi.fn(() => true); + + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate: vi.fn(), + create: async (verifyCreatedSandbox) => { + await verifyCreatedSandbox("created"); + throw createFailure; + }, + ...exactIdentityBoundary(), + persistRetainedSandboxRecovery, + cleanupTemporarySources: vi.fn(), + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).errors).toContain(createFailure); + expect(persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining("left sandbox 'alpha' in place"), + exactIdentity, + "verified", + ); + }); + + it.each(["false", "throw", "journal readback mismatch"] as const)( + "retries create-runner recovery when its durable writer returns %s (#9833)", + async (failureMode) => { + const exitHandlers: Array<() => void> = []; + const retryOwner = installPostCreateRecoveryRetryOwner({ + log: vi.fn(), + registerExitHandler: (handler) => exitHandlers.push(handler), + }); + const createFailure = new Error("runtime patch failed after verification"); + const writerFailures = { + false: () => false, + throw: () => { + throw new Error("retained recovery writer threw"); + }, + "journal readback mismatch": () => { + throw new Error("Retained sandbox recovery record did not survive durable readback."); + }, + } satisfies Record boolean>; + const writer = vi + .fn() + .mockImplementationOnce(writerFailures[failureMode]) + .mockReturnValue(true); + const create = vi.fn(async (verifyCreatedSandbox: (created: string) => Promise) => { + await verifyCreatedSandbox("created"); + throw createFailure; + }); + + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate: vi.fn(), + create, + ...exactIdentityBoundary(), + persistRetainedSandboxRecovery: writer, + retainedSandboxRecoveryRetryOwner: retryOwner, + cleanupTemporarySources: vi.fn(), + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect(writer).toHaveBeenCalledOnce(); + expect(create).toHaveBeenCalledOnce(); + + exitHandlers[0](); + expect(writer).toHaveBeenCalledTimes(2); + expect(create).toHaveBeenCalledOnce(); + + exitHandlers[0](); + expect(writer).toHaveBeenCalledTimes(2); + }, + ); + it("does not delete a same-name replacement after final authority failure (#9833)", async () => { let sandboxIdentity = "created"; const revalidate = vi.fn(); @@ -722,7 +1002,7 @@ describe("sandbox create policy authority checks", () => { expect.objectContaining({ message: expect.stringMatching( new RegExp( - `left sandbox 'alpha' in place.*identity fingerprint: ${exactIdentity}.*Do not delete the sandbox by name, even after this comparison`, + `left sandbox 'alpha' in place.*identity fingerprint: ${exactIdentity}.*Do not delete the sandbox by mutable sandbox name`, "u", ), ), @@ -742,6 +1022,75 @@ describe("sandbox create policy authority checks", () => { expect(sandboxIdentity).toBe("replacement"); }); + it("retains the durable checkpoint when identity-bound provider attachment is unavailable (#9833)", async () => { + const runOpenshell = vi.fn(() => ({ status: 0 })); + const checkpoint = { state: "absent" }; + const providerBoundary = createProviderEffectBoundary({ + deferred: true, + sandboxName: "alpha", + gatewayName: "nemoclaw", + preparationInput: { + openshellDriver: "kubernetes", + inferenceProvider: null, + messagingProviders: [], + messagingProviderRequests: [], + extraProviders: [], + gatewayName: "nemoclaw", + }, + preparationDeps: { + providerExistsInGateway: vi.fn(() => true), + runOpenshell: runOpenshell as never, + cleanupCreateSources: vi.fn(), + }, + runVerifiedSandboxCreateEffects: null, + activateDeferredProviderEffects: () => ["credential-provider"], + revalidatePolicyAuthorityBeforeCreate: vi.fn(), + }); + const error = await runSandboxCreateWithPolicyAuthorityChecks({ + sandboxName: "alpha", + revalidate: vi.fn(), + create: async (verifyCreatedSandbox) => { + await verifyCreatedSandbox("created"); + return "created"; + }, + ...exactIdentityBoundary(), + persistVerifiedPolicy: () => { + checkpoint.state = "verified-create"; + }, + runVerifiedCreateEffects: async () => { + await providerBoundary.runAfterVerifiedCreate?.({ + registration: { + policyAuthority: "nemoclaw-managed", + policyCreationReceipt: { + schemaVersion: 1, + origin: "sandbox-create", + gatewayName: "nemoclaw", + gatewayPort: 8080, + sandboxName: "alpha", + lifecycleGeneration: "00000000-0000-4000-8000-000000000001", + sandboxIdentityFingerprint: exactIdentity, + policyHash: "policy-alpha", + policyVersion: 1, + }, + observedPolicyAuthority: "owner-unknown", + }, + sandboxName: "alpha", + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "00000000-0000-4000-8000-000000000001", + lifecycleLiveIdentityFingerprint: exactIdentity, + route: "none", + revalidatePolicyRequirements: vi.fn(), + }); + }, + cleanupTemporarySources: vi.fn(), + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(AggregateError); + expect(checkpoint.state).toBe("verified-create"); + expect(runOpenshell).not.toHaveBeenCalled(); + }); + it("reports temporary source cleanup failure with sandbox preservation (#9833)", async () => { const revalidate = vi.fn(); @@ -932,6 +1281,7 @@ describe("sandbox create policy authority checks", () => { it("refuses continuation when identity changes during effective-policy verification (#9833)", async () => { const continuationEffect = vi.fn(); + const persistRetainedSandboxRecovery = vi.fn(() => true); const revalidate = vi .fn() .mockImplementationOnce(() => undefined) @@ -956,11 +1306,17 @@ describe("sandbox create policy authority checks", () => { persistCreatedSandboxIdentity: vi.fn(), revalidateCreatedSandboxIdentity, ...verifiedPolicyBoundary(), + persistRetainedSandboxRecovery, cleanupTemporarySources: vi.fn(), }), ).rejects.toThrow("automatic sandbox cleanup was not safe"); expect(continuationEffect).not.toHaveBeenCalled(); + expect(persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining("left sandbox 'alpha' in place"), + exactIdentity, + null, + ); }); it("stops before policy verification when the exact identity cannot be persisted (#9833)", async () => { @@ -1008,6 +1364,9 @@ describe("sandbox create policy authority checks", () => { }).catch((caught: unknown) => caught); expect(error).toBeInstanceOf(AggregateError); + expect((error as AggregateError).message).toMatch( + /left sandbox 'alpha' in place.*did not return a durable sandbox identity fingerprint.*Do not delete the sandbox by mutable sandbox name.*identity-bound recovery or removal procedure/u, + ); expect((error as AggregateError).errors).toEqual( expect.arrayContaining([ expect.objectContaining({ message: expect.stringContaining("post-create verification") }), diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index b2e96c3a600..45ea119325c 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -15,7 +15,7 @@ import type { AgentDefinition } from "../../agent/defs"; import type { WebSearchConfig } from "../../inference/web-search"; import type { SandboxMessagingPlan } from "../../messaging/manifest"; import type { BackupResult } from "../../state/sandbox"; -import type { Session } from "../../state/onboard-session"; +import type { RetainedSandboxRecoveryContext, Session } from "../../state/onboard-session"; import type { SandboxEntry } from "../../state/registry"; import type { PendingSandboxPolicyVerification, @@ -25,6 +25,7 @@ import type { HermesAuthMethod } from "../hermes-auth"; import * as policyAuthorityPreflight from "../policy-authority/preflight"; import type { PreparedSandboxBuildContext } from "../build-context-stage"; import type { DcodeSelectionDriftReader } from "../dcode-selection-drift"; +import { assertProviderlessInterceptorEnvironment } from "../entry-options"; import type { ManagedHermesStateVolumeCleanupResult, ManagedHermesStateVolumeContext, @@ -55,36 +56,179 @@ import { export const createOnboardPolicyAuthorityBindings = policyAuthorityPreflight.createOnboardPolicyAuthorityBindings; -type RetainedSandboxRecoveryReadback = { - readonly failure?: { readonly message?: string | null } | null; - readonly steps?: { - readonly sandbox?: { readonly error?: string | null } | null; - } | null; -}; +function cancelRecoveryIdentity( + liveExists: boolean, + requireVerifiedPolicyGate: () => VerifiedSandboxPolicyBoundary, +): { readonly lifecycleLiveIdentityFingerprint?: string } { + if (liveExists) return {}; + return { + lifecycleLiveIdentityFingerprint: requireVerifiedPolicyGate().lifecycleLiveIdentityFingerprint, + }; +} /** Persist one create-attempt recovery message through the onboard session owner. */ export function persistRetainedSandboxRecoveryMessage( - message: string, - finalizeIncompleteOnboardStep: ( - stepName: string, + input: { + readonly sandboxName: string; + readonly message: string; + readonly sandboxIdentityFingerprint?: string; + readonly recoveryContext: RetainedSandboxRecoveryContext; + }, + markRetainedSandboxRecovery: ( + sandboxName: string, message: string, - ) => RetainedSandboxRecoveryReadback | null, + sandboxIdentityFingerprint?: string, + context?: RetainedSandboxRecoveryContext, + ) => unknown | null, ): boolean { - const stored = finalizeIncompleteOnboardStep("sandbox", message); - const storedFailure = stored?.failure?.message; - const storedStep = stored?.steps?.sandbox?.error; - const authorityFields = [ - message.match(/Create-attempt label: ai\.nvidia\.nemoclaw\.create-attempt=[0-9a-f]{62}/u)?.[0], - message.match(/Durable sandbox identity fingerprint: [0-9a-f]{64}/u)?.[0], - ].filter((field): field is string => Boolean(field)); - return ( - typeof storedFailure === "string" && - storedFailure === storedStep && - authorityFields.length > 0 && - authorityFields.every((field) => storedFailure.includes(field)) + return Boolean( + markRetainedSandboxRecovery( + input.sandboxName, + input.message, + input.sandboxIdentityFingerprint, + input.recoveryContext, + ), ); } +export class RetainedSandboxRecoveryPersistenceError extends Error { + constructor( + readonly stage: "registry publication" | "onboarding finalization", + options?: ErrorOptions, + ) { + super(`NemoClaw could not save the retained sandbox recovery record after ${stage}.`, options); + this.name = "RetainedSandboxRecoveryPersistenceError"; + } +} + +export interface PostCreateRecoveryRetryOwner { + record(recordRecovery: () => void): void; +} + +export function installPostCreateRecoveryRetryOwner( + options: { + readonly log?: (message: string) => void; + readonly registerExitHandler?: (handler: () => void) => void; + } = {}, +): PostCreateRecoveryRetryOwner { + let pending: (() => void) | null = null; + const log = options.log ?? ((message: string) => console.error(message)); + const attemptPending = (propagateFailure: boolean): void => { + if (pending === null) return; + const attempt = pending; + try { + attempt(); + if (pending === attempt) pending = null; + } catch (error) { + if (propagateFailure) throw error; + log( + " NemoClaw still could not save the retained sandbox recovery record; the recovery-only session remains blocked for administrator recovery.", + ); + } + }; + const owner: PostCreateRecoveryRetryOwner = { + record(recordRecovery): void { + attemptPending(true); + pending = recordRecovery; + attemptPending(true); + }, + }; + const register = + options.registerExitHandler ?? + ((handler: () => void) => { + process.on("exit", handler); + }); + register(() => attemptPending(false)); + return owner; +} + +function persistRetainedSandboxRecoveryWithRetry( + retryOwner: PostCreateRecoveryRetryOwner | undefined, + persist: () => boolean, +): boolean { + let persisted = false; + const attempt = (): void => { + persisted = persist(); + if (!persisted) { + throw new Error("NemoClaw could not save the retained sandbox recovery record."); + } + }; + if (retryOwner) retryOwner.record(attempt); + else attempt(); + return persisted; +} + +export function persistPostCreateRecovery(input: { + readonly stage: "registry publication" | "onboarding finalization"; + readonly sandboxName: string; + readonly gatewayName: string; + readonly lifecycleGeneration: string; + readonly exactIdentity?: string; + readonly recoveryContext: RetainedSandboxRecoveryContext; + readonly markRetainedSandboxRecovery: ( + sandboxName: string, + message: string, + sandboxIdentityFingerprint?: string, + context?: RetainedSandboxRecoveryContext, + ) => unknown | null; +}): void { + const message = + `Sandbox '${input.sandboxName}' was retained after ${input.stage} failed. ` + + `Gateway '${input.gatewayName}'. Lifecycle generation '${input.lifecycleGeneration}'. ` + + "Do not delete the sandbox by mutable name; preserve it for identity-bound administrator recovery."; + let persisted = false; + try { + persisted = persistRetainedSandboxRecoveryMessage( + { + sandboxName: input.sandboxName, + message, + ...(input.exactIdentity ? { sandboxIdentityFingerprint: input.exactIdentity } : {}), + recoveryContext: input.recoveryContext, + }, + input.markRetainedSandboxRecovery, + ); + } catch (cause) { + throw new RetainedSandboxRecoveryPersistenceError(input.stage, { cause }); + } + if (!persisted) { + throw new RetainedSandboxRecoveryPersistenceError(input.stage); + } +} + +function throwPostCreateFailure(error: unknown, recordRecovery: () => void): never { + try { + recordRecovery(); + } catch (recoveryError) { + throw new AggregateError( + [error, recoveryError], + "The sandbox operation failed, and its retained recovery record could not be persisted.", + ); + } + throw error; +} + +export async function runAsyncWithPostCreateRecovery( + operation: () => Promise, + recordRecovery: () => void, +): Promise { + try { + return await operation(); + } catch (error) { + return throwPostCreateFailure(error, recordRecovery); + } +} + +export function runWithPostCreateRecovery( + operation: () => Result, + recordRecovery: () => void, +): Result { + try { + return operation(); + } catch (error) { + return throwPostCreateFailure(error, recordRecovery); + } +} + export type EffectiveVerifiedSandboxPolicyBoundary = VerifiedSandboxPolicyBoundary & { readonly policySourcePath: string; }; @@ -172,6 +316,48 @@ export function assertApfCreateIntent( } } +function assertProviderlessApfCreateInput(input: { + readonly createIntent: SandboxCreateIntent | null; + readonly agent: AgentDefinition | null; + readonly model: string; + readonly provider: string; + readonly preferredInferenceApi: string | null; + readonly webSearchConfig: WebSearchConfig | null; + readonly enabledChannels: readonly string[] | null; + readonly hermesToolGateways: readonly string[]; +}): void { + if (input.createIntent?.apfInterceptorRequested !== true) return; + const resolved = input.createIntent.resolved; + const requestedAgent = input.agent?.name.trim().toLowerCase() ?? "openclaw"; + const hasProviderIntent = + requestedAgent !== "openclaw" || + input.webSearchConfig !== null || + input.createIntent.reuseRegisteredCredentials === true || + [ + input.provider, + input.model, + input.preferredInferenceApi, + input.createIntent.endpointUrl, + resolved?.inferenceProvider, + ].some((value) => Boolean(value?.trim())) || + [ + input.enabledChannels, + input.hermesToolGateways, + input.createIntent.extraProviders, + resolved?.activeMessagingChannels, + resolved?.messagingProviderRequests, + resolved?.reusableMessagingProviders, + resolved?.extraProviders, + resolved?.staleExtraProviders, + resolved?.hermesToolGateways, + resolved?.extraPlaceholderKeys, + ].some((values) => (values?.length ?? 0) > 0); + if (!hasProviderIntent) return; + throw new Error( + "Interceptor onboarding supports providerless sandbox creation only. No sandbox or provider was created.", + ); +} + type SandboxRecreateReasonInput = { sandboxName: string; recreateForAgentDrift: boolean; @@ -356,32 +542,35 @@ export function reconcileCreatedHermesCredentialEnvironment( readonly plan: SandboxMessagingPlan | null; }, deps: CreatedHermesCredentialEnvReconciliationDeps, + recordRecovery: () => void, ): void { - if (input.plan?.agent !== "hermes") return; - - deps.revalidatePolicyAuthority( - `reconciling Hermes messaging credentials for sandbox '${input.sandboxName}'`, - ); - const reconciliation = deps.reconcileCredentialEnv(input.plan); - deps.revalidatePolicyAuthority( - `confirming Hermes messaging credential reconciliation for sandbox '${input.sandboxName}'`, - ); - if (!reconciliation.changed) return; + return runWithPostCreateRecovery(() => { + if (input.plan?.agent !== "hermes") return; - const restart = deps.restartGateway(input.sandboxName); - if (!deps.parseRestartCompletion(restart)) { - throw new Error( - `Hermes messaging credential reconciliation changed the gateway environment for sandbox '${input.sandboxName}', but the managed gateway restart did not complete.`, + deps.revalidatePolicyAuthority( + `reconciling Hermes messaging credentials for sandbox '${input.sandboxName}'`, ); - } - if (!deps.waitForGateway(input.sandboxName)) { - throw new Error( - `Hermes messaging credential reconciliation restarted sandbox '${input.sandboxName}', but the managed gateway did not remain healthy.`, + const reconciliation = deps.reconcileCredentialEnv(input.plan); + deps.revalidatePolicyAuthority( + `confirming Hermes messaging credential reconciliation for sandbox '${input.sandboxName}'`, ); - } - deps.revalidatePolicyAuthority( - `completing Hermes messaging credential reconciliation for sandbox '${input.sandboxName}'`, - ); + if (!reconciliation.changed) return; + + const restart = deps.restartGateway(input.sandboxName); + if (!deps.parseRestartCompletion(restart)) { + throw new Error( + `Hermes messaging credential reconciliation changed the gateway environment for sandbox '${input.sandboxName}', but the managed gateway restart did not complete.`, + ); + } + if (!deps.waitForGateway(input.sandboxName)) { + throw new Error( + `Hermes messaging credential reconciliation restarted sandbox '${input.sandboxName}', but the managed gateway did not remain healthy.`, + ); + } + deps.revalidatePolicyAuthority( + `completing Hermes messaging credential reconciliation for sandbox '${input.sandboxName}'`, + ); + }, recordRecovery); } export async function finalizeCreatedSandboxBeforeHermesCredentialReconciliation( @@ -428,11 +617,19 @@ export async function runSandboxCreateWithPolicyAuthorityChecks< exactIdentity: string, evidence: Evidence, ) => Promise; + readonly persistRetainedSandboxRecovery?: ( + message: string, + exactIdentity: string | null, + evidence: Evidence | null, + ) => boolean; + readonly retainedSandboxRecoveryRetryOwner?: PostCreateRecoveryRetryOwner; readonly cleanupTemporarySources: () => void; }): Promise { input.revalidate(false, `creating sandbox '${input.sandboxName}'`); let exactIdentity: string | null = null; + let observedPolicyEvidence: Evidence | null = null; let cleanupAttempted = false; + let recoveryAttempted = false; const cleanupTemporarySources = (): unknown[] => { if (cleanupAttempted) return []; cleanupAttempted = true; @@ -444,22 +641,37 @@ export async function runSandboxCreateWithPolicyAuthorityChecks< } }; const refuseAfterCreate = (validationError: unknown): never => { - const compensationErrors = cleanupTemporarySources(); + recoveryAttempted = true; const validationDetail = validationError instanceof Error && isPolicyAuthorityRefusalError(validationError) ? validationError.message : null; const identityGuidance = exactIdentity - ? ` Durable sandbox identity fingerprint: ${exactIdentity}. Use it only to compare the surviving sandbox with the failed create. Do not delete the sandbox by name, even after this comparison. Contact the OpenShell administrator for an identity-bound recovery or removal procedure.` - : " OpenShell did not return a durable identity for comparison. Do not delete the sandbox by name. Contact the OpenShell administrator for an identity-bound recovery or removal procedure."; - compensationErrors.push( - new Error( - `NemoClaw left sandbox '${input.sandboxName}' in place after policy authority validation failed because OpenShell can delete it only by mutable name.${identityGuidance}`, - ), - ); + ? `Durable sandbox identity fingerprint: ${exactIdentity}. Use it only to compare the surviving sandbox with the failed create.` + : "OpenShell did not return a durable sandbox identity fingerprint for comparison."; + const recoveryGuidance = + `NemoClaw left sandbox '${input.sandboxName}' in place after policy authority validation failed. ` + + `${identityGuidance} NemoClaw did not run OpenShell's mutable-name deletion command because the name may now identify a replacement sandbox. ` + + "Do not delete the sandbox by mutable sandbox name. Ask the OpenShell administrator to inspect the surviving sandbox and use an identity-bound recovery or removal procedure."; + const compensationErrors: unknown[] = []; + if (input.persistRetainedSandboxRecovery) { + try { + persistRetainedSandboxRecoveryWithRetry(input.retainedSandboxRecoveryRetryOwner, () => + input.persistRetainedSandboxRecovery!( + recoveryGuidance, + exactIdentity, + observedPolicyEvidence, + ), + ); + } catch (error) { + compensationErrors.push(error); + } + } + compensationErrors.push(...cleanupTemporarySources()); + compensationErrors.push(new Error(recoveryGuidance)); throw new AggregateError( [validationError, ...compensationErrors], - `Sandbox policy authority validation failed after creation${validationDetail ? `: ${validationDetail}` : ""}; automatic sandbox cleanup was not safe.`, + `Sandbox policy authority validation failed after creation${validationDetail ? `: ${validationDetail}` : ""}; automatic sandbox cleanup was not safe. ${recoveryGuidance}`, ); }; const verifyCreatedSandbox = async (created: Created): Promise => { @@ -481,6 +693,7 @@ export async function runSandboxCreateWithPolicyAuthorityChecks< capturedIdentity, `recording verified policy for sandbox '${input.sandboxName}'`, ); + observedPolicyEvidence = evidence; input.persistVerifiedPolicy(created, capturedIdentity, evidence); input.revalidateVerifiedPolicy( created, @@ -502,6 +715,7 @@ export async function runSandboxCreateWithPolicyAuthorityChecks< try { result = await input.create(verifyCreatedSandbox); } catch (error) { + if (exactIdentity !== null && !recoveryAttempted) return refuseAfterCreate(error); const cleanupErrors = cleanupTemporarySources(); if (cleanupErrors.length > 0) { throw new AggregateError( @@ -671,8 +885,6 @@ export function createProviderEffectBoundary(input: { | ((revalidatePolicyRequirements: (operation: string) => void) => readonly string[]) | null; readonly revalidatePolicyAuthorityBeforeCreate: () => void; - readonly runOpenshell: SandboxCreateOrchestrationRuntime["runOpenshell"]; - readonly revalidateSandboxIdentity: (exactIdentity: string, operation: string) => void; }): ProviderEffectBoundary { const validate = () => validateAttachedMessagingProvidersBeforeSandboxCreation( @@ -715,20 +927,11 @@ export function createProviderEffectBoundary(input: { context.revalidatePolicyRequirements( `attaching deferred providers to sandbox '${input.sandboxName}'`, ); - attachProvidersAfterSandboxCreation( - { - sandboxName: input.sandboxName, - gatewayName: input.gatewayName, - providerNames, - }, - { - runOpenshell: input.runOpenshell, - revalidateSandboxIdentity: (operation) => { - input.revalidateSandboxIdentity(context.lifecycleLiveIdentityFingerprint, operation); - context.revalidatePolicyRequirements(operation); - }, - }, - ); + attachProvidersAfterSandboxCreation({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + providerNames, + }); }, }; } @@ -851,6 +1054,7 @@ function readHermesPortableLifecycleGeneration(input: { } export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrchestrationRuntime) { + const postCreateRecoveryRetryOwner = installPostCreateRecoveryRetryOwner(); return async function createSandboxWithBaseImageResolution( baseImageResolutionContext: import("../base-image-resolution-flow").BaseImageResolutionContext, portableRuntimeContext: PortableOnboardRuntimeContext | null, @@ -984,12 +1188,26 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche runCapture, } = runtime; + assertApfCreateIntent(createIntent); + assertProviderlessApfCreateInput({ + createIntent, + agent, + model, + provider, + preferredInferenceApi, + webSearchConfig, + enabledChannels, + hermesToolGateways, + }); + assertProviderlessInterceptorEnvironment( + createIntent?.apfInterceptorRequested === true, + process.env, + ); step(6, 8, "Creating sandbox"); const sandboxName = validateName( sandboxNameOverride ?? (await promptValidatedSandboxName(agent)), "sandbox name", ); - assertApfCreateIntent(createIntent); preparedDcodeRebuild.assertPreparedDcodeTarget(preparedBuildContext, agent, fromDockerfile); const effectiveAgent = sandboxAgent.getEffectiveSandboxAgent(agent); const requestedAgentName = getRequestedSandboxAgentName(effectiveAgent); @@ -2153,6 +2371,50 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche requirePendingPolicyVerification(), ); }; + const retainedSandboxRecoveryContext = ( + boundary: VerifiedSandboxPolicyBoundary | null, + ): RetainedSandboxRecoveryContext => { + const checkpoint = boundary ? pendingSandboxPolicyVerificationForBoundary(boundary) : null; + return { + gatewayName: GATEWAY_NAME, + gatewayPort: GATEWAY_PORT, + lifecycleGeneration: createdSandboxLifecycle.generation, + verifiedEffectivePolicyIdentity: checkpoint + ? { hash: checkpoint.policyHash, activeVersion: checkpoint.policyVersion } + : null, + }; + }; + const recordPostCreateRecovery = ( + stage: "registry publication" | "onboarding finalization", + ): void => { + const boundary = requireVerifiedPolicyGate(); + postCreateRecoveryRetryOwner.record(() => + persistPostCreateRecovery({ + stage, + sandboxName, + gatewayName: GATEWAY_NAME, + lifecycleGeneration: createdSandboxLifecycle.generation, + exactIdentity: boundary.lifecycleLiveIdentityFingerprint, + recoveryContext: retainedSandboxRecoveryContext(boundary), + markRetainedSandboxRecovery: onboardSession.markRetainedSandboxRecovery, + }), + ); + }; + const persistCreateFlowRecovery = ( + message: string, + exactIdentity: string | null = null, + ): boolean => + persistRetainedSandboxRecoveryWithRetry(postCreateRecoveryRetryOwner, () => + persistRetainedSandboxRecoveryMessage( + { + sandboxName, + message, + ...(exactIdentity ? { sandboxIdentityFingerprint: exactIdentity } : {}), + recoveryContext: retainedSandboxRecoveryContext(verifiedPolicyGate), + }, + onboardSession.markRetainedSandboxRecovery, + ), + ); const runCreateFlow = async ( attemptCreateArgv: string[], hermesPortableReadyCapture?: import("../sandbox-gpu-create-flow").HermesPortableReadyCapture, @@ -2248,6 +2510,17 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche revalidateVerifiedPolicy: (_identity, _exactIdentity, boundary, operation) => { revalidateVerifiedPolicyRegistration(boundary, operation); }, + persistRetainedSandboxRecovery: (message, exactIdentity, boundary) => + persistRetainedSandboxRecoveryMessage( + { + sandboxName, + message, + ...(exactIdentity ? { sandboxIdentityFingerprint: exactIdentity } : {}), + recoveryContext: retainedSandboxRecoveryContext(boundary), + }, + onboardSession.markRetainedSandboxRecovery, + ), + retainedSandboxRecoveryRetryOwner: postCreateRecoveryRetryOwner, cleanupTemporarySources: cleanupSandboxCreateSources, runVerifiedCreateEffects: runDeferredProviderEffects ? async (_identity, _exactIdentity, boundary) => { @@ -2271,11 +2544,8 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche requirePolicylessCreate: true as const, } : {}), - persistRetainedSandboxRecovery: (message) => - persistRetainedSandboxRecoveryMessage( - message, - onboardSession.finalizeIncompleteOnboardStep, - ), + persistRetainedSandboxRecovery: (message, sandboxIdentityFingerprint) => + persistCreateFlowRecovery(message, sandboxIdentityFingerprint ?? null), provider, sandboxGpuConfig: effectiveSandboxGpuConfig, gpuRoutePlan, @@ -2436,16 +2706,6 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche false, `publishing providers before creating sandbox gateway '${GATEWAY_NAME}'`, ), - runOpenshell, - revalidateSandboxIdentity: (exactIdentity, operation) => - sandboxRecreateTransaction.revalidateCreatedSandboxLifecycleRegistration( - { sandboxName, gatewayName: GATEWAY_NAME }, - { - lifecycleGeneration: createdSandboxLifecycle.generation, - lifecycleLiveIdentityFingerprint: exactIdentity, - }, - getSandboxRecreateObservation, - ), }); providerEffectBoundary.validateBeforeCreate(); @@ -2551,7 +2811,10 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche try { await finalizeCreatedSandboxBeforeHermesCredentialReconciliation( async () => { - const registration = await completeCreatedSandboxRegistration(created, null); + const registration = await runAsyncWithPostCreateRecovery( + () => completeCreatedSandboxRegistration(created, null), + () => recordPostCreateRecovery("registry publication"), + ); verifiedPolicyRegistrationFinalized = true; return registration; }, @@ -2565,34 +2828,52 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche (args, options) => runOpenshell([...args], options), (operation) => revalidatePolicyAuthority(true, operation), ), + () => recordPostCreateRecovery("onboarding finalization"), ), ); } finally { cleanupInitialCreateSource(); } } - hermesStateVolumeLifecycle?.commit(); - if ("complete" in recreateRuntime) recreateRuntime.complete(); - if (agentCreateInput.hermesPortableLifecycle) return sandboxName; - return completeOrdinaryOnboardSandboxCreation( - { - sandboxName, - sandboxWasLiveDefault, - runtimeFields: sandboxRuntimeFields, - messagingProviders, - liveExists, - }, - { - setDefault: registry.setDefault, - runFile, - scriptsDir: SCRIPTS, - gatewayName: GATEWAY_NAME, - providerExistsInGateway, - armCancelRollback: sandboxCancelRollback.arm, - dockerInfoFormat, - runCapture, - revalidatePolicyAuthority: (operation) => revalidatePolicyAuthority(true, operation), + return runWithPostCreateRecovery( + () => { + hermesStateVolumeLifecycle?.commit(); + if ("complete" in recreateRuntime) recreateRuntime.complete(); + if (agentCreateInput.hermesPortableLifecycle) return sandboxName; + return completeOrdinaryOnboardSandboxCreation( + { + sandboxName, + sandboxWasLiveDefault, + runtimeFields: sandboxRuntimeFields, + messagingProviders, + liveExists, + ...cancelRecoveryIdentity(liveExists, requireVerifiedPolicyGate), + }, + { + setDefault: registry.setDefault, + runFile, + scriptsDir: SCRIPTS, + gatewayName: GATEWAY_NAME, + providerExistsInGateway, + armCancelRollback: (name, identity) => + sandboxCancelRollback.arm( + name, + identity, + retainedSandboxRecoveryContext(requireVerifiedPolicyGate()), + ), + markCancellationRecovery: (name) => + onboardSession.markCancellationRecovery( + name, + undefined, + retainedSandboxRecoveryContext(requireVerifiedPolicyGate()), + ), + dockerInfoFormat, + runCapture, + revalidatePolicyAuthority: (operation) => revalidatePolicyAuthority(true, operation), + }, + ); }, + () => recordPostCreateRecovery("onboarding finalization"), ); }; } diff --git a/src/lib/onboard/sandbox-create/provider-publication.test.ts b/src/lib/onboard/sandbox-create/provider-publication.test.ts index b7dbdd0aa10..d194600dfbc 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.test.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.test.ts @@ -117,56 +117,24 @@ function prepareProviders( } describe("sandbox provider preparation", () => { - it("identity-fences every deferred provider attachment (#9833)", () => { - const events: string[] = []; - const runOpenshell = vi.fn((args: string[]) => { - events.push(args.join(" ")); - return { status: 0 }; - }); - - attachProvidersAfterSandboxCreation( - { + it("refuses name-addressed deferred provider attachment before mutation (#9833)", () => { + expect(() => + attachProvidersAfterSandboxCreation({ sandboxName: "alpha", gatewayName: "nemoclaw", providerNames: ["inference", "alpha-telegram"], - }, - { - runOpenshell: runOpenshell as never, - revalidateSandboxIdentity: (operation) => events.push(operation), - }, - ); - - expect(events).toEqual([ - "attaching provider 'inference' to sandbox 'alpha'", - "sandbox provider attach -g nemoclaw alpha inference", - "confirming provider 'inference' on sandbox 'alpha'", - "attaching provider 'alpha-telegram' to sandbox 'alpha'", - "sandbox provider attach -g nemoclaw alpha alpha-telegram", - "confirming provider 'alpha-telegram' on sandbox 'alpha'", - ]); + }), + ).toThrow("OpenShell cannot attach providers to the immutable identity of sandbox 'alpha'"); }); - it("redacts deferred attachment command output on failure (#9833)", () => { - const revalidateSandboxIdentity = vi.fn(); - + it("allows an empty deferred attachment set without a mutable-name operation (#9833)", () => { expect(() => - attachProvidersAfterSandboxCreation( - { - sandboxName: "alpha", - gatewayName: "nemoclaw", - providerNames: ["alpha-telegram"], - }, - { - runOpenshell: vi.fn(() => ({ - status: 1, - stdout: "secret-stdout", - stderr: "secret-stderr", - })) as never, - revalidateSandboxIdentity, - }, - ), - ).toThrow("OpenShell did not attach provider 'alpha-telegram' to the verified sandbox."); - expect(revalidateSandboxIdentity).toHaveBeenCalledOnce(); + attachProvidersAfterSandboxCreation({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + providerNames: [], + }), + ).not.toThrow(); }); it("confirms an exact messaging binding before and after publication (#9875)", () => { diff --git a/src/lib/onboard/sandbox-create/provider-publication.ts b/src/lib/onboard/sandbox-create/provider-publication.ts index e50249c13d3..bf1d203d22a 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.ts @@ -33,10 +33,6 @@ type DeferredProviderAttachmentInput = { readonly providerNames: readonly string[]; }; -type DeferredProviderAttachmentDeps = Pick & { - readonly revalidateSandboxIdentity: (operation: string) => void; -}; - function expectedMessagingBindings(input: ProviderPreparationInput) { return new Map( input.messagingProviderRequests @@ -149,25 +145,10 @@ export function publishAttachedProvidersBeforeDockerSandboxCreation( } /** Attach the planned providers only after the created sandbox passed its exact policy gate. */ -export function attachProvidersAfterSandboxCreation( - input: DeferredProviderAttachmentInput, - deps: DeferredProviderAttachmentDeps, -): void { - for (const providerName of input.providerNames) { - deps.revalidateSandboxIdentity( - `attaching provider '${providerName}' to sandbox '${input.sandboxName}'`, - ); - const attached = deps.runOpenshell( - ["sandbox", "provider", "attach", "-g", input.gatewayName, input.sandboxName, providerName], - { ignoreError: true, suppressOutput: true }, - ); - if (attached.status !== 0) { - throw new Error( - `OpenShell did not attach provider '${providerName}' to the verified sandbox.`, - ); - } - deps.revalidateSandboxIdentity( - `confirming provider '${providerName}' on sandbox '${input.sandboxName}'`, - ); - } +export function attachProvidersAfterSandboxCreation(input: DeferredProviderAttachmentInput): void { + if (input.providerNames.length === 0) return; + throw new Error( + `OpenShell cannot attach providers to the immutable identity of sandbox '${input.sandboxName}'. ` + + `The sandbox remains incomplete on gateway '${input.gatewayName}'; preserve its verified create checkpoint for administrator recovery.`, + ); } diff --git a/src/lib/onboard/sandbox-gpu-create-flow.ts b/src/lib/onboard/sandbox-gpu-create-flow.ts index 15ea2470281..cf3952b885c 100644 --- a/src/lib/onboard/sandbox-gpu-create-flow.ts +++ b/src/lib/onboard/sandbox-gpu-create-flow.ts @@ -218,7 +218,10 @@ export interface SandboxGpuCreateFlowInput { /** Reject every initial or fallback create attempt that carries a caller policy. */ requirePolicylessCreate?: true; /** Durably retain exact create-attempt recovery evidence before identity-bound recovery stops. */ - persistRetainedSandboxRecovery?: (message: string) => boolean; + persistRetainedSandboxRecovery?: ( + message: string, + sandboxIdentityFingerprint?: string, + ) => boolean; provider: string; sandboxGpuConfig: SandboxGpuConfig; gpuRoutePlan: import("./docker-gpu-route").DockerGpuRoutePlan; @@ -567,7 +570,9 @@ export async function runSandboxGpuCreateFlow( "Do not delete a sandbox by mutable name; use an identity-bound administrator recovery procedure."; let persisted = false; try { - persisted = persistRetainedSandboxRecovery(message); + persisted = evidence.liveIdentityFingerprint + ? persistRetainedSandboxRecovery(message, evidence.liveIdentityFingerprint) + : persistRetainedSandboxRecovery(message); } catch { persisted = false; } diff --git a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts index 09ff21e980f..4c93be667cf 100644 --- a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts +++ b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts @@ -582,6 +582,12 @@ describe("created sandbox identity gate", () => { ); expect(input.verifyCreatedSandboxBeforeEffects).not.toHaveBeenCalled(); + expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining( + `Durable sandbox identity fingerprint: ${fingerprintSandboxRecreateValue("alpha-sandbox-id")}`, + ), + fingerprintSandboxRecreateValue("alpha-sandbox-id"), + ); expect(patch.exitOnPatchError).not.toHaveBeenCalled(); expect(patch.ensureApplied).not.toHaveBeenCalled(); expect(mocks.waitForCreatedSandboxReadyWithTrace).not.toHaveBeenCalled(); @@ -615,6 +621,12 @@ describe("created sandbox identity gate", () => { ); expect(input.verifyCreatedSandboxBeforeEffects).not.toHaveBeenCalled(); + expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining( + `Durable sandbox identity fingerprint: ${fingerprintSandboxRecreateValue("alpha-sandbox-id")}`, + ), + fingerprintSandboxRecreateValue("alpha-sandbox-id"), + ); expect(patch.exitOnPatchError).not.toHaveBeenCalled(); expect(patch.ensureApplied).not.toHaveBeenCalled(); expect(mocks.waitForCreatedSandboxReadyWithTrace).not.toHaveBeenCalled(); @@ -724,6 +736,38 @@ describe("created sandbox identity gate", () => { expect(mocks.waitForCreatedSandboxReadyWithTrace).not.toHaveBeenCalled(); }); + it("returns a post-verification readiness failure to the recovery owner (#9833)", async () => { + let nonce = ""; + const input = noGpuInput(); + input.verifyCreatedSandboxBeforeEffects = vi.fn(); + input.revalidateVerifiedSandboxBeforeEffect = vi.fn(); + const patch = createGpuPatchFixture(); + mocks.createDockerGpuSandboxCreatePatch.mockReturnValue(patch); + mocks.streamSandboxCreate.mockImplementation(async (_command, args) => { + nonce = createAttemptNonce(args); + return { status: 0, output: "Created sandbox: alpha", sawProgress: true }; + }); + mocks.waitForCreatedSandboxReadyWithTrace.mockReturnValue({ + ready: false, + reason: "timeout", + failurePhase: null, + }); + const deps = createGpuFlowDeps(); + vi.mocked(deps.runCaptureOpenshell).mockImplementationOnce(() => + sandboxListJson("alpha-sandbox-id", { [NEMOCLAW_CREATE_ATTEMPT_LABEL]: nonce }), + ); + const exit = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("direct process exit bypassed the recovery owner"); + }); + + await expect(runSandboxGpuCreateFlow(input, deps)).rejects.toThrow( + "Sandbox 'alpha' did not become ready after verified creation", + ); + + expect(input.verifyCreatedSandboxBeforeEffects).toHaveBeenCalledOnce(); + expect(exit).not.toHaveBeenCalled(); + }); + it("uses a distinct identity label for each create attempt (#9833)", async () => { const input = createGpuFlowInput(); input.verifyCreatedSandboxBeforeEffects = vi.fn(); @@ -806,6 +850,7 @@ describe("created sandbox identity gate", () => { "u", ), ), + fingerprint, ); expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledBefore(exit); const output = vi.mocked(console.error).mock.calls.flat().join("\n"); diff --git a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts index 82f910fb50e..f605b664237 100644 --- a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts +++ b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts @@ -393,7 +393,9 @@ export function createSandboxGpuCreateAttemptRunner( const createAttemptNonce = deferPostCreateEffects ? randomBytes(NEMOCLAW_CREATE_ATTEMPT_NONCE_HEX_LENGTH / 2).toString("hex") : null; - const persistIdentitySettlementRecovery = (): void => { + const persistIdentitySettlementRecovery = ( + sandboxIdentityFingerprint: string | null = null, + ): void => { if (!createAttemptNonce) { throw new Error("Sandbox create-attempt identity was not generated."); } @@ -401,15 +403,18 @@ export function createSandboxGpuCreateAttemptRunner( if (!persist) { throw new Error("Verified sandbox creation has no durable recovery evidence owner."); } + const identityEvidence = sandboxIdentityFingerprint + ? `Durable sandbox identity fingerprint: ${sandboxIdentityFingerprint}. Sandbox '${input.sandboxName}' did not remain visible through owning gateway '${input.gatewayName}' before policy verification. ` + : `Sandbox '${input.sandboxName}' reached Ready before OpenShell returned one exact durable create identity. Gateway '${input.gatewayName}'. OpenShell did not return one exact durable sandbox identity for this create attempt. `; const message = `Create-attempt label: ${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${createAttemptNonce}. ` + - `Sandbox '${input.sandboxName}' reached Ready before OpenShell returned one exact durable create identity. ` + - `Gateway '${input.gatewayName}'. ` + - "OpenShell did not return one exact durable sandbox identity for this create attempt. " + + identityEvidence + "Do not delete a sandbox by mutable name; preserve it until an OpenShell administrator resolves the create-attempt label to one sandbox."; let persisted = false; try { - persisted = persist(message); + persisted = sandboxIdentityFingerprint + ? persist(message, sandboxIdentityFingerprint) + : persist(message); } catch { persisted = false; } @@ -420,6 +425,14 @@ export function createSandboxGpuCreateAttemptRunner( ); } }; + const waitForCreatedSandboxPublication = (sandboxId: string): void => { + try { + waitForCreatedOpenShellSandboxPublication(sandboxId, input, deps); + } catch (error) { + persistIdentitySettlementRecovery(fingerprintSandboxRecreateValue(sandboxId)); + throw error; + } + }; const captureRetainedSandboxRecovery = () => { if (!input.requirePolicylessCreate || !createAttemptNonce) return {}; let liveIdentityFingerprint: string | null = null; @@ -565,6 +578,10 @@ export function createSandboxGpuCreateAttemptRunner( let resumedSandboxId: string | null = null; let managedIncompleteCreateRecovered = false; let createdSandboxVerified = false; + const failAfterCreatedSandboxVerification = (message: string, status: number): never => { + if (createdSandboxVerified) throw new Error(message); + return process.exit(status); + }; if (input.resumeVerifiedCreate) { if (route !== input.resumeVerifiedCreate.route) { throw new Error("Verified sandbox recovery route changed before continuation."); @@ -618,6 +635,7 @@ export function createSandboxGpuCreateAttemptRunner( sleep: deps.sleep, }); if (!readiness.ready) { + if (createAttemptNonce) persistIdentitySettlementRecovery(); throw new Error( sandboxReadinessTracing .formatCreatedSandboxReadinessFailureMessage( @@ -634,6 +652,7 @@ export function createSandboxGpuCreateAttemptRunner( timeout: SANDBOX_READY_PROBE_TIMEOUT_MS, }); if (!isSandboxReady(list, input.sandboxName)) { + if (createAttemptNonce) persistIdentitySettlementRecovery(); throw new Error( "Managed bootstrap create completed without an authoritative Ready sandbox.", ); @@ -659,7 +678,7 @@ export function createSandboxGpuCreateAttemptRunner( { cause: error }, ); } - waitForCreatedOpenShellSandboxPublication(sandboxId, input, deps); + waitForCreatedSandboxPublication(sandboxId); await verifyCreatedSandboxBeforeEffects(sandboxId, route, input); createdSandboxVerified = true; if (deferPostCreateEffects) { @@ -787,7 +806,7 @@ export function createSandboxGpuCreateAttemptRunner( { cause: error }, ); } - waitForCreatedOpenShellSandboxPublication(sandboxId, input, deps); + waitForCreatedSandboxPublication(sandboxId); await verifyCreatedSandboxBeforeEffects(sandboxId, route, input); createdSandboxVerified = true; } @@ -810,7 +829,10 @@ export function createSandboxGpuCreateAttemptRunner( printCreateFailureDiagnostics(input.sandboxName, { backupPath: input.restoreBackupPath, }); - process.exit(createResult?.status === 0 ? 1 : (createResult?.status ?? 1)); + failAfterCreatedSandboxVerification( + `Sandbox '${input.sandboxName}' did not return one exact durable sandbox ID before runtime recreation after verified creation.`, + createResult?.status === 0 ? 1 : (createResult?.status ?? 1), + ); } if (!portableLifecycle || managedLifecycle) { revalidatePostCreateEffect(`apply runtime patch for sandbox '${input.sandboxName}'`); @@ -900,7 +922,10 @@ export function createSandboxGpuCreateAttemptRunner( ); console.error(" Verify the sandbox identity before manual cleanup."); } - process.exit(createResult?.status === 0 ? 1 : (createResult?.status ?? 1)); + failAfterCreatedSandboxVerification( + `Sandbox '${input.sandboxName}' did not become ready after verified creation.`, + createResult?.status === 0 ? 1 : (createResult?.status ?? 1), + ); } if (input.sandboxGpuConfig.sandboxGpuEnabled) { revalidatePostCreateEffect(`verify GPU access for sandbox '${input.sandboxName}'`); @@ -959,7 +984,10 @@ export function createSandboxGpuCreateAttemptRunner( console.error( " To explicitly select the compatibility route, clean up the sandbox and retry with NEMOCLAW_DOCKER_GPU_PATCH=1.", ); - process.exit(1); + failAfterCreatedSandboxVerification( + `Sandbox '${input.sandboxName}' failed GPU proof after verified creation.`, + 1, + ); } if (proof.status === "failed") { await runtimePatch.rollbackManagedStartupAfterCreateFailure(); diff --git a/src/lib/state/onboard-session-cross-process-lock.test.ts b/src/lib/state/onboard-session-cross-process-lock.test.ts index d8f501a1c47..0f4c4cc7619 100644 --- a/src/lib/state/onboard-session-cross-process-lock.test.ts +++ b/src/lib/state/onboard-session-cross-process-lock.test.ts @@ -39,6 +39,23 @@ afterEach(() => { }); describe("cross-process onboard lock", () => { + it("rejects caller-asserted onboarding lock ownership without a live descriptor (#9833)", async () => { + const authority = await import("../onboard/portable-retirement-authority"); + + expect(() => + authority.beginPortableOnboardRetirementEntry({ + alreadyHeld: true, + command: "nemoclaw onboard --resume", + displayName: "NemoClaw", + homeDir: tempHome, + loadRegistry: () => ({ defaultSandbox: null, sandboxes: {} }), + registryFile: path.join(tempHome, ".nemoclaw", "registry.json"), + sessionFile: session.SESSION_FILE, + withLifecycleLock: async (_sandboxName, operation) => await operation(), + }), + ).toThrow(/does not own.*onboarding lock/u); + }); + it("updates under a caller-owned onboard lock without releasing it", () => { session.saveSession( session.createSession({ @@ -159,4 +176,81 @@ describe("cross-process onboard lock", () => { await exited; } }); + + it("never reports two successful recovery writes after losing one record (#9833)", async () => { + const readyA = path.join(tempHome, "writer-a.ready"); + const readyB = path.join(tempHome, "writer-b.ready"); + const childScript = ` + const fs = require("node:fs"); + const session = require(process.argv[1]); + const ownReady = process.argv[2]; + const peerReady = process.argv[3]; + const role = process.argv[4]; + const originalWriteFileSync = fs.writeFileSync; + const wait = (milliseconds) => Atomics.wait( + new Int32Array(new SharedArrayBuffer(4)), + 0, + 0, + milliseconds, + ); + let synchronized = false; + fs.writeFileSync = (...args) => { + if (!synchronized && typeof args[0] === "number") { + synchronized = true; + originalWriteFileSync(ownReady, role); + const deadline = Date.now() + 750; + while (!fs.existsSync(peerReady) && Date.now() < deadline) wait(10); + if (role === "b") wait(100); + } + return originalWriteFileSync(...args); + }; + try { + const recorded = session.recordRetainedSandboxRecovery({ + sandboxName: "writer-" + role, + sandboxIdentityFingerprint: role.repeat(64), + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "generation-" + role, + verifiedEffectivePolicyIdentity: null, + resources: { + sharedInferenceProviders: [], + sandboxScopedProviders: [], + credentialEnvironmentVariables: [], + }, + reason: "retained_after_sandbox_creation_failure", + }); + process.stdout.write(JSON.stringify({ ok: true, recordId: recorded.recordId })); + } catch (error) { + process.stdout.write(JSON.stringify({ ok: false, error: String(error) })); + } + `; + const runWriter = (role: "a" | "b", ownReady: string, peerReady: string) => + new Promise<{ ok: boolean }>((resolve, reject) => { + const child = spawn( + process.execPath, + ["--require", "tsx/cjs", "-e", childScript, sessionPath, ownReady, peerReady, role], + { env: { ...process.env, HOME: tempHome }, stdio: ["ignore", "pipe", "pipe"] }, + ); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk) => (stdout += String(chunk))); + child.stderr.on("data", (chunk) => (stderr += String(chunk))); + child.once("error", reject); + child.once("close", (code) => { + code === 0 + ? resolve(JSON.parse(stdout) as { ok: boolean }) + : reject(new Error(`recovery writer exited ${String(code)}: ${stderr}`)); + }); + }); + + const results = await Promise.all([ + runWriter("a", readyA, readyB), + runWriter("b", readyB, readyA), + ]); + const successfulWrites = results.filter((result) => result.ok).length; + const records = session.listRetainedSandboxRecoveryRecords(); + + expect(successfulWrites).toBeGreaterThan(0); + expect(records).toHaveLength(successfulWrites); + }); }); diff --git a/src/lib/state/onboard-session-normalization.test.ts b/src/lib/state/onboard-session-normalization.test.ts index 4a02572817d..7e04d971ec0 100644 --- a/src/lib/state/onboard-session-normalization.test.ts +++ b/src/lib/state/onboard-session-normalization.test.ts @@ -3,7 +3,12 @@ import { describe, expect, it } from "vitest"; -import { createSession, filterSafeUpdates, normalizeSession } from "./onboard-session"; +import { + createSession, + filterSafeUpdates, + normalizeSession, + summarizeForDebug, +} from "./onboard-session"; type LegacySession = Omit, "machine"> & { machine?: unknown; @@ -16,6 +21,29 @@ function requireNormalizedSession(legacy: LegacySession) { } describe("onboard session normalization", () => { + it("preserves valid recovery-only cancellation state (#9833)", () => { + const cancellationRecovery = { + reason: "cancelled_after_sandbox_creation" as const, + sandboxName: "retained-sb", + sandboxIdentityFingerprint: "a".repeat(64), + recordedAt: "2026-08-27T00:00:00.000Z", + }; + const normalized = normalizeSession({ + ...createSession({ sandboxName: "retained-sb" }), + resumable: false, + status: "recovery_required", + cancellationRecovery, + }); + + expect(normalized).toMatchObject({ + sandboxName: "retained-sb", + resumable: false, + status: "recovery_required", + cancellationRecovery, + }); + expect(summarizeForDebug(normalized)?.cancellationRecovery).toEqual(cancellationRecovery); + }); + it("keeps APF create intent and defaults legacy sessions to false (#9833)", () => { const selected = createSession({ apfInterceptorRequested: true }); expect(normalizeSession(selected)?.apfInterceptorRequested).toBe(true); diff --git a/src/lib/state/onboard-session.test.ts b/src/lib/state/onboard-session.test.ts index 7f76bd6b119..2414e1b5a68 100644 --- a/src/lib/state/onboard-session.test.ts +++ b/src/lib/state/onboard-session.test.ts @@ -129,24 +129,24 @@ describe("onboard session", () => { ); }); - it.each([ - true, - false, - ])("persists explicit observability intent when enabled=$enabled", (observabilityEnabled) => { - session.saveSession( - session.createSession({ - observabilityEnabled, - observabilityRequestedExplicitly: true, - }), - ); - const loaded = requireLoadedSession(session.loadSession()); - const summary = requireDebugSummary(session.summarizeForDebug()); - - expect(loaded.observabilityEnabled).toBe(observabilityEnabled); - expect(loaded.observabilityRequestedExplicitly).toBe(true); - expect(summary.observabilityEnabled).toBe(observabilityEnabled); - expect(summary.observabilityRequestedExplicitly).toBe(true); - }); + it.each([true, false])( + "persists explicit observability intent when enabled=$enabled", + (observabilityEnabled) => { + session.saveSession( + session.createSession({ + observabilityEnabled, + observabilityRequestedExplicitly: true, + }), + ); + const loaded = requireLoadedSession(session.loadSession()); + const summary = requireDebugSummary(session.summarizeForDebug()); + + expect(loaded.observabilityEnabled).toBe(observabilityEnabled); + expect(loaded.observabilityRequestedExplicitly).toBe(true); + expect(summary.observabilityEnabled).toBe(observabilityEnabled); + expect(summary.observabilityRequestedExplicitly).toBe(true); + }, + ); it("defaults legacy observability intent and provenance off", () => { const legacy = session.createSession() as unknown as Record; diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index efeb6d54354..796bba634b5 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -19,7 +19,12 @@ import { parseServingProfileProvenance, type ServingProfileProvenance, } from "../inference/serving/profile-provenance"; -import { normalizeWebSearchConfig, type WebSearchConfig } from "../inference/web-search"; +import { + normalizeWebSearchConfig, + webSearchEnvFor, + webSearchProviderForConfig, + type WebSearchConfig, +} from "../inference/web-search"; import type { SandboxMessagingPlan } from "../messaging/manifest"; import { compactSandboxMessagingPlanForPersistence } from "../messaging/persistence"; import { parseSandboxMessagingPlan } from "../messaging/plan-validation"; @@ -48,7 +53,6 @@ import { } from "../onboard/station-express-resume"; import { redactSensitiveText, redactUrl } from "../security/redact"; import { inspectCheckpoint, serializeCheckpoint } from "./onboard-checkpoint"; -import { decisionUnset } from "./onboard-checkpoint-decision"; import type { OnboardCheckpoint } from "./onboard-checkpoint-types"; import { assignSafeToolDisclosureUpdate, @@ -57,6 +61,15 @@ import { type ToolDisclosure, } from "./onboard-session-tool-disclosure"; import { nextMachineStateAfterCompletedStep } from "./onboard-step-state"; +import { + listRetainedSandboxRecoveryRecords as readRetainedSandboxRecoveryRecords, + recordRetainedSandboxRecovery as writeRetainedSandboxRecovery, + retainedSandboxRecoveryFile, + type RecordRetainedSandboxRecoveryInput, + type RetainedSandboxRecoveryRecord, + type RetainedSandboxRecoveryReason, + type RetainedSandboxVerifiedEffectivePolicyIdentity, +} from "./onboard-session/retained-sandbox-recovery"; import type { SandboxHostMount } from "./registry/types"; import { hasUnsafeHostMountTerminalText } from "./registry/host-mount"; import { nemoclawStateRoot } from "./state-root"; @@ -65,10 +78,12 @@ export { normalizePersistedSandboxHostMounts } from "./registry/host-mount"; export const SESSION_VERSION = 1; export const MACHINE_SNAPSHOT_VERSION = 1; +export const CANCELLATION_RECOVERY_STATUS = "recovery_required"; const INVALID_HOST_MOUNT_SESSIONS = new WeakSet(); export const SESSION_DIR = nemoclawStateRoot(process.env.HOME || "/tmp", GATEWAY_PORT); export const SESSION_FILE = path.join(SESSION_DIR, "onboard-session.json"); export const LOCK_FILE = path.join(SESSION_DIR, "onboard.lock"); +export const RETAINED_SANDBOX_RECOVERY_FILE = retainedSandboxRecoveryFile(SESSION_DIR); const SAFE_VLLM_INSTALL_MODEL = /^[A-Za-z0-9._:/-]+$/; export class InvalidPersistedPolicyAuthorityError extends Error {} @@ -107,6 +122,13 @@ export interface SessionFailure { interrupted?: boolean; } +export interface SessionCancellationRecovery { + readonly reason: "cancelled_after_sandbox_creation" | "retained_after_sandbox_creation_failure"; + readonly sandboxName: string; + readonly sandboxIdentityFingerprint: string | null; + readonly recordedAt: string; +} + export interface SessionMetadata { gatewayName: string; fromDockerfile: string | null; @@ -205,6 +227,7 @@ export interface Session { lastStepStarted: string | null; lastCompletedStep: string | null; failure: SessionFailure | null; + cancellationRecovery: SessionCancellationRecovery | null; agent: string | null; sandboxName: string | null; provider: string | null; @@ -365,6 +388,7 @@ export interface DebugSessionSummary { lastStepStarted: string | null; lastCompletedStep: string | null; failure: SessionFailure | null; + cancellationRecovery: SessionCancellationRecovery | null; gatewayAuthority: GatewayOwnerDescription | null; machine: OnboardMachineSnapshot; steps: Record; @@ -373,7 +397,86 @@ export interface DebugSessionSummary { // ── Helpers ────────────────────────────────────────────────────── function ensureSessionDir(): void { + assertSessionDirectoryHasNoSymlinks(); fs.mkdirSync(SESSION_DIR, { recursive: true, mode: 0o700 }); + assertSessionDirectoryHasNoSymlinks(); + const stat = fs.lstatSync(SESSION_DIR); + if (!stat.isDirectory() || stat.isSymbolicLink()) { + throw new Error("NemoClaw onboarding state directory is not a secure directory."); + } +} + +function assertSessionDirectoryHasNoSymlinks(): void { + const home = path.resolve(process.env.HOME || "/tmp"); + let current = path.resolve(SESSION_DIR); + while (current !== home && current !== path.dirname(current)) { + try { + if (fs.lstatSync(current).isSymbolicLink()) { + throw new Error( + `NemoClaw onboarding state directory cannot be a symbolic link: ${current}`, + ); + } + } catch (error) { + if (!(isErrnoException(error) && error.code === "ENOENT")) throw error; + } + current = path.dirname(current); + } +} + +interface PinnedSessionDirectory { + readonly descriptor: number; + readonly stat: fs.Stats; +} + +function sameSessionFileIdentity(left: fs.Stats, right: fs.Stats): boolean { + return left.dev === right.dev && left.ino === right.ino; +} + +function revalidatePinnedSessionDirectory(directory: PinnedSessionDirectory): void { + assertSessionDirectoryHasNoSymlinks(); + const descriptorStat = fs.fstatSync(directory.descriptor); + const pathStat = fs.lstatSync(SESSION_DIR); + if ( + !descriptorStat.isDirectory() || + pathStat.isSymbolicLink() || + !pathStat.isDirectory() || + !sameSessionFileIdentity(directory.stat, descriptorStat) || + !sameSessionFileIdentity(directory.stat, pathStat) + ) { + throw new Error("NemoClaw onboarding state directory changed during validation."); + } +} + +function openPinnedSessionDirectory(): PinnedSessionDirectory { + ensureSessionDir(); + const descriptor = fs.openSync( + SESSION_DIR, + fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_DIRECTORY ?? 0), + ); + try { + const directory = { descriptor, stat: fs.fstatSync(descriptor) }; + revalidatePinnedSessionDirectory(directory); + return directory; + } catch (error) { + fs.closeSync(descriptor); + throw error; + } +} + +function assertTemporarySessionFile(descriptor: number, temporary: string): fs.Stats { + const descriptorStat = fs.fstatSync(descriptor); + const pathStat = fs.lstatSync(temporary); + if ( + !descriptorStat.isFile() || + descriptorStat.nlink !== 1 || + pathStat.isSymbolicLink() || + !pathStat.isFile() || + pathStat.nlink !== 1 || + !sameSessionFileIdentity(descriptorStat, pathStat) + ) { + throw new Error("NemoClaw onboarding temporary state changed during validation."); + } + return descriptorStat; } export function sessionPath(): string { @@ -678,6 +781,37 @@ export function sanitizeFailure( return step || message ? { step, message, recordedAt, interrupted } : null; } +function parseSessionCancellationRecovery( + value: SessionJsonValue | undefined, +): SessionCancellationRecovery | null { + if ( + !isObject(value) || + (value.reason !== "cancelled_after_sandbox_creation" && + value.reason !== "retained_after_sandbox_creation_failure") + ) { + return null; + } + const sandboxName = readString(value.sandboxName); + const recordedAt = readCanonicalIsoTimestamp(value.recordedAt); + const fingerprint = + value.sandboxIdentityFingerprint === null ? null : readString(value.sandboxIdentityFingerprint); + if ( + !sandboxName || + sandboxName.length > NAME_MAX_LENGTH || + !NAME_VALID_PATTERN.test(sandboxName) || + !recordedAt || + (fingerprint !== null && !/^[0-9a-f]{64}$/u.test(fingerprint)) + ) { + return null; + } + return { + reason: value.reason, + sandboxName, + sandboxIdentityFingerprint: fingerprint, + recordedAt, + }; +} + // ── Session CRUD ───────────────────────────────────────────────── function createMachineSnapshot( @@ -775,6 +909,9 @@ export function createSession(overrides: Partial = {}): Session { lastStepStarted: overrides.lastStepStarted ?? null, lastCompletedStep: overrides.lastCompletedStep ?? null, failure: overrides.failure ?? null, + cancellationRecovery: parseSessionCancellationRecovery( + overrides.cancellationRecovery as SessionJsonValue | undefined, + ), agent: overrides.agent ?? null, sandboxName: overrides.sandboxName ?? null, provider: overrides.provider ?? null, @@ -900,6 +1037,14 @@ export function normalizeSession(data: Session | SessionJsonValue | undefined): ) { return null; } + const cancellationRecovery = parseSessionCancellationRecovery(data.cancellationRecovery); + if ( + hasOwn(data, "cancellationRecovery") && + data.cancellationRecovery !== null && + !cancellationRecovery + ) { + return null; + } const normalized = createSession({ sessionId: readString(data.sessionId) ?? undefined, @@ -943,11 +1088,20 @@ export function normalizeSession(data: Session | SessionJsonValue | undefined): lastStepStarted: readString(data.lastStepStarted), lastCompletedStep: readString(data.lastCompletedStep), failure: sanitizeFailure(isObject(data.failure) ? data.failure : null), + cancellationRecovery, metadata: parseSessionMetadata(data.metadata), checkpoint: data.checkpoint as unknown as OnboardCheckpoint | null, }); normalized.resumable = data.resumable !== false; normalized.status = readString(data.status) ?? normalized.status; + if ( + (normalized.status === CANCELLATION_RECOVERY_STATUS) !== Boolean(cancellationRecovery) || + (cancellationRecovery !== null && + (normalized.resumable !== false || + normalized.sandboxName !== cancellationRecovery.sandboxName)) + ) { + return null; + } if ( normalized.stationExpressIntent && (data.resumable !== true || @@ -1044,16 +1198,53 @@ function serializeSessionForDisk(session: Session): Record { export function saveSession(session: Session): Session { const normalized = normalizeSession(session) || createSession(); normalized.updatedAt = new Date().toISOString(); - ensureSessionDir(); + const directory = openPinnedSessionDirectory(); const tmpFile = path.join( SESSION_DIR, `.onboard-session.${process.pid}.${Date.now()}.${randomUUID()}.tmp`, ); - fs.writeFileSync(tmpFile, JSON.stringify(serializeSessionForDisk(normalized), null, 2), { - mode: 0o600, - }); - fs.renameSync(tmpFile, SESSION_FILE); - return normalized; + let descriptor: number | null = null; + let temporaryStat: fs.Stats | null = null; + try { + descriptor = fs.openSync( + tmpFile, + fs.constants.O_WRONLY | + fs.constants.O_CREAT | + fs.constants.O_EXCL | + (fs.constants.O_NOFOLLOW ?? 0), + 0o600, + ); + revalidatePinnedSessionDirectory(directory); + temporaryStat = assertTemporarySessionFile(descriptor, tmpFile); + fs.writeFileSync(descriptor, JSON.stringify(serializeSessionForDisk(normalized), null, 2)); + fs.fchmodSync(descriptor, 0o600); + fs.fsyncSync(descriptor); + temporaryStat = assertTemporarySessionFile(descriptor, tmpFile); + fs.closeSync(descriptor); + descriptor = null; + revalidatePinnedSessionDirectory(directory); + fs.renameSync(tmpFile, SESSION_FILE); + revalidatePinnedSessionDirectory(directory); + fs.fsyncSync(directory.descriptor); + return normalized; + } finally { + if (descriptor !== null) fs.closeSync(descriptor); + try { + revalidatePinnedSessionDirectory(directory); + const pathStat = fs.lstatSync(tmpFile); + if ( + temporaryStat !== null && + pathStat.isFile() && + pathStat.nlink === 1 && + sameSessionFileIdentity(temporaryStat, pathStat) + ) { + fs.unlinkSync(tmpFile); + } + } catch { + // Preserve the original result. Ambiguous paths are left untouched. + } + fs.closeSync(directory.descriptor); + } } export function clearSession(): void { @@ -1161,6 +1352,46 @@ function lockHolderStillMatches(lock: LockInfo): boolean { // descriptor rather than a value re-read from disk. See #1281. let heldLockFd: number | null = null; +export function assertOnboardLockOwned(): void { + if (heldLockFd === null) { + throw new Error("This process does not own the NemoClaw onboarding lock."); + } + assertSessionDirectoryHasNoSymlinks(); + const descriptorStat = fs.fstatSync(heldLockFd); + const pathStat = fs.lstatSync(LOCK_FILE); + if ( + !descriptorStat.isFile() || + descriptorStat.nlink !== 1 || + pathStat.isSymbolicLink() || + !pathStat.isFile() || + pathStat.nlink !== 1 || + descriptorStat.dev !== pathStat.dev || + descriptorStat.ino !== pathStat.ino + ) { + throw new Error("NemoClaw onboarding lock ownership changed during the operation."); + } +} + +function withOwnedOnboardLock(command: string, operation: () => T): T { + const managesOnboardLock = heldLockFd === null; + if (managesOnboardLock) { + const lock = acquireOnboardLock(command); + if (!lock.acquired) { + throw new Error( + "Cannot update onboarding recovery while another onboarding run owns the lock.", + ); + } + } + try { + assertOnboardLockOwned(); + const result = operation(); + assertOnboardLockOwned(); + return result; + } finally { + if (managesOnboardLock) releaseOnboardLock(); + } +} + /** Report whether this process holds the exclusive onboarding writer lock. */ export function isOnboardLockHeldByCurrentProcess(): boolean { if (heldLockFd === null) return false; @@ -1275,6 +1506,13 @@ export function acquireOnboardLock(command: string | null = null): LockResult { throw writeError; } heldLockFd = fd; + try { + assertOnboardLockOwned(); + } catch (error) { + heldLockFd = null; + fs.closeSync(fd); + throw error; + } return { acquired: true, lockFile: LOCK_FILE, stale: false }; } @@ -1590,6 +1828,170 @@ export function updateSession(mutator: (session: Session) => Session | void): Se return saveSession(next); } +export interface RetainedSandboxRecoveryContext { + readonly gatewayName?: string; + readonly gatewayPort?: number; + readonly lifecycleGeneration?: string | null; + readonly verifiedEffectivePolicyIdentity?: RetainedSandboxVerifiedEffectivePolicyIdentity | null; +} + +function persistIndependentRetainedSandboxRecovery( + session: Session, + reason: RetainedSandboxRecoveryReason, + sandboxIdentityFingerprint: string | null, + context: RetainedSandboxRecoveryContext, +): void { + const messagingCredentialEnvironmentVariables = + session.messagingPlan?.credentialBindings.map((binding) => binding.providerEnvKey) ?? []; + const credentialEnvironmentVariables = [ + ...(session.credentialEnv ? [session.credentialEnv] : []), + ...(session.webSearchConfig + ? [webSearchEnvFor(webSearchProviderForConfig(session.webSearchConfig))] + : []), + ...messagingCredentialEnvironmentVariables, + ]; + writeRetainedSandboxRecovery(RETAINED_SANDBOX_RECOVERY_FILE, { + sandboxName: session.sandboxName!, + sandboxIdentityFingerprint, + gatewayName: context.gatewayName ?? session.metadata.gatewayName, + gatewayPort: context.gatewayPort ?? GATEWAY_PORT, + lifecycleGeneration: context.lifecycleGeneration ?? null, + verifiedEffectivePolicyIdentity: context.verifiedEffectivePolicyIdentity ?? null, + resources: { + sharedInferenceProviders: session.provider ? [session.provider] : [], + sandboxScopedProviders: session.stagedCredentialProviders, + credentialEnvironmentVariables, + }, + reason, + }); +} + +export function listRetainedSandboxRecoveryRecords(): readonly RetainedSandboxRecoveryRecord[] { + if (heldLockFd !== null) assertOnboardLockOwned(); + const records = readRetainedSandboxRecoveryRecords(RETAINED_SANDBOX_RECOVERY_FILE); + if (heldLockFd !== null) assertOnboardLockOwned(); + return records; +} + +export function recordRetainedSandboxRecovery( + input: RecordRetainedSandboxRecoveryInput, +): RetainedSandboxRecoveryRecord { + return withOwnedOnboardLock("nemoclaw retained sandbox recovery", () => + writeRetainedSandboxRecovery(RETAINED_SANDBOX_RECOVERY_FILE, input), + ); +} + +export function markCancellationRecovery( + sandboxName: string, + sandboxIdentityFingerprint?: string, + context: RetainedSandboxRecoveryContext = {}, +): Session { + if ( + sandboxName.length > NAME_MAX_LENGTH || + !NAME_VALID_PATTERN.test(sandboxName) || + (sandboxIdentityFingerprint !== undefined && + !/^[0-9a-f]{64}$/u.test(sandboxIdentityFingerprint)) + ) { + throw new Error("Cannot record cancellation recovery with invalid sandbox identity data."); + } + return withOwnedOnboardLock("nemoclaw cancellation recovery", () => { + const saved = updateSession((session) => { + if (session.sandboxName !== null && session.sandboxName !== sandboxName) { + throw new Error("Cannot record cancellation recovery for a different onboarding sandbox."); + } + const recordedAt = new Date().toISOString(); + session.sandboxName = sandboxName; + session.resumable = false; + session.status = CANCELLATION_RECOVERY_STATUS; + session.cancellationRecovery = { + reason: "cancelled_after_sandbox_creation", + sandboxName, + sandboxIdentityFingerprint: sandboxIdentityFingerprint ?? null, + recordedAt, + }; + session.failure = { + step: session.lastStepStarted, + message: + "Onboarding was cancelled after sandbox creation; administrator recovery is required.", + recordedAt, + interrupted: true, + }; + return session; + }); + persistIndependentRetainedSandboxRecovery( + saved, + "cancelled_after_sandbox_creation", + sandboxIdentityFingerprint ?? null, + context, + ); + return saved; + }); +} + +export function markRetainedSandboxRecovery( + sandboxName: string, + message: string, + sandboxIdentityFingerprint?: string, + context: RetainedSandboxRecoveryContext = {}, +): Session { + if ( + sandboxName.length > NAME_MAX_LENGTH || + !NAME_VALID_PATTERN.test(sandboxName) || + (sandboxIdentityFingerprint !== undefined && + !/^[0-9a-f]{64}$/u.test(sandboxIdentityFingerprint)) + ) { + throw new Error("Cannot record retained sandbox recovery with invalid identity data."); + } + return withOwnedOnboardLock("nemoclaw retained sandbox recovery", () => { + const saved = updateSession((session) => { + if (session.sandboxName !== null && session.sandboxName !== sandboxName) { + throw new Error( + "Cannot record retained sandbox recovery for a different onboarding sandbox.", + ); + } + const recordedAt = new Date().toISOString(); + const sanitizedMessage = redactSensitiveText(message); + session.sandboxName = sandboxName; + session.resumable = false; + session.status = CANCELLATION_RECOVERY_STATUS; + session.cancellationRecovery = { + reason: "retained_after_sandbox_creation_failure", + sandboxName, + sandboxIdentityFingerprint: sandboxIdentityFingerprint ?? null, + recordedAt, + }; + session.failure = { + step: session.lastStepStarted, + message: sanitizedMessage, + recordedAt, + interrupted: true, + }; + const sandboxStep = session.steps.sandbox; + if (sandboxStep) sandboxStep.error = sanitizedMessage; + return session; + }); + const reread = loadSession(); + if ( + reread?.sessionId !== saved.sessionId || + reread.status !== CANCELLATION_RECOVERY_STATUS || + reread.resumable !== false || + reread.cancellationRecovery?.reason !== "retained_after_sandbox_creation_failure" || + reread.cancellationRecovery.sandboxName !== sandboxName || + reread.cancellationRecovery.sandboxIdentityFingerprint !== + (sandboxIdentityFingerprint ?? null) + ) { + throw new Error("Retained sandbox recovery did not survive durable readback."); + } + persistIndependentRetainedSandboxRecovery( + reread, + "retained_after_sandbox_creation_failure", + sandboxIdentityFingerprint ?? null, + context, + ); + return reread; + }); +} + export type CompareAndSwapSessionResult = "updated" | "busy" | "mismatch"; /** @@ -1714,7 +2116,7 @@ export function markStepRejected(stepName: string): Session { if (session.checkpoint) { session.checkpoint = { ...session.checkpoint, - sandboxIdentity: decisionUnset(), + sandboxIdentity: { kind: "unset" }, updatedAt: new Date().toISOString(), }; } @@ -1767,6 +2169,12 @@ export function finalizeIncompleteOnboardStep( ): Session | null { const existing = loadSession(); if (!existing) return null; + // A cancellation after sandbox creation has its own fail-closed lifecycle. + // Preserve that durable marker when the ordinary process-exit backstop runs + // later in the same exit sequence. + if (existing.status === CANCELLATION_RECOVERY_STATUS && existing.cancellationRecovery !== null) { + return existing; + } if (isTerminalOnboardMachineState(existing.machine.state)) return null; let emitted = false; @@ -1953,6 +2361,7 @@ export function summarizeForDebug( lastStepStarted: session.lastStepStarted, lastCompletedStep: session.lastCompletedStep, failure: sanitizeFailure(session.failure), + cancellationRecovery: session.cancellationRecovery, gatewayAuthority, machine: session.machine, steps: Object.fromEntries( diff --git a/src/lib/state/onboard-session/retained-sandbox-recovery.ts b/src/lib/state/onboard-session/retained-sandbox-recovery.ts new file mode 100644 index 00000000000..c5fe7552f77 --- /dev/null +++ b/src/lib/state/onboard-session/retained-sandbox-recovery.ts @@ -0,0 +1,541 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash, randomUUID } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; + +import { openRegularFileNoFollow } from "../../adapters/fs/regular-file"; + +const SCHEMA_VERSION = 1; +const FINGERPRINT_PATTERN = /^[0-9a-f]{64}$/u; +const SAFE_EVIDENCE_PATTERN = /^[A-Za-z0-9._:@/-]{1,256}$/u; +const NAME_MAX_LENGTH = 63; +const NAME_VALID_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u; + +export function retainedSandboxRecoveryFile(sessionDirectory: string): string { + return path.join(sessionDirectory, "retained-sandbox-recovery.json"); +} + +export type RetainedSandboxRecoveryReason = + | "cancelled_after_sandbox_creation" + | "retained_after_sandbox_creation_failure"; + +export interface RetainedSandboxResourceEvidence { + readonly sharedInferenceProviders: readonly string[]; + readonly sandboxScopedProviders: readonly string[]; + readonly credentialEnvironmentVariables: readonly string[]; +} + +export interface RetainedSandboxVerifiedEffectivePolicyIdentity { + readonly hash: string; + readonly activeVersion: number; +} + +export interface RetainedSandboxRecoveryRecord { + readonly schemaVersion: typeof SCHEMA_VERSION; + readonly recordId: string; + readonly sandboxName: string; + readonly sandboxIdentityFingerprint: string | null; + readonly identityWasUnavailable: boolean; + readonly gatewayName: string; + readonly gatewayPort: number; + readonly lifecycleGeneration: string | null; + readonly verifiedEffectivePolicyIdentity: RetainedSandboxVerifiedEffectivePolicyIdentity | null; + readonly resources: RetainedSandboxResourceEvidence; + readonly reason: RetainedSandboxRecoveryReason; + readonly recordedAt: string; +} + +interface RetainedSandboxAdministratorResolutionReceipt { + readonly schemaVersion: typeof SCHEMA_VERSION; + readonly receiptId: string; + readonly recordId: string; + readonly sandboxName: string; + readonly sandboxIdentityFingerprint: string | null; + readonly gatewayName: string; + readonly gatewayPort: number; + readonly outcome: "removed_verified_identity" | "confirmed_absent_without_identity"; + readonly resolvedAt: string; +} + +interface RetainedSandboxRecoveryState { + readonly schemaVersion: typeof SCHEMA_VERSION; + readonly unresolved: readonly RetainedSandboxRecoveryRecord[]; + readonly resolutions: readonly RetainedSandboxAdministratorResolutionReceipt[]; +} + +interface RetainedSandboxStateDirectory { + readonly ancestors: readonly { readonly path: string; readonly stat: fs.Stats }[]; + readonly descriptor: number; + readonly path: string; + readonly stat: fs.Stats; +} + +export interface RecordRetainedSandboxRecoveryInput { + readonly sandboxName: string; + readonly sandboxIdentityFingerprint: string | null; + readonly gatewayName: string; + readonly gatewayPort: number; + readonly lifecycleGeneration: string | null; + readonly verifiedEffectivePolicyIdentity: RetainedSandboxVerifiedEffectivePolicyIdentity | null; + readonly resources: RetainedSandboxResourceEvidence; + readonly reason: RetainedSandboxRecoveryReason; + readonly recordedAt?: string; +} + +const emptyState = (): RetainedSandboxRecoveryState => ({ + schemaVersion: SCHEMA_VERSION, + unresolved: [], + resolutions: [], +}); + +function sameFileIdentity(left: fs.Stats, right: fs.Stats): boolean { + return left.dev === right.dev && left.ino === right.ino; +} + +function stateDirectoryAncestors(directory: string): string[] { + const home = path.resolve(process.env.HOME ?? path.dirname(directory)); + const resolved = path.resolve(directory); + const relative = path.relative(home, resolved); + if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) { + return [resolved]; + } + const ancestors: string[] = []; + let current = home; + for (const component of relative.split(path.sep).filter(Boolean)) { + current = path.join(current, component); + ancestors.push(current); + } + return ancestors; +} + +function assertStateDirectoryComponent(candidate: string, stat: fs.Stats): void { + if (stat.isSymbolicLink()) { + throw new Error( + `Retained sandbox recovery state directory cannot be a symbolic link: ${candidate}`, + ); + } + if (!stat.isDirectory()) { + throw new Error(`Retained sandbox recovery state directory is not a directory: ${candidate}`); + } +} + +function openStateDirectory( + filePath: string, + create: boolean, +): RetainedSandboxStateDirectory | null { + const directory = path.dirname(filePath); + const ancestorPaths = stateDirectoryAncestors(directory); + for (const candidate of ancestorPaths) { + try { + assertStateDirectoryComponent(candidate, fs.lstatSync(candidate)); + } catch (error) { + if ( + error instanceof Error && + "code" in error && + (error as NodeJS.ErrnoException).code === "ENOENT" + ) { + continue; + } + throw error; + } + } + if (create) fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + + const ancestors: Array<{ path: string; stat: fs.Stats }> = []; + try { + for (const candidate of ancestorPaths) { + const stat = fs.lstatSync(candidate); + assertStateDirectoryComponent(candidate, stat); + ancestors.push({ path: candidate, stat }); + } + } catch (error) { + if ( + !create && + error instanceof Error && + "code" in error && + (error as NodeJS.ErrnoException).code === "ENOENT" + ) { + return null; + } + throw error; + } + + const flags = + fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_DIRECTORY ?? 0); + const descriptor = fs.openSync(directory, flags); + try { + const descriptorStat = fs.fstatSync(descriptor); + const pathStat = fs.lstatSync(directory); + assertStateDirectoryComponent(directory, descriptorStat); + assertStateDirectoryComponent(directory, pathStat); + if (!sameFileIdentity(descriptorStat, pathStat)) { + throw new Error("Retained sandbox recovery state directory changed during validation."); + } + return { ancestors, descriptor, path: directory, stat: descriptorStat }; + } catch (error) { + fs.closeSync(descriptor); + throw error; + } +} + +function revalidateStateDirectory(directory: RetainedSandboxStateDirectory): void { + for (const ancestor of directory.ancestors) { + const current = fs.lstatSync(ancestor.path); + assertStateDirectoryComponent(ancestor.path, current); + if (!sameFileIdentity(ancestor.stat, current)) { + throw new Error("Retained sandbox recovery state directory changed during validation."); + } + } + const descriptorStat = fs.fstatSync(directory.descriptor); + const pathStat = fs.lstatSync(directory.path); + assertStateDirectoryComponent(directory.path, descriptorStat); + assertStateDirectoryComponent(directory.path, pathStat); + if ( + !sameFileIdentity(directory.stat, descriptorStat) || + !sameFileIdentity(directory.stat, pathStat) + ) { + throw new Error("Retained sandbox recovery state directory changed during validation."); + } +} + +function isObjectRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function readStateFile(filePath: string): unknown { + const directory = openStateDirectory(filePath, false); + if (directory === null) return emptyState(); + try { + revalidateStateDirectory(directory); + const file = openRegularFileNoFollow(filePath); + try { + const value = JSON.parse(file.readUtf8()); + revalidateStateDirectory(directory); + return value; + } finally { + file.close(); + } + } catch (error) { + if ( + error instanceof Error && + "code" in error && + (error as NodeJS.ErrnoException).code === "ENOENT" + ) { + return emptyState(); + } + if ( + error instanceof Error && + "code" in error && + ((error as NodeJS.ErrnoException).code === "ELOOP" || + (error as NodeJS.ErrnoException).code === "EMLINK") + ) { + throw new Error("Retained sandbox recovery state cannot be a symbolic link."); + } + throw error; + } finally { + fs.closeSync(directory.descriptor); + } +} + +function assertTemporaryStateFile(descriptor: number, temporary: string): fs.Stats { + const descriptorStat = fs.fstatSync(descriptor); + const pathStat = fs.lstatSync(temporary); + if ( + !descriptorStat.isFile() || + descriptorStat.nlink !== 1 || + pathStat.isSymbolicLink() || + !pathStat.isFile() || + pathStat.nlink !== 1 || + !sameFileIdentity(descriptorStat, pathStat) + ) { + throw new Error("Retained sandbox recovery temporary state changed during validation."); + } + return descriptorStat; +} + +function writeStateFile(filePath: string, state: RetainedSandboxRecoveryState): void { + const directory = openStateDirectory(filePath, true)!; + try { + revalidateStateDirectory(directory); + if (fs.lstatSync(filePath).isSymbolicLink()) { + throw new Error("Retained sandbox recovery state cannot be a symbolic link."); + } + } catch (error) { + if ( + !( + error instanceof Error && + "code" in error && + (error as NodeJS.ErrnoException).code === "ENOENT" + ) + ) { + fs.closeSync(directory.descriptor); + throw error; + } + } + const temporary = path.join( + directory.path, + `.retained-sandbox-recovery.${String(process.pid)}.${randomUUID()}.tmp`, + ); + let descriptor: number | null = null; + let temporaryStat: fs.Stats | null = null; + try { + descriptor = fs.openSync( + temporary, + fs.constants.O_WRONLY | + fs.constants.O_CREAT | + fs.constants.O_EXCL | + (fs.constants.O_NOFOLLOW ?? 0), + 0o600, + ); + revalidateStateDirectory(directory); + temporaryStat = assertTemporaryStateFile(descriptor, temporary); + fs.writeFileSync(descriptor, JSON.stringify(state, null, 2)); + fs.fchmodSync(descriptor, 0o600); + fs.fsyncSync(descriptor); + temporaryStat = assertTemporaryStateFile(descriptor, temporary); + fs.closeSync(descriptor); + descriptor = null; + revalidateStateDirectory(directory); + fs.renameSync(temporary, filePath); + revalidateStateDirectory(directory); + fs.fsyncSync(directory.descriptor); + } finally { + if (descriptor !== null) fs.closeSync(descriptor); + try { + revalidateStateDirectory(directory); + const pathStat = fs.lstatSync(temporary); + if ( + temporaryStat !== null && + pathStat.isFile() && + pathStat.nlink === 1 && + sameFileIdentity(temporaryStat, pathStat) + ) { + fs.unlinkSync(temporary); + } + } catch { + // Preserve the original result. Ambiguous paths are left untouched. + } + fs.closeSync(directory.descriptor); + } +} + +function validSandboxName(value: unknown): value is string { + return ( + typeof value === "string" && value.length <= NAME_MAX_LENGTH && NAME_VALID_PATTERN.test(value) + ); +} + +function validSafeEvidence(value: unknown): value is string { + return typeof value === "string" && SAFE_EVIDENCE_PATTERN.test(value); +} + +function validTimestamp(value: unknown): value is string { + return typeof value === "string" && Number.isFinite(Date.parse(value)); +} + +function validGatewayPort(value: unknown): value is number { + return Number.isInteger(value) && Number(value) >= 1024 && Number(value) <= 65535; +} + +function parseEvidence(value: unknown): RetainedSandboxResourceEvidence | null { + if (!isObjectRecord(value)) return null; + const parse = (candidate: unknown): string[] | null => + Array.isArray(candidate) && candidate.every(validSafeEvidence) + ? [...new Set(candidate)].sort() + : null; + const sharedInferenceProviders = parse(value.sharedInferenceProviders); + const sandboxScopedProviders = parse(value.sandboxScopedProviders); + const credentialEnvironmentVariables = parse(value.credentialEnvironmentVariables); + return sharedInferenceProviders && sandboxScopedProviders && credentialEnvironmentVariables + ? { sharedInferenceProviders, sandboxScopedProviders, credentialEnvironmentVariables } + : null; +} + +function parseVerifiedEffectivePolicyIdentity( + value: unknown, +): RetainedSandboxVerifiedEffectivePolicyIdentity | null | undefined { + if (value === null || value === undefined) return null; + if ( + !isObjectRecord(value) || + !validSafeEvidence(value.hash) || + !Number.isSafeInteger(value.activeVersion) || + Number(value.activeVersion) < 1 + ) { + return undefined; + } + return { hash: value.hash, activeVersion: Number(value.activeVersion) }; +} + +function parseRecord(value: unknown): RetainedSandboxRecoveryRecord | null { + if (!isObjectRecord(value)) return null; + const resources = parseEvidence(value.resources); + const fingerprint = value.sandboxIdentityFingerprint; + const verifiedEffectivePolicyIdentity = parseVerifiedEffectivePolicyIdentity( + value.verifiedEffectivePolicyIdentity, + ); + const reason = value.reason; + if ( + value.schemaVersion !== SCHEMA_VERSION || + typeof value.recordId !== "string" || + !FINGERPRINT_PATTERN.test(value.recordId) || + !validSandboxName(value.sandboxName) || + (fingerprint !== null && + (typeof fingerprint !== "string" || !FINGERPRINT_PATTERN.test(fingerprint))) || + value.identityWasUnavailable !== (fingerprint === null) || + !validSafeEvidence(value.gatewayName) || + !validGatewayPort(value.gatewayPort) || + (value.lifecycleGeneration !== null && !validSafeEvidence(value.lifecycleGeneration)) || + verifiedEffectivePolicyIdentity === undefined || + !resources || + !["cancelled_after_sandbox_creation", "retained_after_sandbox_creation_failure"].includes( + String(reason), + ) || + !validTimestamp(value.recordedAt) + ) { + return null; + } + return { + schemaVersion: SCHEMA_VERSION, + recordId: value.recordId, + sandboxName: value.sandboxName, + sandboxIdentityFingerprint: fingerprint, + identityWasUnavailable: fingerprint === null, + gatewayName: value.gatewayName, + gatewayPort: value.gatewayPort, + lifecycleGeneration: value.lifecycleGeneration, + verifiedEffectivePolicyIdentity, + resources, + reason: reason as RetainedSandboxRecoveryReason, + recordedAt: value.recordedAt, + }; +} + +function parseReceipt(value: unknown): RetainedSandboxAdministratorResolutionReceipt | null { + if (!isObjectRecord(value)) return null; + const fingerprint = value.sandboxIdentityFingerprint; + const outcome = value.outcome; + if ( + value.schemaVersion !== SCHEMA_VERSION || + typeof value.receiptId !== "string" || + !FINGERPRINT_PATTERN.test(value.receiptId) || + typeof value.recordId !== "string" || + !FINGERPRINT_PATTERN.test(value.recordId) || + !validSandboxName(value.sandboxName) || + (fingerprint !== null && + (typeof fingerprint !== "string" || !FINGERPRINT_PATTERN.test(fingerprint))) || + !validSafeEvidence(value.gatewayName) || + !validGatewayPort(value.gatewayPort) || + !["removed_verified_identity", "confirmed_absent_without_identity"].includes(String(outcome)) || + !validTimestamp(value.resolvedAt) + ) { + return null; + } + return { + schemaVersion: SCHEMA_VERSION, + receiptId: value.receiptId, + recordId: value.recordId, + sandboxName: value.sandboxName, + sandboxIdentityFingerprint: fingerprint, + gatewayName: value.gatewayName, + gatewayPort: value.gatewayPort, + outcome: outcome as RetainedSandboxAdministratorResolutionReceipt["outcome"], + resolvedAt: value.resolvedAt, + }; +} + +function loadState(filePath: string): RetainedSandboxRecoveryState { + const value = readStateFile(filePath); + if (!isObjectRecord(value) || value.schemaVersion !== SCHEMA_VERSION) { + throw new Error("Retained sandbox recovery state has an unsupported schema."); + } + const unresolved = Array.isArray(value.unresolved) ? value.unresolved.map(parseRecord) : null; + const resolutions = Array.isArray(value.resolutions) ? value.resolutions.map(parseReceipt) : null; + if (!unresolved || unresolved.includes(null) || !resolutions || resolutions.includes(null)) { + throw new Error("Retained sandbox recovery state is invalid; onboarding remains blocked."); + } + return { + schemaVersion: SCHEMA_VERSION, + unresolved: unresolved as RetainedSandboxRecoveryRecord[], + resolutions: resolutions as RetainedSandboxAdministratorResolutionReceipt[], + }; +} + +function recoveryRecordId(input: RecordRetainedSandboxRecoveryInput): string { + return createHash("sha256") + .update( + JSON.stringify([ + input.gatewayName, + input.gatewayPort, + input.sandboxName, + input.sandboxIdentityFingerprint, + input.lifecycleGeneration, + input.verifiedEffectivePolicyIdentity, + ]), + ) + .digest("hex"); +} + +function assertRecordInput(input: RecordRetainedSandboxRecoveryInput): void { + if ( + !validSandboxName(input.sandboxName) || + (input.sandboxIdentityFingerprint !== null && + !FINGERPRINT_PATTERN.test(input.sandboxIdentityFingerprint)) || + !validSafeEvidence(input.gatewayName) || + !validGatewayPort(input.gatewayPort) || + (input.lifecycleGeneration !== null && !validSafeEvidence(input.lifecycleGeneration)) || + parseVerifiedEffectivePolicyIdentity(input.verifiedEffectivePolicyIdentity) === undefined || + !parseEvidence(input.resources) + ) { + throw new Error("Cannot persist invalid retained sandbox recovery evidence."); + } +} + +export function listRetainedSandboxRecoveryRecords( + filePath: string, +): readonly RetainedSandboxRecoveryRecord[] { + return loadState(filePath).unresolved; +} + +export function recordRetainedSandboxRecovery( + filePath: string, + input: RecordRetainedSandboxRecoveryInput, +): RetainedSandboxRecoveryRecord { + assertRecordInput(input); + const record: RetainedSandboxRecoveryRecord = { + schemaVersion: SCHEMA_VERSION, + recordId: recoveryRecordId(input), + sandboxName: input.sandboxName, + sandboxIdentityFingerprint: input.sandboxIdentityFingerprint, + identityWasUnavailable: input.sandboxIdentityFingerprint === null, + gatewayName: input.gatewayName, + gatewayPort: input.gatewayPort, + lifecycleGeneration: input.lifecycleGeneration, + verifiedEffectivePolicyIdentity: input.verifiedEffectivePolicyIdentity + ? { ...input.verifiedEffectivePolicyIdentity } + : null, + resources: parseEvidence(input.resources)!, + reason: input.reason, + recordedAt: input.recordedAt ?? new Date().toISOString(), + }; + if (!validTimestamp(record.recordedAt)) { + throw new Error("Cannot persist retained sandbox recovery with an invalid timestamp."); + } + const current = loadState(filePath); + const next: RetainedSandboxRecoveryState = { + ...current, + unresolved: [ + ...current.unresolved.filter((candidate) => candidate.recordId !== record.recordId), + record, + ], + }; + writeStateFile(filePath, next); + const reread = loadState(filePath).unresolved.find( + (candidate) => candidate.recordId === record.recordId, + ); + if (!reread || JSON.stringify(reread) !== JSON.stringify(record)) { + throw new Error("Retained sandbox recovery record did not survive durable readback."); + } + return reread; +} diff --git a/src/lib/state/registry-create-only-reservation.test.ts b/src/lib/state/registry-create-only-reservation.test.ts new file mode 100644 index 00000000000..f5baf8a187b --- /dev/null +++ b/src/lib/state/registry-create-only-reservation.test.ts @@ -0,0 +1,107 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +const PROVIDERLESS_ROUTE = { + provider: null, + model: null, + endpointUrl: null, + endpointSource: null, + credentialEnv: null, + preferredInferenceApi: null, + gatewayName: "nemoclaw", + reservationSessionId: "session-apf", +} as const; + +describe("create-only sandbox route reservation", () => { + afterEach(() => { + vi.unstubAllEnvs(); + vi.resetModules(); + }); + + it("atomically refuses a reservation when any registry row exists", async () => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-create-reservation-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + registry.registerSandbox({ + name: "alpha", + provider: "nim", + model: "model-a", + endpointUrl: null, + endpointSource: null, + credentialEnv: null, + preferredInferenceApi: null, + agent: "openclaw", + openshellDriver: "docker", + gatewayName: "nemoclaw", + }); + const before = registry.getSandbox("alpha"); + + expect( + registry.reserveSandboxInferenceRoute("alpha", PROVIDERLESS_ROUTE, { + requireAbsent: true, + }), + ).toBe(false); + expect(registry.getSandbox("alpha")).toEqual(before); + } finally { + await fs.rm(home, { recursive: true, force: true }); + } + }); + + it("creates an absent providerless reservation without claiming the default", async () => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-create-reservation-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + + expect( + registry.reserveSandboxInferenceRoute("alpha", PROVIDERLESS_ROUTE, { + requireAbsent: true, + }), + ).toBe(true); + expect(registry.getSandbox("alpha")).toMatchObject({ + name: "alpha", + pendingRouteReservation: true, + reservationSessionId: "session-apf", + provider: null, + model: null, + }); + expect(registry.getDefault()).toBeNull(); + } finally { + await fs.rm(home, { recursive: true, force: true }); + } + }); + + it.each(["session-apf", "session-foreign"])( + "does not reuse an existing %s pending row", + async (existingSessionId) => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-create-reservation-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + registry.reserveSandboxInferenceRoute("alpha", { + ...PROVIDERLESS_ROUTE, + reservationSessionId: existingSessionId, + }); + const before = registry.getSandbox("alpha"); + + expect( + registry.reserveSandboxInferenceRoute("alpha", PROVIDERLESS_ROUTE, { + requireAbsent: true, + }), + ).toBe(false); + expect(registry.getSandbox("alpha")).toEqual(before); + } finally { + await fs.rm(home, { recursive: true, force: true }); + } + }, + ); +}); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 32da269bdde..6b2af682664 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -257,9 +257,7 @@ function assertPendingPolicyVerificationMatchesRegistration( checkpoint.policyAuthority === "nemoclaw-managed" ? isDeepStrictEqual(checkpoint.policyCreationReceipt, requestedEntry.policyCreationReceipt) : requestedEntry.policyCreationReceipt === undefined; - const mismatches: string[] = commonChecks - .filter(([, matches]) => !matches) - .map(([name]) => name); + const mismatches: string[] = commonChecks.filter(([, matches]) => !matches).map(([name]) => name); if (!authorityMatches) mismatches.push("policy receipt"); if (mismatches.length > 0) { throw new PolicyAuthorityRefusalError( @@ -672,6 +670,11 @@ type SandboxInferenceRouteReservation = Pick< hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; }; +interface SandboxInferenceRouteReservationOptions { + /** Refuse instead of changing any existing registry row. */ + requireAbsent?: boolean; +} + /** * Persist a route dependency before releasing the shared-gateway mutation * lock. A newly reserved row deliberately does not claim the default sandbox; @@ -680,10 +683,12 @@ type SandboxInferenceRouteReservation = Pick< export function reserveSandboxInferenceRoute( name: string, route: SandboxInferenceRouteReservation, + options: SandboxInferenceRouteReservationOptions = {}, ): boolean { return withLock(() => { const data = load(); const existing = data.sandboxes[name]; + if (options.requireAbsent === true && existing !== undefined) return false; const normalized = normalizeInferenceSelection(route); const provenance = cloneSandboxHostLocalInferenceProvenance(route.hostLocalInferenceProvenance); if ( diff --git a/src/lib/state/retained-sandbox-recovery.test.ts b/src/lib/state/retained-sandbox-recovery.test.ts new file mode 100644 index 00000000000..605df8ac27e --- /dev/null +++ b/src/lib/state/retained-sandbox-recovery.test.ts @@ -0,0 +1,317 @@ +// 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"; + +let home: string; + +beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-retained-recovery-")); + vi.stubEnv("HOME", home); + vi.resetModules(); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); +}); + +const evidence = { + sharedInferenceProviders: ["nvidia"], + sandboxScopedProviders: ["sandbox-telegram"], + credentialEnvironmentVariables: ["NVIDIA_API_KEY", "TELEGRAM_BOT_TOKEN"], +} as const; + +describe("retained sandbox recovery state", () => { + it("persists verified identity and secret-free resource evidence independently", async () => { + const recovery = await import("./onboard-session"); + const fingerprint = "a".repeat(64); + const input = { + sandboxName: "retained-sb", + sandboxIdentityFingerprint: fingerprint, + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "00000000-0000-4000-8000-000000000001", + verifiedEffectivePolicyIdentity: { hash: "sha256:policy-1", activeVersion: 1 }, + resources: evidence, + reason: "cancelled_after_sandbox_creation", + recordedAt: "2026-08-27T00:00:00.000Z", + } as const; + + const recorded = recovery.recordRetainedSandboxRecovery(input); + + expect(recovery.listRetainedSandboxRecoveryRecords()).toEqual([recorded]); + expect(recorded).toMatchObject({ + sandboxName: "retained-sb", + sandboxIdentityFingerprint: fingerprint, + identityWasUnavailable: false, + verifiedEffectivePolicyIdentity: input.verifiedEffectivePolicyIdentity, + resources: evidence, + }); + expect(fs.readFileSync(recovery.RETAINED_SANDBOX_RECOVERY_FILE, "utf8")).not.toContain( + "secret-value", + ); + }); + + it("records an explicit missing identity", async () => { + const recovery = await import("./onboard-session"); + + const recorded = recovery.recordRetainedSandboxRecovery({ + sandboxName: "missing-id", + sandboxIdentityFingerprint: null, + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: null, + verifiedEffectivePolicyIdentity: null, + resources: { + sharedInferenceProviders: [], + sandboxScopedProviders: [], + credentialEnvironmentVariables: [], + }, + reason: "retained_after_sandbox_creation_failure", + }); + + expect(recorded).toMatchObject({ + sandboxIdentityFingerprint: null, + identityWasUnavailable: true, + lifecycleGeneration: null, + }); + }); + + it("preserves distinct unresolved lifecycle tuples for one sandbox name (#9833)", async () => { + const recovery = await import("./onboard-session"); + const first = recovery.recordRetainedSandboxRecovery({ + sandboxName: "retained-sb", + sandboxIdentityFingerprint: "1".repeat(64), + gatewayName: "nemoclaw-18080", + gatewayPort: 18080, + lifecycleGeneration: "00000000-0000-4000-8000-000000000001", + verifiedEffectivePolicyIdentity: { hash: "sha256:policy-1", activeVersion: 1 }, + resources: evidence, + reason: "cancelled_after_sandbox_creation", + }); + const second = recovery.recordRetainedSandboxRecovery({ + sandboxName: "retained-sb", + sandboxIdentityFingerprint: "2".repeat(64), + gatewayName: "nemoclaw-18080", + gatewayPort: 18080, + lifecycleGeneration: "00000000-0000-4000-8000-000000000002", + verifiedEffectivePolicyIdentity: { hash: "sha256:policy-2", activeVersion: 2 }, + resources: evidence, + reason: "retained_after_sandbox_creation_failure", + }); + + expect(recovery.listRetainedSandboxRecoveryRecords()).toEqual([first, second]); + }); + + it("refuses a symbolic-link recovery state without reading its target", async () => { + const recovery = await import("./onboard-session"); + const externalState = path.join(home, "external-recovery.json"); + const externalContents = "{not recovery json"; + fs.writeFileSync(externalState, externalContents); + fs.mkdirSync(path.dirname(recovery.RETAINED_SANDBOX_RECOVERY_FILE), { recursive: true }); + fs.symlinkSync(externalState, recovery.RETAINED_SANDBOX_RECOVERY_FILE); + + expect(() => recovery.listRetainedSandboxRecoveryRecords()).toThrow(/symbolic link/u); + expect(fs.readFileSync(externalState, "utf8")).toBe(externalContents); + }); + + it("refuses a symbolic-link recovery state directory ancestor (#9833)", async () => { + const externalStateDirectory = path.join(home, "external-state"); + fs.mkdirSync(externalStateDirectory); + fs.symlinkSync(externalStateDirectory, path.join(home, ".nemoclaw"), "dir"); + const recovery = await import("./onboard-session"); + + expect(() => recovery.listRetainedSandboxRecoveryRecords()).toThrow(/symbolic link/u); + }); + + it("refuses recovery publication after the locked state directory is replaced (#9833)", async () => { + const recovery = await import("./onboard-session"); + expect(recovery.acquireOnboardLock("recovery directory replacement test").acquired).toBe(true); + const originalDirectory = path.dirname(recovery.RETAINED_SANDBOX_RECOVERY_FILE); + const displacedDirectory = `${originalDirectory}.displaced`; + const replacementDirectory = path.join(home, "replacement-state"); + fs.renameSync(originalDirectory, displacedDirectory); + fs.mkdirSync(replacementDirectory); + fs.symlinkSync(replacementDirectory, originalDirectory, "dir"); + + expect(() => + recovery.recordRetainedSandboxRecovery({ + sandboxName: "retained-sb", + sandboxIdentityFingerprint: "f".repeat(64), + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "generation-1", + verifiedEffectivePolicyIdentity: null, + resources: evidence, + reason: "retained_after_sandbox_creation_failure", + }), + ).toThrow(/symbolic link|lock ownership changed/u); + expect(fs.existsSync(path.join(replacementDirectory, "retained-sandbox-recovery.json"))).toBe( + false, + ); + expect(fs.existsSync(path.join(displacedDirectory, "onboard.lock"))).toBe(true); + }); + + it("writes no recovery evidence after the state directory changes at temporary open (#9833)", async () => { + const recovery = await import("./onboard-session"); + const stateDirectory = path.dirname(recovery.RETAINED_SANDBOX_RECOVERY_FILE); + const displacedDirectory = `${stateDirectory}.displaced`; + const openSync = fs.openSync.bind(fs); + let replaced = false; + vi.spyOn(fs, "openSync").mockImplementation((file, flags, mode) => { + !replaced && + path.basename(String(file)).startsWith(".retained-sandbox-recovery.") && + (() => { + replaced = true; + fs.renameSync(stateDirectory, displacedDirectory); + fs.mkdirSync(stateDirectory, { mode: 0o700 }); + })(); + return openSync(file, flags, mode); + }); + + expect(() => + recovery.recordRetainedSandboxRecovery({ + sandboxName: "retained-sb", + sandboxIdentityFingerprint: "f".repeat(64), + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "generation-1", + verifiedEffectivePolicyIdentity: null, + resources: evidence, + reason: "retained_after_sandbox_creation_failure", + }), + ).toThrow(/state directory changed|lock ownership changed/u); + expect(replaced).toBe(true); + expect( + fs + .readdirSync(stateDirectory) + .map((name) => fs.statSync(path.join(stateDirectory, name)).size) + .filter((size) => size > 0), + ).toEqual([]); + }); + + it("writes no session evidence after the state directory changes at temporary open (#9833)", async () => { + const recovery = await import("./onboard-session"); + const stateDirectory = path.dirname(recovery.SESSION_FILE); + const displacedDirectory = `${stateDirectory}.displaced`; + const openSync = fs.openSync.bind(fs); + let replaced = false; + vi.spyOn(fs, "openSync").mockImplementation((file, flags, mode) => { + !replaced && + path.basename(String(file)).startsWith(".onboard-session.") && + (() => { + replaced = true; + fs.renameSync(stateDirectory, displacedDirectory); + fs.mkdirSync(stateDirectory, { mode: 0o700 }); + })(); + return openSync(file, flags, mode); + }); + + expect(() => + recovery.markRetainedSandboxRecovery( + "retained-sb", + "Sandbox creation failed after identity verification.", + "f".repeat(64), + { + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "generation-1", + verifiedEffectivePolicyIdentity: null, + }, + ), + ).toThrow(/state directory changed|lock ownership changed/u); + expect(replaced).toBe(true); + expect( + fs + .readdirSync(stateDirectory) + .map((name) => fs.statSync(path.join(stateDirectory, name)).size) + .filter((size) => size > 0), + ).toEqual([]); + }); + + it("does not expose a caller-supplied recovery resolution path (#9833)", async () => { + const recovery = await import("./onboard-session"); + const recoveryStore = await import("./onboard-session/retained-sandbox-recovery"); + const fingerprint = "b".repeat(64); + const recorded = recovery.recordRetainedSandboxRecovery({ + sandboxName: "retained-sb", + sandboxIdentityFingerprint: fingerprint, + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "generation-1", + verifiedEffectivePolicyIdentity: null, + resources: evidence, + reason: "cancelled_after_sandbox_creation", + }); + const unsupportedClear = (recovery as unknown as Record)[ + "resolveRetainedSandboxRecovery" + ]; + (unsupportedClear as undefined | ((input: Record) => unknown))?.({ + recordId: recorded.recordId, + receiptId: "c".repeat(64), + sandboxName: recorded.sandboxName, + sandboxIdentityFingerprint: fingerprint, + gatewayName: recorded.gatewayName, + gatewayPort: recorded.gatewayPort, + outcome: "removed_verified_identity", + }); + + expect(unsupportedClear).toBeUndefined(); + expect( + (recoveryStore as unknown as Record)["resolveRetainedSandboxRecovery"], + ).toBeUndefined(); + expect(recovery.listRetainedSandboxRecoveryRecords()).toEqual([recorded]); + }); + + it("preserves legacy resolution evidence while recording new recovery state (#9833)", async () => { + const recovery = await import("./onboard-session"); + const recorded = recovery.recordRetainedSandboxRecovery({ + sandboxName: "legacy-sb", + sandboxIdentityFingerprint: "d".repeat(64), + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "legacy-generation", + verifiedEffectivePolicyIdentity: null, + resources: evidence, + reason: "cancelled_after_sandbox_creation", + }); + const legacyResolution = { + schemaVersion: 1, + receiptId: "e".repeat(64), + recordId: recorded.recordId, + sandboxName: recorded.sandboxName, + sandboxIdentityFingerprint: recorded.sandboxIdentityFingerprint, + gatewayName: recorded.gatewayName, + gatewayPort: recorded.gatewayPort, + outcome: "removed_verified_identity", + resolvedAt: "2026-08-27T00:00:00.000Z", + }; + const legacyState = JSON.parse( + fs.readFileSync(recovery.RETAINED_SANDBOX_RECOVERY_FILE, "utf8"), + ); + legacyState.unresolved = []; + legacyState.resolutions = [legacyResolution]; + fs.writeFileSync(recovery.RETAINED_SANDBOX_RECOVERY_FILE, JSON.stringify(legacyState)); + + recovery.recordRetainedSandboxRecovery({ + sandboxName: "new-sb", + sandboxIdentityFingerprint: null, + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: null, + verifiedEffectivePolicyIdentity: null, + resources: evidence, + reason: "retained_after_sandbox_creation_failure", + }); + + const durableState = JSON.parse( + fs.readFileSync(recovery.RETAINED_SANDBOX_RECOVERY_FILE, "utf8"), + ); + expect(durableState.resolutions).toEqual([legacyResolution]); + }); +}); diff --git a/test/onboarding/onboard-fresh-create-identity.test.ts b/test/onboarding/onboard-fresh-create-identity.test.ts index d1006a9fab0..07d72231869 100644 --- a/test/onboarding/onboard-fresh-create-identity.test.ts +++ b/test/onboarding/onboard-fresh-create-identity.test.ts @@ -11,6 +11,7 @@ import path from "node:path"; import { beforeEach, describe, it, vi } from "vitest"; import { writeOkOpenshell } from "../helpers/onboard-openshell-fixture"; import { type CommandEntry, onboardScriptMocksPath } from "../helpers/onboard-split-context"; +import { encodeMessagingPlan, makeMessagingPlan } from "../helpers/messaging-plan-fixtures"; beforeEach(() => { vi.stubEnv("NEMOCLAW_TEST_MANAGED_IMAGE_CATALOG", "1"); @@ -19,14 +20,125 @@ beforeEach(() => { describe("fresh create identity", () => { it.each([ - { label: "managed creation", apfInterceptorRequested: false }, - { label: "APF-selected creation", apfInterceptorRequested: true }, + { + title: "binds ordinary providers at create time before managed registration (#9833)", + apfInterceptorRequested: false, + provider: "nvidia-prod", + model: "gpt-5.4", + agent: null, + expectedOutcome: "managed-provider" as const, + }, + { + title: "rejects provider-backed APF creation before sandbox or provider effects (#9833)", + apfInterceptorRequested: true, + provider: "nvidia-prod", + model: "gpt-5.4", + agent: null, + expectedOutcome: "provider-refusal" as const, + }, + { + title: "rejects a nondefault agent before credential reads or sandbox inspection (#9833)", + apfInterceptorRequested: true, + provider: null, + model: null, + agent: { name: "hermes" }, + expectedOutcome: "unsupported-agent-refusal" as const, + }, + { + title: + "registers providerless APF only after identity, policy, and checkpoint verification (#9833)", + apfInterceptorRequested: true, + provider: null, + model: null, + agent: null, + expectedOutcome: "providerless-apf" as const, + }, + { + title: "surfaces retained sandbox recovery through the public error message (#9833)", + apfInterceptorRequested: true, + provider: null, + model: null, + agent: null, + expectedOutcome: "post-create-authority-refusal" as const, + }, + { + title: "retains recovery state when the create runner fails after verification (#9833)", + apfInterceptorRequested: true, + provider: null, + model: null, + agent: null, + expectedOutcome: "post-create-runner-refusal" as const, + }, + { + title: "retains recovery state when registry publication fails after create (#9833)", + apfInterceptorRequested: true, + provider: null, + model: null, + agent: null, + expectedOutcome: "post-create-registration-refusal" as const, + }, + { + title: "blocks every reentry when registry-failure recovery has no durable journal (#9833)", + apfInterceptorRequested: true, + provider: null, + model: null, + agent: null, + expectedOutcome: "post-create-registration-recovery-readback-failure" as const, + }, + { + title: "retries registry-failure recovery from the process-exit owner (#9833)", + apfInterceptorRequested: true, + provider: null, + model: null, + agent: null, + expectedOutcome: "post-create-registration-recovery-retry" as const, + }, + { + title: "retains recovery state when final checks fail after registration (#9833)", + apfInterceptorRequested: true, + provider: null, + model: null, + agent: null, + expectedOutcome: "post-create-finalization-refusal" as const, + }, + { + title: "rejects staged messaging intent before any onboarding side effect (#9833)", + apfInterceptorRequested: true, + provider: null, + model: null, + agent: null, + expectedOutcome: "staged-messaging-refusal" as const, + }, + { + title: "makes a tier-cancelled created sandbox recovery-only (#9833)", + apfInterceptorRequested: false, + provider: "nvidia-prod", + model: "gpt-5.4", + agent: null, + expectedOutcome: "cancel-after-create-tier" as const, + }, + { + title: "makes a tier-preset-cancelled created sandbox recovery-only (#9833)", + apfInterceptorRequested: false, + provider: "nvidia-prod", + model: "gpt-5.4", + agent: null, + expectedOutcome: "cancel-after-create-tier-presets" as const, + }, + { + title: "makes a custom-preset-cancelled created sandbox recovery-only (#9833)", + apfInterceptorRequested: false, + provider: "nvidia-prod", + model: "gpt-5.4", + agent: null, + expectedOutcome: "cancel-after-create-custom-presets" as const, + }, ])( - "registers $label only after owner-scoped identity and policy confirmation (#9833)", + "$title", { timeout: 45000, }, - async ({ apfInterceptorRequested }) => { + async ({ agent, apfInterceptorRequested, expectedOutcome, model, provider }) => { const repoRoot = path.join(import.meta.dirname, "../.."); const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-create-ready-")); const fakeBin = path.join(tmpDir, "bin"); @@ -37,9 +149,6 @@ describe("fresh create identity", () => { const registryPath = JSON.stringify( path.join(repoRoot, "src", "lib", "state", "registry.ts"), ); - const onboardSessionPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "state", "onboard-session.ts"), - ); const recreateJournalPath = JSON.stringify( path.join(repoRoot, "src", "lib", "onboard", "onboard-recreate-journal.ts"), ); @@ -49,6 +158,12 @@ describe("fresh create identity", () => { const credentialsPath = JSON.stringify( path.join(repoRoot, "src", "lib", "credentials", "store.ts"), ); + const entryOptionsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "entry-options.ts"), + ); + const retainedRecoveryPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "onboard-session.ts"), + ); const dockerExecPath = JSON.stringify( path.join(repoRoot, "src", "lib", "adapters", "docker", "exec.ts"), ); @@ -66,10 +181,11 @@ describe("fresh create identity", () => { const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); let _deleted = false; const registry = require(${registryPath}); -const onboardSession = require(${onboardSessionPath}); const recreateJournal = require(${recreateJournalPath}); const preflight = require(${preflightPath}); const credentials = require(${credentialsPath}); +const entryOptions = require(${entryOptionsPath}); +const retainedRecovery = require(${retainedRecoveryPath}); const childProcess = require("node:child_process"); const { EventEmitter } = require("node:events"); const dockerExec = require(${dockerExecPath}); @@ -87,14 +203,60 @@ let dockerPsCalls = 0; let sandboxCreated = false; let registeredSandbox = null; let effectivePolicy = {}; +let credentialReadCalls = 0; +let routeReservationCalls = 0; const keepAlive = setInterval(() => {}, 1000); const apfInterceptorRequested = ${JSON.stringify(apfInterceptorRequested)}; +const agent = ${JSON.stringify(agent)}; +const model = ${JSON.stringify(model)}; +const provider = ${JSON.stringify(provider)}; +const selectedChannels = ${JSON.stringify(expectedOutcome === "provider-refusal" ? ["telegram"] : null)}; +const cancellationSelector = ${JSON.stringify( + expectedOutcome.startsWith("cancel-after-create-") + ? expectedOutcome.slice("cancel-after-create-".length) + : null, + )}; +const cancelAfterCreate = cancellationSelector !== null; +const recoveryReentry = process.env.NEMOCLAW_RECOVERY_REENTRY || ""; +const stagedMessagingRefusal = ${JSON.stringify(expectedOutcome === "staged-messaging-refusal")}; +const postCreateAuthorityRefusal = ${JSON.stringify( + expectedOutcome === "post-create-authority-refusal", + )}; +const postCreateRunnerRefusal = ${JSON.stringify(expectedOutcome === "post-create-runner-refusal")}; +const postCreateRegistrationRefusal = ${JSON.stringify( + expectedOutcome === "post-create-registration-refusal" || + expectedOutcome === "post-create-registration-recovery-readback-failure" || + expectedOutcome === "post-create-registration-recovery-retry", + )}; +let recoveryJournalReadbackFailuresRemaining = ${JSON.stringify( + expectedOutcome === "post-create-registration-recovery-readback-failure" + ? 100 + : expectedOutcome === "post-create-registration-recovery-retry" || + expectedOutcome === "post-create-runner-refusal" + ? 1 + : 0, + )}; +const postCreateFinalizationRefusal = ${JSON.stringify( + expectedOutcome === "post-create-finalization-refusal", + )}; +let cancelPrompt = false; +const originalGetCredential = credentials.getCredential; +credentials.getCredential = (...args) => { + credentialReadCalls += 1; + if (typeof args[0] !== "string") return null; + return originalGetCredential(...args); +}; +const originalReserveSandboxInferenceRoute = registry.reserveSandboxInferenceRoute; +registry.reserveSandboxInferenceRoute = (...args) => { + routeReservationCalls += 1; + return originalReserveSandboxInferenceRoute(...args); +}; runner.run = (command, opts = {}) => { const cmd = _n(command); - const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); - if (profileResult !== null) return profileResult; _deleted = _deleted || cmd.includes("sandbox delete"); commands.push({ command: cmd, env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; if (cmd.includes("sandbox list")) { return { status: 0, stdout: Buffer.from("No sandboxes found.\n"), stderr: Buffer.alloc(0) }; } @@ -104,8 +266,13 @@ runner.run = (command, opts = {}) => { }; runner.runCapture = (command) => { const cmd = _n(command); - if (cmd.includes("gateway info")) return "Gateway endpoint: http://127.0.0.1:8080"; - if (cmd.includes("policy get") && cmd.includes("--output json")) return JSON.stringify({ scope: "sandbox", sandbox: "my-assistant", status: "effective", policy_source: "sandbox", hash: "fixture-policy", active_version: 1, policy: effectivePolicy }); + if (cmd.includes("gateway info")) return "Gateway endpoint: http://127.0.0.1:18080"; + if (cmd.includes("policy get") && cmd.includes("--output json")) { + if (postCreateFinalizationRefusal && registeredSandbox) { + throw new Error("final onboarding policy check failed"); + } + return JSON.stringify({ scope: "sandbox", sandbox: "my-assistant", status: "effective", policy_source: "sandbox", hash: "fixture-policy", active_version: 1, policy: effectivePolicy }); + } if (cmd.includes("sandbox get") || cmd.includes("sandbox list")) { lifecycleObservationCommands.push(cmd); } @@ -132,67 +299,107 @@ runner.run = (command, opts = {}) => { if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; return ""; }; - const session = onboardSession.createSession({ - sessionId: "session-owner", - sandboxName: "my-assistant", - agent: "openclaw", - }); - onboardSession.saveSession(session); - registry.save({ - defaultSandbox: null, - sandboxes: { - "my-assistant": { - name: "my-assistant", - gatewayName: "nemoclaw", - provider: "nvidia-prod", - model: "gpt-5.4", - endpointUrl: null, - endpointSource: null, - credentialEnv: null, + const retainedRegistryEntry = recoveryReentry && fs.existsSync(${JSON.stringify(payloadPath)}) + ? JSON.parse(fs.readFileSync(${JSON.stringify(payloadPath)}, "utf8")).currentRegistryEntry + : null; + const registryMutationCalls = []; + let checkpointReadCalls = 0; + if (!recoveryReentry) { + const session = retainedRecovery.createSession({ + sessionId: "session-owner", + sandboxName: "my-assistant", + agent: agent?.name ?? "openclaw", + }); + retainedRecovery.saveSession(session); + registry.save({ + defaultSandbox: null, + sandboxes: { + "my-assistant": { + name: "my-assistant", + gatewayName: "nemoclaw-18080", + gatewayPort: 18080, + provider, + model, + endpointUrl: null, + endpointSource: null, + credentialEnv: null, + preferredInferenceApi: null, + pendingRouteReservation: true, + reservationSessionId: "session-owner", + }, + }, + }); + recreateJournal.openOnboardRecreateJournal({ + target: { + sandboxName: "my-assistant", + gatewayName: "nemoclaw-18080", + gatewayPort: 18080, + }, + agentName: agent?.name ?? "openclaw", + note: () => {}, + observe: () => ({ state: "missing", liveIdentityFingerprint: null }), + intent: { + agent: agent?.name ?? "openclaw", + fromDockerfile: null, + provider, + model, preferredInferenceApi: null, - pendingRouteReservation: true, - reservationSessionId: "session-owner", + sandboxGpuConfig: null, + gatewayName: "nemoclaw-18080", + gatewayPort: 18080, + toolDisclosure: "progressive", + dcodeAutoApprovalMode: null, + observabilityEnabled: false, + policyTier: null, }, - }, - }); - recreateJournal.openOnboardRecreateJournal({ - target: { sandboxName: "my-assistant", gatewayName: "nemoclaw", gatewayPort: 8080 }, - agentName: "openclaw", - note: () => {}, - observe: () => ({ state: "missing", liveIdentityFingerprint: null }), - intent: { - agent: "openclaw", - fromDockerfile: null, - provider: "nvidia-prod", - model: "gpt-5.4", - preferredInferenceApi: null, - sandboxGpuConfig: null, - gatewayName: "nemoclaw", - gatewayPort: 8080, - toolDisclosure: "progressive", - dcodeAutoApprovalMode: null, - observabilityEnabled: false, - policyTier: null, - }, - }); - const transaction = onboardSession.loadSession()?.checkpoint?.sandboxRecreate; - if (!transaction) throw new Error("failed to seed the fresh-create lifecycle journal"); + }); + } + const durableGetSandbox = registry.getSandbox.bind(registry); const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { sandboxName: "my-assistant", - provider: "nvidia-prod", - model: "gpt-5.4", + gatewayName: "nemoclaw-18080", + gatewayPort: 18080, + provider, + model, sessionId: "session-owner", - getSandbox: registry.getSandbox, apfInterceptorRequested, + getSandbox: (name) => retainedRegistryEntry ?? durableGetSandbox(name), onVerifyCreatedPolicy: (input) => { + if (postCreateAuthorityRefusal) { + throw new Error("external policy authority changed"); + } effectivePolicy = require(${policyMergePath}).parseOpenShellPolicy( fs.readFileSync(input.policySourcePath, "utf8"), ).policy; }, - registerSandbox: (entry) => { registeredSandbox = entry; }, + registerSandbox: (entry) => { + if (postCreateRegistrationRefusal) { + throw new Error("registry publication failed"); + } + registeredSandbox = entry; + registryMutationCalls.push({ operation: "register", name: entry.name }); + }, + updateSandbox: (name) => { registryMutationCalls.push({ operation: "update", name }); }, + setDefault: (name) => { registryMutationCalls.push({ operation: "set-default", name }); }, + removeSandbox: (name) => { registryMutationCalls.push({ operation: "remove", name }); }, }); +if (postCreateRunnerRefusal) { + const requireCurrentCheckpoint = registry.requireCurrentPendingSandboxPolicyVerification; + registry.requireCurrentPendingSandboxPolicyVerification = (...args) => { + checkpointReadCalls += 1; + if (checkpointReadCalls === 6) { + throw new Error("post-verification create runner checkpoint failed"); + } + return requireCurrentCheckpoint(...args); + }; +} preflight.checkPortAvailable = async () => ({ ok: true }); -credentials.prompt = async () => ""; +credentials.prompt = async () => { + if (cancelPrompt) { + throw Object.assign(new Error("Prompt interrupted"), { code: "SIGINT" }); + } + return ""; +}; const groupKillCalls = []; const realProcessKill = process.kill.bind(process); @@ -240,15 +447,149 @@ childProcess.spawn = (...args) => { return child; }; -const { createSandbox } = require(${onboardPath}); +const onboardModule = require(${onboardPath}); +const { createSandbox } = onboardModule; +if (recoveryJournalReadbackFailuresRemaining > 0) { + const renameSync = fs.renameSync.bind(fs); + fs.renameSync = (source, destination) => { + renameSync(source, destination); + if ( + recoveryJournalReadbackFailuresRemaining > 0 && + String(destination).endsWith("retained-sandbox-recovery.json") + ) { + recoveryJournalReadbackFailuresRemaining -= 1; + fs.writeFileSync( + destination, + JSON.stringify({ schemaVersion: 1, unresolved: [], resolutions: [] }), + ); + } + }; +} +if (cancelAfterCreate && !recoveryReentry) { + const session = onboardModule.onboardSession.loadSession(); + if (!session) throw new Error("missing seeded onboarding session"); + session.mode = "interactive"; + session.sandboxName = "my-assistant"; + session.metadata = { gatewayName: "nemoclaw-18080", fromDockerfile: null }; + onboardModule.onboardSession.saveSession(session); + onboardModule.registerIncompleteOnboardExitHandlerForSession( + onboardModule.onboardSession, + () => false, + ); +} + +const writePayload = (sandboxName, creationError, exitCode = 0) => { + const createCommand = commands.find((entry) => entry.command.includes("sandbox create")); + fs.writeFileSync(${JSON.stringify(payloadPath)}, JSON.stringify({ + sandboxName, + creationError, + exitCode, + deleted: _deleted, + sandboxCreated, + sandboxListCalls, + killCalls: createCommand?.child?.killCalls ?? [], + groupKillCalls, + unrefCalls: createCommand?.child?.unrefCalls ?? 0, + stdoutDestroyCalls: createCommand?.child?.stdout.destroyCalls ?? 0, + stderrDestroyCalls: createCommand?.child?.stderr.destroyCalls ?? 0, + lifecycleObservationCommands, + registeredSandbox, + credentialReadCalls, + routeReservationCalls, + checkpointReadCalls, + registryMutationCalls, + currentRegistryEntry: cancelAfterCreate ? registry.getSandbox("my-assistant") : null, + recoveryRegistryEntry: registry.getSandbox("my-assistant"), + savedSession: + cancelAfterCreate || + postCreateAuthorityRefusal || + postCreateRunnerRefusal || + postCreateRegistrationRefusal || + postCreateFinalizationRefusal + ? onboardModule.onboardSession.loadSession() + : null, + retainedRecoveryRecords: retainedRecovery.listRetainedSandboxRecoveryRecords(), + createCommand: createCommand?.command ?? null, + commandNames: commands.map((entry) => entry.command), + })); +}; +let finalCreationError = null; +if (${JSON.stringify( + expectedOutcome === "post-create-registration-recovery-retry" || + expectedOutcome === "post-create-runner-refusal", + )}) { + process.on("exit", (code) => writePayload(null, finalCreationError, code)); +} (async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.OPENSHELL_GATEWAY = "nemoclaw-18080"; + if (recoveryReentry) { + if (recoveryReentry === "fresh-different-no-journal") { + try { + await onboardModule.onboard({ + fresh: true, + sandboxName: "replacement-sb", + deferProcessExit: true, + }); + writePayload(null, "recovery-only onboarding unexpectedly continued", 0); + } catch (error) { + writePayload( + null, + error instanceof Error ? error.message : String(error), + typeof error?.code === "number" ? error.code : 1, + ); + } + clearInterval(keepAlive); + return; + } + if (recoveryReentry === "fresh-different") { + const retainedNames = retainedRecovery + .listRetainedSandboxRecoveryRecords() + .map((record) => record.sandboxName); + const resolved = entryOptions.resolveDefaultRunEntryOptions( + { fresh: true, sandboxName: "replacement-sb" }, + onboardModule.onboardSession.loadSession(), + runner.validateName, + process.env, + retainedNames, + ); + onboardModule.onboardSession.clearSession(); + onboardModule.onboardSession.saveSession( + onboardModule.onboardSession.createSession({ + mode: resolved.nonInteractive ? "non-interactive" : "interactive", + sandboxName: resolved.requestedSandboxName, + metadata: { gatewayName: "nemoclaw-18080", fromDockerfile: null }, + }), + ); + writePayload("replacement-sb", null, 0); + clearInterval(keepAlive); + return; + } + try { + await onboardModule.onboard({ + resume: recoveryReentry === "explicit", + fresh: recoveryReentry === "fresh-same", + recreateSandbox: recoveryReentry === "recreate", + sandboxName: "my-assistant", + deferProcessExit: true, + }); + writePayload(null, "recovery-only onboarding unexpectedly continued", 0); + } catch (error) { + writePayload( + null, + error instanceof Error ? error.message : String(error), + typeof error?.code === "number" ? error.code : 1, + ); + } + clearInterval(keepAlive); + return; + } const createArgs = fixtureMocks.sandboxCreateArgsWithVerifiedReservation( - [null, "gpt-5.4", "nvidia-prod", null, null, null, null, null, null, null, null, null, []], + [null, model, provider, null, null, null, selectedChannels, null, agent, null, null, null, []], createFixture, ); createArgs[15] = { + ...createArgs[15], ...(apfInterceptorRequested ? { apfInterceptorRequested: true, @@ -258,27 +599,35 @@ const { createSandbox } = require(${onboardPath}); recreate: false, toolDisclosure: "progressive", observabilityEnabled: false, - recreateTransaction: { - id: transaction.id, - targetGeneration: transaction.targetGeneration, - targetIntentFingerprint: transaction.targetIntentFingerprint, - }, }; - const sandboxName = await createSandbox(...createArgs); - const createCommand = commands.find((entry) => entry.command.includes("sandbox create")); - fs.writeFileSync(${JSON.stringify(payloadPath)}, JSON.stringify({ - sandboxName, - sandboxListCalls, - killCalls: createCommand.child.killCalls, - groupKillCalls, - unrefCalls: createCommand.child.unrefCalls, - stdoutDestroyCalls: createCommand.child.stdout.destroyCalls, - stderrDestroyCalls: createCommand.child.stderr.destroyCalls, - lifecycleObservationCommands, - registeredSandbox, - createCommand: createCommand.command, - commandNames: commands.map((entry) => entry.command), - })); + try { + const sandboxName = await createSandbox(...createArgs); + if (cancelAfterCreate) { + process.on("exit", (code) => writePayload(sandboxName, null, code)); + cancelPrompt = true; + if (cancellationSelector === "tier") { + await onboardModule.selectPolicyTier(); + } else if (cancellationSelector === "tier-presets") { + await onboardModule.selectTierPresetsAndAccess( + "balanced", + [{ name: "github", description: "GitHub" }], + ["github"], + ); + } else { + await onboardModule.presetsCheckboxSelector( + [{ name: "github", description: "GitHub" }], + ["github"], + ); + } + throw new Error("expected policy selection cancellation"); + } + writePayload(sandboxName, null); + } catch (error) { + if (cancelAfterCreate) throw error; + if (!apfInterceptorRequested) throw error; + finalCreationError = error instanceof Error ? error.message : String(error); + writePayload(null, finalCreationError); + } clearInterval(keepAlive); })().catch((error) => { clearInterval(keepAlive); @@ -288,74 +637,436 @@ const { createSandbox } = require(${onboardPath}); `; fs.writeFileSync(scriptPath, script); + const childEnv = { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: expectedOutcome.startsWith("cancel-after-create-") ? "" : "1", + NEMOCLAW_GATEWAY_PORT: "18080", + OPENSHELL_DRIVERS: "docker", + NEMOCLAW_MESSAGING_PLAN_B64: + expectedOutcome === "staged-messaging-refusal" + ? encodeMessagingPlan( + makeMessagingPlan({ sandboxName: "my-assistant", channels: ["telegram"] }), + ) + : "", + }; const result = spawnSync(process.execPath, [scriptPath], { cwd: repoRoot, encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - OPENSHELL_DRIVERS: "docker", - }, + env: childEnv, timeout: 30000, }); - assert.equal(result.status, 0, result.stderr); + const cancellationOutcome = expectedOutcome.startsWith("cancel-after-create-"); + assert.equal(result.status, cancellationOutcome ? 1 : 0, result.stderr); + assert.ok(fs.existsSync(payloadPath), result.stderr); const payload = JSON.parse(fs.readFileSync(payloadPath, "utf8")); - assert.equal(payload.sandboxName, "my-assistant"); - assert.ok(payload.sandboxListCalls >= 2); - assert.deepEqual(payload.groupKillCalls, [{ pid: -4242, signal: "SIGTERM" }]); - assert.deepEqual(payload.killCalls, []); - assert.equal(payload.unrefCalls, 0); - assert.equal(payload.stdoutDestroyCalls, 0); - assert.equal(payload.stderrDestroyCalls, 0); - assert.match(payload.registeredSandbox.lifecycleGeneration, /^[0-9a-f-]{36}$/u); - assert.equal( - payload.registeredSandbox.lifecycleLiveIdentityFingerprint, - createHash("sha256").update("sbx-fresh-create").digest("hex"), - ); - const assertPolicyMode = apfInterceptorRequested - ? () => { - assert.equal(payload.registeredSandbox.policyAuthority, "externally-managed"); - assert.equal(payload.registeredSandbox.policyCreationReceipt, undefined); - assert.deepEqual(payload.registeredSandbox.appliedPolicies ?? [], []); - assert.doesNotMatch(payload.createCommand, /(?:^|\s)--policy(?:=|\s)/u); - const createIndex = payload.commandNames.findIndex((command: string) => - command.includes("sandbox create"), - ); - const deferredEffectIndexes = payload.commandNames - .map((command: string, index: number) => ({ command, index })) - .filter(({ command }: { command: string }) => - /provider (?:profile import|create)|sandbox provider attach/u.test(command), - ) - .map(({ index }: { index: number }) => index); - assert.ok(deferredEffectIndexes.every((index: number) => index > createIndex)); - } - : () => { - assert.equal(payload.registeredSandbox.policyAuthority, "nemoclaw-managed"); - assert.ok(payload.registeredSandbox.policyCreationReceipt); - }; - assertPolicyMode(); - assert.match( - payload.createCommand, - /--label ai\.nvidia\.nemoclaw\.create-attempt=[0-9a-f]{62}/u, - ); - const ownerScopedObservations = payload.lifecycleObservationCommands.filter( - (command: string) => command.includes("-g nemoclaw"), - ); - assert.ok( - ownerScopedObservations.length >= 6, - "expected owner-scoped sandbox identity observations", + const providerEffectCommands = payload.commandNames.filter((command: string) => + /(?:^|\s)provider (?:create|update|delete|profile import)\b|(?:^|\s)sandbox provider (?:attach|detach)\b/u.test( + command, + ), ); - assert.ok( - ownerScopedObservations.every( - (command: string) => - command.includes("sandbox get -g nemoclaw my-assistant") || - command.includes("sandbox list -g nemoclaw"), + const providerExposureCommands = payload.commandNames.filter((command: string) => + /(?:^|\s)provider (?:create|update|profile import)\b|(?:^|\s)sandbox provider attach\b/u.test( + command, ), - `fresh identity observations must remain scoped to the owning gateway: ${JSON.stringify(ownerScopedObservations)}`, ); + const identityFingerprint = createHash("sha256").update("sbx-fresh-create").digest("hex"); + const assertRecoveryTuple = (record: Record) => { + assert.equal(record.gatewayName, "nemoclaw-18080"); + assert.equal(record.gatewayPort, 18080); + assert.equal(record.sandboxIdentityFingerprint, identityFingerprint); + assert.equal(record.lifecycleGeneration, payload.recoveryRegistryEntry.lifecycleGeneration); + assert.deepEqual(record.verifiedEffectivePolicyIdentity, { + hash: "fixture-policy", + activeVersion: 1, + }); + }; + const assertProviderBackedApfRefusal = () => { + assert.match( + payload.creationError, + /supports providerless sandbox creation only.*No sandbox or provider was created/u, + ); + assert.equal(payload.sandboxName, null); + assert.equal(payload.sandboxCreated, false); + assert.equal(payload.createCommand, null); + assert.equal(payload.registeredSandbox, null); + assert.equal(payload.credentialReadCalls, 0); + assert.equal(payload.routeReservationCalls, 0); + assert.deepEqual(payload.registryMutationCalls, []); + assert.deepEqual(providerEffectCommands, []); + assert.equal( + payload.commandNames.some((command: string) => command.includes("sandbox create")), + false, + ); + }; + const assertUnsupportedAgentRefusal = () => { + assertProviderBackedApfRefusal(); + assert.deepEqual(payload.commandNames, []); + assert.equal(payload.sandboxListCalls, 0); + }; + const assertStagedMessagingRefusal = () => { + assert.match( + payload.creationError, + /supports providerless sandbox creation only.*No sandbox or provider was created/u, + ); + assert.equal(payload.sandboxName, null); + assert.equal(payload.sandboxCreated, false); + assert.equal(payload.createCommand, null); + assert.equal(payload.registeredSandbox, null); + assert.equal(payload.credentialReadCalls, 0); + assert.equal(payload.routeReservationCalls, 0); + assert.deepEqual(providerEffectCommands, []); + assert.equal( + payload.commandNames.some((command: string) => + /(?:^|\s)(?:docker build|policy (?:set|apply)|sandbox create)(?:\s|$)/u.test(command), + ), + false, + ); + }; + const assertSuccessfulCreation = () => { + assert.equal(payload.creationError, null, result.stderr); + assert.equal(payload.sandboxName, "my-assistant"); + assert.ok(payload.sandboxListCalls >= 2); + assert.deepEqual(payload.groupKillCalls, [{ pid: -4242, signal: "SIGTERM" }]); + assert.deepEqual(payload.killCalls, []); + assert.equal(payload.unrefCalls, 0); + assert.equal(payload.stdoutDestroyCalls, 0); + assert.equal(payload.stderrDestroyCalls, 0); + assert.equal(payload.registeredSandbox.workload.kind, "managed-image"); + assert.match(payload.registeredSandbox.lifecycleGeneration, /^[0-9a-f-]{36}$/u); + assert.equal( + payload.registeredSandbox.lifecycleLiveIdentityFingerprint, + createHash("sha256").update("sbx-fresh-create").digest("hex"), + ); + assert.match( + payload.createCommand, + /--label ai\.nvidia\.nemoclaw\.create-attempt=[0-9a-f]{62}/u, + ); + const ownerScopedObservations = payload.lifecycleObservationCommands.filter( + (command: string) => command.includes("-g nemoclaw-18080"), + ); + assert.ok( + ownerScopedObservations.length >= 6, + "expected owner-scoped sandbox identity observations", + ); + assert.ok( + ownerScopedObservations.every( + (command: string) => + command.includes("sandbox get -g nemoclaw-18080 my-assistant") || + command.includes("sandbox list -g nemoclaw-18080"), + ), + `fresh identity observations must remain scoped to the owning gateway: ${JSON.stringify(ownerScopedObservations)}`, + ); + }; + const assertManagedProviderCreation = () => { + assertSuccessfulCreation(); + assert.equal(payload.registeredSandbox.policyAuthority, "nemoclaw-managed"); + assert.ok(payload.registeredSandbox.policyCreationReceipt); + assert.match(payload.createCommand, /--policy \S+/u); + assert.match(payload.createCommand, /--provider nvidia-prod/u); + }; + const assertProviderlessApfCreation = () => { + assertSuccessfulCreation(); + assert.equal(payload.registeredSandbox.policyAuthority, "externally-managed"); + assert.equal(payload.registeredSandbox.policyCreationReceipt, undefined); + assert.doesNotMatch(payload.createCommand, /(?:^|\s)--policy(?:\s|$)/u); + assert.doesNotMatch(payload.createCommand, /(?:^|\s)--provider(?:\s|$)/u); + assert.equal(payload.credentialReadCalls, 0); + assert.deepEqual(providerExposureCommands, []); + }; + const assertPostCreateAuthorityRefusal = () => { + assert.equal(payload.sandboxName, null); + assert.equal(payload.sandboxCreated, true); + assert.equal(payload.deleted, false); + assert.match(payload.creationError, /left sandbox 'my-assistant' in place/u); + assert.match(payload.creationError, new RegExp(identityFingerprint, "u")); + assert.match( + payload.creationError, + /did not run OpenShell's mutable-name deletion command because the name may now identify a replacement sandbox/u, + ); + assert.match(payload.creationError, /Do not delete the sandbox by mutable sandbox name/u); + assert.match( + payload.creationError, + /Ask the OpenShell administrator.*identity-bound recovery or removal procedure/u, + ); + assert.equal(payload.savedSession.status, "recovery_required"); + assert.equal(payload.savedSession.resumable, false); + assert.equal( + payload.savedSession.cancellationRecovery.reason, + "retained_after_sandbox_creation_failure", + ); + assert.equal( + payload.savedSession.cancellationRecovery.sandboxIdentityFingerprint, + identityFingerprint, + ); + assert.equal(payload.retainedRecoveryRecords.length, 1); + const record = payload.retainedRecoveryRecords[0]; + assert.equal(record.sandboxName, "my-assistant"); + assert.equal(record.sandboxIdentityFingerprint, identityFingerprint); + assert.equal(record.identityWasUnavailable, false); + assert.equal(record.gatewayName, "nemoclaw-18080"); + assert.equal(record.gatewayPort, 18080); + assert.match(record.lifecycleGeneration, /^[0-9a-f-]{36}$/u); + assert.equal(record.verifiedEffectivePolicyIdentity, null); + assert.equal(record.reason, "retained_after_sandbox_creation_failure"); + }; + const assertPostCreateRunnerRefusal = () => { + assert.equal(payload.sandboxName, null); + assert.equal(payload.sandboxCreated, true); + assert.equal(payload.deleted, false); + assert.equal(payload.registeredSandbox, null); + assert.match(payload.creationError, /automatic sandbox cleanup was not safe/u); + assert.equal(payload.savedSession.status, "recovery_required"); + assert.equal(payload.savedSession.resumable, false); + assert.equal( + payload.savedSession.cancellationRecovery.sandboxIdentityFingerprint, + identityFingerprint, + ); + assert.equal(payload.retainedRecoveryRecords.length, 1); + assert.equal(payload.retainedRecoveryRecords[0].sandboxName, "my-assistant"); + assertRecoveryTuple(payload.retainedRecoveryRecords[0]); + assert.ok(payload.checkpointReadCalls >= 6); + assert.equal( + payload.commandNames.filter((command: string) => command.includes("sandbox create")) + .length, + 1, + ); + }; + const assertPostCreateRegistrationRefusal = () => { + assert.equal(payload.sandboxName, null); + assert.equal(payload.sandboxCreated, true); + assert.equal(payload.deleted, false); + assert.equal(payload.registeredSandbox, null); + assert.match(payload.creationError, /registry publication failed/u); + assert.equal(payload.savedSession.status, "recovery_required"); + assert.equal(payload.savedSession.resumable, false); + assert.equal( + payload.savedSession.cancellationRecovery.sandboxIdentityFingerprint, + identityFingerprint, + ); + assert.equal(payload.retainedRecoveryRecords.length, 1); + const record = payload.retainedRecoveryRecords[0]; + assert.equal(record.sandboxName, "my-assistant"); + assert.equal(record.identityWasUnavailable, false); + assert.equal(record.reason, "retained_after_sandbox_creation_failure"); + assertRecoveryTuple(record); + }; + const assertPostCreateRegistrationRecoveryReadbackFailure = () => { + assert.equal(payload.sandboxName, null); + assert.equal(payload.sandboxCreated, true); + assert.equal(payload.deleted, false); + assert.equal(payload.registeredSandbox, null); + assert.match(payload.creationError, /recovery record could not be persisted/u); + assert.equal(payload.savedSession.status, "recovery_required"); + assert.equal(payload.savedSession.resumable, false); + assert.equal( + payload.savedSession.cancellationRecovery.sandboxIdentityFingerprint, + identityFingerprint, + ); + assert.deepEqual(payload.retainedRecoveryRecords, []); + + const reentryCases = [ + { + mode: "fresh-different-no-journal", + message: /independent retained sandbox recovery record is unavailable/u, + }, + { + mode: "fresh-same", + message: /explicit sandbox name different from the retained sandbox/u, + }, + ] as const; + for (const { message, mode } of reentryCases) { + const reentry = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...childEnv, + NEMOCLAW_RECOVERY_REENTRY: mode, + }, + timeout: 30000, + }); + assert.equal(reentry.status, 0, reentry.stderr); + const reentryPayload = JSON.parse(fs.readFileSync(payloadPath, "utf8")); + assert.equal(reentryPayload.exitCode, 1); + assert.match(reentry.stderr, message); + assert.deepEqual(reentryPayload.commandNames, []); + assert.equal(reentryPayload.credentialReadCalls, 0); + assert.equal(reentryPayload.routeReservationCalls, 0); + assert.deepEqual(reentryPayload.registryMutationCalls, []); + assert.equal(reentryPayload.savedSession.sandboxName, "my-assistant"); + assert.deepEqual(reentryPayload.retainedRecoveryRecords, []); + } + }; + const assertPostCreateRegistrationRecoveryRetry = () => { + assert.equal(payload.sandboxName, null); + assert.equal(payload.sandboxCreated, true); + assert.equal(payload.deleted, false); + assert.equal(payload.registeredSandbox, null); + assert.match(payload.creationError, /recovery record could not be persisted/u); + assert.equal(payload.savedSession.status, "recovery_required"); + assert.equal(payload.savedSession.resumable, false); + assert.equal(payload.retainedRecoveryRecords.length, 1); + assert.equal(payload.retainedRecoveryRecords[0].sandboxName, "my-assistant"); + assertRecoveryTuple(payload.retainedRecoveryRecords[0]); + assert.equal( + payload.commandNames.filter((command: string) => command.includes("sandbox create")) + .length, + 1, + ); + }; + const assertPostCreateFinalizationRefusal = () => { + assert.equal(payload.sandboxName, null); + assert.equal(payload.sandboxCreated, true); + assert.equal(payload.deleted, false); + assert.equal(payload.registeredSandbox.name, "my-assistant"); + assert.match( + payload.creationError, + /OpenShell sandbox policy authority inspection failed/u, + ); + assert.equal(payload.savedSession.status, "recovery_required"); + assert.equal(payload.savedSession.resumable, false); + assert.equal( + payload.savedSession.cancellationRecovery.sandboxIdentityFingerprint, + identityFingerprint, + ); + assertRecoveryTuple(payload.retainedRecoveryRecords[0]); + }; + const assertCancellationRecovery = () => { + assert.equal(payload.exitCode, 1); + assert.equal(payload.sandboxName, "my-assistant"); + assert.equal(payload.deleted, false); + assert.equal(payload.registeredSandbox.name, "my-assistant"); + assert.equal( + payload.currentRegistryEntry.lifecycleLiveIdentityFingerprint, + identityFingerprint, + ); + assert.equal(payload.currentRegistryEntry.name, "my-assistant"); + assert.equal(payload.savedSession.status, "recovery_required"); + assert.equal(payload.savedSession.resumable, false); + assert.equal(payload.savedSession.sandboxName, "my-assistant"); + assert.equal( + payload.savedSession.cancellationRecovery.reason, + "cancelled_after_sandbox_creation", + ); + assert.equal(payload.savedSession.cancellationRecovery.sandboxName, "my-assistant"); + assert.equal( + payload.savedSession.cancellationRecovery.sandboxIdentityFingerprint, + identityFingerprint, + ); + assert.equal( + payload.commandNames.some((command: string) => command.includes("sandbox delete")), + false, + ); + assertRecoveryTuple(payload.retainedRecoveryRecords[0]); + assert.match(result.stderr, /preserved incomplete sandbox 'my-assistant'/u); + assert.match(result.stderr, new RegExp(identityFingerprint, "u")); + assert.match(result.stderr, /Do not delete the sandbox by mutable sandbox name/u); + assert.match(result.stderr, /Shared inference providers are gateway configuration/u); + assert.match(result.stderr, /not sandbox cleanup targets/u); + assert.match(result.stderr, /sandbox-scoped resources whose ownership is confirmed/u); + assert.match(result.stderr, /no supported operation to clear this recovery record/u); + assert.match(result.stderr, /credential environment name alone does not prove exposure/u); + assert.match( + result.stderr, + /rotate a credential only when identity-bound inspection proves/u, + ); + assert.doesNotMatch(result.stderr, /rotate any credential/u); + + const differentName = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...childEnv, + NEMOCLAW_RECOVERY_REENTRY: "fresh-different", + }, + timeout: 30000, + }); + assert.equal(differentName.status, 0, differentName.stderr); + const differentNamePayload = JSON.parse(fs.readFileSync(payloadPath, "utf8")); + assert.equal(differentNamePayload.exitCode, 0); + assert.equal(differentNamePayload.savedSession.sandboxName, "replacement-sb"); + assert.deepEqual( + differentNamePayload.retainedRecoveryRecords, + payload.retainedRecoveryRecords, + ); + assert.deepEqual(differentNamePayload.commandNames, []); + assert.equal(differentNamePayload.credentialReadCalls, 0); + assert.equal(differentNamePayload.routeReservationCalls, 0); + assert.deepEqual(differentNamePayload.registryMutationCalls, []); + + const reentryCases = [ + { + mode: "automatic", + messages: [ + /cannot use retained sandbox 'my-assistant'/u, + /same-name fresh onboarding remain disabled/u, + ], + }, + { + mode: "explicit", + messages: [ + /cannot use retained sandbox 'my-assistant'/u, + /same-name fresh onboarding remain disabled/u, + ], + }, + { + mode: "recreate", + messages: [ + /cannot use retained sandbox 'my-assistant'/u, + /same-name fresh onboarding remain disabled/u, + ], + }, + { + mode: "fresh-same", + messages: [ + /cannot use retained sandbox 'my-assistant'/u, + /same-name fresh onboarding remain disabled/u, + ], + }, + ] as const; + for (const { messages, mode: reentryMode } of reentryCases) { + const reentry = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...childEnv, + NEMOCLAW_RECOVERY_REENTRY: reentryMode, + }, + timeout: 30000, + }); + assert.equal(reentry.status, 0, reentry.stderr); + const reentryPayload = JSON.parse(fs.readFileSync(payloadPath, "utf8")); + assert.equal(reentryPayload.exitCode, 1); + messages.forEach((message) => assert.match(reentry.stderr, message)); + assert.deepEqual(reentryPayload.commandNames, []); + assert.equal(reentryPayload.credentialReadCalls, 0); + assert.equal(reentryPayload.routeReservationCalls, 0); + assert.deepEqual(reentryPayload.registryMutationCalls, []); + assert.deepEqual(reentryPayload.currentRegistryEntry, payload.currentRegistryEntry); + assert.deepEqual(reentryPayload.savedSession, differentNamePayload.savedSession); + assert.deepEqual(reentryPayload.retainedRecoveryRecords, payload.retainedRecoveryRecords); + } + }; + const assertions = { + "managed-provider": assertManagedProviderCreation, + "provider-refusal": assertProviderBackedApfRefusal, + "unsupported-agent-refusal": assertUnsupportedAgentRefusal, + "providerless-apf": assertProviderlessApfCreation, + "post-create-authority-refusal": assertPostCreateAuthorityRefusal, + "post-create-runner-refusal": assertPostCreateRunnerRefusal, + "post-create-registration-refusal": assertPostCreateRegistrationRefusal, + "post-create-registration-recovery-readback-failure": + assertPostCreateRegistrationRecoveryReadbackFailure, + "post-create-registration-recovery-retry": assertPostCreateRegistrationRecoveryRetry, + "post-create-finalization-refusal": assertPostCreateFinalizationRefusal, + "staged-messaging-refusal": assertStagedMessagingRefusal, + "cancel-after-create-tier": assertCancellationRecovery, + "cancel-after-create-tier-presets": assertCancellationRecovery, + "cancel-after-create-custom-presets": assertCancellationRecovery, + }; + assertions[expectedOutcome](); }, ); }); diff --git a/test/onboarding/onboard-fsm-live-slices.test.ts b/test/onboarding/onboard-fsm-live-slices.test.ts index 65bdeae5469..660713d1d75 100644 --- a/test/onboarding/onboard-fsm-live-slices.test.ts +++ b/test/onboarding/onboard-fsm-live-slices.test.ts @@ -23,6 +23,9 @@ type ProbeMode = | "authoritative-core-gateway-policy-tier" | "dashboard-port-composition" | "ordinary-policy-tier" + | "providerless-staged-messaging" + | "stale-recovery-admission" + | "stale-session-decision" | "ahead-core"; interface ProbeOptions { @@ -183,6 +186,12 @@ function runSliceProbe(options: ProbeOptions) { const sessionPath = JSON.stringify( path.join(repoRoot, "src", "lib", "state", "onboard-session.ts"), ); + const entryOptionsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "entry-options.ts"), + ); + const lockedRuntimePath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "resume", "locked-runtime.ts"), + ); const preflightHandlerPath = JSON.stringify( path.join(repoRoot, "src", "lib", "onboard", "machine", "handlers", "preflight.ts"), ); @@ -217,6 +226,8 @@ const scenario = ${JSON.stringify(scenario)}; const flowSlices = require(${flowSlicesPath}); const { advanceTo, branchTo } = require(${resultPath}); const onboardSession = require(${sessionPath}); +const onboardEntryOptions = require(${entryOptionsPath}); +const lockedRuntime = require(${lockedRuntimePath}); const preflightHandlers = require(${preflightHandlerPath}); const providerHandlers = require(${providerHandlerPath}); const gatewayHandlers = require(${gatewayHandlerPath}); @@ -224,6 +235,7 @@ const coreFlowPhases = require(${coreFlowPhasesPath}); const registry = require(${registryPath}); const called = []; const sentinel = new Error("slice-called"); +const staleAdmissionExit = new Error("stale recovery admission refused"); if (scenario.mode === "dashboard-port-composition") { const finalizationHandlerDeps = require(${finalizationDepsPath}).finalizationHandlerDeps; @@ -450,6 +462,59 @@ if ( }); } +if (scenario.mode === "stale-recovery-admission") { + const listRetainedSandboxRecoveryRecords = + onboardSession.listRetainedSandboxRecoveryRecords; + let recoveryReads = 0; + onboardSession.listRetainedSandboxRecoveryRecords = () => { + recoveryReads += 1; + if (recoveryReads === 1) { + onboardSession.recordRetainedSandboxRecovery({ + sandboxName: "fsm-sandbox", + sandboxIdentityFingerprint: "a".repeat(64), + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "stale-admission-generation", + verifiedEffectivePolicyIdentity: null, + resources: { + sharedInferenceProviders: [], + sandboxScopedProviders: [], + credentialEnvironmentVariables: [], + }, + reason: "retained_after_sandbox_creation_failure", + }); + return []; + } + return listRetainedSandboxRecoveryRecords(); + }; + process.exit = () => { + throw staleAdmissionExit; + }; +} + +if (scenario.mode === "stale-session-decision") { + const resolveEntryOptions = onboardEntryOptions.resolveDefaultRunEntryOptionsFromState; + let optionReads = 0; + onboardEntryOptions.resolveDefaultRunEntryOptionsFromState = (...args) => { + optionReads += 1; + const resolved = resolveEntryOptions(...args); + if (optionReads === 1) { + seedResumeSession("preflight", false); + } + return resolved; + }; + lockedRuntime.prepare = async (_opts, resume) => { + called.push("locked-resume:" + String(resume)); + throw sentinel; + }; +} + +const ownsAuthoritativeOnboardLock = scenario.mode.startsWith("authoritative-"); +if (ownsAuthoritativeOnboardLock) { + const lock = onboardSession.acquireOnboardLock("authoritative rebuild fixture"); + if (!lock.acquired) throw new Error("authoritative rebuild fixture did not acquire onboard lock"); +} + const { onboard } = require(${onboardPath}); (async () => { @@ -460,6 +525,7 @@ const { onboard } = require(${onboardPath}); acceptThirdPartySoftware: true, noGpu: true, sandboxName: "fsm-sandbox", + apfInterceptorRequested: scenario.mode === "providerless-staged-messaging", resume: scenario.mode === "resume-initial" || scenario.mode.includes("core-gateway"), ...(scenario.mode.startsWith("authoritative-") ? { @@ -473,11 +539,15 @@ const { onboard } = require(${onboardPath}); }); throw new Error("expected slice sentinel"); } catch (error) { + if (ownsAuthoritativeOnboardLock) onboardSession.releaseOnboardLock(); if ( error === sentinel || error?.message === sentinel.message || + (scenario.mode === "stale-recovery-admission" && error === staleAdmissionExit) || (scenario.mode === "endpoint-override" && - error?.name === "OpenShellGatewayEndpointOverrideError") + error?.name === "OpenShellGatewayEndpointOverrideError") || + (scenario.mode === "providerless-staged-messaging" && + /supports providerless sandbox creation only/.test(String(error?.message))) ) { const payload = JSON.stringify({ called }); if (scenario.mode === "dashboard-port-composition") { @@ -506,6 +576,19 @@ const { onboard } = require(${onboardPath}); ? { OPENSHELL_GATEWAY_ENDPOINT: "http://127.0.0.1:65535" } : {}), ...(options.policyTier ? { NEMOCLAW_POLICY_TIER: options.policyTier } : {}), + ...(scenario.mode === "providerless-staged-messaging" + ? { + NEMOCLAW_MESSAGING_PLAN_B64: Buffer.from( + JSON.stringify({ + schemaVersion: 1, + sandboxName: "fsm-sandbox", + agent: "openclaw", + workflow: "onboard", + channels: [{ channelId: "telegram", active: true }], + }), + ).toString("base64"), + } + : {}), }, timeout: scenario.mode === "dashboard-port-composition" ? 60_000 : probeTimeoutMs, }, @@ -545,6 +628,23 @@ describe("live onboard FSM slice boundaries", () => { assert.deepEqual(runSliceProbe({ slice: "initial", mode: "endpoint-override" }), []); }); + it("rejects staged messaging before entering the onboarding state machine (#9833)", () => { + assert.deepEqual( + runSliceProbe({ slice: "initial", mode: "providerless-staged-messaging" }), + [], + ); + }); + + it("rechecks retained sandbox admission after acquiring the onboarding lock (#9833)", () => { + assert.deepEqual(runSliceProbe({ slice: "initial", mode: "stale-recovery-admission" }), []); + }); + + it("uses the session decision read after acquiring the onboarding lock (#9833)", () => { + assert.deepEqual(runSliceProbe({ slice: "initial", mode: "stale-session-decision" }), [ + "locked-resume:true", + ]); + }); + it("enters the core slice after the initial slice reaches provider selection", () => { assert.deepEqual(runSliceProbe({ slice: "core" }), ["initial:init", "core"]); }); diff --git a/test/onboarding/onboard-messaging.test.ts b/test/onboarding/onboard-messaging.test.ts index 542bb6de719..2f950520602 100644 --- a/test/onboarding/onboard-messaging.test.ts +++ b/test/onboarding/onboard-messaging.test.ts @@ -159,7 +159,6 @@ const { createSandbox, setupMessagingChannels } = require(${onboardPath}); }); `; fs.writeFileSync(scriptPath, script); - const result = spawnSync(process.execPath, [scriptPath], { cwd: repoRoot, encoding: "utf-8", @@ -790,7 +789,8 @@ const { createSandbox } = require(${onboardPath}); const result = spawnSync(process.execPath, [scriptPath], { cwd: repoRoot, - encoding: "utf-8", timeout: 30_000, + encoding: "utf-8", + timeout: 30_000, env: { ...process.env, HOME: tmpDir, diff --git a/test/onboarding/onboard-reservation-recreate.test.ts b/test/onboarding/onboard-reservation-recreate.test.ts index 3c526f8b303..58adb17c3d5 100644 --- a/test/onboarding/onboard-reservation-recreate.test.ts +++ b/test/onboarding/onboard-reservation-recreate.test.ts @@ -265,7 +265,9 @@ const { createSandbox } = require(${onboardPath}); assert.equal( result.status, replaceBeforeCleanup ? 1 : 0, - result.stderr || result.error?.message || "onboarding subprocess returned an unexpected status", + result.stderr || + result.error?.message || + "onboarding subprocess returned an unexpected status", ); const payload = trailingJsonPayload<{ sandboxName: string | null; @@ -384,8 +386,8 @@ if (mode === "seed") { "my-assistant": { name: "my-assistant", gatewayName: "nemoclaw", - provider: "nvidia-prod", - model: "gpt-5.4", + provider: null, + model: null, endpointUrl: null, endpointSource: null, credentialEnv: null, @@ -403,8 +405,8 @@ if (mode === "seed") { intent: { agent: "openclaw", fromDockerfile: null, - provider: "nvidia-prod", - model: "gpt-5.4", + provider: null, + model: null, preferredInferenceApi: null, sandboxGpuConfig: null, gatewayName: "nemoclaw", @@ -419,8 +421,8 @@ if (mode === "seed") { const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { sandboxName: "my-assistant", - provider: "nvidia-prod", - model: "gpt-5.4", + provider: null, + model: null, sessionId: "session-owner", durableRegistry: true, }); @@ -521,7 +523,7 @@ const { createSandbox } = require(${onboardPath}); const transaction = onboardSession.loadSession()?.checkpoint?.sandboxRecreate; if (!transaction) throw new Error("verified-create recovery has no lifecycle journal"); const createArgs = fixtureMocks.sandboxCreateArgsWithVerifiedReservation( - [null, "gpt-5.4", "nvidia-prod", null, "my-assistant", null, null, null, null, null, null, null, []], + [null, null, null, null, "my-assistant", null, null, null, null, null, null, null, []], createFixture, ); createArgs[15] = { @@ -590,7 +592,10 @@ createArgs[16] = async () => { assert.match(retained.error, /automatic sandbox cleanup was not safe/u); assert.equal(retained.registryEntry.pendingRouteReservation, true); assert.ok(retained.registryEntry.pendingPolicyVerification); - assert.match(retained.registryEntry.lifecycleLiveIdentityFingerprint ?? "", /^[0-9a-f]{64}$/u); + assert.match( + retained.registryEntry.lifecycleLiveIdentityFingerprint ?? "", + /^[0-9a-f]{64}$/u, + ); assert.equal(retained.journal.phase, "created"); assert.equal( retained.journal.targetLiveIdentityFingerprint, @@ -611,8 +616,16 @@ createArgs[16] = async () => { policyAuthority?: string; }; }>(second.stdout); - const createEvents = fs.readFileSync(createCountPath, "utf8").trim().split(/\n/u).filter(Boolean); - const effectEvents = fs.readFileSync(effectCountPath, "utf8").trim().split(/\n/u).filter(Boolean); + const createEvents = fs + .readFileSync(createCountPath, "utf8") + .trim() + .split(/\n/u) + .filter(Boolean); + const effectEvents = fs + .readFileSync(effectCountPath, "utf8") + .trim() + .split(/\n/u) + .filter(Boolean); assert.equal(createEvents.length, 1, "recovery must never create a second sandbox"); assert.match( recovered.error ?? "completed", diff --git a/test/runtime/policy/managed-policy-receipt-fixture.ts b/test/runtime/policy/managed-policy-receipt-fixture.ts deleted file mode 100644 index 11e9ed20c4b..00000000000 --- a/test/runtime/policy/managed-policy-receipt-fixture.ts +++ /dev/null @@ -1,4 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -export * from "../../helpers/managed-policy-receipt-fixture"; diff --git a/test/runtime/policy/policies-permissive-policy.test.ts b/test/runtime/policy/policies-permissive-policy.test.ts index 42a759660f0..138ca28ee76 100644 --- a/test/runtime/policy/policies-permissive-policy.test.ts +++ b/test/runtime/policy/policies-permissive-policy.test.ts @@ -13,7 +13,7 @@ import { managedPolicyMetadata, managedRegistrationSource, SANDBOX_ID, -} from "./managed-policy-receipt-fixture"; +} from "../../helpers/managed-policy-receipt-fixture"; const REPO_ROOT = path.join(import.meta.dirname, "../../.."); const POLICIES_PATH = JSON.stringify(path.join(REPO_ROOT, "src", "lib", "policy", "index.ts")); diff --git a/test/runtime/policy/policies.test.ts b/test/runtime/policy/policies.test.ts index 2b524041f24..f7ab0e5ffc9 100644 --- a/test/runtime/policy/policies.test.ts +++ b/test/runtime/policy/policies.test.ts @@ -17,7 +17,7 @@ import { POLICY_VERSION, SANDBOX_ID, SANDBOX_IDENTITY, -} from "./managed-policy-receipt-fixture"; +} from "../../helpers/managed-policy-receipt-fixture"; const requireForTest = createRequire(import.meta.url); const YAML = requireForTest("yaml"); diff --git a/test/runtime/policy/policy-explain-cli.test.ts b/test/runtime/policy/policy-explain-cli.test.ts index aac129948bc..7c55c148850 100644 --- a/test/runtime/policy/policy-explain-cli.test.ts +++ b/test/runtime/policy/policy-explain-cli.test.ts @@ -12,7 +12,7 @@ import { POLICY_HASH, POLICY_VERSION, SANDBOX_ID, -} from "./managed-policy-receipt-fixture"; +} from "../../helpers/managed-policy-receipt-fixture"; const CLI = path.join(import.meta.dirname, "../../..", "bin", "nemoclaw.js"); diff --git a/test/runtime/policy/policy-mutation-read-failure.test.ts b/test/runtime/policy/policy-mutation-read-failure.test.ts index 59b2b8004f3..81560f7761a 100644 --- a/test/runtime/policy/policy-mutation-read-failure.test.ts +++ b/test/runtime/policy/policy-mutation-read-failure.test.ts @@ -12,7 +12,7 @@ import { POLICY_HASH, POLICY_VERSION, SANDBOX_IDENTITY, -} from "./managed-policy-receipt-fixture"; +} from "../../helpers/managed-policy-receipt-fixture"; const requireForTest = createRequire(import.meta.url); const policies = requireForTest(