diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index dc426c134c2..b8632fc8cf3 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -549,7 +549,8 @@ Use the result from `destroy` to choose the next action: - If OpenShell reports the sandbox present and its durable identity matches the recovery record, `destroy` checks that identity during cleanup and immediately before deletion. It can delete the retained sandbox. A failed check or deletion preserves the recovery record. If you cannot prevent another gateway client from replacing the sandbox name during cleanup, use a different explicit name instead. - If OpenShell cannot determine whether the sandbox is present, `destroy` reports unknown presence, removes no resources, and preserves the recovery record. Correct the OpenShell gateway or list failure, then rerun `destroy`. -- If OpenShell confirms the sandbox is absent, `destroy` selects one retained record from its registry generation, gateway, create-attempt evidence, and available identity fingerprint. +- For the existing residual-cleanup path, `destroy` selects one retained record from its registry generation, gateway, create-attempt evidence, and available identity fingerprint. + Cleanup requires the owning OpenShell gateway to confirm sandbox absence. Before pending identity publication, it can instead select one record with a durable identity fingerprint when the pending reservation belongs to the recorded onboarding session, the saved session recovery evidence matches the record, and the registry has no lifecycle identity evidence. Provider and Docker cleanup then apply their own immutable identity checks. `destroy` removes only qualified residual resources and clears the matching recovery record only after verified cleanup. @@ -562,7 +563,24 @@ Only then rerun the owning provider setup workflow to restore those attachments. If you cannot prevent replacement or verify attachment ownership, leave the attachments untouched and use a different sandbox name. Keep the recovery record and retry `destroy` only after resolving the identity drift. -If OpenShell did not return a durable identity fingerprint, `destroy` cannot authorize deletion of a live sandbox. It can still select one recovery record that matches the immutable registry generation, gateway, and create-attempt evidence. It clears that record only after the owning gateway reports absence and verified residual cleanup succeeds. If the sandbox is present or presence is unknown, preserve the record and do not delete by mutable name. If NemoClaw could not save recovery evidence, preserve the registry entry and terminal output. +If OpenShell did not return a durable identity fingerprint, `destroy` cannot authorize deletion of a live sandbox. + +For an unpublished reservation without lifecycle identity, `destroy` can clear local recovery metadata on native Linux with the default Docker daemon. +It requires exactly one matching retained record, a recorded Docker ownership marker, and sandbox absence confirmed by the owning gateway. +Docker must report no matching containers or managed state volumes. +Any reservation must match its recovery-only onboarding session; conflicting state, recorded sandbox-scoped providers, or additional resource ownership block recovery. + +Use the failed onboarding attempt's gateway port to select its state root, for example: + +```bash +NEMOCLAW_GATEWAY_PORT=19260 $$nemoclaw destroy --yes +``` + +Success clears the matching recovery metadata and releases the sandbox name without removing runtime resources. +If a local metadata write fails, resolve the reported write error. +Then rerun the same command with that port, even if the reservation was removed. + +If NemoClaw could not save recovery evidence, preserve the registry entry and terminal output. This fail-closed record keeps only the affected sandbox name unavailable. This command does not accept externally supplied identity authority. To onboard another sandbox while the record remains unresolved, supply a different explicit name: diff --git a/src/lib/actions/sandbox/destroy-execution.ts b/src/lib/actions/sandbox/destroy-execution.ts index 9b8f7ad8174..207642fc4b2 100644 --- a/src/lib/actions/sandbox/destroy-execution.ts +++ b/src/lib/actions/sandbox/destroy-execution.ts @@ -69,6 +69,23 @@ export function redactDestroyError(error: unknown): string { return redactFull(error instanceof Error ? error.message : String(error)); } +export function stopSandboxInferenceResources( + sandboxName: string, + sandbox: SandboxEntry | null, +): void { + const nim = require("../../inference/nim") as { + stopNimContainer: (name: string, opts?: { silent?: boolean }) => void; + stopNimContainerByName: (name: string) => void; + }; + if (sandbox?.nimContainer) { + console.log(` Stopping NIM for '${sandboxName}'...`); + nim.stopNimContainerByName(sandbox.nimContainer); + } else { + // Older registry entries may not record the convention-named container. + nim.stopNimContainer(sandboxName, { silent: true }); + } +} + const SANDBOX_NATIVE_ROOT = "/sandbox"; const COMPLETE_NATIVE_HOME_AGENTS = new Set(["hermes", "langchain-deepagents-code", "openclaw"]); diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts index 9b245514062..8697f588cb9 100644 --- a/src/lib/actions/sandbox/destroy-gateway.ts +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -59,6 +59,8 @@ interface ResolveGatewayCleanupRuntimeProviderDeps extends Pick< "resolveOwnedRuntimeProviderId" > { configuredRuntimeProviderId?: string | null; + requireOwnedRuntime?: boolean; + recoveryRecordedAt?: string; } // Compute the Docker-driver gateway state directory that belongs to @@ -96,8 +98,12 @@ export function resolveGatewayCleanupRuntimeProviderId( gatewayName, gatewayPort: perGatewayState.port, stateDir: perGatewayState.stateDir, + ...(deps.recoveryRecordedAt !== undefined + ? { recoveryRecordedAt: deps.recoveryRecordedAt } + : {}), }, ); + if (deps.requireOwnedRuntime && !recorded) return null; if (registered && recorded && registered !== recorded) { throw new Error( `Refusing cleanup for gateway '${gatewayName}': registered runtime provider '${registered}' does not match recorded gateway runtime provider '${recorded}'.`, diff --git a/src/lib/actions/sandbox/destroy-preflight.ts b/src/lib/actions/sandbox/destroy-preflight.ts index ee02d15fdd6..91617282cce 100644 --- a/src/lib/actions/sandbox/destroy-preflight.ts +++ b/src/lib/actions/sandbox/destroy-preflight.ts @@ -55,6 +55,40 @@ import { } from "./gateway-target"; export { teardownSandboxDashboardForward } from "./forward-recovery"; +import { reconcileIdentityFreeRecovery as reconcileRetainedMetadata } from "./lifecycle/retained-recovery"; + +/** Probe only the recorded gateway before reconciling identity-free local metadata. */ +export function reconcileIdentityFreeRecovery( + sandboxName: string, + records: Parameters[1], + owningGatewayPort: number, + state: Omit< + Parameters[3], + "observeSandbox" | "timeoutMs" | "registryEntryGatewayPort" + > & { + captureOpenshell?: typeof import("../../adapters/openshell/runtime").captureOpenshell; + }, +): boolean { + const captureOpenshell = + state.captureOpenshell ?? + ( + require("../../adapters/openshell/runtime") as typeof import("../../adapters/openshell/runtime") + ).captureOpenshell; + return reconcileRetainedMetadata(sandboxName, records, owningGatewayPort, { + ...state, + registryEntryGatewayPort, + timeoutMs: OPENSHELL_PROBE_TIMEOUT_MS, + observeSandbox: (gatewayName) => + classifyDestroySandboxPresence( + sandboxName, + captureOpenshell(["sandbox", "list", "-g", gatewayName, "--output", "json"], { + ignoreError: true, + includeStreams: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }), + ), + }); +} export type SandboxDestroyPreflight = { cleanupGatewayName: string; @@ -128,23 +162,6 @@ export function resolveSandboxDestroyRuntimeSelection( return undefined; } -export function stopSandboxInferenceResources( - sandboxName: string, - sandbox: SandboxEntry | null, -): void { - const nim = require("../../inference/nim") as { - stopNimContainer: (name: string, opts?: { silent?: boolean }) => void; - stopNimContainerByName: (name: string) => void; - }; - if (sandbox?.nimContainer) { - console.log(` Stopping NIM for '${sandboxName}'...`); - nim.stopNimContainerByName(sandbox.nimContainer); - } else { - // Older registry entries may not record the convention-named container. - nim.stopNimContainer(sandboxName, { silent: true }); - } -} - function sandboxGatewayPort(entry: SandboxEntry): number { return registryEntryGatewayPort({ name: entry.name, diff --git a/src/lib/actions/sandbox/destroy-presence.ts b/src/lib/actions/sandbox/destroy-presence.ts index e8d3351c5b9..b58ddef511d 100644 --- a/src/lib/actions/sandbox/destroy-presence.ts +++ b/src/lib/actions/sandbox/destroy-presence.ts @@ -74,8 +74,9 @@ export type DestroyContainerIdentityProof = { /** Read the host observation consumed by the pure identity classifier. */ export function observeDestroyContainerIdentity( sandboxName: string, + inspect?: Parameters[1], ): DockerSandboxIdentityObservation { - return inspectDockerSandboxNameLabeledContainers(sandboxName); + return inspectDockerSandboxNameLabeledContainers(sandboxName, inspect); } /** diff --git a/src/lib/actions/sandbox/destroy-retained-recovery-flow.test.ts b/src/lib/actions/sandbox/destroy-retained-recovery-flow.test.ts index 24a2bd57adb..bc8577b11f9 100644 --- a/src/lib/actions/sandbox/destroy-retained-recovery-flow.test.ts +++ b/src/lib/actions/sandbox/destroy-retained-recovery-flow.test.ts @@ -58,16 +58,13 @@ function cancellationRecoveryFor( function prepublicationRecoveryHarness( options: { - identityFree?: boolean; partialLifecycleGeneration?: boolean; reservationSessionId?: string; sandboxPresent?: boolean; sessionRecoveryOverrides?: Partial; } = {}, ) { - const recovery = options.identityFree - ? retainedRecoveryRecordWithoutIdentity() - : retainedRecoveryRecord(); + const recovery = retainedRecoveryRecord(); const harness = createDestroyHarness({ sandboxPresent: options.sandboxPresent ?? false, dockerRunResult: { status: 0, stdout: "" }, @@ -267,21 +264,6 @@ describe("destroySandbox retained recovery flow", () => { }, ); - it( - "refuses identity-free recovery before pending identity publication (#11418)", - { timeout: 30_000 }, - async () => { - const { harness } = prepublicationRecoveryHarness({ identityFree: true }); - - await expect(harness.destroySandbox("alpha", { yes: true })).rejects.toThrow( - "process.exit(1)", - ); - - expect(harness.resolveRetainedSandboxRecoverySpy).not.toHaveBeenCalled(); - expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); - }, - ); - it( "removes every container after OpenShell confirms the retained sandbox absent (#10547)", { timeout: 30_000 }, diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index f00bf4d2183..67de3961970 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -63,6 +63,7 @@ import { preparePortableDemoSandboxDestroyAuthority, redactDestroyError, retirePortableLifecycleAuthority, + stopSandboxInferenceResources, } from "./destroy-execution"; import { cleanupGatewayAfterLastSandbox, @@ -83,6 +84,7 @@ import { import { withSandboxLifecycleLock } from "./lifecycle/lock"; import { prepareSandboxDestroy, + reconcileIdentityFreeRecovery, recordManagedVllmRetirementPending, reportManagedVllmDestroyOutcome, resolveSandboxDestroyRegistryAuthority, @@ -92,7 +94,6 @@ import { listInferenceRouteOwnersAcrossGatewayRoots, stopModelRouterForDestroyedSandbox, stopDestroyedSandboxProxy, - stopSandboxInferenceResources, teardownSandboxDashboardForward, } from "./destroy-preflight"; @@ -753,6 +754,34 @@ async function destroySandboxUnlocked( } const destroySession = onboardSession.loadSession(); const retainedRecoveryRecords = onboardSession.listRetainedSandboxRecoveryRecords(); + try { + if ( + reconcileIdentityFreeRecovery( + sandboxName, + retainedRecoveryRecords, + registryAuthority.gatewayPort, + { + session: onboardSession, + registry, + ...(retireRemovedImmutabilityState + ? { + retireRemovedImmutabilityState: () => { + retireRemovedImmutabilityStateRecord(sandboxName, "sandbox-destroyed"); + }, + } + : {}), + }, + ) + ) { + console.log( + ` Cleared retained recovery for '${sandboxName}'. No sandbox resources were removed.`, + ); + return; + } + } catch (error) { + console.error(` ${redactDestroyError(error)}`); + requestSandboxDestroyExit(1); + } const retainedRecoveryAuthority = selectRetainedSandboxRecoveryAuthority( sandboxName, registeredSandbox, diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts new file mode 100644 index 00000000000..1d1d3682b4a --- /dev/null +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts @@ -0,0 +1,556 @@ +// 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, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; + +let testHome: string; +const emptyDockerResult = { + status: 0, + stdout: "", + stderr: "", + pid: 0, + output: [null, "", ""], + signal: null, +}; + +beforeAll(async () => { + // Load the shared CLI graph before timing recovery operations in each isolated state root. + await import("../destroy"); +}); + +beforeEach(() => { + testHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recovery-metadata-")); + vi.stubEnv("HOME", testHome); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + fs.rmSync(testHome, { recursive: true, force: true }); +}); + +async function setup(port = 19260, dockerHost?: string) { + vi.stubEnv("NEMOCLAW_GATEWAY_PORT", String(port)); + vi.stubEnv("DOCKER_HOST", dockerHost); + vi.stubEnv("DOCKER_CONTEXT", "default"); + vi.resetModules(); + const dockerExec = await import("../../../adapters/docker/exec"); + vi.spyOn(dockerExec, "dockerSpawnSync").mockReturnValue({ + ...emptyDockerResult, + stdout: "unix:///var/run/docker.sock", + }); + const session = await import("../../../state/onboard-session"); + const registry = await import("../../../state/registry"); + const docker = await import("../../../adapters/docker/run"); + const presence = await import("../destroy-presence"); + const { reconcileIdentityFreeRecovery } = await import("../destroy-preflight"); + const gatewayName = port === 8080 ? "nemoclaw" : `nemoclaw-${port}`; + const { resolveGatewayStateDirForPort } = await import("../../../onboard/gateway-binding"); + const { + clearDockerDriverGatewayRuntimeMarker, + writeDockerDriverGatewayRuntimeMarkerForStateDir, + } = await import("../../../onboard/docker-driver-gateway-runtime-marker"); + const stateDir = resolveGatewayStateDirForPort({ home: testHome, port }); + const writeRuntime = (host: string | null, createdAt: string, runtimeProviderId = "docker") => + writeDockerDriverGatewayRuntimeMarkerForStateDir(stateDir, { + pid: 4242, + desiredEnv: {}, + endpoint: `https://127.0.0.1:${port}`, + dockerHost: host, + createdAt, + runtimeProviderId, + }); + writeRuntime(dockerHost ?? null, new Date(Date.now() - 1_000).toISOString()); + const route = { + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: null, + credentialEnv: null, + preferredInferenceApi: null, + gatewayName, + reservationSessionId: "failed-create-session", + }; + session.saveSession( + session.createSession({ + sessionId: route.reservationSessionId, + sandboxName: "alpha", + agent: "openclaw", + provider: route.provider, + model: route.model, + }), + ); + registry.reserveSandboxInferenceRoute("alpha", route); + session.markRetainedSandboxRecovery("alpha", "identity lookup failed", undefined, { + gatewayName, + gatewayPort: port, + lifecycleGeneration: "failed-generation", + createAttemptNonce: "a".repeat(62), + }); + const record = session.listRetainedSandboxRecoveryRecords()[0]!; + const capture = vi + .fn() + .mockReturnValue({ + status: 0, + output: "[]", + stdout: "[]", + stderr: "", + }); + const containers = vi.spyOn(presence, "observeDestroyContainerIdentity").mockReturnValue({ + status: "observed", + rows: [], + malformedRows: 0, + }); + const volumes = vi.spyOn(docker, "dockerRun").mockReturnValue(emptyDockerResult); + const files = [ + registry.REGISTRY_FILE, + session.SESSION_FILE, + session.RETAINED_SANDBOX_RECOVERY_FILE, + ]; + const snapshot = () => files.map((file) => fs.readFileSync(file, "utf8")); + const run = () => + reconcileIdentityFreeRecovery("alpha", session.listRetainedSandboxRecoveryRecords(), port, { + session, + registry, + captureOpenshell: capture, + }); + return { + session, + registry, + route, + record, + capture, + containers, + volumes, + clearRuntime: () => clearDockerDriverGatewayRuntimeMarker(stateDir), + writeRuntime, + snapshot, + run, + }; +} + +async function setupDestroy(port = 19260) { + const h = await setup(port); + const preflight = await import("../destroy-preflight"); + const reconcile = preflight.reconcileIdentityFreeRecovery; + vi.spyOn(preflight, "reconcileIdentityFreeRecovery").mockImplementation( + (name, records, port, state) => + reconcile(name, records, port, { ...state, captureOpenshell: h.capture }), + ); + const ordinaryDestroy = vi + .spyOn(preflight, "prepareSandboxDestroy") + .mockRejectedValue(new Error("Unexpected resource cleanup during metadata recovery")); + const confirmation = await import("../destroy-confirmation"); + vi.spyOn(confirmation, "confirmSandboxDestroy").mockResolvedValue(true); + const exit = vi.spyOn(process, "exit").mockImplementation(((code: number) => { + throw new Error(`process.exit(${code})`); + }) as never); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + vi.spyOn(console, "error").mockImplementation(() => undefined); + const { destroySandbox } = await import("../destroy"); + const { resolveNemoclawStateDir } = await import("../../../state/paths"); + const { enforceRemovedImmutabilityMigrationBoundary } = + await import("../../../state/migrations/removed-immutability"); + const stateDir = resolveNemoclawStateDir(); + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + return { + ...h, + destroy: () => destroySandbox("alpha", { yes: true }), + ordinaryDestroy, + exit, + log, + legacyState: path.join(stateDir, "shields-alpha.json"), + assertMigrationClear: () => enforceRemovedImmutabilityMigrationBoundary("alpha"), + }; +} + +describe.skipIf(process.platform !== "linux")("identity-free retained recovery", () => { + it.each([8080, 19260])( + "releases the retained name through destroy on gateway port %s without resource cleanup (#12260)", + async (port) => { + const h = await setupDestroy(port); + h.writeRuntime( + "unix:///var/run/docker.sock", + new Date(Date.parse(h.record.recordedAt) - 1_000).toISOString(), + ); + h.containers.mockRestore(); + expect(process.env.DOCKER_HOST).toBe("unix:///var/run/docker.sock"); + expect(process.env.DOCKER_CONTEXT).toBeUndefined(); + expect(h.registry.getSandbox("alpha")?.gatewayPort).toBeUndefined(); + expect(h.record.sandboxIdentityFingerprint).toBeNull(); + + await expect(h.destroy()).resolves.toBeUndefined(); + + expect(h.capture).toHaveBeenCalledWith( + ["sandbox", "list", "-g", h.record.gatewayName, "--output", "json"], + expect.objectContaining({ ignoreError: true, includeStreams: true }), + ); + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(h.session.loadSession()).toMatchObject({ + status: "failed", + sandboxName: null, + cancellationRecovery: null, + }); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + expect(h.exit).not.toHaveBeenCalled(); + expect(h.log).toHaveBeenCalledWith( + " Cleared retained recovery for 'alpha'. No sandbox resources were removed.", + ); + expect( + h.capture.mock.calls.every(([args]) => args[0] === "sandbox" && args[1] === "list"), + ).toBe(true); + expect(h.volumes.mock.calls.some(([args]) => args[2] === "ps")).toBe(true); + expect( + h.volumes.mock.calls.every( + ([args]) => + args[0] === "--context" && args[1] === "default" && ["ps", "volume"].includes(args[2]!), + ), + ).toBe(true); + expect( + h.registry.reserveSandboxInferenceRoute("alpha", { + ...h.route, + reservationSessionId: "new-session", + }), + ).toBe(true); + }, + ); + + it("preserves recovery for retry when removed Shields state retirement fails (#12260)", async () => { + const h = await setupDestroy(); + fs.writeFileSync(h.legacyState, "{}\n", { mode: 0o600 }); + expect(h.assertMigrationClear).toThrow(/state record from the removed Shields feature/u); + const before = h.snapshot(); + const rename = fs.renameSync; + const failure = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => + String(source) === h.legacyState + ? (() => { + throw new Error("legacy state retirement unavailable"); + })() + : rename(source, destination), + ); + + await expect(h.destroy()).rejects.toThrow("process.exit(1)"); + + expect(h.snapshot()).toEqual(before); + expect(fs.existsSync(h.legacyState)).toBe(true); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + expect(h.log).not.toHaveBeenCalledWith(expect.stringContaining("Cleared retained recovery")); + failure.mockRestore(); + + await expect(h.destroy()).resolves.toBeUndefined(); + + expect(fs.existsSync(h.legacyState)).toBe(false); + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + expect(h.assertMigrationClear).not.toThrow(); + }); + + it("preserves legacy state and recovery when destroy cannot verify gateway absence (#12260)", async () => { + const h = await setupDestroy(); + fs.writeFileSync(h.legacyState, "{}\n", { mode: 0o600 }); + expect(h.assertMigrationClear).toThrow(/state record from the removed Shields feature/u); + const before = h.snapshot(); + h.capture.mockReturnValue({ status: 1, output: "", stdout: "", stderr: "gateway unavailable" }); + + await expect(h.destroy()).rejects.toThrow("process.exit(1)"); + + expect(fs.existsSync(h.legacyState)).toBe(true); + expect(h.snapshot()).toEqual(before); + expect(h.volumes).not.toHaveBeenCalled(); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + }); + + it("preserves state when the gateway still reports the sandbox present (#12260)", async () => { + const h = await setup(); + const before = h.snapshot(); + h.capture.mockReturnValue({ + status: 0, + output: "", + stdout: JSON.stringify([ + { + id: "sandbox-alpha", + name: "alpha", + labels: {}, + phase: "Ready", + created_at: "2026-10-08", + resource_version: 1, + current_policy_version: 1, + }, + ]), + stderr: "", + }); + + expect(h.run).toThrow(/presence as/u); + + expect(h.snapshot()).toEqual(before); + }); + + it.each(["residual", "failed"])( + "preserves state for a %s container observation (#12260)", + async (kind) => { + const h = await setup(); + const before = h.snapshot(); + h.containers.mockReturnValue( + kind === "failed" + ? { status: "probe-failed", detail: "Docker unavailable" } + : { + status: "observed", + malformedRows: 0, + rows: [ + { + id: "b".repeat(64), + managedBy: "openshell", + workspace: "default", + sandboxId: "sandbox-alpha", + }, + ], + }, + ); + + expect(h.run).toThrow(/container runtime/u); + + expect(h.snapshot()).toEqual(before); + }, + ); + + it.each(["nemoclaw-openclaw-state-v1-alpha", "nemoclaw-hermes-state-v1-alpha"])( + "preserves the recovery record when volume %s remains (#12260)", + async (volume) => { + const h = await setup(); + const before = h.snapshot(); + h.volumes.mockReturnValue({ ...emptyDockerResult, stdout: `${volume}\n` }); + + expect(h.run).toThrow(/volume absence/u); + + expect(h.snapshot()).toEqual(before); + }, + ); + + it("preserves state when volume inspection fails (#12260)", async () => { + const h = await setup(); + const before = h.snapshot(); + h.volumes.mockReturnValue({ ...emptyDockerResult, status: 1, stderr: "unavailable" }); + expect(h.run).toThrow(/inspect retained volumes/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves sandbox-scoped provider ownership after sandbox absence (#12260)", async () => { + const h = await setup(); + h.session.recordRetainedSandboxRecovery({ + ...h.record, + resources: { ...h.record.resources, sandboxScopedProviders: ["alpha-provider"] }, + }); + const before = h.snapshot(); + expect(h.run).toThrow(/sandbox-scoped resources/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves recovery when the recorded Docker runtime marker is missing (#12260)", async () => { + const h = await setup(); + h.registry.updateSandbox("alpha", { openshellDriver: "docker" }); + h.clearRuntime(); + const before = h.snapshot(); + expect(h.run).toThrow(/owning Docker runtime/u); + expect(h.snapshot()).toEqual(before); + expect(h.capture).not.toHaveBeenCalled(); + }); + + it("preserves recovery owned by a different runtime provider (#12260)", async () => { + const h = await setup(); + h.writeRuntime(null, new Date(Date.parse(h.record.recordedAt) - 1_000).toISOString(), "podman"); + const before = h.snapshot(); + expect(h.run).toThrow(/owning Docker runtime/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves records when more than one failed create uses the same name (#12260)", async () => { + const h = await setup(); + h.session.recordRetainedSandboxRecovery({ ...h.record, createAttemptNonce: "b".repeat(62) }); + const before = h.snapshot(); + expect(h.run).toThrow(/exactly one/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves a reservation owned by another session (#12260)", async () => { + const h = await setup(); + h.session.saveSession({ ...h.session.loadSession()!, sessionId: "replacement-session" }); + const before = h.snapshot(); + expect(h.run).toThrow(/conflicting ownership/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves identity-free recovery while the session is still in progress (#12260)", async () => { + const h = await setup(); + h.session.saveSession( + h.session.createSession({ + sessionId: h.route.reservationSessionId, + sandboxName: "alpha", + }), + ); + const before = h.snapshot(); + expect(h.run).toThrow(/conflicting ownership/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves metadata when Docker targets another daemon (#12260)", async () => { + const h = await setup(); + vi.stubEnv("DOCKER_HOST", "unix:///tmp/other-docker.sock"); + const before = h.snapshot(); + expect(h.run).toThrow(/default daemon/u); + expect(h.snapshot()).toEqual(before); + expect(h.capture).not.toHaveBeenCalled(); + expect(h.containers).not.toHaveBeenCalled(); + expect(h.volumes).not.toHaveBeenCalled(); + }); + + it("preserves recovery created on another Docker daemon (#12260)", async () => { + const h = await setup(19260, "unix:///tmp/other-docker.sock"); + vi.stubEnv("DOCKER_HOST", "unix:///var/run/docker.sock"); + const before = h.snapshot(); + + expect(h.run).toThrow(/owning Docker runtime/u); + + expect(h.snapshot()).toEqual(before); + expect(h.capture).not.toHaveBeenCalled(); + }); + + it("preserves recovery after its gateway is replaced on the default daemon (#12260)", async () => { + const h = await setup(19260, "unix:///tmp/other-docker.sock"); + vi.stubEnv("DOCKER_HOST", "unix:///var/run/docker.sock"); + h.writeRuntime(null, new Date(Date.parse(h.record.recordedAt) + 1_000).toISOString()); + const before = h.snapshot(); + + expect(h.run).toThrow(/owning Docker runtime/u); + + expect(h.snapshot()).toEqual(before); + expect(h.capture).not.toHaveBeenCalled(); + }); + + it("preserves recovery when its gateway differs from the owning registry root (#12260)", async () => { + const h = await setup(); + const before = h.snapshot(); + const { reconcileIdentityFreeRecovery } = await import("../destroy-preflight"); + expect(() => + reconcileIdentityFreeRecovery("alpha", [h.record], 8080, { + session: h.session, + registry: h.registry, + captureOpenshell: h.capture, + }), + ).toThrow(/recovery gateway/u); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves a changed recovery record after successful absence probes (#12260)", async () => { + const h = await setup(); + h.capture.mockImplementationOnce(() => { + h.session.recordRetainedSandboxRecovery({ + ...h.record, + resources: { + ...h.record.resources, + sandboxScopedProviders: ["alpha-provider"], + }, + }); + return { status: 0, output: "[]", stdout: "[]", stderr: "" }; + }); + expect(h.run).toThrow(/recovery record changed/u); + expect(h.registry.getSandbox("alpha")).not.toBeNull(); + expect( + h.session.listRetainedSandboxRecoveryRecords()[0]?.resources.sandboxScopedProviders, + ).toEqual(["alpha-provider"]); + }); + + it("preserves recovery when its gateway changes during absence probes (#12260)", async () => { + const h = await setup(); + const before = h.snapshot(); + h.capture.mockImplementationOnce(() => { + h.writeRuntime(null, new Date(Date.parse(h.record.recordedAt) + 1_000).toISOString()); + return { status: 0, output: "[]", stdout: "[]", stderr: "" }; + }); + + expect(h.run).toThrow(/owning Docker runtime/u); + + expect(h.capture).toHaveBeenCalledTimes(2); + expect(h.snapshot()).toEqual(before); + }); + + it("preserves metadata when the reservation gateway name and port conflict (#12260)", async () => { + const h = await setup(); + expect(h.registry.updateSandbox("alpha", { gatewayPort: 8080 })).toBe(true); + const before = h.snapshot(); + + expect(h.run).toThrow(/conflicting gateway identity/u); + + expect(h.snapshot()).toEqual(before); + expect(h.capture).not.toHaveBeenCalled(); + expect(h.volumes).not.toHaveBeenCalled(); + }); + + it("preserves a registry replacement that appears during absence verification (#12260)", async () => { + const h = await setup(); + h.capture.mockImplementationOnce(() => { + h.registry.removeSandboxRouteReservationIfCurrent(h.registry.getSandbox("alpha")!); + h.registry.reserveSandboxInferenceRoute("alpha", { + ...h.route, + model: "replacement", + reservationSessionId: "replacement-session", + }); + return { status: 0, output: "[]", stdout: "[]", stderr: "" }; + }); + expect(h.run).toThrow(/registry changed/u); + expect(h.registry.getSandbox("alpha")?.model).toBe("replacement"); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([h.record]); + }); + + it("preserves recovery when absence cannot be confirmed again before retirement (#12260)", async () => { + const h = await setup(); + const before = h.snapshot(); + h.capture.mockReturnValueOnce({ status: 0, output: "[]", stdout: "[]", stderr: "" }); + h.capture.mockReturnValue({ status: 1, output: "", stdout: "", stderr: "gateway lost" }); + expect(h.run).toThrow(/presence as unknown/u); + expect(h.snapshot()).toEqual(before); + }); + + it("finishes on retry after recovery record retirement fails (#12260)", async () => { + const h = await setup(); + const { hasIdentityFreeRetainedRecovery } = await import("../../../registry-recovery-action"); + const rename = fs.renameSync; + const failure = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => + String(destination) === h.session.RETAINED_SANDBOX_RECOVERY_FILE + ? (() => { + throw new Error("recovery storage unavailable"); + })() + : rename(source, destination), + ); + expect(h.run).toThrow(/storage unavailable/u); + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.loadSession()?.cancellationRecovery).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([h.record]); + expect(hasIdentityFreeRetainedRecovery("alpha")).toBe(true); + failure.mockRestore(); + h.session.saveSession( + h.session.createSession({ sessionId: "replacement-session", sandboxName: "other-sandbox" }), + ); + const replacement = fs.readFileSync(h.session.SESSION_FILE, "utf8"); + + expect(h.run()).toBe(true); + expect(fs.readFileSync(h.session.SESSION_FILE, "utf8")).toBe(replacement); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(hasIdentityFreeRetainedRecovery("alpha")).toBe(false); + }); + + it("does not admit destroy from recovery retained in another gateway root (#12260)", async () => { + const h = await setup(19260); + const before = h.snapshot(); + vi.stubEnv("NEMOCLAW_GATEWAY_PORT", "8080"); + vi.resetModules(); + const { hasIdentityFreeRetainedRecovery } = await import("../../../registry-recovery-action"); + + expect(hasIdentityFreeRetainedRecovery("alpha")).toBe(false); + expect(h.snapshot()).toEqual(before); + }); +}); diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts new file mode 100644 index 00000000000..e83de88d853 --- /dev/null +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts @@ -0,0 +1,220 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isDeepStrictEqual } from "node:util"; + +import { dockerRun } from "../../../adapters/docker/run"; +import { dockerContextIsDefaultFromBuild } from "../../../adapters/docker/client-isolation"; +import { normalizeInferenceSelection } from "../../../inference/selection"; +import { MANAGED_IMAGE_AGENTS } from "../../../onboard/managed-image/agents"; +import { managedStartupStateRootOwnership } from "../../../onboard/managed-startup/state-roots"; +import type { registryEntryGatewayPort } from "../../../state/gateway-registry"; +import type * as OnboardSession from "../../../state/onboard-session"; +import { resolveNemoclawStateGatewayPort } from "../../../state/paths"; +import type * as Registry from "../../../state/registry"; +import { + classifySandboxInferenceRouteReservation, + isRouteOnlySandboxReservation, +} from "../../../state/registry/route-reservation"; +import { resolveGatewayCleanupRuntimeProviderId } from "../destroy-gateway"; +import { + classifyDestroyContainerIdentity, + observeDestroyContainerIdentity, + type DestroySandboxPresence, +} from "../destroy-presence"; + +type Recovery = OnboardSession.RetainedSandboxRecoveryRecord; +type RecoveryState = { + observeSandbox(gatewayName: string): DestroySandboxPresence; + registryEntryGatewayPort: typeof registryEntryGatewayPort; + retireRemovedImmutabilityState?: () => void; + timeoutMs: number; + session: Pick< + typeof OnboardSession, + | "withOwnedOnboardLock" + | "loadSession" + | "listRetainedSandboxRecoveryRecords" + | "retainedSandboxRecoveryMatchesSession" + | "resolveRetainedSandboxRecovery" + >; + registry: Pick; +}; + +function unpublished(entry: Registry.SandboxEntry | null): boolean { + return ( + entry === null || + (isRouteOnlySandboxReservation(entry) && + entry.pendingCreateIdentity === undefined && + entry.lifecycleGeneration === undefined && + entry.lifecycleLiveIdentityFingerprint === undefined) + ); +} + +function refuse(name: string, reason: string): never { + throw new Error( + `Cannot reconcile retained sandbox '${name}': ${reason}. No sandbox resources were removed. ` + + "Recovery remains unresolved; correct the reported condition, then rerun destroy.", + ); +} + +function requireGatewayAbsence(record: Recovery, state: RecoveryState): void { + const { sandboxName, gatewayName } = record; + const presence = state.observeSandbox(gatewayName); + if (presence !== "absent") { + refuse(sandboxName, `the owning OpenShell gateway reports sandbox presence as ${presence}`); + } +} + +function requireAbsence(record: Recovery, state: RecoveryState): void { + const { sandboxName } = record; + requireGatewayAbsence(record, state); + const containers = classifyDestroyContainerIdentity( + sandboxName, + observeDestroyContainerIdentity(sandboxName, (args, options) => + dockerRun(["--context", "default", ...args], options), + ), + ); + if (containers.status !== "clear" || containers.identity !== null) { + refuse(sandboxName, "the container runtime did not confirm sandbox absence"); + } + const volumes = dockerRun(["--context", "default", "volume", "ls", "--format", "{{.Name}}"], { + ignoreError: true, + suppressOutput: true, + timeout: state.timeoutMs, + }); + if (volumes.status !== 0 || String(volumes.stderr ?? "").trim()) { + refuse(sandboxName, "the container runtime could not inspect retained volumes"); + } + const names = String(volumes.stdout ?? "") + .split(/\r?\n/u) + .filter(Boolean); + const reservedNames = MANAGED_IMAGE_AGENTS.flatMap((agent) => + managedStartupStateRootOwnership({ agent, sandboxName }).map((root) => root.resourceIdentity), + ); + if ( + names.some( + (name) => !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u.test(name) || reservedNames.includes(name), + ) + ) { + refuse(sandboxName, "retained volume absence is not established"); + } + requireGatewayAbsence(record, state); +} + +function requireReservationOwner( + record: Recovery, + entry: Registry.SandboxEntry, + session: OnboardSession.Session | null, + state: RecoveryState, +): void { + const { name, gatewayName, gatewayPort } = entry; + if ( + session?.status !== "recovery_required" || + session.sandboxName !== record.sandboxName || + session.cancellationRecovery?.reason !== record.reason || + !state.session.retainedSandboxRecoveryMatchesSession(record, session) || + state.registryEntryGatewayPort({ name, gatewayName, gatewayPort }) !== record.gatewayPort || + entry.hostLocalInferenceReceipt != null || + entry.nativeNvidiaProviderAttachment !== undefined || + classifySandboxInferenceRouteReservation( + { + sandboxName: record.sandboxName, + gatewayName: record.gatewayName, + sessionId: session.sessionId, + selection: normalizeInferenceSelection(entry), + }, + entry, + ).kind !== "owned" + ) { + refuse( + record.sandboxName, + "the unpublished reservation has conflicting ownership or retained resources", + ); + } +} + +/** Retire only local recovery metadata; a missing identity never authorizes resource deletion. */ +export function reconcileIdentityFreeRecovery( + sandboxName: string, + observedRecords: readonly Recovery[], + owningGatewayPort: number, + state: RecoveryState, +): boolean { + const { session: sessionState, registry } = state; + if (process.platform !== "linux") return false; + const candidates = observedRecords.filter((record) => record.sandboxName === sandboxName); + if (!candidates.some((record) => record.sandboxIdentityFingerprint === null)) return false; + const observedEntry = registry.getSandbox(sandboxName); + if (!unpublished(observedEntry)) return false; + + return sessionState.withOwnedOnboardLock("nemoclaw retained recovery reconciliation", () => { + const record = candidates[0]; + if (!record || candidates.length !== 1 || record.sandboxIdentityFingerprint !== null) { + refuse(sandboxName, "exactly one identity-free recovery record is required"); + } + if ( + record.gatewayPort !== owningGatewayPort || + record.gatewayPort !== resolveNemoclawStateGatewayPort() || + state.registryEntryGatewayPort({ name: sandboxName, gatewayName: record.gatewayName }) !== + record.gatewayPort || + record.resources.sandboxScopedProviders.length > 0 + ) { + refuse( + sandboxName, + "the recovery gateway or sandbox-scoped resources could not be qualified", + ); + } + const entry = registry.getSandbox(sandboxName); + if (!isDeepStrictEqual(entry, observedEntry) || !unpublished(entry)) { + refuse(sandboxName, "the registry changed before reconciliation"); + } + if (entry) requireReservationOwner(record, entry, sessionState.loadSession(), state); + const requireOwnedRuntime = () => { + if ( + resolveGatewayCleanupRuntimeProviderId(record.gatewayName, entry?.openshellDriver, { + requireOwnedRuntime: true, + recoveryRecordedAt: record.recordedAt, + }) !== "docker" + ) { + refuse( + sandboxName, + "the owning Docker runtime on the original default daemon could not be established", + ); + } + }; + requireOwnedRuntime(); + // The runner can normalize the native Linux default context to its explicit Unix endpoint. + if ( + process.env.DOCKER_HOST?.trim() !== "unix:///var/run/docker.sock" && + !dockerContextIsDefaultFromBuild(process.env) + ) { + refuse( + sandboxName, + "the Docker observation target is not the native gateway's default daemon", + ); + } + requireAbsence(record, state); + requireOwnedRuntime(); + // The onboarding lock prevents a new create while CAS protects the observed reservation. + const currentRecords = sessionState + .listRetainedSandboxRecoveryRecords() + .filter((current) => current.sandboxName === sandboxName); + if (!isDeepStrictEqual(currentRecords, candidates)) { + refuse(sandboxName, "the recovery record changed during absence verification"); + } + if (entry) requireReservationOwner(record, entry, sessionState.loadSession(), state); + // Legacy state retirement must succeed while the recovery authority is still available for retry. + state.retireRemovedImmutabilityState?.(); + if (entry && !registry.removeSandboxRouteReservationIfCurrent(entry)) { + refuse(sandboxName, "the registry changed during absence verification"); + } + if (registry.getSandbox(sandboxName) !== null) { + refuse(sandboxName, "a registry entry appeared during reconciliation"); + } + // Keep the independent record until both earlier local writes succeed so a retry can finish. + if (!sessionState.resolveRetainedSandboxRecovery(record)) { + refuse(sandboxName, "the recovery record could not be retired"); + } + return true; + }); +} diff --git a/src/lib/cli/public-dispatch.ts b/src/lib/cli/public-dispatch.ts index 7b941d079b8..c5f0a685009 100644 --- a/src/lib/cli/public-dispatch.ts +++ b/src/lib/cli/public-dispatch.ts @@ -561,9 +561,15 @@ async function dispatchSandboxArgv( // sandbox missing. The printed guidance runs it after `destroy --yes` // removed the registry entry, so registry recovery here can only exit with // "does not exist" or start a gateway the retirement never needs. + // An identity-free destroy retry can also retain only its local recovery + // record after reservation retirement. Its lifecycle owner still checks + // ownership and absence; admission must not require recreating a registry row. if ( - isRebuildRecoveryRetirement(requestedSandboxAction, requestedSandboxActionArgs) && - !registry().getSandbox(cmd) + (isRebuildRecoveryRetirement(requestedSandboxAction, requestedSandboxActionArgs) && + !registry().getSandbox(cmd)) || + (requestedSandboxAction === "destroy" && + !findKnownSandboxEntry(cmd) && + registryRecovery().hasIdentityFreeRetainedRecovery(cmd)) ) { validateName(cmd, "sandbox name"); await runPublicTranslationResult( diff --git a/src/lib/onboard/host-gateway-process.ts b/src/lib/onboard/host-gateway-process.ts index ddf8ffb1eb1..b4fc6446e1a 100644 --- a/src/lib/onboard/host-gateway-process.ts +++ b/src/lib/onboard/host-gateway-process.ts @@ -240,6 +240,7 @@ export function resolveOwnedHostGatewayRuntimeProviderId(options: { architecture?: NodeJS.Architecture; platform?: NodeJS.Platform; uid?: number; + recoveryRecordedAt?: string; }): string | null { const platform = options.platform ?? process.platform; const architecture = options.architecture ?? process.arch; @@ -260,6 +261,19 @@ export function resolveOwnedHostGatewayRuntimeProviderId(options: { return null; } if (markerPort !== options.gatewayPort) return null; + if (options.recoveryRecordedAt !== undefined) { + // A replacement gateway cannot establish the daemon used by an earlier failed create. + const recordedAt = Date.parse(options.recoveryRecordedAt); + const startedAt = Date.parse(marker.createdAt); + if ( + (marker.dockerHost !== null && marker.dockerHost !== "unix:///var/run/docker.sock") || + !Number.isFinite(recordedAt) || + !Number.isFinite(startedAt) || + startedAt >= recordedAt + ) { + return null; + } + } const provider = resolveRegisteredRuntimeProvider(marker.driver); return provider?.gateway.supported === true ? provider.identity.id : null; } diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index b39d00f2186..4085a37a775 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 and an independent identity-bound recovery record. A later `destroy` can delete a live retained sandbox whose OpenShell identity matches the recorded durable fingerprint. It rechecks that identity during cleanup and immediately before deletion. Missing identity, uncertain presence, or observed identity drift blocks deletion and preserves the recovery record. OpenShell deletes by mutable name; the final identity check and deletion are not atomic. Another gateway client can replace the sandbox between those operations, causing deletion of the replacement. After OpenShell authoritatively reports absence, destroy uses the record to qualify immutable runtime identity and, for Docker-backed sandboxes, exact container identities before residual cleanup and record retirement. A different explicit sandbox name starts a fresh session without changing the retained record. Exact provider-owned GPU cleanup can proceed through its owner receipt. NemoClaw attempts to remove temporary policy and build-context sources and reports cleanup failures with the onboarding error; post-create failures retain recovery state. Cancellation before sandbox creation can leave the session resumable. Shared inference providers remain gateway configuration and are not sandbox cleanup targets. Coverage: `transition-traces.test.ts`, `sandbox-create-intent-boundary.test.ts`, `sandbox-create-plan.test.ts`, and the focused cancellation, readiness, GPU cleanup, dashboard, policy-authority, destroy, and retained-recovery tests. Gap: gateway upserts can outlive a failed or interrupted create. | +| **New interactive or non-interactive onboard** — `onboard()` and `resolveOnboardEntryOptions` | Current flags, environment, and prompts. `MessagingWorkflowPlanner.buildPlan`, `prepareSandboxMessagingPreflight`, resource-profile selection, `resolveSandboxCreateIntent`, and `materializeSandboxCreatePlan` assemble policy, provider, package, resource, host-forward, and runtime-setup contributions. Non-interactive mode replaces prompts with defaults or hard aborts. | Consent/session/lock setup and preflight can persist local state, install OpenShell, or clean stale gateway artifacts before the gateway handler. Gateway reuse/recovery/start is the first provider-routing effect; inference-provider upserts follow. For OpenClaw, messaging selection and plan reconciliation complete before web-search or messaging provider registration. Each validated provider group is then created or updated and checkpointed before resource selection. A name with no live sandbox has no sandbox-destructive boundary; an existing target enters the recreate contract below. | Whole-step session plus machine snapshot. OpenClaw adds narrow checkpoints after each completed secret-free sandbox prompt group; sandbox registry registration is deferred until readiness and live validation. The session stores credential environment names, redacted endpoint metadata, legacy-value digests, and non-secret names of web-search and messaging providers registered for resume; real values remain process- or gateway-bound. | Readiness, post-create policy verification, dashboard forwarding, and cancellation failures preserve the live sandbox and an independent identity-bound recovery record. A later `destroy` can delete a live retained sandbox whose OpenShell identity matches the recorded durable fingerprint. It rechecks that identity during cleanup and immediately before deletion. Missing identity, uncertain presence, or observed identity drift blocks deletion and preserves the recovery record. OpenShell deletes by mutable name; the final identity check and deletion are not atomic. Another gateway client can replace the sandbox between those operations, causing deletion of the replacement. After OpenShell authoritatively reports absence, destroy uses the record to qualify immutable runtime identity and, for Docker-backed sandboxes, exact container identities before residual cleanup and record retirement. Eligible identity-free records instead follow the native Linux Docker ownership and absence contract below, retiring only local metadata without deleting runtime resources. A different explicit sandbox name starts a fresh session without changing the retained record. Exact provider-owned GPU cleanup can proceed through its owner receipt. NemoClaw attempts to remove temporary policy and build-context sources and reports cleanup failures with the onboarding error; post-create failures retain recovery state. Cancellation before sandbox creation can leave the session resumable. Shared inference providers remain gateway configuration and are not sandbox cleanup targets. Coverage: `transition-traces.test.ts`, `sandbox-create-intent-boundary.test.ts`, `sandbox-create-plan.test.ts`, and the focused cancellation, readiness, GPU cleanup, dashboard, policy-authority, destroy, and retained-recovery tests. Gap: gateway upserts can outlive a failed or interrupted create. | | **`--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` | The registry remains authoritative only for non-MCP sandbox settings. Agent-native configuration and live OpenShell state are the MCP sources. A matching session may fill guarded legacy non-MCP 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. MCP detach/scrub uses a bounded source-derived handoff and NIM stop is a destructive in-place effect before the **sandbox delete** boundary. Legacy and custom-image paths recheck prepared context and mutation-edge conditions before delete. Managed-image paths revalidate the 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. MCP handoff state and rollback receipts 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 source-derived MCP state, but process death after non-MCP delete can still lose non-MCP registry metadata. The inner onboarding consumes the 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. | @@ -136,6 +136,13 @@ runtime mutation | **Credential rotation** — `configRotateToken` in `src/lib/sandbox/config.ts`; `rotateSandboxToken` in `src/lib/sandbox/config-rotate-token.ts` | A named sandbox registry route selects the provider and credential binding whenever that registry row exists; an incomplete route fails closed. Only a sandbox with no registry row falls back to the onboard session, which must name exactly the requested sandbox; a different or null `sandboxName` is rejected before any credential side effect. An endpoint-backed fallback session without a concrete provider type is also rejected before prompting. The new value comes from a named environment variable, stdin, or a secret prompt; it is trimmed, then rejected when empty or still containing internal whitespace. | OpenShell provider update runs first, with provider create as a fallback using the provider type owned by onboarding metadata and the registered gateway-reachable endpoint; an endpoint-backed provider without that metadata fails closed instead of being recreated incompletely. After provider rotation succeeds, `saveCredential` stages the value in the current process and audit runs last. No sandbox deletion. | The logical binding is unchanged, so session and registry are not rewritten. The raw value exists only in process memory/environment and the gateway provider; audit records action/sandbox/reason without the value. | No rollback follows a successful provider update; a later credential-staging or audit failure can report failure after the credential is already active. Covered by `test/security/config-rotate-token.test.ts` and the rotate-token case in `test/security/config-set-nested-ssrf.test.ts`. | | **Config, policy, resource, port-forward, and runtime setup contributions** — `configSet`; `prepareInitialSandboxCreatePolicy`; `selectResourceProfileForSandbox`; manifest compiler/runtime appliers; dashboard and channel forward helpers | Config uses validated dotpaths and SSRF-safe URL rewriting. Create/rebuild contributions are assembled by `sandbox-create-plan.ts` and `MessagingWorkflowPlanner`: policy presets/keys, resource flags, package/build steps, `hostForward`, runtime node preloads, env aliases, and secret scans. | Config’s first effect is a compare-and-swap sandbox write. Build-time contributions inherit the enclosing create/recreate boundary. Forward helpers launch OpenShell service forwarding only on free host ports. OpenShell ends each forward when its sandbox or gateway becomes unavailable. | Durable owners are compact registry messaging/policy/inference metadata, current manifests used for plan rehydration, onboard session, sandbox config/hash, and gateway provider state. An interrupted onboarding session records the selected resource values or an explicit OpenShell-default choice; the resolved create intent remains process-local. Logical bindings are serializable; raw provider values are not. | CAS rejects stale config writes; OpenClaw/Hermes commit config and integrity hashes together, while other agents may refresh a path hash afterward. Audit and optional restart are post-commit and forward-only. Forward recovery can re-establish declared forwards. Gaps: no cross-contribution effect transaction/checkpoint. | +For identity-free recovery on native Linux, `actions/sandbox/lifecycle/retained-recovery.ts` owns local metadata retirement and preserves runtime resources. +It requires an owned default-Docker runtime marker that predates the recovery record, owning-gateway absence, and no matching containers or managed state volumes on that daemon. Missing, alternate-daemon, or newer runtime evidence keeps recovery blocked. +Any reservation must match its recovery-only session; conflicting state, recorded sandbox-scoped providers, or additional resource ownership block retirement. +Legacy Shields state retires before registry and recovery metadata; interrupted retirement retains recovery authority for retry. +The public CLI admits `destroy` from the selected root's retained record after reservation removal; the lifecycle owner revalidates authority and absence and preserves unrelated sessions. +`actions/sandbox/lifecycle/retained-recovery.test.ts` covers completion, refusal, and retry. + ## Durable resumed recreate journal A resumed same-name replacement writes a secret-free journal before the lower create path can delete the source sandbox. diff --git a/src/lib/onboard/openshell-docker-sandbox-containers.ts b/src/lib/onboard/openshell-docker-sandbox-containers.ts index e6e0d4a699a..f2ed3de5242 100644 --- a/src/lib/onboard/openshell-docker-sandbox-containers.ts +++ b/src/lib/onboard/openshell-docker-sandbox-containers.ts @@ -223,12 +223,17 @@ type ExactDockerContainerCleanupDeps = { export function inspectDockerSandboxNameLabeledContainers( sandboxName: string, + inspect?: Parameters[2], ): DockerSandboxIdentityObservation { - return inspectDockerSandboxIdentities(`${OPENSHELL_SANDBOX_NAME_LABEL}=${sandboxName}`, { - managedBy: OPENSHELL_MANAGED_BY_LABEL, - workspace: OPENSHELL_SANDBOX_WORKSPACE_LABEL, - sandboxId: OPENSHELL_SANDBOX_ID_LABEL, - }); + return inspectDockerSandboxIdentities( + `${OPENSHELL_SANDBOX_NAME_LABEL}=${sandboxName}`, + { + managedBy: OPENSHELL_MANAGED_BY_LABEL, + workspace: OPENSHELL_SANDBOX_WORKSPACE_LABEL, + sandboxId: OPENSHELL_SANDBOX_ID_LABEL, + }, + inspect, + ); } function exactCleanupContainerIds( diff --git a/src/lib/registry-recovery-action.ts b/src/lib/registry-recovery-action.ts index 3d243c0653a..c58f83f5f84 100644 --- a/src/lib/registry-recovery-action.ts +++ b/src/lib/registry-recovery-action.ts @@ -39,6 +39,15 @@ export type RecoveredSandboxEntry = SandboxEntry & { type Session = ReturnType; +/** Route a metadata-only destroy retry using recovery retained in the selected state root. */ +export function hasIdentityFreeRetainedRecovery(sandboxName: string): boolean { + return onboardSession + .listRetainedSandboxRecoveryRecords() + .some( + (record) => record.sandboxName === sandboxName && record.sandboxIdentityFingerprint === null, + ); +} + type RecoveredSandboxMetadata = Partial< Pick< SandboxEntry, diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 39146788a3e..ef143c64837 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -1556,7 +1556,8 @@ function onboardLockContentionGuidance( return [lead, ...holderDetails, remediation].join(" "); } -function withOwnedOnboardLock(command: string, operation: () => T): T { +/** Hold the onboarding writer lock through one synchronous state transition. */ +export function withOwnedOnboardLock(command: string, operation: () => T): T { const managesOnboardLock = heldLockHandle === null; if (managesOnboardLock) { const lock = acquireOnboardLock(command); diff --git a/test/cli/dispatch-recovery-routing.test.ts b/test/cli/dispatch-recovery-routing.test.ts index 3528dadd9b0..db013962bdf 100644 --- a/test/cli/dispatch-recovery-routing.test.ts +++ b/test/cli/dispatch-recovery-routing.test.ts @@ -14,6 +14,48 @@ afterEach(() => { }); describe("CLI recovery routing", () => { + it("routes destroy to retained recovery after its registry row is retired (#12260)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, recoverRegistryEntries, runOclifCommandById, exitSpy }) => { + await dispatchCli(["alpha", "destroy", "--yes"]); + + expect(runOclifCommandById).toHaveBeenCalledWith( + "sandbox:destroy", + ["alpha", "--yes"], + expect.objectContaining({ publicSandboxName: "alpha" }), + ); + expect(recoverRegistryEntries).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + }, + { retainedRecoverySandboxNames: ["alpha"] }, + ); + }); + + it("keeps missing-name checks for destroy without matching local recovery (#12260)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, recoverRegistryEntries, runOclifCommandById, stderr }) => { + await expect(dispatchCli(["alpha", "destroy", "--yes"])).rejects.toThrow("process.exit:1"); + + expect(recoverRegistryEntries).toHaveBeenCalledWith({ requestedSandboxName: "alpha" }); + expect(runOclifCommandById).not.toHaveBeenCalled(); + expect(stderr.join("\n")).toContain("Sandbox 'alpha' does not exist."); + }, + { retainedRecoverySandboxNames: ["beta"] }, + ); + }); + + it("does not admit other sandbox actions from a retained recovery record (#12260)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, recoverRegistryEntries, runOclifCommandById }) => { + await expect(dispatchCli(["alpha", "status"])).rejects.toThrow("process.exit:1"); + + expect(recoverRegistryEntries).toHaveBeenCalledWith({ requestedSandboxName: "alpha" }); + expect(runOclifCommandById).not.toHaveBeenCalled(); + }, + { retainedRecoverySandboxNames: ["alpha"] }, + ); + }); + it.each([ { argv: ["term"], diff --git a/test/support/public-dispatch-test-harness.ts b/test/support/public-dispatch-test-harness.ts index f707bfa8018..3aabea0597c 100644 --- a/test/support/public-dispatch-test-harness.ts +++ b/test/support/public-dispatch-test-harness.ts @@ -24,6 +24,7 @@ export type DirectPublicDispatchHarness = { migrateLegacyPortState: ReturnType; printSandboxConnectHelp: ReturnType; recoverRegistryEntries: ReturnType; + hasIdentityFreeRetainedRecovery: ReturnType; resetObservedCalls: () => void; runOclifArgv: ReturnType; runOclifCommandById: ReturnType; @@ -40,6 +41,8 @@ type DirectPublicDispatchOptions = { defaultSandbox?: string | null; /** Registered route reservations that are not ready or default-eligible. */ pendingSandboxNames?: readonly string[]; + /** Identity-free recovery records in the selected gateway's state root. */ + retainedRecoverySandboxNames?: readonly string[]; /** Args the sandbox-connect stub treats as connect flags (default: none). */ connectFlags?: readonly string[]; /** Legacy sandbox rows that belong to the selected gateway but are not migrated yet. */ @@ -143,6 +146,9 @@ export async function withDirectPublicDispatch( recoveredFromSession: false, recoveredFromGateway: 0, })); + const hasIdentityFreeRetainedRecovery = vi.fn((name: string) => + (options.retainedRecoverySandboxNames ?? []).includes(name), + ); const migrateLegacyPortState = vi.fn(() => { if (options.migrationError) throw options.migrationError; return { migratedSandboxNames: [], migratedSession: false, warnings: [] }; @@ -169,6 +175,7 @@ export async function withDirectPublicDispatch( listSandboxes.mockClear(); migrateLegacyPortState.mockClear(); recoverRegistryEntries.mockClear(); + hasIdentityFreeRetainedRecovery.mockClear(); runOclifArgv.mockClear(); runOclifCommandById.mockClear(); }; @@ -193,7 +200,7 @@ export async function withDirectPublicDispatch( }); } cacheModule(legacyPortMigrationPath, { hasMigratableLegacySandbox, migrateLegacyPortState }); - cacheModule(registryRecoveryPath, { recoverRegistryEntries }); + cacheModule(registryRecoveryPath, { recoverRegistryEntries, hasIdentityFreeRetainedRecovery }); cacheModule(oclifRunnerPath, { runOclifArgv, runOclifCommandById }); const connectFlags = new Set(options.connectFlags ?? []); cacheModule(sandboxConnectPath, { @@ -219,6 +226,7 @@ export async function withDirectPublicDispatch( migrateLegacyPortState, printSandboxConnectHelp, recoverRegistryEntries, + hasIdentityFreeRetainedRecovery, resetObservedCalls, runOclifArgv, runOclifCommandById,