Skip to content
Merged
11 changes: 9 additions & 2 deletions docs/reference/commands.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -2168,6 +2170,11 @@ If you want to upgrade the sandbox while preserving state, use `$$nemoclaw <name

If another terminal has an active SSH session to the sandbox, `destroy` prints an active-session warning and requires a second confirmation before it proceeds. Pass `--yes`, `-y`, or `--force`, or set `NEMOCLAW_NON_INTERACTIVE=1`, to authorize deletion without prompting in scripted workflows. These controls do not suppress the active-session warning. The warning lists the detected process IDs, and destroy still terminates those sessions with a `Broken pipe` error.

For eligible recovery without a sandbox identity on native Linux with default Docker, `--force` archives and removes local tracking after the owning gateway and current Docker daemon confirm absence.
It preserves runtime resources and shared providers; cleanup on the original runtime remains unverified.
A conflicting active session for the same name, sandbox-scoped providers, or additional resource ownership still blocks this operation.
The command prints the private archive path and keeps the archive after recovery.

Before changing a Docker-backed sandbox, NemoClaw inspects every container with the requested `openshell.ai/sandbox-name` label. The command continues when Docker returns no matching containers. For one matching container, the command continues only when all these labels have the required values:

- `openshell.ai/managed-by=openshell`
Expand Down
4 changes: 3 additions & 1 deletion src/commands/sandbox/destroy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ export default class DestroyCliCommand extends NemoClawCommand {
};
static flags = {
yes: yesFlag(),
force: forceFlag(),
force: forceFlag(
"Skip confirmation. For eligible recovery records with no sandbox identity, archive and remove local tracking after current absence checks. Original runtime cleanup remains unverified.",
),
"cleanup-gateway": Flags.boolean({
description:
"When destroying the last sandbox, also tear down the shared NemoClaw gateway. Default: preserve on Linux; cleanup for unattended macOS destroys. NEMOCLAW_CLEANUP_GATEWAY overrides the platform default.",
Expand Down
2 changes: 2 additions & 0 deletions src/lib/actions/sandbox/destroy-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ interface ResolveGatewayCleanupRuntimeProviderDeps extends Pick<
configuredRuntimeProviderId?: string | null;
requireOwnedRuntime?: boolean;
recoveryRecordedAt?: string;
requireDefaultDockerDaemon?: boolean;
}

// Compute the Docker-driver gateway state directory that belongs to
Expand Down Expand Up @@ -101,6 +102,7 @@ export function resolveGatewayCleanupRuntimeProviderId(
...(deps.recoveryRecordedAt !== undefined
? { recoveryRecordedAt: deps.recoveryRecordedAt }
: {}),
...(deps.requireDefaultDockerDaemon ? { requireDefaultDockerDaemon: true } : {}),
},
);
if (deps.requireOwnedRuntime && !recorded) return null;
Expand Down
1 change: 1 addition & 0 deletions src/lib/actions/sandbox/destroy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,7 @@ async function destroySandboxUnlocked(
{
session: onboardSession,
registry,
forceLocal: normalized.force === true,
...(retireRemovedImmutabilityState
? {
retireRemovedImmutabilityState: () => {
Expand Down
203 changes: 173 additions & 30 deletions src/lib/actions/sandbox/lifecycle/retained-recovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -125,6 +136,9 @@ async function setup(port = 19260, dockerHost?: string) {
capture,
containers,
volumes,
setDaemonId: (value: string) => {
daemonId = value;
},
clearRuntime: () => clearDockerDriverGatewayRuntimeMarker(stateDir),
writeRuntime,
snapshot,
Expand Down Expand Up @@ -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,
Expand All @@ -168,6 +182,131 @@ async function setupDestroy(port = 19260) {
}

describe.skipIf(process.platform !== "linux")("identity-free retained recovery", () => {
type Harness = Awaited<ReturnType<typeof setup>>;

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) => {
Expand Down Expand Up @@ -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);
Expand Down
Loading