diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 5a9687c1c95..d956ac33485 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -575,10 +575,12 @@ Keep the recovery record and retry `destroy` only after resolving the identity d 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. +For normal recovery, `destroy` can clear local recovery metadata on native Linux with default Docker when no lifecycle identity was published. 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. +When the record includes ownership captured before creation, recovery rechecks the original Docker daemon, gateway binding, and any remaining reservation owner. +Otherwise, it requires a Docker ownership marker predating the recovery record and, while a reservation remains, its matching recovery-only session. +Sandbox-scoped providers or additional resource ownership block recovery. Use the failed onboarding attempt's gateway port to select its state root, for example: @@ -2168,6 +2170,11 @@ If you want to upgrade the sandbox while preserving state, use `$$nemoclaw { diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts index 1d1d3682b4a..8fdc54ed0ee 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts @@ -33,7 +33,7 @@ afterEach(() => { fs.rmSync(testHome, { recursive: true, force: true }); }); -async function setup(port = 19260, dockerHost?: string) { +async function setup(port = 19260, dockerHost?: string, captureAuthority = false) { vi.stubEnv("NEMOCLAW_GATEWAY_PORT", String(port)); vi.stubEnv("DOCKER_HOST", dockerHost); vi.stubEnv("DOCKER_CONTEXT", "default"); @@ -84,11 +84,22 @@ async function setup(port = 19260, dockerHost?: string) { }), ); registry.reserveSandboxInferenceRoute("alpha", route); + let daemonId = "original-daemon-id"; + const volumes = vi.spyOn(docker, "dockerRun").mockImplementation((args) => ({ + ...emptyDockerResult, + stdout: args.includes("info") ? daemonId : "", + })); + const { captureNativeDockerRecoveryAuthority } = + await import("../../../onboard/gateway/state-ownership"); + const createAuthority = captureAuthority + ? captureNativeDockerRecoveryAuthority(gatewayName, port, route.reservationSessionId) + : undefined; session.markRetainedSandboxRecovery("alpha", "identity lookup failed", undefined, { gatewayName, gatewayPort: port, lifecycleGeneration: "failed-generation", createAttemptNonce: "a".repeat(62), + ...(createAuthority ? { createAuthority } : {}), }); const record = session.listRetainedSandboxRecoveryRecords()[0]!; const capture = vi @@ -104,18 +115,18 @@ async function setup(port = 19260, dockerHost?: string) { 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 = () => + const run = (forceLocal = false) => reconcileIdentityFreeRecovery("alpha", session.listRetainedSandboxRecoveryRecords(), port, { session, registry, captureOpenshell: capture, + forceLocal, }); return { session, @@ -125,6 +136,9 @@ async function setup(port = 19260, dockerHost?: string) { capture, containers, volumes, + setDaemonId: (value: string) => { + daemonId = value; + }, clearRuntime: () => clearDockerDriverGatewayRuntimeMarker(stateDir), writeRuntime, snapshot, @@ -158,7 +172,7 @@ async function setupDestroy(port = 19260) { fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); return { ...h, - destroy: () => destroySandbox("alpha", { yes: true }), + destroy: (force = false) => destroySandbox("alpha", { yes: true, force }), ordinaryDestroy, exit, log, @@ -168,6 +182,131 @@ async function setupDestroy(port = 19260) { } describe.skipIf(process.platform !== "linux")("identity-free retained recovery", () => { + type Harness = Awaited>; + + it("retires recovery with captured authority after gateway restart (#13071)", async () => { + const h = await setup(19260, undefined, true); + expect(h.record.createAuthority?.daemonId).toBe("original-daemon-id"); + h.writeRuntime(null, new Date(Date.parse(h.record.recordedAt) + 1000).toISOString()); + expect(h.run()).toBe(true); + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(h.session.loadSession()?.cancellationRecovery).toBeNull(); + }); + + it.each([ + { + condition: "changed-daemon", + prepare: (h: Harness) => h.setDaemonId("replacement-daemon-id"), + }, + { + condition: "daemon-changes-during-probe", + prepare: (h: Harness) => + h.containers.mockImplementation(() => { + h.setDaemonId("replacement-daemon-id"); + return { status: "observed", rows: [], malformedRows: 0 }; + }), + }, + { + condition: "changed-owner", + prepare: (h: Harness) => + h.registry.updateSandbox("alpha", { reservationSessionId: "another-owner" }), + }, + ])( + "preserves captured recovery when $condition invalidates its authority (#13071)", + async ({ prepare }) => { + const h = await setup(19260, undefined, true); + prepare(h); + const before = h.snapshot(); + expect(() => h.run()).toThrow(/daemon|conflicting ownership/u); + expect(h.snapshot()).toEqual(before); + }, + ); + + it("archives an explicit local discard after gateway restart without changing another session", async () => { + const h = await setupDestroy(); + const originalReservation = h.registry.getSandbox("alpha"); + h.session.saveSession( + h.session.createSession({ + sessionId: "new-owner", + sandboxName: "other-sandbox", + status: "complete", + }), + ); + const otherSession = fs.readFileSync(h.session.SESSION_FILE, "utf8"); + h.writeRuntime(null, new Date(Date.parse(h.record.recordedAt) + 1_000).toISOString()); + await expect(h.destroy()).rejects.toThrow("process.exit(1)"); + + await h.destroy(true); + + expect(h.registry.getSandbox("alpha")).toBeNull(); + expect(h.session.listRetainedSandboxRecoveryRecords()).toEqual([]); + expect(fs.readFileSync(h.session.SESSION_FILE, "utf8")).toBe(otherSession); + const archive = path.join( + h.session.SESSION_DIR, + ".retained-recovery-archive", + `${h.record.recordId}.json`, + ); + expect(JSON.parse(fs.readFileSync(archive, "utf8"))).toMatchObject({ + operation: "forced-local-recovery-discard", + originalResourceAbsence: "unverified", + record: h.record, + reservation: originalReservation, + }); + expect(fs.statSync(archive).mode & 0o777).toBe(0o600); + expect(h.ordinaryDestroy).not.toHaveBeenCalled(); + expect( + h.capture.mock.calls.every(([args]) => args[0] === "sandbox" && args[1] === "list"), + ).toBe(true); + }); + + it.each([ + { + condition: "present", + prepare: (h: Harness) => + h.capture.mockReturnValue({ + status: 0, + output: '[{"name":"alpha","phase":"Ready"}]', + stdout: '[{"name":"alpha","phase":"Ready"}]', + stderr: "", + }), + }, + { + condition: "other-daemon", + prepare: (h: Harness) => + h.writeRuntime("unix:///tmp/other-docker.sock", new Date().toISOString()), + }, + { + condition: "same-name-owner", + prepare: (h: Harness) => + h.session.saveSession({ ...h.session.loadSession()!, sessionId: "replacement-owner" }), + }, + ])( + "preserves state under --force when $condition prevents local retirement", + async ({ prepare }) => { + const h = await setup(); + prepare(h); + const before = h.snapshot(); + expect(() => h.run(true)).toThrow(); + expect(h.snapshot()).toEqual(before); + expect(fs.existsSync(path.join(h.session.SESSION_DIR, ".retained-recovery-archive"))).toBe( + false, + ); + }, + ); + + it("preserves active metadata and an existing conflicting archive under --force", async () => { + const h = await setup(); + const directory = path.join(h.session.SESSION_DIR, ".retained-recovery-archive"); + fs.mkdirSync(directory, { mode: 0o700 }); + const archive = path.join(directory, `${h.record.recordId}.json`); + fs.writeFileSync(archive, "{}\n", { mode: 0o600 }); + const before = h.snapshot(); + expect(() => h.run(true)).toThrow(/archive conflicts/u); + expect(h.snapshot()).toEqual(before); + expect(fs.readFileSync(archive, "utf8")).toBe("{}\n"); + }); + it.each([8080, 19260])( "releases the retained name through destroy on gateway port %s without resource cleanup (#12260)", async (port) => { @@ -515,33 +654,37 @@ describe.skipIf(process.platform !== "linux")("identity-free retained recovery", 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"); + it.each(["legacy", "force", "captured"])( + "finishes on retry after recovery retirement fails (%s) (#12260, #13071)", + async (mode) => { + const forceLocal = mode === "force"; + const h = await setup(19260, undefined, mode === "captured"); + 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(forceLocal)).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); - }); + expect(h.run(forceLocal)).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); diff --git a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts index e83de88d853..0773da3d0b6 100644 --- a/src/lib/actions/sandbox/lifecycle/retained-recovery.ts +++ b/src/lib/actions/sandbox/lifecycle/retained-recovery.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { isDeepStrictEqual } from "node:util"; +import { captureNativeDockerRecoveryAuthority } from "../../../onboard/gateway/state-ownership"; import { dockerRun } from "../../../adapters/docker/run"; import { dockerContextIsDefaultFromBuild } from "../../../adapters/docker/client-isolation"; @@ -29,6 +30,7 @@ type RecoveryState = { registryEntryGatewayPort: typeof registryEntryGatewayPort; retireRemovedImmutabilityState?: () => void; timeoutMs: number; + forceLocal?: boolean; session: Pick< typeof OnboardSession, | "withOwnedOnboardLock" @@ -36,6 +38,7 @@ type RecoveryState = { | "listRetainedSandboxRecoveryRecords" | "retainedSandboxRecoveryMatchesSession" | "resolveRetainedSandboxRecovery" + | "archiveRetainedSandboxRecoveryForLocalDiscard" >; registry: Pick; }; @@ -103,16 +106,30 @@ function requireAbsence(record: Recovery, state: RecoveryState): void { function requireReservationOwner( record: Recovery, - entry: Registry.SandboxEntry, + entry: Registry.SandboxEntry | null, session: OnboardSession.Session | null, state: RecoveryState, ): void { + if (!entry) { + if ( + (state.forceLocal || record.createAuthority) && + session?.sandboxName === record.sandboxName && + (session.status !== "recovery_required" || + !state.session.retainedSandboxRecoveryMatchesSession(record, session)) + ) { + refuse(record.sandboxName, "another onboarding session still claims this name"); + } + return; + } const { name, gatewayName, gatewayPort } = entry; + const sessionMustMatch = + (!state.forceLocal && !record.createAuthority) || session?.sandboxName === record.sandboxName; if ( - session?.status !== "recovery_required" || - session.sandboxName !== record.sandboxName || - session.cancellationRecovery?.reason !== record.reason || - !state.session.retainedSandboxRecoveryMatchesSession(record, session) || + (sessionMustMatch && + (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 || @@ -120,7 +137,13 @@ function requireReservationOwner( { sandboxName: record.sandboxName, gatewayName: record.gatewayName, - sessionId: session.sessionId, + // Force is an explicit local-record discard, not proof of the original session owner. + sessionId: + (!state.forceLocal && record.createAuthority + ? record.createAuthority.reservationSessionId + : sessionMustMatch + ? session?.sessionId + : entry.reservationSessionId) ?? "", selection: normalizeInferenceSelection(entry), }, entry, @@ -168,12 +191,14 @@ export function reconcileIdentityFreeRecovery( if (!isDeepStrictEqual(entry, observedEntry) || !unpublished(entry)) { refuse(sandboxName, "the registry changed before reconciliation"); } - if (entry) requireReservationOwner(record, entry, sessionState.loadSession(), state); + requireReservationOwner(record, entry, sessionState.loadSession(), state); const requireOwnedRuntime = () => { if ( resolveGatewayCleanupRuntimeProviderId(record.gatewayName, entry?.openshellDriver, { requireOwnedRuntime: true, - recoveryRecordedAt: record.recordedAt, + ...(state.forceLocal || record.createAuthority + ? { requireDefaultDockerDaemon: true } + : { recoveryRecordedAt: record.recordedAt }), }) !== "docker" ) { refuse( @@ -181,6 +206,23 @@ export function reconcileIdentityFreeRecovery( "the owning Docker runtime on the original default daemon could not be established", ); } + if ( + !state.forceLocal && + record.createAuthority && + !isDeepStrictEqual( + record.createAuthority, + captureNativeDockerRecoveryAuthority( + record.gatewayName, + record.gatewayPort, + record.createAuthority.reservationSessionId, + ), + ) + ) { + refuse( + sandboxName, + "the Docker daemon or gateway binding changed since the create attempt", + ); + } }; requireOwnedRuntime(); // The runner can normalize the native Linux default context to its explicit Unix endpoint. @@ -202,7 +244,14 @@ export function reconcileIdentityFreeRecovery( if (!isDeepStrictEqual(currentRecords, candidates)) { refuse(sandboxName, "the recovery record changed during absence verification"); } - if (entry) requireReservationOwner(record, entry, sessionState.loadSession(), state); + const currentSession = sessionState.loadSession(); + requireReservationOwner(record, entry, currentSession, state); + if (state.forceLocal) { + const archivePath = sessionState.archiveRetainedSandboxRecoveryForLocalDiscard(record, entry); + console.warn( + ` --force discards local recovery tracking only; original runtime cleanup is not asserted. Archive: ${archivePath}`, + ); + } // Legacy state retirement must succeed while the recovery authority is still available for retry. state.retireRemovedImmutabilityState?.(); if (entry && !registry.removeSandboxRouteReservationIfCurrent(entry)) { @@ -212,7 +261,11 @@ export function reconcileIdentityFreeRecovery( 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)) { + if ( + !sessionState.resolveRetainedSandboxRecovery(record, { + preserveSession: currentSession?.sandboxName !== sandboxName, + }) + ) { refuse(sandboxName, "the recovery record could not be retired"); } return true; diff --git a/src/lib/onboard/gateway/state-ownership.ts b/src/lib/onboard/gateway/state-ownership.ts index 588b77ff310..996bf836bbf 100644 --- a/src/lib/onboard/gateway/state-ownership.ts +++ b/src/lib/onboard/gateway/state-ownership.ts @@ -1,10 +1,22 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import os from "node:os"; import path from "node:path"; +import { dockerContextIsDefaultFromBuild } from "../../adapters/docker/client-isolation"; +import { dockerRun } from "../../adapters/docker/run"; +import { + parseRetainedSandboxCreateAuthority, + type RetainedSandboxCreateAuthority, +} from "../../state/onboard-session/retained-sandbox-recovery"; +import { resolveGatewayStateDirForPort } from "./state-dir"; + import { readDockerDriverGatewayProcessEnvironment } from "../docker-driver-gateway-process-identity"; -import { HOST_GATEWAY_PGREP_PATTERN } from "../host-gateway-process"; +import { + HOST_GATEWAY_PGREP_PATTERN, + resolveOwnedHostGatewayRuntimeProviderId, +} from "../host-gateway-process"; import { NEMOCLAW_OPENSHELL_SANDBOX_NAMESPACE_ENV, processEnvironmentUsesSelectedGatewayState, @@ -113,3 +125,51 @@ export function createDockerDriverGatewayStateOwnership( return { isDockerDriverGatewayPidUsingSelectedState, isDockerDriverGatewayStateInUse }; } + +/** Observe the same native gateway and daemon authority for create and retained recovery. */ +export function captureNativeDockerRecoveryAuthority( + gatewayName: string, + gatewayPort: number, + reservationSessionId: string, +): RetainedSandboxCreateAuthority | undefined { + if (process.platform !== "linux") return undefined; + if ( + process.env.DOCKER_HOST?.trim() !== "unix:///var/run/docker.sock" && + !dockerContextIsDefaultFromBuild(process.env) + ) + return undefined; + const gatewayStateDir = resolveGatewayStateDirForPort({ + configured: process.env.NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR, + home: os.homedir(), + port: gatewayPort, + }); + const ownedRuntime = () => + resolveOwnedHostGatewayRuntimeProviderId({ + gatewayName, + gatewayPort, + stateDir: gatewayStateDir, + requireDefaultDockerDaemon: true, + }); + if (ownedRuntime() !== "docker") return undefined; + const result = dockerRun(["--context", "default", "info", "--format", "{{.ID}}"], { + ignoreError: true, + suppressOutput: true, + timeout: 5_000, + }); + const authority = parseRetainedSandboxCreateAuthority({ + schemaVersion: 1, + runtime: "native-linux-default-docker", + reservationSessionId, + gatewayStateDir, + daemonId: String(result.stdout ?? "").trim(), + }); + if ( + result.status !== 0 || + String(result.stderr ?? "").trim() || + !authority || + ownedRuntime() !== "docker" + ) { + throw new Error("Cannot establish the owned Docker daemon for retained create recovery."); + } + return authority; +} diff --git a/src/lib/onboard/host-gateway-process.ts b/src/lib/onboard/host-gateway-process.ts index b4fc6446e1a..6e1e7d19cbb 100644 --- a/src/lib/onboard/host-gateway-process.ts +++ b/src/lib/onboard/host-gateway-process.ts @@ -241,6 +241,7 @@ export function resolveOwnedHostGatewayRuntimeProviderId(options: { platform?: NodeJS.Platform; uid?: number; recoveryRecordedAt?: string; + requireDefaultDockerDaemon?: boolean; }): string | null { const platform = options.platform ?? process.platform; const architecture = options.architecture ?? process.arch; @@ -261,6 +262,13 @@ export function resolveOwnedHostGatewayRuntimeProviderId(options: { return null; } if (markerPort !== options.gatewayPort) return null; + if ( + options.requireDefaultDockerDaemon && + marker.dockerHost !== null && + marker.dockerHost !== "unix:///var/run/docker.sock" + ) { + 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); diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 837aa05ee72..11eac6a0728 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -137,8 +137,12 @@ runtime mutation | **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. +When the owned native Linux gateway and Docker client use the default daemon, each create request captures the reservation owner, daemon ID, and gateway state directory. Retained recovery preserves that authority independently of the active session. Records with this authority use schema 2 so older CLIs refuse them; schema 1 records remain readable. +Without `--force`, captured authority must match the observed daemon, gateway binding, and any remaining reservation owner. A gateway restart or different-name session does not invalidate captured authority. +Without captured authority, automatic retirement requires a default-Docker runtime marker predating the record. A remaining reservation also requires its matching recovery-only session. +The owning gateway must report the sandbox absent; Docker must report no matching containers or managed state volumes. +Explicit `--force` archives eligible local tracking before retirement. It checks current absence but does not establish the original daemon or reservation owner; original runtime cleanup remains unverified. +Retirement with captured authority or `--force` rejects a conflicting active session for the same name. Recorded sandbox-scoped providers or additional resource ownership block retirement. Shared providers remain unchanged. 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. diff --git a/src/lib/onboard/sandbox-create/identity-boundary.ts b/src/lib/onboard/sandbox-create/identity-boundary.ts index 1b3693e5b78..d7086122b7d 100644 --- a/src/lib/onboard/sandbox-create/identity-boundary.ts +++ b/src/lib/onboard/sandbox-create/identity-boundary.ts @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 import { isDeepStrictEqual } from "node:util"; - import type { DockerSandboxIdentityObservation } from "../../adapters/docker/inspect"; import { normalizePendingSandboxCreateIdentity } from "../../state/registry-normalization"; import type { PendingSandboxCreateIdentity } from "../../state/registry/types"; @@ -14,6 +13,8 @@ import { import { fingerprintSandboxRecreateValue } from "../sandbox-recreate-transaction"; import type { VerifiedSandboxCreateBoundary } from "../types"; +export { captureNativeDockerRecoveryAuthority } from "../gateway/state-ownership"; + /** Recover one exact Docker runtime from immutable legacy identity evidence. */ export function resolveLegacyCompatibilityFinalHandoffRuntime(input: { readonly checkpoint: PendingSandboxCreateIdentity; diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 118c32e80e7..89eb64bad98 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -81,6 +81,7 @@ import type { } from "../types"; import * as sandboxCreatePlanMaterialization from "../sandbox-create-plan-materialization"; import { + captureNativeDockerRecoveryAuthority, pendingSandboxCreateIdentityForBoundary, resolveLegacyCompatibilityFinalHandoffRuntime, sandboxCreateBoundaryFromPendingIdentity, @@ -3244,6 +3245,10 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche requirePendingCreateIdentity(), ); }; + const createAuthorities = new Map< + string, + ReturnType + >(); const retainedSandboxRecoveryContext = ( boundary: VerifiedSandboxCreateBoundary | null, createAttemptNonceOverride: string | null = null, @@ -3257,6 +3262,9 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche gatewayPort: GATEWAY_PORT, lifecycleGeneration: createdSandboxLifecycle.generation, createAttemptNonce, + ...(createAuthorities.get(createAttemptNonce) + ? { createAuthority: createAuthorities.get(createAttemptNonce)! } + : {}), }; }; const recordPostCreateRecovery = ( @@ -3484,6 +3492,17 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche requirePolicylessCreate: true as const, } : {}), + beforeCreateAttempt: (nonce) => { + const reservation = requireCreateReservation(); + createAuthorities.set( + nonce, + captureNativeDockerRecoveryAuthority( + GATEWAY_NAME, + GATEWAY_PORT, + reservation.authority.sessionId, + ), + ); + }, persistRetainedSandboxRecovery: ( message, sandboxIdentityFingerprint, diff --git a/src/lib/onboard/sandbox-gpu-create-flow.ts b/src/lib/onboard/sandbox-gpu-create-flow.ts index ce079004c2a..2d24748161f 100644 --- a/src/lib/onboard/sandbox-gpu-create-flow.ts +++ b/src/lib/onboard/sandbox-gpu-create-flow.ts @@ -203,6 +203,8 @@ export interface SandboxGpuCreateFlowInput { sandboxIdentityFingerprint?: string, createAttemptNonce?: string, ) => boolean; + /** Capture recovery authority before submitting each create request. */ + beforeCreateAttempt?: (createAttemptNonce: string) => void; provider: string; sandboxGpuConfig: SandboxGpuConfig; gpuRoutePlan: import("./docker-gpu-route").DockerGpuRoutePlan; 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 985f33433d5..77d7a44ea89 100644 --- a/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts +++ b/src/lib/onboard/sandbox-gpu-create-identity-gate.test.ts @@ -647,9 +647,14 @@ describe("created sandbox identity gate", () => { const input = noGpuInput(); input.verifyCreatedSandboxBeforeEffects = vi.fn(); input.revalidateVerifiedSandboxBeforeEffect = vi.fn(); + let capturedNonce = ""; + input.beforeCreateAttempt = (nonce) => { + capturedNonce = nonce; + }; const patch = createGpuPatchFixture(); mocks.createDockerGpuSandboxCreatePatch.mockReturnValue(patch); - mocks.streamSandboxCreate.mockImplementation(async (_command, _args, _env, options) => { + mocks.streamSandboxCreate.mockImplementation(async (_command, args, _env, options) => { + expect(capturedNonce).toBe(createAttemptNonce(args)); expect(options.readyCheck?.()).toBe(false); return { status: 1, output: "accepted then disconnected", sawProgress: true }; }); @@ -661,7 +666,11 @@ describe("created sandbox identity gate", () => { await expect(runSandboxGpuCreateFlow(input, deps)).rejects.toThrow("exact durable sandbox"); - expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledOnce(); + expect(input.persistRetainedSandboxRecovery).toHaveBeenCalledExactlyOnceWith( + expect.any(String), + undefined, + capturedNonce, + ); expect(input.verifyCreatedSandboxBeforeEffects).not.toHaveBeenCalled(); expect(input.revalidateVerifiedSandboxBeforeEffect).not.toHaveBeenCalled(); expect(patch.exitOnPatchError).not.toHaveBeenCalled(); @@ -730,16 +739,8 @@ describe("created sandbox identity gate", () => { expect(output).toContain(`${NEMOCLAW_CREATE_ATTEMPT_LABEL}=${nonce}`); expect(output).toContain(`Durable sandbox identity fingerprint: ${fingerprint}`); expect(output).toContain("Run 'nemoclaw alpha destroy'"); - expect(output).toContain("the command removes nothing and preserves the recovery record"); - expect(output).toContain("Inspection is diagnostic only"); - expect(output).toContain("Recovery remains blocked while the sandbox is present"); expect(output).toContain("after the owning gateway reports absence"); - expect(output).toContain("run 'nemoclaw alpha destroy --yes'"); - expect(output).not.toContain("administrator"); - expect(output).not.toContain("alpha-sandbox-id"); - expect(output).not.toContain("Recovery:"); - expect(output).not.toContain("Or: nemoclaw onboard"); - expect(output).not.toContain("onboard --resume"); + expect(output).not.toMatch(/openshell sandbox delete|onboard --resume/); expect(input.verifyCreatedSandboxBeforeEffects).not.toHaveBeenCalled(); expect(input.revalidateVerifiedSandboxBeforeEffect).not.toHaveBeenCalled(); expect(patch.exitOnPatchError).not.toHaveBeenCalled(); diff --git a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts index cbcf6da8679..fd87c6f4f2d 100644 --- a/src/lib/onboard/sandbox-gpu-create-run-attempt.ts +++ b/src/lib/onboard/sandbox-gpu-create-run-attempt.ts @@ -805,6 +805,7 @@ export function createSandboxGpuCreateAttemptRunner( ? "create" : undefined, } as const; + if (createAttemptNonce) input.beforeCreateAttempt?.(createAttemptNonce); const createResult = await deps.createSandbox( Object.freeze({ ...attemptRequest, environment: Object.freeze({ ...input.sandboxEnv }) }), createOptions, diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 96e1bfc4e2f..c73125613e5 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -83,6 +83,7 @@ function recordRecovery( sandboxName: string, gatewayPort: number, seed: string, + createAuthority?: import("./onboard-session/retained-sandbox-recovery").RetainedSandboxCreateAuthority, ): void { recordRetainedSandboxRecovery(filePath, { sandboxName, @@ -91,6 +92,7 @@ function recordRecovery( gatewayPort, lifecycleGeneration: `generation-${seed}`, createAttemptNonce: seed.repeat(62), + ...(createAuthority ? { createAuthority } : {}), resources: { sharedInferenceProviders: [], sandboxScopedProviders: [], @@ -379,7 +381,14 @@ describe("legacy non-default gateway state migration", () => { metadata: { gatewayName: "nemoclaw-9123" }, }); const sharedRecovery = path.join(shared, "retained-sandbox-recovery.json"); - recordRecovery(sharedRecovery, "port-box", 9123, "a"); + const createAuthority = { + schemaVersion: 1 as const, + runtime: "native-linux-default-docker" as const, + reservationSessionId: "original-session", + gatewayStateDir: path.join(home, "gateway"), + daemonId: "original-daemon", + }; + recordRecovery(sharedRecovery, "port-box", 9123, "a", createAuthority); recordRecovery(sharedRecovery, "default-box", 8080, "b"); writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "legacy-secret" }); writeJson(path.join(shared, "usage-notice.json"), { acceptedVersion: "1" }); @@ -407,6 +416,7 @@ describe("legacy non-default gateway state migration", () => { ); const remainingRecoveryRecords = listRetainedSandboxRecoveryRecords(sharedRecovery); expect(selectedRecoveryRecords.map((record) => record.sandboxName)).toEqual(["port-box"]); + expect(selectedRecoveryRecords[0]?.createAuthority).toEqual(createAuthority); expect(remainingRecoveryRecords.map((record) => record.sandboxName)).toEqual(["default-box"]); expectRetainedNameBlocked(selectedRecoveryRecords, "port-box"); expectRetainedNameBlocked(remainingRecoveryRecords, "default-box"); diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index bbd7b9ac8d4..c59c23bd646 100644 --- a/src/lib/state/legacy-port-migration.ts +++ b/src/lib/state/legacy-port-migration.ts @@ -18,6 +18,7 @@ import { } from "./gateway-registry"; import { listRetainedSandboxRecoveryRecords, + retainedSandboxRecoveryDocument as retainedRecoveryDocument, retainedSandboxRecoveryFile, retainedRebuildSessionFileName, readRetainedRebuildSession, @@ -133,10 +134,7 @@ interface LegacyPortMigrationIntent { remainingRecovery: RetainedRecoveryDocument | null; } -interface RetainedRecoveryDocument { - schemaVersion: 1; - unresolved: readonly RetainedSandboxRecoveryRecord[]; -} +type RetainedRecoveryDocument = ReturnType; function migrationError(message: string): Error { return new Error(`Cannot safely migrate legacy NemoClaw state for this gateway port: ${message}`); @@ -255,12 +253,6 @@ function readJsonNoFollow(home: string, filePath: string): unknown | null { } } -function retainedRecoveryDocument( - records: readonly RetainedSandboxRecoveryRecord[], -): RetainedRecoveryDocument { - return { schemaVersion: 1, unresolved: records }; -} - function readRetainedRecoveryDocument( home: string, filePath: string, 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 0320bb5233f..f64ce8480d1 100644 --- a/src/lib/state/onboard-session-cross-process-lock.test.ts +++ b/src/lib/state/onboard-session-cross-process-lock.test.ts @@ -521,6 +521,13 @@ describe("cross-process onboard lock", () => { }); it("reconstructs retained recovery after an independent writer failure and restart (#9833)", () => { + const createAuthority = { + schemaVersion: 1, + runtime: "native-linux-default-docker", + reservationSessionId: "recovery-writer", + gatewayStateDir: path.join(tempHome, "gateway"), + daemonId: "original-daemon", + }; const fingerprint = "a".repeat(64); const createAttemptNonce = "b".repeat(62); const lifecycleGeneration = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; @@ -557,6 +564,7 @@ describe("cross-process onboard lock", () => { gatewayPort: 8080, lifecycleGeneration, createAttemptNonce, + createAuthority, }), ], { env: { ...process.env, HOME: tempHome }, encoding: "utf8" }, @@ -574,6 +582,7 @@ describe("cross-process onboard lock", () => { gatewayPort: 8080, lifecycleGeneration, createAttemptNonce, + createAuthority, }), ]); }); diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index ef143c64837..c21277e11f0 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -9,6 +9,7 @@ import { createHash, randomUUID } from "node:crypto"; import fs from "node:fs"; +import { isDeepStrictEqual } from "node:util"; import path from "node:path"; import { readModelSelectionProvenance, @@ -65,6 +66,7 @@ import { nextMachineStateAfterCompletedStep } from "./onboard-step-state"; import { listRetainedSandboxRecoveryRecords as readRetainedSandboxRecoveryRecords, recordRetainedSandboxRecovery as writeRetainedSandboxRecovery, + archiveRetainedSandboxRecoveryForLocalDiscard as archiveRecoveryForLocalDiscard, retainedSandboxRecoveryAuthorityIsCurrent, retainedSandboxRecoveryFile, retainedRebuildSessionFileName, @@ -74,6 +76,8 @@ import { type RetainedSandboxRecoveryRecord, type RetainedSandboxRecoveryReason, validSafeEvidence, + parseRetainedSandboxCreateAuthority, + type RetainedSandboxCreateAuthority, } from "./onboard-session/retained-sandbox-recovery"; import { acquireOnboardStateLock, @@ -146,6 +150,7 @@ export interface SessionFailure { } export interface SessionCancellationRecovery { + readonly createAuthority?: RetainedSandboxCreateAuthority; readonly reason: "cancelled_after_sandbox_creation" | "retained_after_sandbox_creation_failure"; readonly sandboxName: string; readonly sandboxIdentityFingerprint: string | null; @@ -178,7 +183,8 @@ function sameCancellationRecovery( left.gatewayPort === right.gatewayPort && left.lifecycleGeneration === right.lifecycleGeneration && left.createAttemptNonce === right.createAttemptNonce && - left.recordedAt === right.recordedAt + left.recordedAt === right.recordedAt && + isDeepStrictEqual(left.createAuthority, right.createAuthority) ); } @@ -815,6 +821,7 @@ function parseSessionCancellationRecovery( const gatewayPort = value.gatewayPort; const lifecycleGeneration = readString(value.lifecycleGeneration); const createAttemptNonce = readString(value.createAttemptNonce); + const createAuthority = parseRetainedSandboxCreateAuthority(value.createAuthority); if ( !sandboxName || sandboxName.length > NAME_MAX_LENGTH || @@ -827,7 +834,8 @@ function parseSessionCancellationRecovery( Number(gatewayPort) > 65_535 || !lifecycleGeneration || !createAttemptNonce || - !/^[0-9a-f]{62}$/u.test(createAttemptNonce) + !/^[0-9a-f]{62}$/u.test(createAttemptNonce) || + (value.createAuthority !== undefined && !createAuthority) ) { return null; } @@ -839,6 +847,7 @@ function parseSessionCancellationRecovery( gatewayPort: Number(gatewayPort), lifecycleGeneration, createAttemptNonce, + ...(createAuthority ? { createAuthority } : {}), recordedAt, }; } @@ -1814,6 +1823,7 @@ export function updateSession(mutator: (session: Session) => Session | void): Se } export interface RetainedSandboxRecoveryContext { + readonly createAuthority?: RetainedSandboxCreateAuthority; readonly gatewayName: string; readonly gatewayPort: number; readonly lifecycleGeneration: string; @@ -1850,6 +1860,7 @@ function persistIndependentRetainedSandboxRecovery( lifecycleGeneration: context.lifecycleGeneration, createAttemptNonce: context.createAttemptNonce, resources: retainedSandboxResourceEvidence(session), + ...(context.createAuthority ? { createAuthority: context.createAuthority } : {}), reason, }); } @@ -1864,6 +1875,8 @@ export function listRetainedSandboxRecoveryRecords(): readonly RetainedSandboxRe recovery && !records.some( (record) => + (!record.createAuthority || + record.createAuthority.reservationSessionId === current.sessionId) && record.sandboxName === recovery.sandboxName && record.sandboxIdentityFingerprint === recovery.sandboxIdentityFingerprint && record.createAttemptNonce === recovery.createAttemptNonce, @@ -1878,6 +1891,7 @@ export function listRetainedSandboxRecoveryRecords(): readonly RetainedSandboxRe lifecycleGeneration: recovery.lifecycleGeneration, createAttemptNonce: recovery.createAttemptNonce, resources: retainedSandboxResourceEvidence(current), + ...(recovery.createAuthority ? { createAuthority: recovery.createAuthority } : {}), reason: recovery.reason, recordedAt: recovery.recordedAt, }); @@ -1978,11 +1992,16 @@ export function recordRetainedSandboxRecovery( export function retainedSandboxRecoveryMatchesSession( record: RetainedSandboxRecoveryRecord, - session: Pick | null | undefined, + session: + | (Pick & Partial>) + | null + | undefined, ): boolean { const recovery = session?.cancellationRecovery; if (!recovery) return false; return ( + (!record.createAuthority || + record.createAuthority.reservationSessionId === session?.sessionId) && record.sandboxName === recovery.sandboxName && record.sandboxIdentityFingerprint === recovery.sandboxIdentityFingerprint && record.gatewayName === recovery.gatewayName && @@ -1992,14 +2011,31 @@ export function retainedSandboxRecoveryMatchesSession( ); } -/** Clear one recovery-only session after destroy verifies the retained resources absent. */ -export function resolveRetainedSandboxRecovery(record: RetainedSandboxRecoveryRecord): boolean { +/** Archive the selected record before an explicit local-only discard. */ +export function archiveRetainedSandboxRecoveryForLocalDiscard( + record: RetainedSandboxRecoveryRecord, + reservation: SandboxEntry | null, +): string { + return withOwnedOnboardLock("nemoclaw forced local recovery archive", () => + archiveRecoveryForLocalDiscard(RETAINED_SANDBOX_RECOVERY_FILE, record, reservation), + ); +} + +/** Preserve another onboarding session when retiring an operator-selected local record. */ +export function resolveRetainedSandboxRecovery( + record: RetainedSandboxRecoveryRecord, + options: { preserveSession?: boolean } = {}, +): boolean { return withOwnedOnboardLock("nemoclaw retained sandbox recovery completion", () => { if (!retainedSandboxRecoveryAuthorityIsCurrent(RETAINED_SANDBOX_RECOVERY_FILE, record)) { return false; } const current = loadSession(); - if (current && retainedSandboxRecoveryMatchesSession(record, current)) { + if ( + !options.preserveSession && + current && + retainedSandboxRecoveryMatchesSession(record, current) + ) { current.status = "failed"; current.resumable = false; current.sandboxName = null; @@ -2029,6 +2065,12 @@ export function markCancellationRecovery( } return withOwnedOnboardLock("nemoclaw cancellation recovery", () => { const saved = updateSession((session) => { + if ( + context.createAuthority && + context.createAuthority.reservationSessionId !== session.sessionId + ) { + throw new Error("The retained create authority belongs to another onboarding session."); + } if (session.sandboxName !== null && session.sandboxName !== sandboxName) { throw new Error("Cannot record cancellation recovery for a different onboarding sandbox."); } @@ -2087,6 +2129,12 @@ export function markRetainedSandboxRecovery( } return withOwnedOnboardLock("nemoclaw retained sandbox recovery", () => { const saved = updateSession((session) => { + if ( + context.createAuthority && + context.createAuthority.reservationSessionId !== session.sessionId + ) { + throw new Error("The retained create authority belongs to another onboarding session."); + } if (session.sandboxName !== null && session.sandboxName !== sandboxName) { throw new Error( "Cannot record retained sandbox recovery for a different onboarding sandbox.", diff --git a/src/lib/state/onboard-session/retained-sandbox-recovery.ts b/src/lib/state/onboard-session/retained-sandbox-recovery.ts index 4c45bd100c1..f5f3663c2dd 100644 --- a/src/lib/state/onboard-session/retained-sandbox-recovery.ts +++ b/src/lib/state/onboard-session/retained-sandbox-recovery.ts @@ -7,11 +7,14 @@ import path from "node:path"; import { isDeepStrictEqual } from "node:util"; import { openRegularFileNoFollow } from "../../adapters/fs/regular-file"; +import { publishExportFile } from "../../adapters/fs/config-export-file"; +import type { SandboxEntry } from "../registry/types"; import { NAME_MAX_LENGTH, NAME_VALID_PATTERN } from "../../sandbox-name-contract"; import type { JsonObject } from "../../core/json-types"; import { inspectCheckpoint } from "../onboard-checkpoint"; const SCHEMA_VERSION = 1; +const CREATE_AUTHORITY_SCHEMA_VERSION = 2; const FINGERPRINT_PATTERN = /^[0-9a-f]{64}$/u; const CREATE_ATTEMPT_NONCE_PATTERN = /^[0-9a-f]{62}$/u; const SAFE_EVIDENCE_PATTERN = /^[A-Za-z0-9._:@/-]{1,256}$/u; @@ -72,8 +75,44 @@ export interface RetainedSandboxResourceEvidence { readonly credentialEnvironmentVariables: readonly string[]; } +/** Authority observed before one native Docker create request, independent of session lifetime. */ +export interface RetainedSandboxCreateAuthority { + readonly schemaVersion: 1; + readonly runtime: "native-linux-default-docker"; + readonly reservationSessionId: string; + readonly gatewayStateDir: string; + readonly daemonId: string; +} + +export function parseRetainedSandboxCreateAuthority( + value: unknown, +): RetainedSandboxCreateAuthority | null { + if ( + !isObjectRecord(value) || + value.schemaVersion !== 1 || + value.runtime !== "native-linux-default-docker" || + !validSafeEvidence(value.reservationSessionId) || + typeof value.gatewayStateDir !== "string" || + !path.isAbsolute(value.gatewayStateDir) || + value.gatewayStateDir.length > 4096 || + /[\x00-\x1f\x7f]/u.test(value.gatewayStateDir) || + typeof value.daemonId !== "string" || + value.daemonId.length === 0 || + value.daemonId.length > 256 || + /[\s\x00-\x1f\x7f]/u.test(value.daemonId) + ) + return null; + return { + schemaVersion: 1, + runtime: "native-linux-default-docker", + reservationSessionId: value.reservationSessionId, + gatewayStateDir: value.gatewayStateDir, + daemonId: value.daemonId, + }; +} + export interface RetainedSandboxRecoveryRecord { - readonly schemaVersion: typeof SCHEMA_VERSION; + readonly schemaVersion: typeof SCHEMA_VERSION | typeof CREATE_AUTHORITY_SCHEMA_VERSION; readonly recordId: string; readonly sandboxName: string; readonly sandboxIdentityFingerprint: string | null; @@ -82,13 +121,14 @@ export interface RetainedSandboxRecoveryRecord { readonly gatewayPort: number; readonly lifecycleGeneration: string | null; readonly createAttemptNonce: string; + readonly createAuthority?: RetainedSandboxCreateAuthority; readonly resources: RetainedSandboxResourceEvidence; readonly reason: RetainedSandboxRecoveryReason; readonly recordedAt: string; } interface RetainedSandboxRecoveryState { - readonly schemaVersion: typeof SCHEMA_VERSION; + readonly schemaVersion: typeof SCHEMA_VERSION | typeof CREATE_AUTHORITY_SCHEMA_VERSION; readonly unresolved: readonly RetainedSandboxRecoveryRecord[]; } @@ -106,15 +146,24 @@ export interface RecordRetainedSandboxRecoveryInput { readonly gatewayPort: number; readonly lifecycleGeneration: string | null; readonly createAttemptNonce: string; + readonly createAuthority?: RetainedSandboxCreateAuthority; readonly resources: RetainedSandboxResourceEvidence; readonly reason: RetainedSandboxRecoveryReason; readonly recordedAt?: string; } -const emptyState = (): RetainedSandboxRecoveryState => ({ - schemaVersion: SCHEMA_VERSION, - unresolved: [], -}); +export function retainedSandboxRecoveryDocument( + records: readonly RetainedSandboxRecoveryRecord[], +): RetainedSandboxRecoveryState { + return { + schemaVersion: records.some((record) => record.createAuthority !== undefined) + ? CREATE_AUTHORITY_SCHEMA_VERSION + : SCHEMA_VERSION, + unresolved: records, + }; +} + +const emptyState = (): RetainedSandboxRecoveryState => retainedSandboxRecoveryDocument([]); function sameFileIdentity(left: fs.Stats, right: fs.Stats): boolean { return left.dev === right.dev && left.ino === right.ino; @@ -335,7 +384,10 @@ function writeStateFile(filePath: string, state: RetainedSandboxRecoveryState): ); revalidateStateDirectory(directory); temporaryStat = assertTemporaryStateFile(descriptor, temporary); - fs.writeFileSync(descriptor, JSON.stringify(state, null, 2)); + fs.writeFileSync( + descriptor, + JSON.stringify(retainedSandboxRecoveryDocument(state.unresolved), null, 2), + ); fs.fchmodSync(descriptor, 0o600); fs.fsyncSync(descriptor); temporaryStat = assertTemporaryStateFile(descriptor, temporary); @@ -402,8 +454,10 @@ function parseRecord(value: unknown): RetainedSandboxRecoveryRecord | null { const resources = parseEvidence(value.resources); const fingerprint = value.sandboxIdentityFingerprint; const reason = value.reason; + const createAuthority = parseRetainedSandboxCreateAuthority(value.createAuthority); if ( - value.schemaVersion !== SCHEMA_VERSION || + value.schemaVersion !== + (value.createAuthority === undefined ? SCHEMA_VERSION : CREATE_AUTHORITY_SCHEMA_VERSION) || typeof value.recordId !== "string" || !FINGERPRINT_PATTERN.test(value.recordId) || !validSandboxName(value.sandboxName) || @@ -416,6 +470,7 @@ function parseRecord(value: unknown): RetainedSandboxRecoveryRecord | null { typeof value.createAttemptNonce !== "string" || !CREATE_ATTEMPT_NONCE_PATTERN.test(value.createAttemptNonce) || !resources || + (value.createAuthority !== undefined && !createAuthority) || !["cancelled_after_sandbox_creation", "retained_after_sandbox_creation_failure"].includes( String(reason), ) || @@ -424,7 +479,7 @@ function parseRecord(value: unknown): RetainedSandboxRecoveryRecord | null { return null; } return { - schemaVersion: SCHEMA_VERSION, + schemaVersion: createAuthority ? CREATE_AUTHORITY_SCHEMA_VERSION : SCHEMA_VERSION, recordId: value.recordId, sandboxName: value.sandboxName, sandboxIdentityFingerprint: fingerprint, @@ -434,24 +489,39 @@ function parseRecord(value: unknown): RetainedSandboxRecoveryRecord | null { lifecycleGeneration: value.lifecycleGeneration, createAttemptNonce: value.createAttemptNonce, resources, + ...(createAuthority ? { createAuthority } : {}), reason: reason as RetainedSandboxRecoveryReason, recordedAt: value.recordedAt, }; } function loadState(filePath: string): RetainedSandboxRecoveryState { - const value = readStateFile(filePath); - if (!isObjectRecord(value) || value.schemaVersion !== SCHEMA_VERSION) { + let value = readStateFile(filePath); + if ( + isObjectRecord(value) && + Array.isArray(value.unresolved) && + value.unresolved.some( + (record) => isObjectRecord(record) && record.createAuthority !== undefined, + ) + ) { + value = readStateFile(filePath, emptyState(), true); + } + if ( + !isObjectRecord(value) || + ![SCHEMA_VERSION, CREATE_AUTHORITY_SCHEMA_VERSION].includes(Number(value.schemaVersion)) || + typeof value.schemaVersion !== "number" + ) { throw new Error("Retained sandbox recovery state has an unsupported schema."); } const unresolved = Array.isArray(value.unresolved) ? value.unresolved.map(parseRecord) : null; - if (!unresolved || unresolved.includes(null)) { + if ( + !unresolved || + unresolved.includes(null) || + (value.schemaVersion === SCHEMA_VERSION && unresolved.some((record) => record?.createAuthority)) + ) { throw new Error("Retained sandbox recovery state is invalid; onboarding remains blocked."); } - return { - schemaVersion: SCHEMA_VERSION, - unresolved: unresolved as RetainedSandboxRecoveryRecord[], - }; + return retainedSandboxRecoveryDocument(unresolved as RetainedSandboxRecoveryRecord[]); } function recoveryRecordId(input: RecordRetainedSandboxRecoveryInput): string { @@ -478,7 +548,9 @@ function assertRecordInput(input: RecordRetainedSandboxRecoveryInput): void { !validGatewayPort(input.gatewayPort) || (input.lifecycleGeneration !== null && !validSafeEvidence(input.lifecycleGeneration)) || !CREATE_ATTEMPT_NONCE_PATTERN.test(input.createAttemptNonce) || - !parseEvidence(input.resources) + !parseEvidence(input.resources) || + (input.createAuthority !== undefined && + !parseRetainedSandboxCreateAuthority(input.createAuthority)) ) { throw new Error("Cannot persist invalid retained sandbox recovery evidence."); } @@ -496,7 +568,7 @@ export function recordRetainedSandboxRecovery( ): RetainedSandboxRecoveryRecord { assertRecordInput(input); const record: RetainedSandboxRecoveryRecord = { - schemaVersion: SCHEMA_VERSION, + schemaVersion: input.createAuthority ? CREATE_AUTHORITY_SCHEMA_VERSION : SCHEMA_VERSION, recordId: recoveryRecordId(input), sandboxName: input.sandboxName, sandboxIdentityFingerprint: input.sandboxIdentityFingerprint, @@ -506,6 +578,9 @@ export function recordRetainedSandboxRecovery( lifecycleGeneration: input.lifecycleGeneration, createAttemptNonce: input.createAttemptNonce, resources: parseEvidence(input.resources)!, + ...(input.createAuthority + ? { createAuthority: parseRetainedSandboxCreateAuthority(input.createAuthority)! } + : {}), reason: input.reason, recordedAt: input.recordedAt ?? new Date().toISOString(), }; @@ -513,6 +588,10 @@ export function recordRetainedSandboxRecovery( throw new Error("Cannot persist retained sandbox recovery with an invalid timestamp."); } const current = loadState(filePath); + const existing = current.unresolved.find((candidate) => candidate.recordId === record.recordId); + if (existing && !isDeepStrictEqual(existing.createAuthority, record.createAuthority)) { + throw new Error("Cannot replace the original create authority of a retained recovery record."); + } const next: RetainedSandboxRecoveryState = { ...current, unresolved: [ @@ -550,7 +629,59 @@ export function retainedSandboxRecoveryAuthorityIsCurrent( return retainedSandboxRecoveryAuthorityMatchesState(loadState(filePath), expected); } -/** Retire only the unchanged record whose external resources were verified absent. */ +/** Preserve the original tracking without asserting historical runtime cleanup. */ +export function archiveRetainedSandboxRecoveryForLocalDiscard( + filePath: string, + record: RetainedSandboxRecoveryRecord, + reservation: SandboxEntry | null, +): string { + if (!retainedSandboxRecoveryAuthorityIsCurrent(filePath, record)) { + throw new Error("Recovery authority changed before archival."); + } + const archivePath = path.join( + path.dirname(filePath), + ".retained-recovery-archive", + `${record.recordId}.json`, + ); + const directory = openStateDirectory(archivePath, true)!; + try { + const reservationSnapshot: unknown = JSON.parse(JSON.stringify(reservation)); + const missing = Symbol("missing recovery archive"); + const existing = readStateFile(archivePath, missing, true); + if (existing === missing) { + const archive = { + schemaVersion: 1, + operation: "forced-local-recovery-discard", + originalResourceAbsence: "unverified", + record, + reservation: reservationSnapshot, + }; + revalidateStateDirectory(directory); + const published = publishExportFile(archivePath, `${JSON.stringify(archive, null, 2)}\n`); + if (!published.ok) { + throw new Error("Could not durably archive recovery; active metadata was preserved."); + } + } + const archived = readStateFile(archivePath, missing, true); + if ( + !isObjectRecord(archived) || + archived.schemaVersion !== 1 || + archived.operation !== "forced-local-recovery-discard" || + archived.originalResourceAbsence !== "unverified" || + !isDeepStrictEqual(archived.record, record) || + (reservation !== null && !isDeepStrictEqual(archived.reservation, reservationSnapshot)) + ) { + throw new Error("Recovery archive conflicts with the current record or reservation."); + } + revalidateStateDirectory(directory); + fs.fsyncSync(directory.descriptor); + return archivePath; + } finally { + fs.closeSync(directory.descriptor); + } +} + +/** Retire only the unchanged record after its caller qualifies retirement. */ export function resolveRetainedSandboxRecovery( filePath: string, expected: RetainedSandboxRecoveryRecord, diff --git a/src/lib/state/retained-sandbox-recovery.test.ts b/src/lib/state/retained-sandbox-recovery.test.ts index fab7ce53f0e..06f5619d732 100644 --- a/src/lib/state/retained-sandbox-recovery.test.ts +++ b/src/lib/state/retained-sandbox-recovery.test.ts @@ -62,7 +62,15 @@ describe("retained sandbox recovery state", () => { it("records an explicit missing identity", async () => { const recovery = await import("./onboard-session"); + const createAuthority = { + schemaVersion: 1 as const, + runtime: "native-linux-default-docker" as const, + reservationSessionId: "original-session", + gatewayStateDir: path.join(home, "gateway"), + daemonId: "original-daemon", + }; const recorded = recovery.recordRetainedSandboxRecovery({ + createAuthority, sandboxName: "missing-id", sandboxIdentityFingerprint: null, gatewayName: "nemoclaw", @@ -81,6 +89,31 @@ describe("retained sandbox recovery state", () => { sandboxIdentityFingerprint: null, identityWasUnavailable: true, lifecycleGeneration: null, + createAuthority, + }); + expect(recovery.listRetainedSandboxRecoveryRecords()).toEqual([recorded]); + expect( + JSON.parse(fs.readFileSync(recovery.RETAINED_SANDBOX_RECOVERY_FILE, "utf8")).schemaVersion, + ).toBe(2); + expect(() => + recovery.recordRetainedSandboxRecovery({ + ...recorded, + createAuthority: { ...createAuthority, daemonId: "replacement-daemon" }, + }), + ).toThrow(/original create authority/u); + expect(() => + recovery.recordRetainedSandboxRecovery({ + ...recorded, + createAuthority: { ...createAuthority, daemonId: "" }, + }), + ).toThrow(/invalid retained/u); + fs.chmodSync(recovery.RETAINED_SANDBOX_RECOVERY_FILE, 0o644); + expect(() => recovery.listRetainedSandboxRecoveryRecords()).toThrow(/private file/u); + fs.chmodSync(recovery.RETAINED_SANDBOX_RECOVERY_FILE, 0o600); + recovery.resolveRetainedSandboxRecovery(recorded); + expect(JSON.parse(fs.readFileSync(recovery.RETAINED_SANDBOX_RECOVERY_FILE, "utf8"))).toEqual({ + schemaVersion: 1, + unresolved: [], }); }); diff --git a/test/onboarding/onboard-fresh-create-identity.test.ts b/test/onboarding/onboard-fresh-create-identity.test.ts index d5bb4c3a2fd..9bc552b29b5 100644 --- a/test/onboarding/onboard-fresh-create-identity.test.ts +++ b/test/onboarding/onboard-fresh-create-identity.test.ts @@ -91,6 +91,14 @@ describe("fresh create identity", () => { agent: null, expectedOutcome: "identity-mismatch-refusal" as const, }, + { + title: "retires the persisted identity-free recovery record after gateway restart (#13071)", + apfInterceptorRequested: false, + provider: "nvidia-prod", + model: "gpt-5.4", + agent: { name: "openclaw" }, + expectedOutcome: "identity-free-recovery-authority" as const, + }, { title: "retains recovery state when the create runner fails after verification (#9833)", apfInterceptorRequested: true, @@ -163,19 +171,25 @@ describe("fresh create identity", () => { agent: null, expectedOutcome: "cancel-after-create-custom-presets" as const, }, - ].flatMap( - (testCase): (Omit & { agent: { name: string } | null })[] => - testCase.agent || testCase.expectedOutcome.startsWith("cancel-after-create-") - ? [testCase] - : [ - testCase, - { - ...testCase, - title: testCase.title.replace(/ \(#\d+\)$/, " for Hermes (#11548)"), - agent: { name: "hermes" }, - }, - ], - ), + ] + .filter( + (testCase) => + testCase.expectedOutcome !== "identity-free-recovery-authority" || + process.platform === "linux", + ) + .flatMap( + (testCase): (Omit & { agent: { name: string } | null })[] => + testCase.agent || testCase.expectedOutcome.startsWith("cancel-after-create-") + ? [testCase] + : [ + testCase, + { + ...testCase, + title: testCase.title.replace(/ \(#\d+\)$/, " for Hermes (#11548)"), + agent: { name: "hermes" }, + }, + ], + ), )( "$title", { @@ -308,8 +322,8 @@ let routeReservationCalls = 0; const keepAlive = setInterval(() => {}, 1000); const apfInterceptorRequested = ${JSON.stringify(apfInterceptorRequested)}; const requestedAgent = ${JSON.stringify(agent)}; -const agent = requestedAgent?.name === "hermes" - ? require(${JSON.stringify(path.join(repoRoot, "src/lib/agent/defs.ts"))}).loadAgent("hermes") +const agent = requestedAgent?.name === "hermes" || requestedAgent?.name === "openclaw" + ? require(${JSON.stringify(path.join(repoRoot, "src/lib/agent/defs.ts"))}).loadAgent(requestedAgent.name) : requestedAgent; const model = ${JSON.stringify(model)}; const provider = ${JSON.stringify(provider)}; @@ -324,6 +338,23 @@ const recoveryReentry = process.env.NEMOCLAW_RECOVERY_REENTRY || ""; const identityMismatchRefusal = ${JSON.stringify(expectedOutcome === "identity-mismatch-refusal")}; const stagedMessagingRefusal = ${JSON.stringify(expectedOutcome === "staged-messaging-refusal")}; const postCreateRunnerRefusal = ${JSON.stringify(expectedOutcome === "post-create-runner-refusal")}; +const identityFreeRecoveryAuthority = ${JSON.stringify(expectedOutcome === "identity-free-recovery-authority")}; +let daemonObserved = false; +let daemonObservedAtCreate = false; +if (identityFreeRecoveryAuthority) { + process.env.DOCKER_HOST = "unix:///var/run/docker.sock"; + process.env.NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR = ${JSON.stringify(path.join(tmpDir, "gateway-state"))}; + require(${JSON.stringify(path.join(repoRoot, "src/lib/onboard/docker-driver-gateway-runtime-marker.ts"))}) + .writeDockerDriverGatewayRuntimeMarkerForStateDir(process.env.NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR, { + pid: 4242, desiredEnv: {}, endpoint: ${JSON.stringify(`https://127.0.0.1:${gatewayPort}`)}, + createdAt: new Date(Date.now() - 1000).toISOString(), runtimeProviderId: "docker", + }); + require(${JSON.stringify(path.join(repoRoot, "src/lib/adapters/docker/run.ts"))}).dockerRun = (args) => { + require("node:assert/strict").deepEqual(args, ["--context", "default", "info", "--format", "{{.ID}}"]); + daemonObserved = true; + return { status: 0, stdout: "fixture-recovery-daemon", stderr: "" }; + }; +} const postCreateRegistrationRefusal = ${JSON.stringify( expectedOutcome === "post-create-registration-refusal" || expectedOutcome === "post-create-registration-recovery-readback-failure" || @@ -370,6 +401,10 @@ runner.run = (command, opts = {}) => { runner.runCapture = (command) => { const cmd = _n(command); if (cmd.includes("gateway info")) return ${JSON.stringify(`Gateway endpoint: http://127.0.0.1:${gatewayPort}`)}; + if (identityFreeRecoveryAuthority && createdSandbox.state.lifecycleState === "created" && + (cmd.includes("sandbox get") || cmd.includes("--selector"))) { + throw Object.assign(new Error("gateway disconnected after create"), { code: 1 }); + } if (cmd.includes("policy get") && cmd.includes("--output json")) { if (postCreatePolicyChange && registeredSandbox) { throw new Error("final onboarding policy check failed"); @@ -467,6 +502,7 @@ managedWorkloadOnboard.createManagedStateVolumeOnboardLifecycle = (input, deps = sessionId: "session-owner", sandboxName: "my-assistant", agent: agent?.name ?? "openclaw", + ...(identityFreeRecoveryAuthority ? { provider, model } : {}), }); retainedRecovery.saveSession(session); registry.save({ @@ -513,6 +549,7 @@ managedWorkloadOnboard.createManagedStateVolumeOnboardLifecycle = (input, deps = } const durableGetSandbox = registry.getSandbox.bind(registry); const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + durableRegistry: identityFreeRecoveryAuthority, sandboxName: "my-assistant", gatewayName: ${JSON.stringify(gatewayName)}, gatewayPort: ${String(gatewayPort)}, @@ -571,6 +608,7 @@ process.kill = (pid, signal) => { childProcess.spawn = (...args) => { const command = [args[0], ...(Array.isArray(args[1]) ? args[1] : [])]; + daemonObservedAtCreate = daemonObserved; createdSandbox.create(command); if (_n(command).includes("sandbox create")) _deleted = false; const child = new EventEmitter(); @@ -600,6 +638,7 @@ childProcess.spawn = (...args) => { process.nextTick(() => { child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); child.stderr.emit("data", Buffer.from("Setting up NemoClaw...\n")); + if (identityFreeRecoveryAuthority) child.emit("close", 0); }); return child; }; @@ -644,6 +683,8 @@ const writePayload = (sandboxName, creationError, exitCode = 0) => { deleted: _deleted, sandboxCreated: createdSandbox.state.lifecycleState === "created", sandboxId: createdSandbox.state.sandboxId, + createAttemptNonce: createdSandbox.state.createAttemptNonce, + daemonObservedAtCreate, sandboxListCalls, killCalls: createCommand?.child?.killCalls ?? [], groupKillCalls, @@ -809,7 +850,7 @@ if (${JSON.stringify( writePayload(sandboxName, null); } catch (error) { if (cancelAfterCreate) throw error; - if (!apfInterceptorRequested) throw error; + if (!apfInterceptorRequested && !identityFreeRecoveryAuthority) throw error; finalCreationError = error instanceof Error ? error.message : String(error); writePayload(null, finalCreationError); } @@ -1046,6 +1087,99 @@ if (${JSON.stringify( "expected recovery output to report the exact create-attempt label", ); }; + const assertIdentityFreeRecoveryAuthority = async () => { + assert.equal(payload.daemonObservedAtCreate, true); + assert.equal(payload.registeredSandbox, null); + assert.equal(payload.deleted, false); + assert.equal(payload.retainedRecoveryRecords.length, 1); + const record = payload.retainedRecoveryRecords[0]; + assert.equal(record.schemaVersion, 2); + assert.equal(record.sandboxIdentityFingerprint, null); + assert.equal(record.createAttemptNonce, payload.createAttemptNonce); + assert.deepEqual(record.createAuthority, { + schemaVersion: 1, + runtime: "native-linux-default-docker", + reservationSessionId: "session-owner", + gatewayStateDir: path.join(tmpDir, "gateway-state"), + daemonId: "fixture-recovery-daemon", + }); + assert.deepEqual(record.resources.sharedInferenceProviders, [provider]); + const recoveryScriptPath = path.join(tmpDir, "destroy-retained-recovery.js"); + fs.writeFileSync( + recoveryScriptPath, + String.raw` +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const session = require(${retainedRecoveryPath}); +const registry = require(${registryPath}); +const producer = JSON.parse(fs.readFileSync(${JSON.stringify(payloadPath)}, "utf8")); +const original = producer.retainedRecoveryRecords[0]; +assert.deepEqual(session.listRetainedSandboxRecoveryRecords(), [original]); +assert.deepEqual(registry.getSandbox("my-assistant"), producer.recoveryRegistryEntry); +const marker = require(${JSON.stringify(path.join(repoRoot, "src/lib/onboard/docker-driver-gateway-runtime-marker.ts"))}); +marker.writeDockerDriverGatewayRuntimeMarkerForStateDir(process.env.NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR, { + pid: 4243, desiredEnv: {}, endpoint: ${JSON.stringify(`https://127.0.0.1:${gatewayPort}`)}, + createdAt: new Date(Date.parse(original.recordedAt) + 1000).toISOString(), runtimeProviderId: "docker", +}); +session.saveSession(session.createSession({ + sessionId: "other-session", sandboxName: "other-sandbox", agent: "openclaw", + provider: ${JSON.stringify(provider)}, model: ${JSON.stringify(model)}, +})); +registry.reserveSandboxInferenceRoute("other-sandbox", { + gatewayName: ${JSON.stringify(gatewayName)}, reservationSessionId: "other-session", + provider: ${JSON.stringify(provider)}, model: ${JSON.stringify(model)}, + endpointUrl: null, credentialEnv: null, preferredInferenceApi: null, +}); +session.markRetainedSandboxRecovery("other-sandbox", "unrelated recovery", undefined, { + gatewayName: ${JSON.stringify(gatewayName)}, gatewayPort: ${String(gatewayPort)}, + lifecycleGeneration: "other-generation", createAttemptNonce: "b".repeat(62), +}); +const controlRecord = session.listRetainedSandboxRecoveryRecords().find((entry) => entry.sandboxName === "other-sandbox"); +const controlReservation = registry.getSandbox("other-sandbox"); +const controlSession = fs.readFileSync(session.SESSION_FILE, "utf8"); +const runtimeFile = marker.getDockerDriverGatewayRuntimeMarkerPath(process.env.NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR); +const runtimeBefore = fs.readFileSync(runtimeFile, "utf8"); +assert.deepEqual(session.listRetainedSandboxRecoveryRecords().find((entry) => entry.sandboxName === "my-assistant"), original); +let cleanupCalls = 0; +const forbidCleanup = () => { cleanupCalls += 1; throw new Error("Unexpected resource cleanup"); }; +require(${runnerPath}).run = forbidCleanup; +const runtime = require(${JSON.stringify(path.join(repoRoot, "src/lib/adapters/openshell/runtime.ts"))}); +runtime.runOpenshell = forbidCleanup; +runtime.captureOpenshell = (args) => { + assert.deepEqual(args, ["sandbox", "list", "-g", ${JSON.stringify(gatewayName)}, "--output", "json"]); + return { status: 0, output: "[]", stdout: "[]", stderr: "" }; +}; +require(${JSON.stringify(path.join(repoRoot, "src/lib/adapters/docker/run.ts"))}).dockerRun = (args) => { + assert.deepEqual(args.slice(0, 2), ["--context", "default"]); + if (args[2] !== "info" && args[2] !== "ps" && !(args[2] === "volume" && args[3] === "ls")) return forbidCleanup(); + return { status: 0, stdout: args[2] === "info" ? "fixture-recovery-daemon" : "", stderr: "" }; +}; +require(${JSON.stringify(path.join(repoRoot, "src/lib/actions/sandbox/destroy-preflight.ts"))}).prepareSandboxDestroy = forbidCleanup; +require(${JSON.stringify(path.join(repoRoot, "src/lib/actions/sandbox/destroy-confirmation.ts"))}).confirmSandboxDestroy = async () => true; +(async () => { + await require(${JSON.stringify(path.join(repoRoot, "src/lib/actions/sandbox/destroy.ts"))}).destroySandbox("my-assistant", { yes: true }); + assert.equal(registry.getSandbox("my-assistant"), null); + assert.deepEqual(session.listRetainedSandboxRecoveryRecords(), [controlRecord]); + assert.deepEqual(registry.getSandbox("other-sandbox"), controlReservation); + assert.equal(fs.readFileSync(session.SESSION_FILE, "utf8"), controlSession); + assert.equal(fs.readFileSync(runtimeFile, "utf8"), runtimeBefore); + assert.equal(cleanupCalls, 0); + assert.equal(fs.existsSync(path.join(path.dirname(session.RETAINED_SANDBOX_RECOVERY_FILE), ".retained-recovery-archive")), false); +})().catch((error) => { console.error(error); process.exit(1); }); +`, + ); + const recovery = await runNodeScript(recoveryScriptPath, { + cwd: repoRoot, + env: { + ...childEnv, + DOCKER_HOST: "unix:///var/run/docker.sock", + NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR: path.join(tmpDir, "gateway-state"), + }, + timeout: 30000, + }); + assert.equal(recovery.status, 0, `${recovery.stdout}\n${recovery.stderr}`); + }; const assertPostCreateRunnerRefusal = () => { assert.equal(payload.sandboxName, null); assert.equal(payload.sandboxCreated, true); @@ -1306,6 +1440,7 @@ if (${JSON.stringify( "resolved-agent-refusal": assertUnsupportedAgentRefusal, "providerless-apf": assertProviderlessApfCreation, "identity-mismatch-refusal": assertIdentityMismatchRefusal, + "identity-free-recovery-authority": assertIdentityFreeRecoveryAuthority, "post-create-runner-refusal": assertPostCreateRunnerRefusal, "post-create-registration-refusal": assertPostCreateRegistrationRefusal, "post-create-registration-recovery-readback-failure":