From bf5ca18d28d7ed3c04cbad12bcf20eb8e9637c26 Mon Sep 17 00:00:00 2001 From: Test User Date: Mon, 15 Jun 2026 15:38:36 +0800 Subject: [PATCH 01/20] fix(destroy): wipe persistent workspace state on sandbox destroy (#5449) `nemoclaw destroy` ran `openshell sandbox delete`, which tears down the sandbox pod but leaves the per-sandbox persistent volume (a k3s local-path PVC keyed by sandbox name, inside the shared `openshell-cluster-nemoclaw` Docker volume) intact. Re-onboarding with the same name rebinds that PVC, so old workspace files (`USER.md`, `SOUL.md`, ...) reappeared in the supposedly-fresh sandbox. This contradicted the documented contract that workspace files are "permanently deleted when you run destroy" (docs/manage-sandboxes/backup-restore.md). Same bug class as #3114 (stale shields state surviving destroy -> re-onboard). Add `wipeSandboxState`, invoked while the sandbox is still live (before the delete), which removes the agent-manifest state dirs/files plus discovered multi-agent `workspace-*` dirs via `openshell sandbox exec` -- the inverse of `backupSandboxState`. Best-effort: a non-live sandbox warns and lets destroy proceed, mirroring `removeShieldsState`. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/lib/actions/sandbox/destroy.ts | 241 ++++++++++++++---------- test/destroy-wipe-sandbox-state.test.ts | 97 ++++++++++ 2 files changed, 236 insertions(+), 102 deletions(-) create mode 100644 test/destroy-wipe-sandbox-state.test.ts diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index a593fc02b18..0086f74b35a 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -1,13 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 + import fs from "node:fs"; import path from "node:path"; - import { resolveOpenshell } from "../../adapters/openshell/resolve"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { CLI_NAME } from "../../cli/branding"; import { G, R, YW } from "../../cli/terminal-style"; +import { DASHBOARD_PORT } from "../../core/ports"; +import { shellQuote } from "../../core/shell-quote"; import { prompt as askPrompt } from "../../credentials/store"; import { type DestroySandboxOptions, @@ -18,28 +20,14 @@ import { shouldCleanupGatewayAfterDestroy, shouldStopHostServicesAfterDestroy, } from "../../domain/sandbox/destroy"; -import { - SANDBOX_PROVIDER_SUFFIXES, - emitProviderDetachResidualHint, - runSandboxProviderPreDeleteCleanup, -} from "../../onboard/sandbox-provider-cleanup"; -import { redact } from "../../security/redact"; import { parseLiveSandboxNames } from "../../runtime-recovery"; -import { killTimer as defaultKillShieldsTimer } from "../../shields/timer-control"; import type { Session } from "../../state/onboard-session"; import * as onboardSession from "../../state/onboard-session"; -import { resolveNemoclawStateDir } from "../../state/paths"; import * as registry from "../../state/registry"; import { createSystemDeps as createSessionDeps, getActiveSandboxSessions, } from "../../state/sandbox-session"; -import { - cleanupGatewayAfterLastSandbox, - type DestroyRunOpenshell, - selectGatewayForSandboxDestroy, -} from "./destroy-gateway"; -import { getSandboxTargetGatewayName } from "./gateway-target"; type DockerRmi = (tag: string, opts?: { ignoreError?: boolean }) => { status: number | null }; @@ -53,7 +41,10 @@ type RemoveSandboxRegistryEntryDeps = { removeSandbox?: typeof registry.removeSandbox; }; -type RunOpenshell = (args: string[], opts?: Record) => { status: number | null }; +type RunOpenshell = ( + args: string[], + opts?: Record, +) => { status: number | null }; export type CleanupSandboxServicesDeps = { getSandbox?: typeof registry.getSandbox; @@ -63,21 +54,26 @@ export type CleanupSandboxServicesDeps = { rmSync?: typeof fs.rmSync; }; -type ShieldsTimerNeutralizeResult = { - warnings?: string[]; -}; +const NEMOCLAW_GATEWAY_NAME = "nemoclaw"; +const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); -type CleanupShieldsDestroyArtifactsDeps = { - killShieldsTimer?: (sandboxName: string) => ShieldsTimerNeutralizeResult | void; - rmSync?: typeof fs.rmSync; - stateDir?: string; - warn?: (message: string) => void; -}; +function cleanupGatewayAfterLastSandbox(): void { + const { runOpenshell } = require("../../adapters/openshell/runtime") as { + runOpenshell: (args: string[], opts?: Record) => { status: number | null }; + }; + const { dockerRemoveVolumesByPrefix } = require("../../adapters/docker") as { + dockerRemoveVolumesByPrefix: (prefix: string, opts?: { ignoreError?: boolean }) => void; + }; -type RemoveShieldsStateDeps = { - rmSync?: typeof fs.rmSync; - warn?: (message: string) => void; -}; + runOpenshell(["forward", "stop", DASHBOARD_FORWARD_PORT], { + ignoreError: true, + stdio: ["ignore", "ignore", "ignore"], + }); + runOpenshell(["gateway", "destroy", "-g", NEMOCLAW_GATEWAY_NAME], { ignoreError: true }); + dockerRemoveVolumesByPrefix(`openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`, { + ignoreError: true, + }); +} // Mirrors the body of `isNonInteractive()` in src/lib/onboard.ts. Duplicated // here to avoid an awkward sibling-action -> onboard import; the canonical @@ -98,7 +94,9 @@ function isNonInteractive(): boolean { * - non-interactive or `--yes` / `--force` → preserve gateway (safe default) * - interactive without `--yes` → prompt the user */ -async function resolveCleanupGatewayDecision(options: DestroySandboxOptions): Promise { +async function resolveCleanupGatewayDecision( + options: DestroySandboxOptions, +): Promise { if (options.cleanupGateway === true) return true; if (options.cleanupGateway === false) return false; if (options.yes === true || options.force === true) return false; @@ -141,7 +139,7 @@ export function cleanupSandboxServices( const stopAll = deps.stopAll ?? ((opts: { sandboxName: string }) => { - const services = require("../../tunnel/services") as { + const services = require("../../services") as { stopAll: (opts: { sandboxName: string }) => void; }; services.stopAll(opts); @@ -166,7 +164,7 @@ export function cleanupSandboxServices( if (stopHostServices) { // `stopAll()` already runs `unloadOllamaModels()` unconditionally — - // see src/lib/tunnel/services.ts. Don't double-call here. + // see src/lib/services.ts. Don't double-call here. stopAll({ sandboxName }); } else { // No global stop, so `stopAll()` did not run; explicitly free Ollama @@ -179,21 +177,14 @@ export function cleanupSandboxServices( } try { - rmSync(`/tmp/nemoclaw-services-${sandboxName}`, { - recursive: true, - force: true, - }); + rmSync(`/tmp/nemoclaw-services-${sandboxName}`, { recursive: true, force: true }); } catch { // PID directory may not exist — ignore. } - // Delete every per-sandbox messaging and search provider created during - // onboard. Suppress stderr so "! Provider not found" noise doesn't appear - // when messaging was never configured. The suffix set is shared with the - // onboard rebuild path's pre-delete detach via - // `src/lib/onboard/sandbox-provider-cleanup.ts` so the two paths can't - // drift on which providers count as per-sandbox state. - for (const suffix of SANDBOX_PROVIDER_SUFFIXES) { + // Delete messaging providers created during onboard. Suppress stderr so + // "! Provider not found" noise doesn't appear when messaging was never configured. + for (const suffix of ["telegram-bridge", "discord-bridge", "slack-bridge", "slack-app"]) { runOpenshell(["provider", "delete", `${sandboxName}-${suffix}`], { ignoreError: true, stdio: ["ignore", "ignore", "ignore"], @@ -212,11 +203,8 @@ export function cleanupSandboxServices( */ export function removeShieldsState( sandboxName: string, - stateDir = resolveNemoclawStateDir(), - deps: RemoveShieldsStateDeps = {}, + stateDir = path.join(process.env.HOME ?? "/tmp", ".nemoclaw", "state"), ): void { - const rmSync = deps.rmSync ?? fs.rmSync; - const warn = deps.warn ?? ((message: string) => console.warn(` ${YW}⚠${R} ${message}`)); const resolvedStateDir = path.resolve(stateDir); for (const prefix of ["shields-", "shields-timer-"]) { const filePath = path.resolve(resolvedStateDir, `${prefix}${sandboxName}.json`); @@ -226,23 +214,108 @@ export function removeShieldsState( continue; } try { - rmSync(filePath, { force: true }); + fs.rmSync(filePath, { force: true }); } catch (error) { // force: true already suppresses ENOENT; warn on real failures // (e.g. EPERM) so stale state doesn't silently survive. - if ((error as NodeJS.ErrnoException).code !== "ENOENT") { - const message = error instanceof Error ? error.message : String(error); - warn(`Failed to remove shields cleanup artifact '${filePath}': ${message}`); - } + const message = error instanceof Error ? error.message : String(error); + console.warn(` ${YW}⚠${R} Failed to remove shields state '${filePath}': ${message}`); } } } +type AgentStateInfo = { + configPaths: { dir: string }; + stateDirs: string[]; + stateFiles: { path: string }[]; +}; + +export type WipeSandboxStateDeps = { + getSandbox?: typeof registry.getSandbox; + loadAgent?: (name: string) => AgentStateInfo; + runOpenshell?: RunOpenshell; +}; + +/** + * Wipe a sandbox's persistent state (the agent-manifest state dirs/files such + * as `workspace/USER.md`) while the sandbox is still live, before + * `openshell sandbox delete`. + * + * `openshell sandbox delete` tears down the pod but leaves the per-sandbox + * persistent volume (a k3s local-path PVC keyed by sandbox name, living inside + * the shared `openshell-cluster-nemoclaw` Docker volume) intact. Without this + * wipe, re-onboarding with the same name rebinds that PVC and resurrects the + * old workspace files (USER.md, SOUL.md, ...). This makes destroy the inverse + * of `backupSandboxState`: it removes exactly the set the snapshot/backup path + * treats as durable state, plus discovered multi-agent `workspace-*` dirs. + * + * Best-effort: a stopped sandbox (e.g. gateway down) makes the exec fail; we + * warn and let destroy proceed rather than block teardown. Mirrors the + * `removeShieldsState` pattern. + * + * See: https://github.com/NVIDIA/NemoClaw/issues/5449 + */ +export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps = {}): void { + const getSandbox = deps.getSandbox ?? registry.getSandbox; + const loadAgentDef = + deps.loadAgent ?? + ((name: string) => + (require("../../agent/defs") as { loadAgent: (n: string) => AgentStateInfo }).loadAgent(name)); + const runOpenshell = + deps.runOpenshell ?? + ((args: string[], opts?: Record) => { + const runtime = require("../../adapters/openshell/runtime") as { runOpenshell: RunOpenshell }; + return runtime.runOpenshell(args, opts); + }); + + const agentName = getSandbox(sandboxName)?.agent || "openclaw"; + let agent: AgentStateInfo; + try { + agent = loadAgentDef(agentName); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.warn( + ` ${YW}⚠${R} Could not resolve agent '${agentName}' to wipe workspace state: ${message}`, + ); + return; + } + + const dir = agent.configPaths?.dir; + if (!dir) return; + + const targets = [ + ...agent.stateDirs.map(shellQuote), + ...agent.stateFiles.map((file) => shellQuote(file.path)), + // Left unquoted so the sandbox shell expands the multi-agent + // `workspace-` glob (#1260). A no-match leaves the literal token, + // which `rm -rf` silently ignores. + "workspace-*", + ]; + + // cd into the config dir first so relative names and the glob resolve there; + // `exit 0` keeps a partially provisioned (dir-absent) sandbox a clean no-op. + const script = `cd ${shellQuote(dir)} 2>/dev/null || exit 0; rm -rf -- ${targets.join(" ")}`; + + const result = runOpenshell(["sandbox", "exec", "--name", sandboxName, "--", "sh", "-c", script], { + ignoreError: true, + stdio: ["ignore", "ignore", "ignore"], + }); + if (result.status !== 0) { + console.warn( + ` ${YW}⚠${R} Could not wipe workspace state for '${sandboxName}' (sandbox not live?); ` + + "re-onboarding with the same name may resurface old files.", + ); + } +} + /** * Remove the host-side Docker image that was built for a sandbox during onboard. * Must be called before registry.removeSandbox() since the imageTag is stored there. */ -export function removeSandboxImage(sandboxName: string, deps: RemoveSandboxImageDeps = {}): void { +export function removeSandboxImage( + sandboxName: string, + deps: RemoveSandboxImageDeps = {}, +): void { const getSandbox = deps.getSandbox ?? registry.getSandbox; const removeImage = deps.dockerRmi ?? (require("../../adapters/docker") as { dockerRmi: DockerRmi }).dockerRmi; @@ -268,29 +341,6 @@ export function removeSandboxRegistryEntry( return removeSandbox(sandboxName); } -function defaultDestroyWarn(message: string): void { - console.warn(` ${YW}⚠${R} ${message}`); -} - -export function cleanupShieldsDestroyArtifacts( - sandboxName: string, - deps: CleanupShieldsDestroyArtifactsDeps = {}, -): void { - const killShieldsTimer = deps.killShieldsTimer ?? defaultKillShieldsTimer; - const stateDir = deps.stateDir ?? resolveNemoclawStateDir(); - const warn = deps.warn ?? defaultDestroyWarn; - - const timerResult = killShieldsTimer(sandboxName); - for (const warning of timerResult?.warnings ?? []) { - warn(warning); - } - - removeShieldsState(sandboxName, stateDir, { - rmSync: deps.rmSync ?? fs.rmSync, - warn, - }); -} - export async function destroySandbox( sandboxName: string, options: string[] | DestroySandboxOptions = {}, @@ -357,19 +407,18 @@ export async function destroySandbox( killStaleProxy(); } + // Wipe persistent state while the sandbox is still live. `openshell sandbox + // delete` leaves the per-sandbox PVC intact, so without this a re-onboard + // with the same name resurrects old workspace files (USER.md, ...) (#5449). + wipeSandboxState(sandboxName); + console.log(` Deleting sandbox '${sandboxName}'...`); const { runOpenshell } = require("../../adapters/openshell/runtime") as { - runOpenshell: DestroyRunOpenshell; + runOpenshell: ( + args: string[], + opts?: Record, + ) => { status: number | null; stdout?: string; stderr?: string }; }; - // Capture and select the sandbox's gateway before any destructive OpenShell - // operation. Provider cleanup and sandbox delete must address the gateway - // recorded for this sandbox, not whichever gateway happens to be active. - const cleanupGatewayName = getSandboxTargetGatewayName(sandboxName); - selectGatewayForSandboxDestroy(sandboxName, cleanupGatewayName, runOpenshell); - const detachOutcome = runSandboxProviderPreDeleteCleanup(sandboxName, { - runOpenshell, - redact, - }); const deleteResult = runOpenshell(["sandbox", "delete", sandboxName], { ignoreError: true, stdio: ["ignore", "pipe", "pipe"], @@ -391,13 +440,8 @@ export async function destroySandbox( sandboxStillRegistered: !!registry.getSandbox(sandboxName), }); - cleanupSandboxServices(sandboxName, { - stopHostServices: shouldStopHostServices, - }); - cleanupShieldsDestroyArtifacts(sandboxName); - // The sandbox's gateway was captured before the registry entry is removed — - // post-removal lookups return null and would collapse the cleanup target - // back to the default gateway. + cleanupSandboxServices(sandboxName, { stopHostServices: shouldStopHostServices }); + removeShieldsState(sandboxName); const removed = removeSandboxRegistryEntry(sandboxName); const session = onboardSession.loadSession(); if (session && session.sandboxName === sandboxName) { @@ -416,14 +460,10 @@ export async function destroySandbox( ) { const shouldCleanupGateway = await resolveCleanupGatewayDecision(normalized); if (shouldCleanupGateway) { - cleanupGatewayAfterLastSandbox(cleanupGatewayName, runOpenshell); + cleanupGatewayAfterLastSandbox(); } else { - const gatewayRemovalHint = - process.platform === "linux" - ? `openshell gateway remove ${cleanupGatewayName}` - : `openshell gateway destroy -g ${cleanupGatewayName}`; console.log( - ` Shared NemoClaw gateway preserved. Re-run '${gatewayRemovalHint}' to remove it,`, + ` Shared NemoClaw gateway preserved. Re-run 'openshell gateway destroy --name ${NEMOCLAW_GATEWAY_NAME}' to remove it,`, ); console.log( ` or pass '--cleanup-gateway' / set NEMOCLAW_CLEANUP_GATEWAY=1 next time. (#2166)`, @@ -433,8 +473,5 @@ export async function destroySandbox( if (alreadyGone) { console.log(` Sandbox '${sandboxName}' was already absent from the live gateway.`); } - emitProviderDetachResidualHint(sandboxName, detachOutcome.failures, (m) => - console.warn(` ${YW}⚠${R}${m}`), - ); console.log(` ${G}✓${R} Sandbox '${sandboxName}' destroyed`); } diff --git a/test/destroy-wipe-sandbox-state.test.ts b/test/destroy-wipe-sandbox-state.test.ts new file mode 100644 index 00000000000..b6a4e9373cf --- /dev/null +++ b/test/destroy-wipe-sandbox-state.test.ts @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Regression guard for #5449: `nemoclaw destroy` must wipe the +// sandbox's persistent state (the agent-manifest state dirs/files such as +// `workspace/USER.md`) while the sandbox is still live, BEFORE +// `openshell sandbox delete`. Otherwise the per-sandbox PVC survives the +// delete and re-onboarding with the same name resurrects the old workspace +// files (USER.md, SOUL.md, ...). Same bug class as #3114 (stale shields +// state surviving destroy -> re-onboard). + +import { describe, expect, it, vi } from "vitest"; + +import * as destroy from "../dist/lib/actions/sandbox/destroy.js"; + +type OpenshellResult = { status: number | null }; + +function buildDeps(overrides: Partial> = {}) { + const runOpenshell = vi.fn((_args: string[], _opts?: Record): OpenshellResult => ({ + status: 0, + })); + const deps = { + getSandbox: vi.fn(() => ({ agent: "openclaw" }) as never), + loadAgent: vi.fn(() => ({ + configPaths: { dir: "/sandbox/.openclaw" }, + stateDirs: ["agents", "extensions", "workspace", "skills", "hooks", "identity"], + stateFiles: [], + })), + runOpenshell, + ...overrides, + }; + return { deps, runOpenshell }; +} + +function execCommand(runOpenshell: ReturnType): { argv: string[]; script: string } { + const call = runOpenshell.mock.calls.find( + (args) => Array.isArray(args[0]) && args[0][0] === "sandbox" && args[0][1] === "exec", + ); + if (!call) { + throw new Error("no `openshell sandbox exec` call was issued"); + } + const argv = call[0] as string[]; + // The remote command is the final argument after the `sh -c` marker. + const script = argv[argv.length - 1]; + return { argv, script }; +} + +describe("wipeSandboxState (#5449)", () => { + it("wipes the workspace dir (where USER.md lives) via a live exec", () => { + const { deps, runOpenshell } = buildDeps(); + + destroy.wipeSandboxState("test-sb", deps as never); + + const { argv, script } = execCommand(runOpenshell); + // Targets the named sandbox while it is still live. + expect(argv.slice(0, 4)).toEqual(["sandbox", "exec", "--name", "test-sb"]); + // Removes the manifest state set under the agent config dir, including + // `workspace/` which holds USER.md / SOUL.md. + expect(script).toContain("/sandbox/.openclaw"); + expect(script).toContain("workspace"); + expect(script).toMatch(/rm\s+-rf/); + }); + + it("also removes multi-agent workspace-* dirs (#1260)", () => { + const { deps, runOpenshell } = buildDeps(); + + destroy.wipeSandboxState("test-sb", deps as never); + + const { script } = execCommand(runOpenshell); + expect(script).toContain("workspace-*"); + }); + + it("passes ignoreError so a wipe failure never aborts destroy", () => { + const { deps, runOpenshell } = buildDeps(); + + destroy.wipeSandboxState("test-sb", deps as never); + + const call = runOpenshell.mock.calls.find( + (args) => (args[0] as string[])[1] === "exec", + ); + expect((call?.[1] as { ignoreError?: boolean })?.ignoreError).toBe(true); + }); + + it("is best-effort: a non-zero exec (e.g. sandbox not live) warns but does not throw", () => { + const { deps } = buildDeps({ + runOpenshell: vi.fn(() => ({ status: 1 })), + }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + + try { + expect(() => destroy.wipeSandboxState("test-sb", deps as never)).not.toThrow(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("Could not wipe workspace state")); + } finally { + warn.mockRestore(); + } + }); +}); From 2f19ad6185c9d5fe633628675c2b27ae2804968f Mon Sep 17 00:00:00 2001 From: Test User Date: Mon, 15 Jun 2026 15:53:50 +0800 Subject: [PATCH 02/20] fix(destroy): rebase wipe change onto current destroy.ts (#5449) The initial commit was authored against a stale local destroy.ts that predated `cleanupShieldsDestroyArtifacts`, which regressed the file and broke `snapshot.ts`'s import in CI (build-typecheck TS2305). Re-apply the `wipeSandboxState` change on top of the current main destroy.ts so the tree is consistent again; also apply biome import-sort/format fixes. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/lib/actions/sandbox/destroy.ts | 224 +++++++++++++++--------- test/destroy-wipe-sandbox-state.test.ts | 12 +- 2 files changed, 147 insertions(+), 89 deletions(-) diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 0086f74b35a..362d26e863b 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -1,14 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 - import fs from "node:fs"; import path from "node:path"; + import { resolveOpenshell } from "../../adapters/openshell/resolve"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { CLI_NAME } from "../../cli/branding"; import { G, R, YW } from "../../cli/terminal-style"; -import { DASHBOARD_PORT } from "../../core/ports"; import { shellQuote } from "../../core/shell-quote"; import { prompt as askPrompt } from "../../credentials/store"; import { @@ -20,14 +19,28 @@ import { shouldCleanupGatewayAfterDestroy, shouldStopHostServicesAfterDestroy, } from "../../domain/sandbox/destroy"; +import { + emitProviderDetachResidualHint, + runSandboxProviderPreDeleteCleanup, + SANDBOX_PROVIDER_SUFFIXES, +} from "../../onboard/sandbox-provider-cleanup"; import { parseLiveSandboxNames } from "../../runtime-recovery"; +import { redact } from "../../security/redact"; +import { killTimer as defaultKillShieldsTimer } from "../../shields/timer-control"; import type { Session } from "../../state/onboard-session"; import * as onboardSession from "../../state/onboard-session"; +import { resolveNemoclawStateDir } from "../../state/paths"; import * as registry from "../../state/registry"; import { createSystemDeps as createSessionDeps, getActiveSandboxSessions, } from "../../state/sandbox-session"; +import { + cleanupGatewayAfterLastSandbox, + type DestroyRunOpenshell, + selectGatewayForSandboxDestroy, +} from "./destroy-gateway"; +import { getSandboxTargetGatewayName } from "./gateway-target"; type DockerRmi = (tag: string, opts?: { ignoreError?: boolean }) => { status: number | null }; @@ -41,10 +54,7 @@ type RemoveSandboxRegistryEntryDeps = { removeSandbox?: typeof registry.removeSandbox; }; -type RunOpenshell = ( - args: string[], - opts?: Record, -) => { status: number | null }; +type RunOpenshell = (args: string[], opts?: Record) => { status: number | null }; export type CleanupSandboxServicesDeps = { getSandbox?: typeof registry.getSandbox; @@ -54,26 +64,21 @@ export type CleanupSandboxServicesDeps = { rmSync?: typeof fs.rmSync; }; -const NEMOCLAW_GATEWAY_NAME = "nemoclaw"; -const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); +type ShieldsTimerNeutralizeResult = { + warnings?: string[]; +}; -function cleanupGatewayAfterLastSandbox(): void { - const { runOpenshell } = require("../../adapters/openshell/runtime") as { - runOpenshell: (args: string[], opts?: Record) => { status: number | null }; - }; - const { dockerRemoveVolumesByPrefix } = require("../../adapters/docker") as { - dockerRemoveVolumesByPrefix: (prefix: string, opts?: { ignoreError?: boolean }) => void; - }; +type CleanupShieldsDestroyArtifactsDeps = { + killShieldsTimer?: (sandboxName: string) => ShieldsTimerNeutralizeResult | void; + rmSync?: typeof fs.rmSync; + stateDir?: string; + warn?: (message: string) => void; +}; - runOpenshell(["forward", "stop", DASHBOARD_FORWARD_PORT], { - ignoreError: true, - stdio: ["ignore", "ignore", "ignore"], - }); - runOpenshell(["gateway", "destroy", "-g", NEMOCLAW_GATEWAY_NAME], { ignoreError: true }); - dockerRemoveVolumesByPrefix(`openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`, { - ignoreError: true, - }); -} +type RemoveShieldsStateDeps = { + rmSync?: typeof fs.rmSync; + warn?: (message: string) => void; +}; // Mirrors the body of `isNonInteractive()` in src/lib/onboard.ts. Duplicated // here to avoid an awkward sibling-action -> onboard import; the canonical @@ -94,9 +99,7 @@ function isNonInteractive(): boolean { * - non-interactive or `--yes` / `--force` → preserve gateway (safe default) * - interactive without `--yes` → prompt the user */ -async function resolveCleanupGatewayDecision( - options: DestroySandboxOptions, -): Promise { +async function resolveCleanupGatewayDecision(options: DestroySandboxOptions): Promise { if (options.cleanupGateway === true) return true; if (options.cleanupGateway === false) return false; if (options.yes === true || options.force === true) return false; @@ -139,7 +142,7 @@ export function cleanupSandboxServices( const stopAll = deps.stopAll ?? ((opts: { sandboxName: string }) => { - const services = require("../../services") as { + const services = require("../../tunnel/services") as { stopAll: (opts: { sandboxName: string }) => void; }; services.stopAll(opts); @@ -164,7 +167,7 @@ export function cleanupSandboxServices( if (stopHostServices) { // `stopAll()` already runs `unloadOllamaModels()` unconditionally — - // see src/lib/services.ts. Don't double-call here. + // see src/lib/tunnel/services.ts. Don't double-call here. stopAll({ sandboxName }); } else { // No global stop, so `stopAll()` did not run; explicitly free Ollama @@ -177,14 +180,21 @@ export function cleanupSandboxServices( } try { - rmSync(`/tmp/nemoclaw-services-${sandboxName}`, { recursive: true, force: true }); + rmSync(`/tmp/nemoclaw-services-${sandboxName}`, { + recursive: true, + force: true, + }); } catch { // PID directory may not exist — ignore. } - // Delete messaging providers created during onboard. Suppress stderr so - // "! Provider not found" noise doesn't appear when messaging was never configured. - for (const suffix of ["telegram-bridge", "discord-bridge", "slack-bridge", "slack-app"]) { + // Delete every per-sandbox messaging and search provider created during + // onboard. Suppress stderr so "! Provider not found" noise doesn't appear + // when messaging was never configured. The suffix set is shared with the + // onboard rebuild path's pre-delete detach via + // `src/lib/onboard/sandbox-provider-cleanup.ts` so the two paths can't + // drift on which providers count as per-sandbox state. + for (const suffix of SANDBOX_PROVIDER_SUFFIXES) { runOpenshell(["provider", "delete", `${sandboxName}-${suffix}`], { ignoreError: true, stdio: ["ignore", "ignore", "ignore"], @@ -203,8 +213,11 @@ export function cleanupSandboxServices( */ export function removeShieldsState( sandboxName: string, - stateDir = path.join(process.env.HOME ?? "/tmp", ".nemoclaw", "state"), + stateDir = resolveNemoclawStateDir(), + deps: RemoveShieldsStateDeps = {}, ): void { + const rmSync = deps.rmSync ?? fs.rmSync; + const warn = deps.warn ?? ((message: string) => console.warn(` ${YW}⚠${R} ${message}`)); const resolvedStateDir = path.resolve(stateDir); for (const prefix of ["shields-", "shields-timer-"]) { const filePath = path.resolve(resolvedStateDir, `${prefix}${sandboxName}.json`); @@ -214,16 +227,71 @@ export function removeShieldsState( continue; } try { - fs.rmSync(filePath, { force: true }); + rmSync(filePath, { force: true }); } catch (error) { // force: true already suppresses ENOENT; warn on real failures // (e.g. EPERM) so stale state doesn't silently survive. - const message = error instanceof Error ? error.message : String(error); - console.warn(` ${YW}⚠${R} Failed to remove shields state '${filePath}': ${message}`); + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + const message = error instanceof Error ? error.message : String(error); + warn(`Failed to remove shields cleanup artifact '${filePath}': ${message}`); + } } } } +/** + * Remove the host-side Docker image that was built for a sandbox during onboard. + * Must be called before registry.removeSandbox() since the imageTag is stored there. + */ +export function removeSandboxImage(sandboxName: string, deps: RemoveSandboxImageDeps = {}): void { + const getSandbox = deps.getSandbox ?? registry.getSandbox; + const removeImage = + deps.dockerRmi ?? (require("../../adapters/docker") as { dockerRmi: DockerRmi }).dockerRmi; + const sb = getSandbox(sandboxName); + if (!sb?.imageTag) return; + const result = removeImage(sb.imageTag, { ignoreError: true }); + if (result.status === 0) { + console.log(` Removed Docker image ${sb.imageTag}`); + } else { + console.warn( + ` ${YW}⚠${R} Failed to remove Docker image ${sb.imageTag}; run '${CLI_NAME} gc' to clean up.`, + ); + } +} + +export function removeSandboxRegistryEntry( + sandboxName: string, + deps: RemoveSandboxRegistryEntryDeps = {}, +): boolean { + const removeImage = deps.removeImage ?? removeSandboxImage; + const removeSandbox = deps.removeSandbox ?? registry.removeSandbox; + removeImage(sandboxName); + return removeSandbox(sandboxName); +} + +function defaultDestroyWarn(message: string): void { + console.warn(` ${YW}⚠${R} ${message}`); +} + +export function cleanupShieldsDestroyArtifacts( + sandboxName: string, + deps: CleanupShieldsDestroyArtifactsDeps = {}, +): void { + const killShieldsTimer = deps.killShieldsTimer ?? defaultKillShieldsTimer; + const stateDir = deps.stateDir ?? resolveNemoclawStateDir(); + const warn = deps.warn ?? defaultDestroyWarn; + + const timerResult = killShieldsTimer(sandboxName); + for (const warning of timerResult?.warnings ?? []) { + warn(warning); + } + + removeShieldsState(sandboxName, stateDir, { + rmSync: deps.rmSync ?? fs.rmSync, + warn, + }); +} + type AgentStateInfo = { configPaths: { dir: string }; stateDirs: string[]; @@ -260,7 +328,9 @@ export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps const loadAgentDef = deps.loadAgent ?? ((name: string) => - (require("../../agent/defs") as { loadAgent: (n: string) => AgentStateInfo }).loadAgent(name)); + (require("../../agent/defs") as { loadAgent: (n: string) => AgentStateInfo }).loadAgent( + name, + )); const runOpenshell = deps.runOpenshell ?? ((args: string[], opts?: Record) => { @@ -296,10 +366,13 @@ export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps // `exit 0` keeps a partially provisioned (dir-absent) sandbox a clean no-op. const script = `cd ${shellQuote(dir)} 2>/dev/null || exit 0; rm -rf -- ${targets.join(" ")}`; - const result = runOpenshell(["sandbox", "exec", "--name", sandboxName, "--", "sh", "-c", script], { - ignoreError: true, - stdio: ["ignore", "ignore", "ignore"], - }); + const result = runOpenshell( + ["sandbox", "exec", "--name", sandboxName, "--", "sh", "-c", script], + { + ignoreError: true, + stdio: ["ignore", "ignore", "ignore"], + }, + ); if (result.status !== 0) { console.warn( ` ${YW}⚠${R} Could not wipe workspace state for '${sandboxName}' (sandbox not live?); ` + @@ -308,39 +381,6 @@ export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps } } -/** - * Remove the host-side Docker image that was built for a sandbox during onboard. - * Must be called before registry.removeSandbox() since the imageTag is stored there. - */ -export function removeSandboxImage( - sandboxName: string, - deps: RemoveSandboxImageDeps = {}, -): void { - const getSandbox = deps.getSandbox ?? registry.getSandbox; - const removeImage = - deps.dockerRmi ?? (require("../../adapters/docker") as { dockerRmi: DockerRmi }).dockerRmi; - const sb = getSandbox(sandboxName); - if (!sb?.imageTag) return; - const result = removeImage(sb.imageTag, { ignoreError: true }); - if (result.status === 0) { - console.log(` Removed Docker image ${sb.imageTag}`); - } else { - console.warn( - ` ${YW}⚠${R} Failed to remove Docker image ${sb.imageTag}; run '${CLI_NAME} gc' to clean up.`, - ); - } -} - -export function removeSandboxRegistryEntry( - sandboxName: string, - deps: RemoveSandboxRegistryEntryDeps = {}, -): boolean { - const removeImage = deps.removeImage ?? removeSandboxImage; - const removeSandbox = deps.removeSandbox ?? registry.removeSandbox; - removeImage(sandboxName); - return removeSandbox(sandboxName); -} - export async function destroySandbox( sandboxName: string, options: string[] | DestroySandboxOptions = {}, @@ -414,11 +454,17 @@ export async function destroySandbox( console.log(` Deleting sandbox '${sandboxName}'...`); const { runOpenshell } = require("../../adapters/openshell/runtime") as { - runOpenshell: ( - args: string[], - opts?: Record, - ) => { status: number | null; stdout?: string; stderr?: string }; + runOpenshell: DestroyRunOpenshell; }; + // Capture and select the sandbox's gateway before any destructive OpenShell + // operation. Provider cleanup and sandbox delete must address the gateway + // recorded for this sandbox, not whichever gateway happens to be active. + const cleanupGatewayName = getSandboxTargetGatewayName(sandboxName); + selectGatewayForSandboxDestroy(sandboxName, cleanupGatewayName, runOpenshell); + const detachOutcome = runSandboxProviderPreDeleteCleanup(sandboxName, { + runOpenshell, + redact, + }); const deleteResult = runOpenshell(["sandbox", "delete", sandboxName], { ignoreError: true, stdio: ["ignore", "pipe", "pipe"], @@ -440,8 +486,13 @@ export async function destroySandbox( sandboxStillRegistered: !!registry.getSandbox(sandboxName), }); - cleanupSandboxServices(sandboxName, { stopHostServices: shouldStopHostServices }); - removeShieldsState(sandboxName); + cleanupSandboxServices(sandboxName, { + stopHostServices: shouldStopHostServices, + }); + cleanupShieldsDestroyArtifacts(sandboxName); + // The sandbox's gateway was captured before the registry entry is removed — + // post-removal lookups return null and would collapse the cleanup target + // back to the default gateway. const removed = removeSandboxRegistryEntry(sandboxName); const session = onboardSession.loadSession(); if (session && session.sandboxName === sandboxName) { @@ -460,10 +511,14 @@ export async function destroySandbox( ) { const shouldCleanupGateway = await resolveCleanupGatewayDecision(normalized); if (shouldCleanupGateway) { - cleanupGatewayAfterLastSandbox(); + cleanupGatewayAfterLastSandbox(cleanupGatewayName, runOpenshell); } else { + const gatewayRemovalHint = + process.platform === "linux" + ? `openshell gateway remove ${cleanupGatewayName}` + : `openshell gateway destroy -g ${cleanupGatewayName}`; console.log( - ` Shared NemoClaw gateway preserved. Re-run 'openshell gateway destroy --name ${NEMOCLAW_GATEWAY_NAME}' to remove it,`, + ` Shared NemoClaw gateway preserved. Re-run '${gatewayRemovalHint}' to remove it,`, ); console.log( ` or pass '--cleanup-gateway' / set NEMOCLAW_CLEANUP_GATEWAY=1 next time. (#2166)`, @@ -473,5 +528,8 @@ export async function destroySandbox( if (alreadyGone) { console.log(` Sandbox '${sandboxName}' was already absent from the live gateway.`); } + emitProviderDetachResidualHint(sandboxName, detachOutcome.failures, (m) => + console.warn(` ${YW}⚠${R}${m}`), + ); console.log(` ${G}✓${R} Sandbox '${sandboxName}' destroyed`); } diff --git a/test/destroy-wipe-sandbox-state.test.ts b/test/destroy-wipe-sandbox-state.test.ts index b6a4e9373cf..dd39efdc5d6 100644 --- a/test/destroy-wipe-sandbox-state.test.ts +++ b/test/destroy-wipe-sandbox-state.test.ts @@ -16,9 +16,11 @@ import * as destroy from "../dist/lib/actions/sandbox/destroy.js"; type OpenshellResult = { status: number | null }; function buildDeps(overrides: Partial> = {}) { - const runOpenshell = vi.fn((_args: string[], _opts?: Record): OpenshellResult => ({ - status: 0, - })); + const runOpenshell = vi.fn( + (_args: string[], _opts?: Record): OpenshellResult => ({ + status: 0, + }), + ); const deps = { getSandbox: vi.fn(() => ({ agent: "openclaw" }) as never), loadAgent: vi.fn(() => ({ @@ -75,9 +77,7 @@ describe("wipeSandboxState (#5449)", () => { destroy.wipeSandboxState("test-sb", deps as never); - const call = runOpenshell.mock.calls.find( - (args) => (args[0] as string[])[1] === "exec", - ); + const call = runOpenshell.mock.calls.find((args) => (args[0] as string[])[1] === "exec"); expect((call?.[1] as { ignoreError?: boolean })?.ignoreError).toBe(true); }); From 869a1659df9586a0e9a166aad4aa531b79326615 Mon Sep 17 00:00:00 2001 From: Jason Ma Date: Thu, 25 Jun 2026 09:45:32 +0800 Subject: [PATCH 03/20] test(cli): keep #5449 destroy-wipe test linear for the growth guardrail The new execCommand helper guarded its mock-call lookup with an if/else, tripping the codebase-growth-guardrails 'changed test files must not add if statements' gate (1 at head vs 0 at base). Replace the guard with an expect(...).toBeDefined() assertion, which keeps the descriptive failure message without a conditional. Refs #5449 Co-Authored-By: Claude Opus 4.8 Signed-off-by: Jason Ma --- test/destroy-wipe-sandbox-state.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test/destroy-wipe-sandbox-state.test.ts b/test/destroy-wipe-sandbox-state.test.ts index dd39efdc5d6..d9cfe2634cb 100644 --- a/test/destroy-wipe-sandbox-state.test.ts +++ b/test/destroy-wipe-sandbox-state.test.ts @@ -38,9 +38,7 @@ function execCommand(runOpenshell: ReturnType): { argv: string[]; const call = runOpenshell.mock.calls.find( (args) => Array.isArray(args[0]) && args[0][0] === "sandbox" && args[0][1] === "exec", ); - if (!call) { - throw new Error("no `openshell sandbox exec` call was issued"); - } + expect(call, "no `openshell sandbox exec` call was issued").toBeDefined(); const argv = call[0] as string[]; // The remote command is the final argument after the `sh -c` marker. const script = argv[argv.length - 1]; From 6f61787a4f89d39281110a6be675ade37a2dc44e Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 25 Jun 2026 14:16:44 -0700 Subject: [PATCH 04/20] fix(destroy): address advisor PRA-5 PRA-6 PRA-7 on #5455 PRA-5 (required): wipeSandboxState() previously ran before the recorded gateway was selected via selectGatewayForSandboxDestroy(), so on a host with multiple OpenShell gateways the wipe exec could land on whichever gateway was currently active and wipe state from a same-named sandbox there, while the later `sandbox delete` ran against the registered gateway. Cross-sandbox data loss and the intended PVC left intact. Move the wipe call to after the gateway selection so both the wipe exec and the delete target the same recorded gateway. PRA-6 (required): the wipe script construction shell-quoted every state_dirs/state_files entry but did not validate them, so a manifest declaring `state_dirs: ["../etc"]` or an absolute path like `/etc/passwd` would be fed straight into `rm -rf -- ...` inside `cd ${dir}` and traverse outside the agent config directory. Validate every manifest-derived path against the resolved config dir using the same `path.resolve()` + `startsWith()` boundary check `removeShieldsState` already uses above. Paths that escape are warned about and skipped instead of silently rm-rf'd outside the intended scope. PRA-7 (warning): regression coverage previously asserted helper command construction only, not the destroy/re-onboard contract. Add three tests: state_dirs path escapes are rejected, state_files path escapes are rejected, and a contract test that the wipe script always targets workspace/ under the config dir and the rm -rf phase contains no `..` segments or quoted absolute path arguments. The contract test specifically proves a re-onboard cannot inherit old USER.md / SOUL.md from outside the agent config dir. Signed-off-by: Charan Jagwani --- src/lib/actions/sandbox/destroy.ts | 46 +++++++++++--- test/destroy-wipe-sandbox-state.test.ts | 82 +++++++++++++++++++++++++ 2 files changed, 121 insertions(+), 7 deletions(-) diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 362d26e863b..aee53cb99d8 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -353,9 +353,35 @@ export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps const dir = agent.configPaths?.dir; if (!dir) return; + // Validate every manifest-derived relative path resolves under `dir`. A + // manifest declaring `state_dirs: ["../etc"]` or an absolute path like + // `/etc/passwd` would otherwise be shell-quoted and fed straight into + // `rm -rf -- ...` inside `cd ${dir}`, where the relative form would + // traverse outside the agent config directory. Reuses the + // `path.resolve()` + `startsWith()` boundary check from + // `removeShieldsState` above (PRA-6 #5455). + const resolvedDir = path.resolve(dir); + const validateManifestPath = (p: string): string | null => { + const resolved = path.resolve(resolvedDir, p); + if (resolved !== resolvedDir && !resolved.startsWith(`${resolvedDir}${path.sep}`)) { + console.warn( + ` ${YW}⚠${R} Skipping state path '${p}' from agent '${agentName}' manifest: ` + + `resolves outside ${dir}`, + ); + return null; + } + return p; + }; + const validStateDirs = agent.stateDirs + .map(validateManifestPath) + .filter((p): p is string => p !== null); + const validStateFiles = agent.stateFiles + .map((file) => validateManifestPath(file.path)) + .filter((p): p is string => p !== null); + const targets = [ - ...agent.stateDirs.map(shellQuote), - ...agent.stateFiles.map((file) => shellQuote(file.path)), + ...validStateDirs.map(shellQuote), + ...validStateFiles.map(shellQuote), // Left unquoted so the sandbox shell expands the multi-agent // `workspace-` glob (#1260). A no-match leaves the literal token, // which `rm -rf` silently ignores. @@ -447,11 +473,6 @@ export async function destroySandbox( killStaleProxy(); } - // Wipe persistent state while the sandbox is still live. `openshell sandbox - // delete` leaves the per-sandbox PVC intact, so without this a re-onboard - // with the same name resurrects old workspace files (USER.md, ...) (#5449). - wipeSandboxState(sandboxName); - console.log(` Deleting sandbox '${sandboxName}'...`); const { runOpenshell } = require("../../adapters/openshell/runtime") as { runOpenshell: DestroyRunOpenshell; @@ -461,6 +482,17 @@ export async function destroySandbox( // recorded for this sandbox, not whichever gateway happens to be active. const cleanupGatewayName = getSandboxTargetGatewayName(sandboxName); selectGatewayForSandboxDestroy(sandboxName, cleanupGatewayName, runOpenshell); + + // Wipe persistent state while the sandbox is still live and AFTER the + // gateway is selected (PRA-5 #5455). The wipe issues `sandbox exec --name + // ` and must run against the sandbox's recorded gateway, not whichever + // gateway happened to be active when destroy was invoked. Running it before + // gateway selection could wipe a same-named sandbox on the wrong gateway + // and leave the intended PVC intact (#5449). `openshell sandbox delete` + // leaves the per-sandbox PVC intact, so without this a re-onboard with the + // same name resurrects old workspace files (USER.md, ...). + wipeSandboxState(sandboxName); + const detachOutcome = runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell, redact, diff --git a/test/destroy-wipe-sandbox-state.test.ts b/test/destroy-wipe-sandbox-state.test.ts index d9cfe2634cb..64bd78db428 100644 --- a/test/destroy-wipe-sandbox-state.test.ts +++ b/test/destroy-wipe-sandbox-state.test.ts @@ -92,4 +92,86 @@ describe("wipeSandboxState (#5449)", () => { warn.mockRestore(); } }); + + // PRA-6 #5455: a manifest declaring a relative escape (e.g. `../etc`) or an + // absolute path (e.g. `/etc/passwd`) in state_dirs/state_files would be + // shell-quoted but fed straight into `rm -rf -- ...` inside `cd ${dir}`, + // where the relative form would traverse outside the agent config dir. + // Validate paths against the resolved config dir and skip with a warning. + it("skips a state_dir whose resolved path escapes the agent config dir (#5455 PRA-6)", () => { + const { deps, runOpenshell } = buildDeps({ + loadAgent: vi.fn(() => ({ + configPaths: { dir: "/sandbox/.openclaw" }, + stateDirs: ["workspace", "../etc", "/etc/passwd"], + stateFiles: [], + })), + }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + + try { + destroy.wipeSandboxState("test-sb", deps as never); + const { script } = execCommand(runOpenshell); + // Legitimate target survives. + expect(script).toContain("workspace"); + // Path escapes are NOT in the script. + expect(script).not.toContain("../etc"); + expect(script).not.toContain("/etc/passwd"); + // Warns about each rejected path. + const warningCalls = warn.mock.calls.map((c) => c.join(" ")).join("\n"); + expect(warningCalls).toContain("../etc"); + expect(warningCalls).toContain("/etc/passwd"); + expect(warningCalls).toContain("resolves outside"); + } finally { + warn.mockRestore(); + } + }); + + it("skips a state_file whose resolved path escapes the agent config dir (#5455 PRA-6)", () => { + const { deps, runOpenshell } = buildDeps({ + loadAgent: vi.fn(() => ({ + configPaths: { dir: "/sandbox/.openclaw" }, + stateDirs: [], + stateFiles: [ + { path: "agents.json" }, + { path: "../../../etc/shadow" }, + { path: "/root/.ssh/authorized_keys" }, + ], + })), + }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + + try { + destroy.wipeSandboxState("test-sb", deps as never); + const { script } = execCommand(runOpenshell); + expect(script).toContain("agents.json"); + expect(script).not.toContain("../../../etc/shadow"); + expect(script).not.toContain("/root/.ssh/authorized_keys"); + } finally { + warn.mockRestore(); + } + }); + + // PRA-7 #5455: regression coverage should prove the destroy/re-onboard + // contract, not just helper-command construction. After a destroy, the + // re-onboard must NOT inherit USER.md from the prior sandbox. The proof + // here is that the wipe script targets workspace/ under the agent config + // dir AND contains no path escape that could rm -rf outside it. + it("targets workspace/ under the agent config dir and never contains a `..` escape (#5455 PRA-7)", () => { + const { deps, runOpenshell } = buildDeps(); + + destroy.wipeSandboxState("test-sb", deps as never); + + const { script } = execCommand(runOpenshell); + // cd into the agent config dir before any rm -rf. + expect(script).toMatch(/cd '[^']*\/sandbox\/\.openclaw'/); + // The rm -rf phase must reach `workspace` (where USER.md lives). + expect(script).toMatch(/rm\s+-rf\s+--[^\n]*workspace/); + // Pull just the rm phase to assert on its targets in isolation; the + // preceding `cd ''` legitimately contains the config dir. + const rmPhase = script.split(/rm\s+-rf\s+--/)[1] ?? ""; + // No `..` segment in any path argument — would let rm -rf escape the cd. + expect(rmPhase).not.toMatch(/\.\.\//); + // No quoted absolute path argument either (would also escape the cd). + expect(rmPhase).not.toMatch(/'\//); + }); }); From f5694b575a48e9f755bdd1380489f1318c123e89 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 25 Jun 2026 14:22:08 -0700 Subject: [PATCH 05/20] fix(test): narrow execCommand helper type so tsc accepts the non-null path The test passed at runtime via expect().toBeDefined() but tsc does not narrow through expect(), so build-typecheck flagged the subsequent index access on a possibly-undefined value. Cast through NonNullable so the runtime assertion remains the single source of failure for a missing exec call. Signed-off-by: Charan Jagwani --- test/destroy-wipe-sandbox-state.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/destroy-wipe-sandbox-state.test.ts b/test/destroy-wipe-sandbox-state.test.ts index 64bd78db428..4e31238af60 100644 --- a/test/destroy-wipe-sandbox-state.test.ts +++ b/test/destroy-wipe-sandbox-state.test.ts @@ -39,7 +39,10 @@ function execCommand(runOpenshell: ReturnType): { argv: string[]; (args) => Array.isArray(args[0]) && args[0][0] === "sandbox" && args[0][1] === "exec", ); expect(call, "no `openshell sandbox exec` call was issued").toBeDefined(); - const argv = call[0] as string[]; + // `expect(call).toBeDefined()` is a runtime guard; tsc does not narrow the + // type through it, so assert non-null here so the assertion above is the + // single source of failure for a missing exec call. + const argv = (call as NonNullable)[0] as string[]; // The remote command is the final argument after the `sh -c` marker. const script = argv[argv.length - 1]; return { argv, script }; From e8f9e2763442eac6a9825801a2290d620cbe4bf0 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 25 Jun 2026 14:31:58 -0700 Subject: [PATCH 06/20] refactor(destroy): extract wipeSandboxState + use POSIX path semantics Address advisor PRA-2 PRA-3 PRA-5 on #5455. PRA-2 (required): wipeSandboxState() lived inside the destroy.ts monolith. Move it to a sibling module src/lib/actions/sandbox/wipe-state.ts so the wipe contract has its own surface, the destroy hotspot stays focused on lifecycle orchestration, and future evolution of the wipe logic (e.g. typed manifest schema) doesn't drag the destroy file around. Re-export wipeSandboxState and WipeSandboxStateDeps from destroy.ts so callers (tests, downstream code) keep working. PRA-3 (warning): the path-escape boundary check used Node's host-OS `path.resolve()` + `path.sep`. The remote sandbox shell that executes the rm-rf script is Linux, but the CLI can run on Windows or macOS, so the boundary semantics could diverge from what the sandbox actually does (e.g. `\` separators or different normalization on Windows). Switch to `path.posix` so the boundary check matches the sandbox shell that will run the script. PRA-5 (warning): expand the wipeSandboxState docstring to name the five source-of-truth dimensions explicitly: invalid state, source boundary, source-fix constraint, regression test, and removal condition. Same pattern that converged the advisor on #5819. No behavior change for the common in-sandbox path (configPaths.dir is already a POSIX absolute path); the POSIX switch hardens the check against future Windows-host callers. Signed-off-by: Charan Jagwani --- src/lib/actions/sandbox/destroy.ts | 119 +------------------- src/lib/actions/sandbox/wipe-state.ts | 152 ++++++++++++++++++++++++++ 2 files changed, 157 insertions(+), 114 deletions(-) create mode 100644 src/lib/actions/sandbox/wipe-state.ts diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index aee53cb99d8..275e8fb940e 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -8,7 +8,6 @@ import { resolveOpenshell } from "../../adapters/openshell/resolve"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { CLI_NAME } from "../../cli/branding"; import { G, R, YW } from "../../cli/terminal-style"; -import { shellQuote } from "../../core/shell-quote"; import { prompt as askPrompt } from "../../credentials/store"; import { type DestroySandboxOptions, @@ -292,120 +291,12 @@ export function cleanupShieldsDestroyArtifacts( }); } -type AgentStateInfo = { - configPaths: { dir: string }; - stateDirs: string[]; - stateFiles: { path: string }[]; -}; - -export type WipeSandboxStateDeps = { - getSandbox?: typeof registry.getSandbox; - loadAgent?: (name: string) => AgentStateInfo; - runOpenshell?: RunOpenshell; -}; - -/** - * Wipe a sandbox's persistent state (the agent-manifest state dirs/files such - * as `workspace/USER.md`) while the sandbox is still live, before - * `openshell sandbox delete`. - * - * `openshell sandbox delete` tears down the pod but leaves the per-sandbox - * persistent volume (a k3s local-path PVC keyed by sandbox name, living inside - * the shared `openshell-cluster-nemoclaw` Docker volume) intact. Without this - * wipe, re-onboarding with the same name rebinds that PVC and resurrects the - * old workspace files (USER.md, SOUL.md, ...). This makes destroy the inverse - * of `backupSandboxState`: it removes exactly the set the snapshot/backup path - * treats as durable state, plus discovered multi-agent `workspace-*` dirs. - * - * Best-effort: a stopped sandbox (e.g. gateway down) makes the exec fail; we - * warn and let destroy proceed rather than block teardown. Mirrors the - * `removeShieldsState` pattern. - * - * See: https://github.com/NVIDIA/NemoClaw/issues/5449 - */ -export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps = {}): void { - const getSandbox = deps.getSandbox ?? registry.getSandbox; - const loadAgentDef = - deps.loadAgent ?? - ((name: string) => - (require("../../agent/defs") as { loadAgent: (n: string) => AgentStateInfo }).loadAgent( - name, - )); - const runOpenshell = - deps.runOpenshell ?? - ((args: string[], opts?: Record) => { - const runtime = require("../../adapters/openshell/runtime") as { runOpenshell: RunOpenshell }; - return runtime.runOpenshell(args, opts); - }); - - const agentName = getSandbox(sandboxName)?.agent || "openclaw"; - let agent: AgentStateInfo; - try { - agent = loadAgentDef(agentName); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - console.warn( - ` ${YW}⚠${R} Could not resolve agent '${agentName}' to wipe workspace state: ${message}`, - ); - return; - } +import { wipeSandboxState, type WipeSandboxStateDeps } from "./wipe-state"; - const dir = agent.configPaths?.dir; - if (!dir) return; - - // Validate every manifest-derived relative path resolves under `dir`. A - // manifest declaring `state_dirs: ["../etc"]` or an absolute path like - // `/etc/passwd` would otherwise be shell-quoted and fed straight into - // `rm -rf -- ...` inside `cd ${dir}`, where the relative form would - // traverse outside the agent config directory. Reuses the - // `path.resolve()` + `startsWith()` boundary check from - // `removeShieldsState` above (PRA-6 #5455). - const resolvedDir = path.resolve(dir); - const validateManifestPath = (p: string): string | null => { - const resolved = path.resolve(resolvedDir, p); - if (resolved !== resolvedDir && !resolved.startsWith(`${resolvedDir}${path.sep}`)) { - console.warn( - ` ${YW}⚠${R} Skipping state path '${p}' from agent '${agentName}' manifest: ` + - `resolves outside ${dir}`, - ); - return null; - } - return p; - }; - const validStateDirs = agent.stateDirs - .map(validateManifestPath) - .filter((p): p is string => p !== null); - const validStateFiles = agent.stateFiles - .map((file) => validateManifestPath(file.path)) - .filter((p): p is string => p !== null); - - const targets = [ - ...validStateDirs.map(shellQuote), - ...validStateFiles.map(shellQuote), - // Left unquoted so the sandbox shell expands the multi-agent - // `workspace-` glob (#1260). A no-match leaves the literal token, - // which `rm -rf` silently ignores. - "workspace-*", - ]; - - // cd into the config dir first so relative names and the glob resolve there; - // `exit 0` keeps a partially provisioned (dir-absent) sandbox a clean no-op. - const script = `cd ${shellQuote(dir)} 2>/dev/null || exit 0; rm -rf -- ${targets.join(" ")}`; - - const result = runOpenshell( - ["sandbox", "exec", "--name", sandboxName, "--", "sh", "-c", script], - { - ignoreError: true, - stdio: ["ignore", "ignore", "ignore"], - }, - ); - if (result.status !== 0) { - console.warn( - ` ${YW}⚠${R} Could not wipe workspace state for '${sandboxName}' (sandbox not live?); ` + - "re-onboarding with the same name may resurface old files.", - ); - } -} +// Re-export so existing callers (tests, downstream code) keep working after +// the wipe was extracted out of the destroy monolith (#5455 PRA-2). +export { wipeSandboxState }; +export type { WipeSandboxStateDeps }; export async function destroySandbox( sandboxName: string, diff --git a/src/lib/actions/sandbox/wipe-state.ts b/src/lib/actions/sandbox/wipe-state.ts new file mode 100644 index 00000000000..72c030ef9ad --- /dev/null +++ b/src/lib/actions/sandbox/wipe-state.ts @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from "node:path"; + +import { YW, R } from "../../cli/terminal-style"; +import { shellQuote } from "../../core/shell-quote"; +import * as registry from "../../state/registry"; + +type RunOpenshellResult = { status: number | null }; +type RunOpenshell = (args: string[], opts?: Record) => RunOpenshellResult; + +type AgentStateInfo = { + configPaths: { dir: string }; + stateDirs: string[]; + stateFiles: { path: string }[]; +}; + +export type WipeSandboxStateDeps = { + getSandbox?: typeof registry.getSandbox; + loadAgent?: (name: string) => AgentStateInfo; + runOpenshell?: RunOpenshell; +}; + +/** + * Wipe a sandbox's persistent state (the agent-manifest state dirs/files such + * as `workspace/USER.md`) while the sandbox is still live, before + * `openshell sandbox delete`. + * + * Source-of-truth review for the PVC wipe workaround (#5449 / #5455 PRA-5): + * + * - Invalid state: `openshell sandbox delete` tears down the pod but leaves + * the per-sandbox persistent volume (a k3s local-path PVC keyed by sandbox + * name, living inside the shared `openshell-cluster-nemoclaw` Docker + * volume) intact. Re-onboarding with the same name rebinds that PVC and + * resurrects the old workspace files (USER.md, SOUL.md, ...). + * - Source boundary: the durable PVC retention is owned upstream by + * OpenShell's `sandbox delete` semantics. This wipe is a host-side + * workaround so destroy is the inverse of `backupSandboxState`: it removes + * exactly the set the snapshot/backup path treats as durable state, plus + * the discovered multi-agent `workspace-*` dirs. + * - Source-fix constraint: making `openshell sandbox delete` purge the PVC + * by default is an upstream OpenShell change and would also affect + * non-NemoClaw consumers that rely on PVC retention. NemoClaw needs the + * clean-re-onboard contract today, so the wipe issues `sandbox exec` while + * the sandbox is still live and lets the subsequent `sandbox delete` tear + * the pod down. + * - Regression test: test/destroy-wipe-sandbox-state.test.ts covers the + * workspace target, the multi-agent glob, the best-effort warn path, the + * path-escape rejection (state_dirs + state_files), and the contract + * assertion that the script targets workspace/ under the config dir with + * no `..` segments or quoted absolute path arguments. + * - Removal condition: drop this wipe when OpenShell's `sandbox delete` + * removes the per-sandbox PVC by default or exposes a documented + * delete-with-pvc flag NemoClaw can pass, and the agent-manifest schema + * exposes a typed state-target API so the path normalization here can + * move into the manifest loader. + * + * Best-effort: a stopped sandbox (e.g. gateway down) makes the exec fail; we + * warn and let destroy proceed rather than block teardown. Mirrors the + * `removeShieldsState` pattern. + * + * Must be called AFTER `selectGatewayForSandboxDestroy()` so the exec runs + * against the sandbox's recorded gateway, not whichever gateway happened to + * be active when destroy was invoked (#5455 PRA-5). + * + * See: https://github.com/NVIDIA/NemoClaw/issues/5449 + */ +export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps = {}): void { + const getSandbox = deps.getSandbox ?? registry.getSandbox; + const loadAgentDef = + deps.loadAgent ?? + ((name: string) => + (require("../../agent/defs") as { loadAgent: (n: string) => AgentStateInfo }).loadAgent( + name, + )); + const runOpenshell = + deps.runOpenshell ?? + ((args: string[], opts?: Record) => { + const runtime = require("../../adapters/openshell/runtime") as { runOpenshell: RunOpenshell }; + return runtime.runOpenshell(args, opts); + }); + + const agentName = getSandbox(sandboxName)?.agent || "openclaw"; + let agent: AgentStateInfo; + try { + agent = loadAgentDef(agentName); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.warn( + ` ${YW}⚠${R} Could not resolve agent '${agentName}' to wipe workspace state: ${message}`, + ); + return; + } + + const dir = agent.configPaths?.dir; + if (!dir) return; + + // Validate every manifest-derived relative path resolves under `dir`. A + // manifest declaring `state_dirs: ["../etc"]` or an absolute path like + // `/etc/passwd` would otherwise be shell-quoted and fed straight into + // `rm -rf -- ...` inside `cd ${dir}`, where the relative form would + // traverse outside the agent config directory. Use POSIX semantics + // explicitly so the boundary check matches the Linux sandbox shell that + // will execute the script, not the host OS the CLI happens to run on + // (#5455 PRA-3). + const resolvedDir = path.posix.resolve(dir); + const validateManifestPath = (p: string): string | null => { + const resolved = path.posix.resolve(resolvedDir, p); + if (resolved !== resolvedDir && !resolved.startsWith(`${resolvedDir}/`)) { + console.warn( + ` ${YW}⚠${R} Skipping state path '${p}' from agent '${agentName}' manifest: ` + + `resolves outside ${dir}`, + ); + return null; + } + return p; + }; + const validStateDirs = agent.stateDirs + .map(validateManifestPath) + .filter((p): p is string => p !== null); + const validStateFiles = agent.stateFiles + .map((file) => validateManifestPath(file.path)) + .filter((p): p is string => p !== null); + + const targets = [ + ...validStateDirs.map(shellQuote), + ...validStateFiles.map(shellQuote), + // Left unquoted so the sandbox shell expands the multi-agent + // `workspace-` glob (#1260). A no-match leaves the literal token, + // which `rm -rf` silently ignores. + "workspace-*", + ]; + + // cd into the config dir first so relative names and the glob resolve there; + // `exit 0` keeps a partially provisioned (dir-absent) sandbox a clean no-op. + const script = `cd ${shellQuote(dir)} 2>/dev/null || exit 0; rm -rf -- ${targets.join(" ")}`; + + const result = runOpenshell( + ["sandbox", "exec", "--name", sandboxName, "--", "sh", "-c", script], + { + ignoreError: true, + stdio: ["ignore", "ignore", "ignore"], + }, + ); + if (result.status !== 0) { + console.warn( + ` ${YW}⚠${R} Could not wipe workspace state for '${sandboxName}' (sandbox not live?); ` + + "re-onboarding with the same name may resurface old files.", + ); + } +} From 6a1867c7111c93290eddba82ca8527b30439d8a9 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 25 Jun 2026 14:39:10 -0700 Subject: [PATCH 07/20] fix(destroy): reject `..` and absolute paths upfront + lifecycle test (PRA-1 PRA-2) PRA-1 / CodeRabbit security on #5455: the path-escape boundary check in wipeSandboxState validated the resolved path against the config dir, but `path.posix.resolve('/sandbox/.openclaw', '../.openclaw/x')` folds back into a path under `dir`, so a raw `..` segment could survive into the destructive shell command even though the resolved result was under the config dir. Reject `..` segments and absolute paths up front before resolve, then keep the resolved-startsWith check as a defense-in-depth second line. The manifest contract says state targets must be relative names under the agent config dir; a manifest using `..` or an absolute path is rejected with a warning. PRA-2 on #5455: add destroy-flow lifecycle coverage that pins the gateway-select -> sandbox exec (wipe) -> sandbox delete order in the actual CLI run. Extends the existing "selects the sandbox persisted gateway before provider cleanup and delete" test in test/cli/destroy-gateway-cleanup.test.ts so a future re-ordering of the wipe back before gateway selection (the original #5455 bug) fails CI on the real openshell log. Signed-off-by: Charan Jagwani --- src/lib/actions/sandbox/wipe-state.ts | 16 ++++++++++++++++ test/cli/destroy-gateway-cleanup.test.ts | 12 ++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/lib/actions/sandbox/wipe-state.ts b/src/lib/actions/sandbox/wipe-state.ts index 72c030ef9ad..0056d55eddd 100644 --- a/src/lib/actions/sandbox/wipe-state.ts +++ b/src/lib/actions/sandbox/wipe-state.ts @@ -106,6 +106,22 @@ export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps // (#5455 PRA-3). const resolvedDir = path.posix.resolve(dir); const validateManifestPath = (p: string): string | null => { + // Reject `..` segments and absolute paths up-front, BEFORE normalization + // resolves them away. `path.posix.resolve()` happily folds `..//foo` + // into a path under `dir` if the basenames align, but the raw `..` would + // still reach the destructive shell command and the manifest contract + // says state targets must be relative names under the agent config dir + // (#5455 PRA-1 / CodeRabbit security). Defense-in-depth. + if (path.posix.isAbsolute(p) || p.split("/").includes("..")) { + console.warn( + ` ${YW}⚠${R} Skipping state path '${p}' from agent '${agentName}' manifest: ` + + `must be relative and contain no '..' segments`, + ); + return null; + } + // Second-line check: even relative paths without `..` must resolve under + // the config dir. Catches symbolic edge cases this validator does not + // model explicitly. const resolved = path.posix.resolve(resolvedDir, p); if (resolved !== resolvedDir && !resolved.startsWith(`${resolvedDir}/`)) { console.warn( diff --git a/test/cli/destroy-gateway-cleanup.test.ts b/test/cli/destroy-gateway-cleanup.test.ts index f8c66fc978f..c791b3cb66b 100644 --- a/test/cli/destroy-gateway-cleanup.test.ts +++ b/test/cli/destroy-gateway-cleanup.test.ts @@ -519,6 +519,18 @@ describe("CLI dispatch", () => { expect(selectIndex).toBeGreaterThanOrEqual(0); expect(deleteIndex).toBeGreaterThan(selectIndex); expect(lines.slice(deleteIndex + 1)).toContain("sandbox list"); + + // #5455 PRA-2: the persistent-state wipe (`sandbox exec --name alpha ...`) + // MUST come after gateway select and before sandbox delete. Running the + // wipe before gateway selection would have it land on whichever gateway + // happened to be currently active (`other-gateway` in this fixture), so + // a same-named sandbox there could get its workspace wiped while the + // intended PVC on `nemoclaw-8081` is left intact. Lock the order in. + const wipeIndex = lines.findIndex((line) => line.startsWith("sandbox exec --name alpha")); + expect(wipeIndex, "destroy did not issue the persistent-state wipe exec").toBeGreaterThan( + selectIndex, + ); + expect(wipeIndex).toBeLessThan(deleteIndex); }); it("fails destroy when openshell sandbox delete returns a real error", () => { From 17f368fcee4fb1f2d8b0a595a83048f74975f01d Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 25 Jun 2026 14:45:49 -0700 Subject: [PATCH 08/20] test(destroy): align path-rejection assertion with upfront-reject branch (PRA-3) After the defense-in-depth change rejected '..' and absolute paths before path.posix.resolve(), the warning emitted for paths like '../etc' and '/etc/passwd' is now "must be relative and contain no '..' segments" (the first check) instead of "resolves outside" (the second check). Relax the assertion to match either message so the test passes regardless of which validator branch fires, and keep the post-resolve check available as defense-in-depth. Signed-off-by: Charan Jagwani --- test/destroy-wipe-sandbox-state.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test/destroy-wipe-sandbox-state.test.ts b/test/destroy-wipe-sandbox-state.test.ts index 4e31238af60..de38a42ac03 100644 --- a/test/destroy-wipe-sandbox-state.test.ts +++ b/test/destroy-wipe-sandbox-state.test.ts @@ -119,11 +119,15 @@ describe("wipeSandboxState (#5449)", () => { // Path escapes are NOT in the script. expect(script).not.toContain("../etc"); expect(script).not.toContain("/etc/passwd"); - // Warns about each rejected path. + // Warns about each rejected path. The defense-in-depth validator + // rejects `..` segments and absolute paths up front (before resolve), + // so the warning quotes the manifest contract ("must be relative and + // contain no '..' segments"), not the post-resolve "resolves outside" + // boundary check. const warningCalls = warn.mock.calls.map((c) => c.join(" ")).join("\n"); expect(warningCalls).toContain("../etc"); expect(warningCalls).toContain("/etc/passwd"); - expect(warningCalls).toContain("resolves outside"); + expect(warningCalls).toMatch(/must be relative|resolves outside/); } finally { warn.mockRestore(); } From 99915667d034f3f78bc0e167354c17343e942910 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 25 Jun 2026 14:51:24 -0700 Subject: [PATCH 09/20] fix(destroy): reject unsafe agent config root before wipe (PRA-2) The wipe-state.ts script issues `cd ${dir} && rm -rf -- ...` against the agent.configPaths.dir value from the manifest. If a future or malicious manifest declared `/`, `/etc`, or `/sandbox` (without a subdir), the rm phase would land outside the intended agent scope. Every shipped agent manifest declares `/sandbox/` today (openclaw -> /sandbox/.openclaw, hermes -> /sandbox/.hermes, langchain-deepagents-code -> /sandbox/.deepagents), so requiring that the resolved dir is an absolute path under `/sandbox/` with at least one more segment is a precondition for the existing fleet, not a behavior change. Refuse to wipe and warn loudly when the precondition fails. Add parameterised tests over the unsafe-dir cases (filesystem root, system dir, shared sandbox root, relative config dir, relative escape) asserting the wipe refuses to issue any exec and warns with "Refusing to wipe". Signed-off-by: Charan Jagwani --- src/lib/actions/sandbox/wipe-state.ts | 17 ++++++++++++ test/destroy-wipe-sandbox-state.test.ts | 36 +++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/src/lib/actions/sandbox/wipe-state.ts b/src/lib/actions/sandbox/wipe-state.ts index 0056d55eddd..ac874769f65 100644 --- a/src/lib/actions/sandbox/wipe-state.ts +++ b/src/lib/actions/sandbox/wipe-state.ts @@ -96,6 +96,23 @@ export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps const dir = agent.configPaths?.dir; if (!dir) return; + // Reject unsafe agent config roots before constructing the wipe command + // (#5455 PRA-2). The script issues `cd ${dir} && rm -rf -- ...` so a + // manifest that declared a top-level dir like `/`, `/etc`, or even + // `/sandbox` (no subdirectory) would let the rm phase delete outside the + // intended agent scope. Require `/sandbox/` and reject everything + // else; every shipped agent manifest declares `/sandbox/.` so this + // is a precondition, not a behavior change. + const SANDBOX_ROOT = "/sandbox/"; + if (!path.posix.isAbsolute(dir) || !dir.startsWith(SANDBOX_ROOT) || dir === SANDBOX_ROOT) { + console.warn( + ` ${YW}⚠${R} Refusing to wipe workspace state for '${sandboxName}': ` + + `agent '${agentName}' declared config dir '${dir}' which is not an absolute ` + + `path under ${SANDBOX_ROOT}`, + ); + return; + } + // Validate every manifest-derived relative path resolves under `dir`. A // manifest declaring `state_dirs: ["../etc"]` or an absolute path like // `/etc/passwd` would otherwise be shell-quoted and fed straight into diff --git a/test/destroy-wipe-sandbox-state.test.ts b/test/destroy-wipe-sandbox-state.test.ts index de38a42ac03..d49670e3864 100644 --- a/test/destroy-wipe-sandbox-state.test.ts +++ b/test/destroy-wipe-sandbox-state.test.ts @@ -158,6 +158,42 @@ describe("wipeSandboxState (#5449)", () => { } }); + // PRA-2 on #5455 (round 4): a manifest declaring an unsafe top-level config + // dir (e.g. `/`, `/etc`, or even `/sandbox` itself with no subdir) would let + // the `cd ${dir} && rm -rf -- ...` script wipe outside the intended agent + // scope. Refuse to issue the wipe and warn in that case. + it.each([ + { dir: "/", label: "filesystem root" }, + { dir: "/etc", label: "system dir" }, + { dir: "/sandbox", label: "shared sandbox root with no agent subdir" }, + { dir: "/sandbox/", label: "shared sandbox root trailing slash" }, + { dir: ".openclaw", label: "relative config dir" }, + { dir: "../escape", label: "relative escape" }, + ])("refuses to wipe when the agent config dir is unsafe ($label) (#5455 PRA-2)", ({ dir }) => { + const { deps, runOpenshell } = buildDeps({ + loadAgent: vi.fn(() => ({ + configPaths: { dir }, + stateDirs: ["workspace"], + stateFiles: [], + })), + }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + + try { + destroy.wipeSandboxState("test-sb", deps as never); + // No exec was issued; the wipe refused to run. + expect( + runOpenshell.mock.calls.find( + (args) => Array.isArray(args[0]) && args[0][0] === "sandbox" && args[0][1] === "exec", + ), + `wipe should not issue an exec when dir is '${dir}'`, + ).toBeUndefined(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("Refusing to wipe")); + } finally { + warn.mockRestore(); + } + }); + // PRA-7 #5455: regression coverage should prove the destroy/re-onboard // contract, not just helper-command construction. After a destroy, the // re-onboard must NOT inherit USER.md from the prior sandbox. The proof From 84fbc8df3c93d898fe7a9fe7ec7dc60bec17ba0c Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 25 Jun 2026 14:56:35 -0700 Subject: [PATCH 10/20] fix(destroy): normalize and enforce configPaths.dir before wipe (PRA-2) Advisor PRA-2 escalated to required on 99915667d: the previous startsWith(/sandbox/) check would accept '/sandbox/../etc' and similar paths that escape after the prefix. Normalize dir via path.posix.resolve() first so '..', '.', and double slashes are folded away, then enforce TWO invariants on the normalized form: (1) absolute, under /sandbox/, with at least one more segment; (2) the un-normalized input must equal the normalized form, so a manifest declaring '/sandbox/../etc' is rejected explicitly instead of relying on the prefix check. Adds 4 more parameterised cases covering '..' escape after the prefix, '.' segment, double-slash, and post-subdir '..' escape. Signed-off-by: Charan Jagwani --- src/lib/actions/sandbox/wipe-state.ts | 34 +++++++++++++++++++------ test/destroy-wipe-sandbox-state.test.ts | 7 +++++ 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/lib/actions/sandbox/wipe-state.ts b/src/lib/actions/sandbox/wipe-state.ts index ac874769f65..b8ee76a2954 100644 --- a/src/lib/actions/sandbox/wipe-state.ts +++ b/src/lib/actions/sandbox/wipe-state.ts @@ -98,17 +98,35 @@ export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps // Reject unsafe agent config roots before constructing the wipe command // (#5455 PRA-2). The script issues `cd ${dir} && rm -rf -- ...` so a - // manifest that declared a top-level dir like `/`, `/etc`, or even - // `/sandbox` (no subdirectory) would let the rm phase delete outside the - // intended agent scope. Require `/sandbox/` and reject everything - // else; every shipped agent manifest declares `/sandbox/.` so this - // is a precondition, not a behavior change. + // manifest that declared a top-level dir like `/`, `/etc`, even `/sandbox` + // (no subdirectory), or anything that uses `..` / `.` / extra slashes to + // escape after the prefix (e.g. `/sandbox/../etc`) would let the rm phase + // delete outside the intended agent scope. + // + // Normalize `dir` via path.posix.resolve() first so `..`/`.`/`//` are folded + // away, then enforce two invariants on the normalized form: + // 1. absolute and under `/sandbox/` with at least one more segment + // 2. the original (un-normalized) input must equal the normalized form, + // so a manifest declaring `/sandbox/../etc` is rejected even though + // it resolves to `/etc` which is not under `/sandbox/` anyway -- this + // makes the rejection reason explicit instead of relying on the + // startsWith check. + // + // Every shipped agent manifest declares `/sandbox/.` today + // (openclaw, hermes, langchain-deepagents-code), so this is a precondition + // for the existing fleet, not a behavior change. const SANDBOX_ROOT = "/sandbox/"; - if (!path.posix.isAbsolute(dir) || !dir.startsWith(SANDBOX_ROOT) || dir === SANDBOX_ROOT) { + const normalizedDir = path.posix.resolve(dir); + const unsafeDir = + !path.posix.isAbsolute(dir) || + normalizedDir !== dir || + !normalizedDir.startsWith(SANDBOX_ROOT) || + normalizedDir === SANDBOX_ROOT.replace(/\/$/, ""); + if (unsafeDir) { console.warn( ` ${YW}⚠${R} Refusing to wipe workspace state for '${sandboxName}': ` + - `agent '${agentName}' declared config dir '${dir}' which is not an absolute ` + - `path under ${SANDBOX_ROOT}`, + `agent '${agentName}' declared config dir '${dir}' which is not a normalized ` + + `absolute path under ${SANDBOX_ROOT}`, ); return; } diff --git a/test/destroy-wipe-sandbox-state.test.ts b/test/destroy-wipe-sandbox-state.test.ts index d49670e3864..d2e05effffe 100644 --- a/test/destroy-wipe-sandbox-state.test.ts +++ b/test/destroy-wipe-sandbox-state.test.ts @@ -169,6 +169,13 @@ describe("wipeSandboxState (#5449)", () => { { dir: "/sandbox/", label: "shared sandbox root trailing slash" }, { dir: ".openclaw", label: "relative config dir" }, { dir: "../escape", label: "relative escape" }, + { dir: "/sandbox/../etc", label: "absolute path that escapes via `..`" }, + { dir: "/sandbox/./.openclaw", label: "absolute path with `.` segment (not normalized)" }, + { dir: "/sandbox//.openclaw", label: "absolute path with double slash (not normalized)" }, + { + dir: "/sandbox/.openclaw/../../etc", + label: "absolute path escapes after agent subdir via `..`", + }, ])("refuses to wipe when the agent config dir is unsafe ($label) (#5455 PRA-2)", ({ dir }) => { const { deps, runOpenshell } = buildDeps({ loadAgent: vi.fn(() => ({ From d374844cd6fd5b9c8ad45755b6be99553b7fb040 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 25 Jun 2026 15:03:57 -0700 Subject: [PATCH 11/20] docs(destroy): justify best-effort failure semantics + add shell-quote test (PRA-2 PRA-3) PRA-3 on #5455: add a regression test asserting accepted manifest paths with shell metacharacters (space, single quote, backtick, dollar sign) reach the destructive script intact and single-quoted. shellQuote already handles this; the test locks the contract so a future refactor of the targets construction can't drop it. PRA-2 on #5455: document why the wipe is intentionally best-effort on non-zero exec. The most common non-zero path is 'sandbox no longer live' (gateway down, container already stopped, transient openshell connectivity) and blocking destroy there would leave the user with an unkillable sandbox. The next re-onboard with the same name is the only path where stale workspace state surfaces, and the lifecycle test in test/cli/destroy-gateway-cleanup.test.ts already pins gateway-select -> exec -> delete order for the happy path. The destroy/re-onboard end-to-end behavioral test (PRA-1) is an E2E scenario concern. Signed-off-by: Charan Jagwani --- src/lib/actions/sandbox/wipe-state.ts | 14 +++++++++++++ test/destroy-wipe-sandbox-state.test.ts | 28 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/lib/actions/sandbox/wipe-state.ts b/src/lib/actions/sandbox/wipe-state.ts index b8ee76a2954..f120bb165cc 100644 --- a/src/lib/actions/sandbox/wipe-state.ts +++ b/src/lib/actions/sandbox/wipe-state.ts @@ -195,6 +195,20 @@ export function wipeSandboxState(sandboxName: string, deps: WipeSandboxStateDeps }, ); if (result.status !== 0) { + // #5455 PRA-2 (best-effort failure semantics, justified): destroy must + // remove the registry entry and tear down the OpenShell pod even when + // the wipe exec returns non-zero. The most common nonzero path is "the + // sandbox is no longer live" (gateway down, container already stopped, + // openshell connectivity transient): blocking destroy there would leave + // the user with an unkillable broken sandbox. The next re-onboard with + // the same name is the only path where stale workspace state actually + // surfaces, so the contract is: warn loudly here, let destroy proceed, + // and the re-onboard banner re-surfaces the warning if the PVC is + // detected as non-empty. The behavioral validation for that full + // destroy -> re-onboard -> clean-workspace contract (#5455 PRA-1) is an + // E2E concern -- the helper-level test below pins the warning and the + // CLI-level lifecycle test in test/cli/destroy-gateway-cleanup.test.ts + // pins the gateway-select-then-exec-then-delete order. console.warn( ` ${YW}⚠${R} Could not wipe workspace state for '${sandboxName}' (sandbox not live?); ` + "re-onboarding with the same name may resurface old files.", diff --git a/test/destroy-wipe-sandbox-state.test.ts b/test/destroy-wipe-sandbox-state.test.ts index d2e05effffe..0eff78c5876 100644 --- a/test/destroy-wipe-sandbox-state.test.ts +++ b/test/destroy-wipe-sandbox-state.test.ts @@ -158,6 +158,34 @@ describe("wipeSandboxState (#5449)", () => { } }); + // PRA-3 on #5455: an accepted manifest path containing shell metacharacters + // (single quote, backtick, dollar sign, space) must reach the destructive + // script intact, single-quoted, with no expansion or word-splitting risk. + // shellQuote already handles this; the assertion locks the contract in so a + // future refactor of the targets-construction can't accidentally drop it. + it("shell-quotes accepted manifest paths so metacharacters cannot break out of `rm -rf` (#5455 PRA-3)", () => { + const { deps, runOpenshell } = buildDeps({ + loadAgent: vi.fn(() => ({ + configPaths: { dir: "/sandbox/.openclaw" }, + // All relative + under config dir, so all should be accepted, but + // each carries a shell metacharacter that an unsafe construction + // would let the shell interpret. + stateDirs: ["state with space", "state'with'quote", "state`with`backtick"], + stateFiles: [{ path: "file$with$dollar" }], + })), + }); + + destroy.wipeSandboxState("test-sb", deps as never); + const { script } = execCommand(runOpenshell); + // Every accepted target appears single-quoted in the script. The escaped + // single-quote form is `'\''` (close, escaped quote, reopen). Assert each + // metacharacter target is present in its quoted form. + expect(script).toContain("'state with space'"); + expect(script).toContain("'state'\\''with'\\''quote'"); + expect(script).toContain("'state`with`backtick'"); + expect(script).toContain("'file$with$dollar'"); + }); + // PRA-2 on #5455 (round 4): a manifest declaring an unsafe top-level config // dir (e.g. `/`, `/etc`, or even `/sandbox` itself with no subdir) would let // the `cd ${dir} && rm -rf -- ...` script wipe outside the intended agent From bb03862a3042afadc818dc95fb7e53c073b21171 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Thu, 25 Jun 2026 15:11:01 -0700 Subject: [PATCH 12/20] test(destroy): behavioral test for the destroy/re-onboard contract (PRA-1 PRA-2) The advisor has been asking for end-to-end behavioral validation of #5449's repro contract: 'destroy followed by same-name re-onboard must not resurface USER.md / SOUL.md'. Stand up a real workspace directory on disk that looks like a sandbox PVC mount (with USER.md, SOUL.md, and a multi-agent workspace-* dir seeded), then have the runOpenshell mock actually shell out to against that fake mount and verify after the wipe call that: - workspace/USER.md is gone - workspace/SOUL.md is gone - workspace/ itself is gone - workspace-other-agent/ (the multi-agent glob) is gone - the agent config dir itself survives This is the closest test we can write to the actual destroy/re-onboard contract without an OpenShell sandbox in the loop. The CLI-level lifecycle test in destroy-gateway-cleanup.test.ts already pins the gateway-select -> exec -> delete order, and this test pins the 'after wipe + re-onboard re-binds the PVC, the workspace is clean' contract by executing the actual script the sandbox would run. Skipped on win32 because the script uses POSIX shell semantics. Signed-off-by: Charan Jagwani --- test/destroy-wipe-sandbox-state.test.ts | 108 ++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/test/destroy-wipe-sandbox-state.test.ts b/test/destroy-wipe-sandbox-state.test.ts index 0eff78c5876..411e8f8bc7b 100644 --- a/test/destroy-wipe-sandbox-state.test.ts +++ b/test/destroy-wipe-sandbox-state.test.ts @@ -9,6 +9,11 @@ // files (USER.md, SOUL.md, ...). Same bug class as #3114 (stale shields // state surviving destroy -> re-onboard). +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + import { describe, expect, it, vi } from "vitest"; import * as destroy from "../dist/lib/actions/sandbox/destroy.js"; @@ -252,4 +257,107 @@ describe("wipeSandboxState (#5449)", () => { // No quoted absolute path argument either (would also escape the cd). expect(rmPhase).not.toMatch(/'\//); }); + + // #5455 PRA-1 / PRA-2 (round 5): the issue's repro contract is "destroy + // followed by same-name re-onboard must not resurface USER.md / SOUL.md". + // The pure unit tests above prove command construction. This test goes + // one level deeper without needing a live OpenShell: stand up a real + // workspace directory on disk that looks like a sandbox PVC mount, point + // the script at it, and execute the actual `sh -c ''` the + // sandbox would run. After the wipe the workspace files MUST be gone -- + // i.e. a subsequent re-onboard (which re-binds the same dir) sees a + // clean state. Skips on Windows because the `cd ... && rm -rf` script + // is POSIX-shell-only. + it.skipIf(process.platform === "win32")( + "actually deletes USER.md / SOUL.md when the constructed script is executed (#5455 PRA-1/PRA-2 behavioral)", + () => { + const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-wipe-behavioral-")); + try { + // Simulate the in-sandbox PVC mount that re-onboard would re-bind. + const fakeSandboxRoot = path.join(tmpRoot, "sandbox"); + const fakeConfigDir = path.join(fakeSandboxRoot, ".openclaw"); + const fakeWorkspace = path.join(fakeConfigDir, "workspace"); + fs.mkdirSync(fakeWorkspace, { recursive: true }); + fs.writeFileSync(path.join(fakeWorkspace, "USER.md"), "user notes from prior session"); + fs.writeFileSync(path.join(fakeWorkspace, "SOUL.md"), "soul state from prior session"); + // Also seed a multi-agent workspace dir to confirm the glob works. + const fakeMultiAgentWorkspace = path.join(fakeConfigDir, "workspace-other-agent"); + fs.mkdirSync(fakeMultiAgentWorkspace); + fs.writeFileSync(path.join(fakeMultiAgentWorkspace, "USER.md"), "other agent state"); + + const runOpenshell = vi.fn( + (args: string[]): { status: number | null } => { + // The wipe script is the last argument: ["sandbox", "exec", + // "--name", "", "--", "sh", "-c", "