From b6a9893c2d1a2ddc5b86b6eba4a4a390e407f6a2 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:22:35 -0700 Subject: [PATCH 01/13] refactor(openshell): remove rebuild probe SSH Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 2 - scripts/checks/test-create-require-budget.ts | 1 - .../actions/sandbox/rebuild-destroy-phase.ts | 4 +- .../sandbox/rebuild-flow-helpers.test.ts | 30 +- .../actions/sandbox/rebuild-flow-helpers.ts | 6 +- .../state/user-managed-files-probe.test.ts | 296 +++++------------- src/lib/state/user-managed-files-probe.ts | 70 ++--- test/helpers/rebuild-flow-harness.ts | 2 +- test/helpers/rebuild-flow-test-harness.ts | 2 +- 9 files changed, 116 insertions(+), 297 deletions(-) diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index c0378ae9c7d..8a758525053 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -61,8 +61,6 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/state/sandbox.ts", "ssh-command", 8], ["src/lib/state/sandbox.ts", "ssh-temp-config", 2], ["src/lib/state/state-file-restore.ts", "ssh-command", 1], - ["src/lib/state/user-managed-files-probe.ts", "ssh-command", 1], - ["src/lib/state/user-managed-files-probe.ts", "ssh-temp-config", 1], ["src/lib/tunnel/sandbox-gateway-stop.ts", "docker-exec-command", 2], ] as const satisfies readonly ReviewedSiteTuple[]; diff --git a/scripts/checks/test-create-require-budget.ts b/scripts/checks/test-create-require-budget.ts index 05eb7934966..2632dfb3d9c 100644 --- a/scripts/checks/test-create-require-budget.ts +++ b/scripts/checks/test-create-require-budget.ts @@ -43,7 +43,6 @@ export const CLI_CREATE_REQUIRE_FILES = [ "src/lib/state/onboard-session-cross-process-lock.test.ts", "src/lib/state/onboard-session-tool-disclosure.test.ts", "src/lib/state/onboard-session.test.ts", - "src/lib/state/user-managed-files-probe.test.ts", ] as const; export const TEST_SUPPORT_CREATE_REQUIRE_FILES = [ diff --git a/src/lib/actions/sandbox/rebuild-destroy-phase.ts b/src/lib/actions/sandbox/rebuild-destroy-phase.ts index 70c7dd71a83..c7da2773f15 100644 --- a/src/lib/actions/sandbox/rebuild-destroy-phase.ts +++ b/src/lib/actions/sandbox/rebuild-destroy-phase.ts @@ -71,8 +71,8 @@ export async function runRebuildDestroyPhase( // MCP preparation removes only adapter entries whose exact ownership // fingerprints match the registry. Probe afterward so a Deep Agents // user `.mcp.json` is not confused with the separate managed projection. - // This can block on SSH, so it must finish before the final DCode check. - if (!staleRecovery) warnUnpreservedUserManagedFiles(sandboxName, log); + // Finish the read-only probe before the final DCode check. + if (!staleRecovery) await warnUnpreservedUserManagedFiles(sandboxName, log); if (validateAfterMcpPreparation) { let validation: RebuildDeleteValidationResult; try { diff --git a/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts index 76b22259a85..5e39bc84ffa 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts @@ -311,7 +311,7 @@ describe("warnUnpreservedUserManagedFiles", () => { errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); backupSpy = vi.spyOn(sandboxState, "backupSandboxState").mockReturnValue(makeBackupResult()); - probeSpy = vi.spyOn(userManagedFilesProbe, "probeUserManagedFiles").mockReturnValue({ + probeSpy = vi.spyOn(userManagedFilesProbe, "probeUserManagedFiles").mockResolvedValue({ declared: [], existing: [], }); @@ -321,13 +321,13 @@ describe("warnUnpreservedUserManagedFiles", () => { vi.restoreAllMocks(); }); - it("warns directly before a rebuild replaces user-managed MCP files", () => { - probeSpy.mockReturnValue({ + it("warns directly before a rebuild replaces user-managed MCP files", async () => { + probeSpy.mockResolvedValue({ declared: [".env", ".mcp.json"], existing: [".env", ".mcp.json"], }); - warnUnpreservedUserManagedFiles("alpha", () => undefined); + await warnUnpreservedUserManagedFiles("alpha", () => undefined); expect(probeSpy).toHaveBeenCalledOnce(); expect(probeSpy).toHaveBeenCalledWith("alpha"); @@ -342,23 +342,23 @@ describe("warnUnpreservedUserManagedFiles", () => { ); }); - it("emits no warning when probe returns no existing user-managed files", () => { - probeSpy.mockReturnValue({ + it("emits no warning when probe returns no existing user-managed files", async () => { + probeSpy.mockResolvedValue({ declared: [".env", ".mcp.json"], existing: [], }); - warnUnpreservedUserManagedFiles("alpha", () => undefined); + await warnUnpreservedUserManagedFiles("alpha", () => undefined); expect(probeSpy).toHaveBeenCalledOnce(); const warnLines = warnSpy.mock.calls.map((args: unknown[]) => String(args[0])); expect(warnLines.some((line: string) => line.includes("will not be preserved"))).toBe(false); }); - it("emits no warning when agent declares no user-managed files", () => { - probeSpy.mockReturnValue({ declared: [], existing: [] }); + it("emits no warning when agent declares no user-managed files", async () => { + probeSpy.mockResolvedValue({ declared: [], existing: [] }); - warnUnpreservedUserManagedFiles("alpha", () => undefined); + await warnUnpreservedUserManagedFiles("alpha", () => undefined); expect(probeSpy).toHaveBeenCalledOnce(); const warnLines = warnSpy.mock.calls.map((args: unknown[]) => String(args[0])); @@ -395,12 +395,12 @@ describe("warnUnpreservedUserManagedFiles", () => { expect(probeSpy).not.toHaveBeenCalled(); }); - it("surfaces a user-visible warning when the post-scrub probe errors", () => { - probeSpy.mockImplementation(() => { - throw new Error("ssh boom"); - }); + it("surfaces a user-visible warning when the post-scrub probe errors", async () => { + probeSpy.mockRejectedValue(new Error("gRPC boom")); - expect(() => warnUnpreservedUserManagedFiles("alpha", () => undefined)).not.toThrow(); + await expect( + warnUnpreservedUserManagedFiles("alpha", () => undefined), + ).resolves.toBeUndefined(); const warnLines = warnSpy.mock.calls.map((args: unknown[]) => String(args[0])); expect( diff --git a/src/lib/actions/sandbox/rebuild-flow-helpers.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.ts index a1ac1fa6f2e..d6a5be57b43 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.ts @@ -331,13 +331,13 @@ export function backupSandboxStateForRebuild( * that transaction; if the file still exists at this point it contains * additional user-owned content that the state backup intentionally excludes. */ -export function warnUnpreservedUserManagedFiles( +export async function warnUnpreservedUserManagedFiles( sandboxName: string, log: (msg: string) => void, -): void { +): Promise { let probe: userManagedFilesProbe.UserManagedFilesProbe; try { - probe = userManagedFilesProbe.probeUserManagedFiles(sandboxName); + probe = await userManagedFilesProbe.probeUserManagedFiles(sandboxName); } catch (err) { const message = err instanceof Error ? err.message : String(err); log(`User-managed file probe errored: ${message}`); diff --git a/src/lib/state/user-managed-files-probe.test.ts b/src/lib/state/user-managed-files-probe.test.ts index 52b3aba931b..6049083c81e 100644 --- a/src/lib/state/user-managed-files-probe.test.ts +++ b/src/lib/state/user-managed-files-probe.test.ts @@ -1,261 +1,105 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import child_process from "node:child_process"; -import fs from "node:fs"; -import { createRequire } from "node:module"; -import os from "node:os"; -import path from "node:path"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +const execReadOnly = vi.hoisted(() => vi.fn()); +const getSandbox = vi.hoisted(() => vi.fn()); +const loadAgent = vi.hoisted(() => vi.fn()); -type SandboxStateModule = typeof import("./sandbox"); -type RegistryModule = typeof import("./registry"); -type DefsModule = typeof import("../agent/defs"); -type ProbeModule = typeof import("./user-managed-files-probe"); +vi.mock("../adapters/openshell/sandbox-control-routing.js", () => ({ + execSandboxReadOnlyWithGrpcFallback: execReadOnly, +})); +vi.mock("./registry.js", () => ({ getSandbox })); +vi.mock("../agent/defs.js", () => ({ loadAgent })); -const requireDist = createRequire(import.meta.url); -const sandboxStatePath = "./sandbox.js"; -const registryPath = "./registry.js"; -const defsPath = "../agent/defs.js"; -const probePath = "./user-managed-files-probe.js"; - -function loadProbe(): ProbeModule { - delete require.cache[requireDist.resolve(probePath)]; - return requireDist(probePath); -} - -function loadSandboxState(): SandboxStateModule { - return requireDist(sandboxStatePath); -} - -function loadRegistry(): RegistryModule { - return requireDist(registryPath); -} - -function loadDefs(): DefsModule { - return requireDist(defsPath); -} - -function makeFakeAgent(declared: string[]): ReturnType { - return { - name: "fake-agent", - displayName: "Fake Agent", - description: null, - binaryPath: null, - versionCommand: "fake --version", - expectedVersion: null, - hasDevicePairing: false, - phoneHomeHosts: [], - runtime: { kind: "terminal" }, - healthProbe: null, - forwardPort: 0, - dashboard: { kind: "headless" }, - dashboardUi: null, - configPaths: { - dir: "/sandbox/.fake", - configFile: "config.toml", - envFile: null, - format: "toml", - }, - inferenceProviderOptions: [], - stateDirs: [], - stateFiles: [], - userManagedFiles: declared, - messagingPlatforms: [], - agentDir: "/tmp/fake-agent", - manifestPath: "/tmp/fake-agent/manifest.yaml", - } as unknown as ReturnType; -} +import { probeUserManagedFiles, USER_MANAGED_FILES_BASE } from "./user-managed-files-probe"; describe("probeUserManagedFiles", () => { - let recordedArgs: string[][]; - let spawnSpy: ReturnType; - let tempSshFiles: Set; - let originalMkdtempSync: typeof fs.mkdtempSync; - beforeEach(() => { - recordedArgs = []; - tempSshFiles = new Set(); - const sandboxState = loadSandboxState(); - const registry = loadRegistry(); - const defs = loadDefs(); - - vi.spyOn(registry, "getSandbox").mockReturnValue({ + vi.clearAllMocks(); + getSandbox.mockReturnValue({ name: "alpha", agent: "fake-agent", - } as unknown as ReturnType); - vi.spyOn(defs, "loadAgent").mockImplementation(() => makeFakeAgent([".env", ".mcp.json"])); - vi.spyOn(sandboxState, "getSshConfig").mockReturnValue( - "Host openshell-alpha\n HostName 127.0.0.1\n", - ); - - originalMkdtempSync = fs.mkdtempSync; - vi.spyOn(fs, "mkdtempSync").mockImplementation(((prefix: string): string => { - const dir = originalMkdtempSync.call(fs, prefix) as string; - tempSshFiles.add(dir); - return dir; - }) as unknown as typeof fs.mkdtempSync); - }); - - afterEach(() => { - vi.restoreAllMocks(); - for (const dir of tempSshFiles) { - try { - fs.rmSync(dir, { recursive: true, force: true }); - } catch { - /* best effort */ - } - } + gatewayName: "nemoclaw-9090", + gatewayPort: 9090, + }); + loadAgent.mockReturnValue({ userManagedFiles: [".env", ".mcp.json"] }); + execReadOnly.mockResolvedValue({ + status: 0, + stdout: ".env\n.mcp.json\n", + stderr: "", + }); }); - function stubSpawnSync(stdout: string, status: number, stderr = ""): void { - spawnSpy = vi.spyOn(child_process, "spawnSync").mockImplementation((( - command: string, - args?: readonly string[], - ) => { - const argList = Array.isArray(args) ? [...args] : []; - const sshCall = command === "ssh" && argList.length > 0; - sshCall && recordedArgs.push(argList); - return { - status, - signal: null, - output: [], - pid: 0, - stdout, - stderr, - } as ReturnType; - }) as typeof child_process.spawnSync); - } - - it("probes declared user-managed files at the sandbox root, not the agent config dir", () => { - stubSpawnSync(".env\n.mcp.json\n", 0); - const { probeUserManagedFiles, USER_MANAGED_FILES_BASE } = loadProbe(); - - const result = probeUserManagedFiles("alpha"); + it("probes declared files at the sandbox root through the named gateway", async () => { + await expect(probeUserManagedFiles("alpha")).resolves.toEqual({ + declared: [".env", ".mcp.json"], + existing: [".env", ".mcp.json"], + }); expect(USER_MANAGED_FILES_BASE).toBe("/sandbox"); - expect(result.declared).toEqual([".env", ".mcp.json"]); - expect(result.existing).toEqual([".env", ".mcp.json"]); - expect(spawnSpy).toHaveBeenCalledOnce(); - const lastArgs = recordedArgs[0] ?? []; - const probeCmd = lastArgs[lastArgs.length - 1] ?? ""; - expect(probeCmd).toContain("if [ -f '/sandbox/.env' ]"); - expect(probeCmd).toContain("if [ -f '/sandbox/.mcp.json' ]"); - expect(probeCmd).not.toContain("/sandbox/.fake/"); + expect(execReadOnly).toHaveBeenCalledWith("nemoclaw-9090", { + sandboxName: "alpha", + command: [ + "sh", + "-c", + "if [ -f '/sandbox/.env' ]; then printf '%s\\n' '.env'; fi; if [ -f '/sandbox/.mcp.json' ]; then printf '%s\\n' '.mcp.json'; fi 2>/dev/null", + ], + timeoutMs: 30_000, + }); }); - it("supports nested declared files relative to the sandbox root", () => { - const defs = loadDefs(); - vi.spyOn(defs, "loadAgent").mockImplementation(() => makeFakeAgent([".hermes/.env"])); - stubSpawnSync(".hermes/.env\n", 0); - const { probeUserManagedFiles } = loadProbe(); + it("supports nested and shell-quoted declared paths", async () => { + loadAgent.mockReturnValue({ userManagedFiles: [".hermes/.env", "user's.env"] }); + execReadOnly.mockResolvedValue({ status: 0, stdout: ".hermes/.env\n", stderr: "" }); - const result = probeUserManagedFiles("alpha"); + const result = await probeUserManagedFiles("alpha"); - expect(result.declared).toEqual([".hermes/.env"]); expect(result.existing).toEqual([".hermes/.env"]); - const lastArgs = recordedArgs[0] ?? []; - const probeCmd = lastArgs[lastArgs.length - 1] ?? ""; - expect(probeCmd).toContain("if [ -f '/sandbox/.hermes/.env' ]"); - }); - - it("returns empty existing when ssh exits 0 with no stdout (no declared files present)", () => { - stubSpawnSync("", 0); - const { probeUserManagedFiles } = loadProbe(); - - const result = probeUserManagedFiles("alpha"); - expect(result.declared).toEqual([".env", ".mcp.json"]); - expect(result.existing).toEqual([]); + const command = execReadOnly.mock.calls[0]?.[1].command[2] as string; + expect(command).toContain("'/sandbox/.hermes/.env'"); + expect(command).toContain("'/sandbox/user'\\''s.env'"); }); - it("throws when ssh exits non-zero with no stdout", () => { - stubSpawnSync("", 255, "connection refused"); - const { probeUserManagedFiles } = loadProbe(); + it("returns no existing files for an empty successful response", async () => { + execReadOnly.mockResolvedValue({ status: 0, stdout: "", stderr: "" }); - expect(() => probeUserManagedFiles("alpha")).toThrow(/user-managed file probe failed/); + await expect(probeUserManagedFiles("alpha")).resolves.toEqual({ + declared: [".env", ".mcp.json"], + existing: [], + }); }); - it("throws when sandbox has no SSH config and the agent declares user-managed files", () => { - stubSpawnSync("", 0); - const sandboxState = loadSandboxState(); - vi.spyOn(sandboxState, "getSshConfig").mockReturnValue(null); - const { probeUserManagedFiles } = loadProbe(); + it("throws with bounded diagnostics when the probe cannot produce output", async () => { + execReadOnly.mockResolvedValue({ + status: null, + stdout: "", + stderr: "connection refused", + error: new Error("UNAVAILABLE"), + }); - expect(() => probeUserManagedFiles("alpha")).toThrow( - /user-managed file probe failed: no SSH config/, + await expect(probeUserManagedFiles("alpha")).rejects.toThrow( + "user-managed file probe failed: connection refused", ); - expect(spawnSpy).not.toHaveBeenCalled(); - }); - - it("returns empty existing when sandbox has no SSH config but agent declares no user-managed files", () => { - stubSpawnSync("", 0); - const defs = loadDefs(); - vi.spyOn(defs, "loadAgent").mockImplementation(() => makeFakeAgent([])); - const sandboxState = loadSandboxState(); - vi.spyOn(sandboxState, "getSshConfig").mockReturnValue(null); - const { probeUserManagedFiles } = loadProbe(); - - const result = probeUserManagedFiles("alpha"); - expect(result.declared).toEqual([]); - expect(result.existing).toEqual([]); - expect(spawnSpy).not.toHaveBeenCalled(); - }); - - it("creates its temp SSH config inside the OS tmpdir", () => { - stubSpawnSync("", 0); - const { probeUserManagedFiles } = loadProbe(); - - probeUserManagedFiles("alpha"); - expect(tempSshFiles.size).toBeGreaterThan(0); - const tmpdir = path.resolve(os.tmpdir()); - for (const dir of tempSshFiles) { - const resolved = path.resolve(dir); - expect(resolved.startsWith(tmpdir + path.sep) || resolved === tmpdir).toBe(true); - } - }); - - it("shell-quotes unusual but permitted filenames safely", () => { - const defs = loadDefs(); - vi.spyOn(defs, "loadAgent").mockImplementation(() => makeFakeAgent(["user's.env", ".env"])); - stubSpawnSync("", 0); - const { probeUserManagedFiles } = loadProbe(); - - probeUserManagedFiles("alpha"); - const lastArgs = recordedArgs[0] ?? []; - const probeCmd = lastArgs[lastArgs.length - 1] ?? ""; - expect(probeCmd).toContain("'/sandbox/user'\\''s.env'"); - expect(probeCmd).toContain("'/sandbox/.env'"); - }); - - it("cleans up the temp SSH config on success", () => { - stubSpawnSync(".env\n", 0); - const { probeUserManagedFiles } = loadProbe(); - - probeUserManagedFiles("alpha"); - for (const dir of tempSshFiles) { - expect(fs.existsSync(dir)).toBe(false); - } }); - it("cleans up the temp SSH config on SSH failure", () => { - stubSpawnSync("", 255, "boom"); - const { probeUserManagedFiles } = loadProbe(); + it("preserves partial successful output from a nonzero remote command", async () => { + execReadOnly.mockResolvedValue({ status: 1, stdout: ".env\n", stderr: "partial" }); - expect(() => probeUserManagedFiles("alpha")).toThrow(); - for (const dir of tempSshFiles) { - expect(fs.existsSync(dir)).toBe(false); - } + await expect(probeUserManagedFiles("alpha")).resolves.toEqual({ + declared: [".env", ".mcp.json"], + existing: [".env"], + }); }); - it("returns empty declared when the agent has no user_managed_files", () => { - const defs = loadDefs(); - vi.spyOn(defs, "loadAgent").mockImplementation(() => makeFakeAgent([])); - stubSpawnSync("", 0); - const { probeUserManagedFiles } = loadProbe(); + it("skips the control plane when the agent declares no user-managed files", async () => { + loadAgent.mockReturnValue({ userManagedFiles: [] }); - const result = probeUserManagedFiles("alpha"); - expect(result.declared).toEqual([]); - expect(result.existing).toEqual([]); + await expect(probeUserManagedFiles("alpha")).resolves.toEqual({ + declared: [], + existing: [], + }); + expect(execReadOnly).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/state/user-managed-files-probe.ts b/src/lib/state/user-managed-files-probe.ts index f89ab8658e3..7597d9db869 100644 --- a/src/lib/state/user-managed-files-probe.ts +++ b/src/lib/state/user-managed-files-probe.ts @@ -1,14 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "child_process"; - +import { execSandboxReadOnlyWithGrpcFallback } from "../adapters/openshell/sandbox-control-routing.js"; import { loadAgent } from "../agent/defs.js"; +import { resolveSandboxGatewayName } from "../onboard/gateway-binding.js"; import { shellQuote } from "../runner.js"; -import { createTempSshConfig } from "../sandbox/temp-ssh-config.js"; - import * as registry from "./registry.js"; -import { getSshConfig, sshArgs } from "./sandbox.js"; export const USER_MANAGED_FILES_BASE = "/sandbox"; @@ -23,53 +20,34 @@ function _log(msg: string): void { if (_verbose()) console.error(` [user-managed-files-probe ${new Date().toISOString()}] ${msg}`); } -export function probeUserManagedFiles(sandboxName: string): UserManagedFilesProbe { +export async function probeUserManagedFiles(sandboxName: string): Promise { const sb = registry.getSandbox(sandboxName); const agentName = sb?.agent || "openclaw"; - const agent = loadAgent(agentName); - const declared = Array.isArray(agent.userManagedFiles) ? [...agent.userManagedFiles] : []; + const declared = [...(loadAgent(agentName).userManagedFiles ?? [])]; if (declared.length === 0) return { declared, existing: [] }; _log( `sandbox=${sandboxName}, agent=${agentName}, declared=[${declared.join(",")}], base=${USER_MANAGED_FILES_BASE}`, ); - - const sshConfig = getSshConfig(sandboxName); - if (!sshConfig) { - _log("no SSH config — cannot probe declared user-managed files"); - throw new Error( - "user-managed file probe failed: no SSH config available for sandbox " + sandboxName, - ); - } - - const tempSshConfig = createTempSshConfig(sshConfig, "nemoclaw-umf-"); - const configFile = tempSshConfig.file; - try { - const probeCmd = - declared - .map( - (relPath) => - `if [ -f ${shellQuote(`${USER_MANAGED_FILES_BASE}/${relPath}`)} ]; then printf '%s\\n' ${shellQuote(relPath)}; fi`, - ) - .join("; ") + " 2>/dev/null"; - const result = spawnSync("ssh", [...sshArgs(configFile, sandboxName), probeCmd], { - encoding: "utf-8", - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, - }); - const stdout = (result.stdout || "").trim(); - if (result.status !== 0 && stdout.length === 0) { - _log( - `SSH probe failed: exit=${result.status}, stderr=${(result.stderr || "").trim().substring(0, 200)}`, - ); - throw new Error( - `user-managed file probe failed: ssh exit=${result.status}, stderr=${(result.stderr || "").trim().substring(0, 200)}`, - ); - } - const existing = stdout.split("\n").filter((line) => line.length > 0); - _log(`${existing.length}/${declared.length} present in sandbox`); - return { declared, existing }; - } finally { - tempSshConfig.cleanup(); + const command = + declared + .map( + (relPath) => + `if [ -f ${shellQuote(`${USER_MANAGED_FILES_BASE}/${relPath}`)} ]; then printf '%s\\n' ${shellQuote(relPath)}; fi`, + ) + .join("; ") + " 2>/dev/null"; + const result = await execSandboxReadOnlyWithGrpcFallback(resolveSandboxGatewayName(sb), { + sandboxName, + command: ["sh", "-c", command], + timeoutMs: 30_000, + }); + const stdout = result.stdout.trim(); + if (result.status !== 0 && stdout.length === 0) { + const detail = result.stderr.trim() || result.error?.message || `exit=${result.status}`; + _log(`OpenShell probe failed: ${detail.substring(0, 200)}`); + throw new Error(`user-managed file probe failed: ${detail.substring(0, 200)}`); } + const existing = stdout.split("\n").filter((line) => line.length > 0); + _log(`${existing.length}/${declared.length} present in sandbox`); + return { declared, existing }; } diff --git a/test/helpers/rebuild-flow-harness.ts b/test/helpers/rebuild-flow-harness.ts index 1f225534c74..d10a4cd8085 100644 --- a/test/helpers/rebuild-flow-harness.ts +++ b/test/helpers/rebuild-flow-harness.ts @@ -614,7 +614,7 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): .mockResolvedValue(undefined); const warnUnpreservedUserManagedFilesSpy = vi .spyOn(rebuildFlowHelpers, "warnUnpreservedUserManagedFiles") - .mockImplementation(() => undefined); + .mockResolvedValue(undefined); errorSpy.mockClear(); logSpy.mockClear(); diff --git a/test/helpers/rebuild-flow-test-harness.ts b/test/helpers/rebuild-flow-test-harness.ts index d9164c137d6..c4a16dda1eb 100644 --- a/test/helpers/rebuild-flow-test-harness.ts +++ b/test/helpers/rebuild-flow-test-harness.ts @@ -137,7 +137,7 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): vi.spyOn(rebuildUsageNotice, "ensureRebuildUsageNoticeAccepted").mockResolvedValue(true); const warnUnpreservedUserManagedFilesSpy = vi .spyOn(rebuildFlowHelpers, "warnUnpreservedUserManagedFiles") - .mockImplementation(() => undefined); + .mockResolvedValue(undefined); vi.spyOn(resolve, "resolveOpenshell").mockReturnValue(null); vi.spyOn(agentDefs, "loadAgent").mockReturnValue(agentDef); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ name: "openclaw" }); From 485274a271afb15415447861c740c822f703702a Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:14:12 -0700 Subject: [PATCH 02/13] refactor(openshell): remove skill SSH transport Signed-off-by: Aaron Erickson --- docs/reference/commands.mdx | 6 + scripts/checks/legacy-sandbox-transports.ts | 3 - src/lib/actions/sandbox/skill-install.test.ts | 105 +++++------ src/lib/actions/sandbox/skill-install.ts | 73 ++++---- .../adapters/openshell/grpc-gateway-config.ts | 14 +- .../openshell/sandbox-control-routing.test.ts | 59 +++++- .../openshell/sandbox-control-routing.ts | 44 ++++- src/lib/skill-install.test.ts | 81 ++++++--- src/lib/skill-install.ts | 65 ++++--- src/lib/skill-remote.test.ts | 171 +++++++++--------- src/lib/skill-remote.ts | 153 ++++++---------- 11 files changed, 430 insertions(+), 344 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 0a43fe93d86..64f83ea6b6b 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2068,6 +2068,11 @@ $$nemoclaw my-assistant mcp remove github [--force] Deploy a skill directory to a running sandbox. The command validates the `SKILL.md` frontmatter (a `name` field is required), uploads all non-dot files preserving subdirectory structure, and performs agent-specific post-install steps. +NemoClaw selects one OpenShell sandbox execution transport before it changes the skill. +It uses the named gateway's direct gRPC API for plaintext, mTLS, and OIDC gateways. +It preselects the OpenShell CLI only when Cloudflare edge-tunnel authentication requires the CLI-owned tunnel. +Any other direct-client configuration error stops the command before dispatch. +After dispatch starts, NemoClaw never retries the mutation through another transport. ```bash $$nemoclaw my-assistant skill install ./my-skill/ @@ -2111,6 +2116,7 @@ For new installs, the agent session index is refreshed so the agent discovers th Remove an installed skill from a running sandbox by skill name. The command validates the skill name, removes the sandbox upload directory, and refreshes the agent session index so the remaining skills are rediscovered on the next session. +It uses the same preselected, fail-closed OpenShell control path as `skill install`. diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index f41ca728cbd..c0378ae9c7d 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -38,8 +38,6 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/actions/sandbox/process-recovery.ts", "privileged-sandbox-exec", 2], ["src/lib/actions/sandbox/process-recovery.ts", "ssh-command", 1], ["src/lib/actions/sandbox/process-recovery.ts", "ssh-temp-config", 1], - ["src/lib/actions/sandbox/skill-install.ts", "openshell-ssh-config", 2], - ["src/lib/actions/sandbox/skill-install.ts", "ssh-temp-config", 2], ["src/lib/actions/sandbox/snapshot.ts", "docker-exec-command", 1], ["src/lib/adapters/docker/container.ts", "docker-exec-command", 1], ["src/lib/adapters/openshell/client.ts", "openshell-ssh-config", 1], @@ -56,7 +54,6 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/share-command.ts", "sshfs-command", 1], ["src/lib/shields/index.ts", "privileged-sandbox-exec", 4], ["src/lib/shields/mutable-config-repair.ts", "privileged-sandbox-exec", 2], - ["src/lib/skill-remote.ts", "ssh-command", 1], ["src/lib/state/openclaw-config-restore-input.ts", "ssh-command", 1], ["src/lib/state/openclaw-plugin-restore.ts", "ssh-command", 2], ["src/lib/state/openclaw-plugin-restore.ts", "ssh-temp-config", 1], diff --git a/src/lib/actions/sandbox/skill-install.test.ts b/src/lib/actions/sandbox/skill-install.test.ts index 9f1dba812de..e34e58b56af 100644 --- a/src/lib/actions/sandbox/skill-install.test.ts +++ b/src/lib/actions/sandbox/skill-install.test.ts @@ -6,7 +6,10 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const captureSandboxSshConfig = vi.hoisted(() => vi.fn()); +const selectOpenShellSandboxControlForMutation = vi.hoisted(() => vi.fn()); +const closeControl = vi.hoisted(() => vi.fn()); +const control = vi.hoisted(() => ({ exec: vi.fn() })); +const getSandbox = vi.hoisted(() => vi.fn()); const getSessionAgent = vi.hoisted(() => vi.fn()); const ensureLiveSandboxOrExit = vi.hoisted(() => vi.fn()); const skillInstall = vi.hoisted(() => ({ @@ -22,10 +25,12 @@ const skillInstall = vi.hoisted(() => ({ verifyInstall: vi.fn(), })); -vi.mock("../../adapters/openshell/runtime", () => ({ - captureSandboxSshConfig, +vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ + selectOpenShellSandboxControlForMutation, })); +vi.mock("../../state/registry", () => ({ getSandbox })); + vi.mock("../../agent/runtime", () => ({ getSessionAgent, })); @@ -57,14 +62,6 @@ function restoreExitCode(previousExitCode: typeof process.exitCode): void { process.exitCode = previousExitCode; } -function expectTempSshConfigCleanedUp(configFile: string): void { - const configDir = path.dirname(configFile); - expect(configDir).not.toBe(os.tmpdir()); - expect(path.basename(configDir)).toMatch(/^nemoclaw-ssh-skill-/); - expect(path.basename(configFile)).toBe("ssh_config"); - expect(fs.existsSync(configDir)).toBe(false); -} - describe("sandbox skill action orchestration", () => { let previousExitCode: typeof process.exitCode; @@ -73,34 +70,39 @@ describe("sandbox skill action orchestration", () => { process.exitCode = undefined; vi.clearAllMocks(); - captureSandboxSshConfig.mockReturnValue({ status: 0, output: "Host openshell-alpha\n" }); + selectOpenShellSandboxControlForMutation.mockReturnValue({ + control, + transport: "grpc", + close: closeControl, + }); + getSandbox.mockReturnValue({ gatewayName: "nemoclaw-9090", gatewayPort: 9090 }); ensureLiveSandboxOrExit.mockResolvedValue(undefined); getSessionAgent.mockReturnValue(agent); skillInstall.validateSkillName.mockReturnValue(true); skillInstall.resolveSkillPaths.mockReturnValue(paths); - skillInstall.checkExisting.mockReturnValue(true); - skillInstall.removeSkill.mockReturnValue({ + skillInstall.checkExisting.mockResolvedValue(true); + skillInstall.removeSkill.mockResolvedValue({ success: true, removedUploadDir: true, removedMirrorDir: true, clearedSessions: true, messages: [], }); - skillInstall.verifyRemove.mockReturnValue(true); + skillInstall.verifyRemove.mockResolvedValue(true); skillInstall.parseFrontmatter.mockReturnValue({ name: "demo-skill" }); skillInstall.collectFiles.mockReturnValue({ files: ["SKILL.md"], skippedDotfiles: [], unsafePaths: [], }); - skillInstall.uploadDirectory.mockReturnValue({ + skillInstall.uploadDirectory.mockResolvedValue({ uploaded: 1, failed: [], skippedDotfiles: [], unsafePaths: [], }); - skillInstall.postInstall.mockReturnValue({ success: true, messages: [] }); - skillInstall.verifyInstall.mockReturnValue(true); + skillInstall.postInstall.mockResolvedValue({ success: true, messages: [] }); + skillInstall.verifyInstall.mockResolvedValue(true); }); afterEach(() => { @@ -108,8 +110,10 @@ describe("sandbox skill action orchestration", () => { vi.restoreAllMocks(); }); - it("fails skill remove when SSH config capture fails", async () => { - captureSandboxSshConfig.mockReturnValue({ status: 1, output: "" }); + it("fails skill remove before dispatch when control selection fails", async () => { + selectOpenShellSandboxControlForMutation.mockImplementation(() => { + throw new Error("invalid mTLS material"); + }); const error = vi.spyOn(console, "error").mockImplementation(() => undefined); const exit = vi.spyOn(process, "exit").mockImplementation(((code?: string | number | null) => { throw new Error(`process.exit ${code}`); @@ -120,19 +124,16 @@ describe("sandbox skill action orchestration", () => { ); expect(ensureLiveSandboxOrExit).toHaveBeenCalledWith("alpha"); - expect(captureSandboxSshConfig).toHaveBeenCalledWith("alpha", expect.any(Object)); - expect(error).toHaveBeenCalledWith(" Failed to obtain SSH configuration for the sandbox."); + expect(selectOpenShellSandboxControlForMutation).toHaveBeenCalledWith("nemoclaw-9090"); + expect(error).toHaveBeenCalledWith( + " Failed to configure OpenShell sandbox execution: invalid mTLS material", + ); expect(skillInstall.checkExisting).not.toHaveBeenCalled(); expect(exit).toHaveBeenCalledWith(1); }); - it("treats unknown skill existence as fatal for remove and deletes the temp SSH config", async () => { - let tempConfig = ""; - skillInstall.checkExisting.mockImplementation((ctx) => { - tempConfig = ctx.configFile; - expect(fs.existsSync(tempConfig)).toBe(true); - return null; - }); + it("treats unknown skill existence as fatal for remove and closes the control", async () => { + skillInstall.checkExisting.mockResolvedValue(null); const error = vi.spyOn(console, "error").mockImplementation(() => undefined); await removeSandboxSkill("alpha", { name: "demo-skill" }); @@ -143,16 +144,11 @@ describe("sandbox skill action orchestration", () => { ); expect(skillInstall.removeSkill).not.toHaveBeenCalled(); expect(skillInstall.verifyRemove).not.toHaveBeenCalled(); - expect(tempConfig).not.toBe(""); - expect(fs.existsSync(tempConfig)).toBe(false); + expect(closeControl).toHaveBeenCalledOnce(); }); - it("reports an absent skill for remove and deletes the temp SSH config", async () => { - let tempConfig = ""; - skillInstall.checkExisting.mockImplementation((ctx) => { - tempConfig = ctx.configFile; - return false; - }); + it("reports an absent skill for remove and closes the control", async () => { + skillInstall.checkExisting.mockResolvedValue(false); const error = vi.spyOn(console, "error").mockImplementation(() => undefined); await removeSandboxSkill("alpha", { name: "demo-skill" }); @@ -161,14 +157,12 @@ describe("sandbox skill action orchestration", () => { expect(error).toHaveBeenCalledWith(" Skill 'demo-skill' is not installed in sandbox 'alpha'."); expect(skillInstall.removeSkill).not.toHaveBeenCalled(); expect(skillInstall.verifyRemove).not.toHaveBeenCalled(); - expect(tempConfig).not.toBe(""); - expect(fs.existsSync(tempConfig)).toBe(false); + expect(closeControl).toHaveBeenCalledOnce(); }); - it("removes and verifies an existing skill, then deletes the temp SSH config", async () => { - let tempConfig = ""; - skillInstall.checkExisting.mockImplementation((ctx, resolvedPaths) => { - tempConfig = ctx.configFile; + it("removes and verifies an existing skill, then closes the selected control", async () => { + skillInstall.checkExisting.mockImplementation(async (ctx, resolvedPaths) => { + expect(ctx.control).toBe(control); expect(resolvedPaths).toBe(paths); return true; }); @@ -179,17 +173,13 @@ describe("sandbox skill action orchestration", () => { expect(ensureLiveSandboxOrExit).toHaveBeenCalledWith("alpha"); expect(getSessionAgent).toHaveBeenCalledWith("alpha"); expect(skillInstall.resolveSkillPaths).toHaveBeenCalledWith(agent, "demo-skill"); - expect(skillInstall.removeSkill).toHaveBeenCalledWith( - expect.objectContaining({ configFile: tempConfig, sandboxName: "alpha" }), - paths, - ); + expect(skillInstall.removeSkill).toHaveBeenCalledWith({ control, sandboxName: "alpha" }, paths); expect(skillInstall.verifyRemove).toHaveBeenCalledWith( - expect.objectContaining({ configFile: tempConfig, sandboxName: "alpha" }), + { control, sandboxName: "alpha" }, paths, ); expect(log).toHaveBeenCalledWith(expect.stringContaining("Skill 'demo-skill' removed")); - expect(fs.existsSync(tempConfig)).toBe(false); - expectTempSshConfigCleanedUp(tempConfig); + expect(closeControl).toHaveBeenCalledOnce(); expect(process.exitCode).toBeUndefined(); }); @@ -207,17 +197,13 @@ describe("sandbox skill action orchestration", () => { } expect(ensureLiveSandboxOrExit).toHaveBeenCalledWith("alpha"); - expect(captureSandboxSshConfig).not.toHaveBeenCalled(); + expect(selectOpenShellSandboxControlForMutation).not.toHaveBeenCalled(); expect(skillInstall.uploadDirectory).not.toHaveBeenCalled(); }); it("continues skill install when the existence probe is unknown because upload plus verify are authoritative", async () => { const skillDir = makeSkillDir(); - let tempConfig = ""; - skillInstall.checkExisting.mockImplementation((ctx) => { - tempConfig = ctx.configFile; - return null; - }); + skillInstall.checkExisting.mockResolvedValue(null); const error = vi.spyOn(console, "error").mockImplementation(() => undefined); const log = vi.spyOn(console, "log").mockImplementation(() => undefined); @@ -233,17 +219,16 @@ describe("sandbox skill action orchestration", () => { ), ); expect(skillInstall.uploadDirectory).toHaveBeenCalledWith( - expect.objectContaining({ configFile: tempConfig, sandboxName: "alpha" }), + { control, sandboxName: "alpha" }, skillDir, paths.uploadDir, ); expect(skillInstall.verifyInstall).toHaveBeenCalledWith( - expect.objectContaining({ configFile: tempConfig, sandboxName: "alpha" }), + { control, sandboxName: "alpha" }, paths, ); expect(log).toHaveBeenCalledWith(expect.stringContaining("Skill 'demo-skill' installed")); - expect(fs.existsSync(tempConfig)).toBe(false); - expectTempSshConfigCleanedUp(tempConfig); + expect(closeControl).toHaveBeenCalledOnce(); expect(process.exitCode).toBeUndefined(); }); }); diff --git a/src/lib/actions/sandbox/skill-install.ts b/src/lib/actions/sandbox/skill-install.ts index 3eb9d547257..e5720e808ef 100644 --- a/src/lib/actions/sandbox/skill-install.ts +++ b/src/lib/actions/sandbox/skill-install.ts @@ -3,13 +3,16 @@ import fs from "node:fs"; import path from "node:path"; -import { captureSandboxSshConfig } from "../../adapters/openshell/runtime"; -import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; +import { + type OpenShellMutationControlSelection, + selectOpenShellSandboxControlForMutation, +} from "../../adapters/openshell/sandbox-control-routing"; import * as agentRuntime from "../../agent/runtime"; import { CLI_NAME } from "../../cli/branding"; import { D, G, R, YW } from "../../cli/terminal-style"; -import { createTempSshConfig } from "../../sandbox/temp-ssh-config"; +import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import * as skillInstall from "../../skill-install"; +import * as registry from "../../state/registry"; import { ensureLiveSandboxOrExit } from "./gateway-state"; export function printSkillInstallUsage(): void { @@ -80,6 +83,18 @@ export function printPluginInstallHint(): void { ); } +function selectSkillControl(sandboxName: string): OpenShellMutationControlSelection { + try { + return selectOpenShellSandboxControlForMutation( + resolveSandboxGatewayName(registry.getSandbox(sandboxName)), + ); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + console.error(` Failed to configure OpenShell sandbox execution: ${detail}`); + process.exit(1); + } +} + /** * Remove an installed skill from a live sandbox by name. */ @@ -114,21 +129,12 @@ export async function removeSandboxSkill( const agent = agentRuntime.getSessionAgent(sandboxName); const paths = skillInstall.resolveSkillPaths(agent, skillName); - const sshConfigResult = captureSandboxSshConfig(sandboxName, { - ignoreError: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }); - if (sshConfigResult.status !== 0) { - console.error(" Failed to obtain SSH configuration for the sandbox."); - process.exit(1); - } - - const tmpSshConfig = createTempSshConfig(sshConfigResult.output, "nemoclaw-ssh-skill-"); + const selected = selectSkillControl(sandboxName); try { - const ctx = { configFile: tmpSshConfig.file, sandboxName }; + const ctx = { control: selected.control, sandboxName }; - const existsCheck = skillInstall.checkExisting(ctx, paths); + const existsCheck = await skillInstall.checkExisting(ctx, paths); if (existsCheck === null) { console.error( ` Could not check if skill '${skillName}' exists — sandbox may be unreachable.`, @@ -142,7 +148,7 @@ export async function removeSandboxSkill( return; } - const result = skillInstall.removeSkill(ctx, paths); + const result = await skillInstall.removeSkill(ctx, paths); for (const msg of result.messages) { if (msg.startsWith("Warning:")) { console.error(` ${YW}${msg}${R}`); @@ -151,7 +157,7 @@ export async function removeSandboxSkill( } } - const gone = skillInstall.verifyRemove(ctx, paths); + const gone = await skillInstall.verifyRemove(ctx, paths); if (gone) { console.log(` ${G}✓${R} Skill '${skillName}' removed`); } else { @@ -161,7 +167,7 @@ export async function removeSandboxSkill( return; } } finally { - tmpSshConfig.cleanup(); + selected.close(); } } @@ -273,30 +279,21 @@ export async function installSandboxSkill( const agent = agentRuntime.getSessionAgent(sandboxName); const paths = skillInstall.resolveSkillPaths(agent, frontmatter.name); - // 4. Get SSH config - const sshConfigResult = captureSandboxSshConfig(sandboxName, { - ignoreError: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }); - if (sshConfigResult.status !== 0) { - console.error(" Failed to obtain SSH configuration for the sandbox."); - process.exit(1); - } - - const tmpSshConfig = createTempSshConfig(sshConfigResult.output, "nemoclaw-ssh-skill-"); + // 4. Select one control-plane transport before any mutation. + const selected = selectSkillControl(sandboxName); try { - const ctx = { configFile: tmpSshConfig.file, sandboxName }; + const ctx = { control: selected.control, sandboxName }; // 5. Check if skill already exists (update vs fresh install). This probe is - // advisory for install only: stale SSH config files and transient remote - // shell startup failures can make the stat probe inconclusive even when a + // advisory for install only: transient control-plane or remote shell + // failures can make the stat probe inconclusive even when a // subsequent upload succeeds. Upload plus verifyInstall() remain the // source of truth for install success; remove keeps null fatal because it - // is destructive. Once OpenShell exposes a typed stat API or SSH probe + // is destructive. Once OpenShell exposes a typed stat API or exec probe // failures are reliably distinguishable from absent dirs across supported // versions, remove this fallback and fail before upload. - const existingCheck = skillInstall.checkExisting(ctx, paths); + const existingCheck = await skillInstall.checkExisting(ctx, paths); if (existingCheck === null) { console.error( ` ${YW}Warning: could not check sandbox for existing skill — treating as fresh install.${R}`, @@ -305,7 +302,7 @@ export async function installSandboxSkill( const isUpdate = existingCheck === true; // 6. Upload skill directory - const { uploaded, failed } = skillInstall.uploadDirectory(ctx, skillDir, paths.uploadDir); + const { uploaded, failed } = await skillInstall.uploadDirectory(ctx, skillDir, paths.uploadDir); if (failed.length > 0) { console.error(` Failed to upload ${failed.length} file(s): ${failed.join(", ")}`); process.exit(1); @@ -315,7 +312,7 @@ export async function installSandboxSkill( // 7. Post-install (OpenClaw mirror + refresh, or restart hint). // OpenClaw caches skill content per session, so always refresh the // session index after an install/update to avoid stale SKILL.md data. - const post = skillInstall.postInstall(ctx, paths, skillDir); + const post = await skillInstall.postInstall(ctx, paths, skillDir); for (const msg of post.messages) { if (msg.startsWith("Warning:")) { console.error(` ${YW}${msg}${R}`); @@ -325,7 +322,7 @@ export async function installSandboxSkill( } // 8. Verify - const verified = skillInstall.verifyInstall(ctx, paths); + const verified = await skillInstall.verifyInstall(ctx, paths); if (verified) { const verb = isUpdate ? "updated" : "installed"; console.log(` ${G}✓${R} Skill '${frontmatter.name}' ${verb}`); @@ -337,6 +334,6 @@ export async function installSandboxSkill( process.exit(1); } } finally { - tmpSshConfig.cleanup(); + selected.close(); } } diff --git a/src/lib/adapters/openshell/grpc-gateway-config.ts b/src/lib/adapters/openshell/grpc-gateway-config.ts index ace3611bf52..4492dc915db 100644 --- a/src/lib/adapters/openshell/grpc-gateway-config.ts +++ b/src/lib/adapters/openshell/grpc-gateway-config.ts @@ -38,6 +38,16 @@ export interface ResolvedOpenShellGrpcGateway { clientConfig: OpenShellGrpcClientConfig; } +/** Direct gRPC cannot traverse OpenShell's CLI-owned Cloudflare edge tunnel. */ +export class OpenShellGrpcEdgeTunnelRequiredError extends Error { + constructor() { + super( + "OpenShell Cloudflare JWT gateways require the OpenShell edge tunnel and are not supported by the direct gRPC client", + ); + this.name = "OpenShellGrpcEdgeTunnelRequiredError"; + } +} + function validateGatewayName(name: string): void { if ( !name || @@ -234,9 +244,7 @@ export function resolveOpenShellGrpcGateway( } clientConfig = oidcConfig(metadata.gateway_endpoint, gatewayDir, nowSeconds); } else if (authMode === "cloudflare_jwt") { - throw new Error( - "OpenShell Cloudflare JWT gateways require the OpenShell edge tunnel and are not supported by the direct gRPC client", - ); + throw new OpenShellGrpcEdgeTunnelRequiredError(); } else { throw new Error(`Unsupported OpenShell gateway auth mode '${authMode}'`); } diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index d4f87339854..393a4c17103 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -4,8 +4,12 @@ import { describe, expect, it, vi } from "vitest"; import type { GrpcOpenShellSandboxControl } from "./grpc-sandbox-control"; +import { OpenShellGrpcEdgeTunnelRequiredError } from "./grpc-gateway-config"; import type { OpenShellSandboxControl, SandboxExecResult } from "./sandbox-control"; -import { execSandboxReadOnlyWithGrpcFallback } from "./sandbox-control-routing"; +import { + execSandboxReadOnlyWithGrpcFallback, + selectOpenShellSandboxControlForMutation, +} from "./sandbox-control-routing"; import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: SandboxExecResult) { @@ -109,3 +113,56 @@ describe("read-only OpenShell sandbox control routing", () => { ); }); }); + +describe("mutating OpenShell sandbox control routing", () => { + it("selects direct gRPC before a mutation and exposes its close hook", () => { + const test = dependencies({ status: 0, stdout: "grpc", stderr: "" }); + + const selected = selectOpenShellSandboxControlForMutation("nemoclaw", test.deps); + + expect(selected).toMatchObject({ control: expect.any(Object), transport: "grpc" }); + expect(selected.control).not.toBe(test.deps.cli); + selected.close(); + expect(test.close).toHaveBeenCalledOnce(); + }); + + it("preselects the CLI only for the edge-tunnel auth mode", () => { + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + test.createGrpc.mockImplementation(() => { + throw new OpenShellGrpcEdgeTunnelRequiredError(); + }); + + const selected = selectOpenShellSandboxControlForMutation("edge", test.deps); + + expect(selected).toEqual({ + control: test.deps.cli, + transport: "cli-edge-tunnel", + close: expect.any(Function), + }); + selected.close(); + expect(test.close).not.toHaveBeenCalled(); + }); + + it("does not turn a completed mutation into failure when the client cannot close", () => { + const test = dependencies({ status: 0, stdout: "grpc", stderr: "" }); + const error = new Error("close failed"); + test.close.mockImplementation(() => { + throw error; + }); + const selected = selectOpenShellSandboxControlForMutation("nemoclaw", test.deps); + + expect(() => selected.close()).not.toThrow(); + expect(test.debug).toHaveBeenCalledWith("OpenShell direct gRPC client close failed", error); + }); + + it("fails before dispatch for every other direct-client configuration error", () => { + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + const error = new Error("invalid mTLS material"); + test.createGrpc.mockImplementation(() => { + throw error; + }); + + expect(() => selectOpenShellSandboxControlForMutation("nemoclaw", test.deps)).toThrow(error); + expect(test.cliExec).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index f170bb100a6..453323b4b37 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -3,7 +3,10 @@ import { log } from "../../cli/logger"; import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; -import { createGrpcOpenShellSandboxControlForGateway } from "./grpc-gateway-config"; +import { + createGrpcOpenShellSandboxControlForGateway, + OpenShellGrpcEdgeTunnelRequiredError, +} from "./grpc-gateway-config"; import { createCliOpenShellSandboxControl, type OpenShellSandboxControl, @@ -24,6 +27,45 @@ const defaultDependencies: ReadOnlyRoutingDependencies = { debug: (message, context) => log.debug(message, context), }; +export interface OpenShellMutationControlSelection { + control: OpenShellSandboxControl; + transport: "grpc" | "cli-edge-tunnel"; + close(): void; +} + +/** + * Select one transport before a mutating workflow starts. Direct gRPC is the + * default. The CLI is selected only for the explicit Cloudflare edge-tunnel + * mode that a direct client cannot traverse. This function never retries an + * operation after dispatch. + */ +export function selectOpenShellSandboxControlForMutation( + gatewayName: string, + dependencies: ReadOnlyRoutingDependencies = defaultDependencies, +): OpenShellMutationControlSelection { + try { + const grpc = dependencies.createGrpc(gatewayName); + return { + control: grpc, + transport: "grpc", + close: () => { + try { + grpc.close(); + } catch (error) { + dependencies.debug("OpenShell direct gRPC client close failed", error); + } + }, + }; + } catch (error) { + if (!(error instanceof OpenShellGrpcEdgeTunnelRequiredError)) throw error; + return { + control: dependencies.cli, + transport: "cli-edge-tunnel", + close: () => {}, + }; + } +} + /** * Prefer direct gRPC for a read-only sandbox exec and retry through the * OpenShell CLI when gateway resolution or transport fails. This retry policy diff --git a/src/lib/skill-install.test.ts b/src/lib/skill-install.test.ts index d3d1438327b..72155f7deec 100644 --- a/src/lib/skill-install.test.ts +++ b/src/lib/skill-install.test.ts @@ -12,10 +12,18 @@ import { postInstall, resolveSkillPaths, shellQuote, + uploadFile, validateRelativePath, verifyInstall, } from "./skill-install"; +const controlContext = { + control: { + exec: async () => ({ status: 0, stdout: "", stderr: "" }), + }, + sandboxName: "alpha", +}; + describe("parseFrontmatter", () => { it("extracts name from valid frontmatter", () => { const result = parseFrontmatter("---\nname: my-skill\ndescription: test\n---\n# Body"); @@ -251,17 +259,17 @@ describe("resolveSkillPaths", () => { }); describe("postInstall", () => { - it("refreshes OpenClaw sessions after installing an updated skill", () => { + it("refreshes OpenClaw sessions after installing an updated skill", async () => { const skillDir = mkdtempSync(join(tmpdir(), "skill-postinstall-")); const commands: string[] = []; try { writeFileSync(skillDir + "/SKILL.md", "---\nname: weather\n---\n# Weather\n"); - const result = postInstall( - { configFile: "/tmp/ssh-config", sandboxName: "alpha" }, + const result = await postInstall( + controlContext, resolveSkillPaths(null, "weather"), skillDir, { - sshExecImpl: (_ctx, command) => { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "", stderr: "" }; }, @@ -277,7 +285,7 @@ describe("postInstall", () => { } }); - it("mirrors the uploaded skill into the OpenClaw home dir so the agent loads it", () => { + it("mirrors the uploaded skill into the OpenClaw home dir so the agent loads it", async () => { // Regression for #4819: on sandboxes whose agent $HOME differs from the // OpenClaw state dir, `skills list` shows the upload dir while the agent // loads skills from $HOME/.openclaw/skills. Install must populate that @@ -287,8 +295,8 @@ describe("postInstall", () => { try { writeFileSync(skillDir + "/SKILL.md", "---\nname: report-writer\n---\n# Report\n"); const paths = resolveSkillPaths(null, "report-writer"); - postInstall({ configFile: "/tmp/ssh-config", sandboxName: "alpha" }, paths, skillDir, { - sshExecImpl: (_ctx, command) => { + await postInstall(controlContext, paths, skillDir, { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "", stderr: "" }; }, @@ -307,24 +315,19 @@ describe("postInstall", () => { } }); - it("warns when the OpenClaw home mirror cannot be created", () => { + it("warns when the OpenClaw home mirror cannot be created", async () => { const skillDir = mkdtempSync(join(tmpdir(), "skill-postinstall-mirror-fail-")); try { writeFileSync(skillDir + "/SKILL.md", "---\nname: report-writer\n---\n# Report\n"); const paths = resolveSkillPaths(null, "report-writer"); - const result = postInstall( - { configFile: "/tmp/ssh-config", sandboxName: "alpha" }, - paths, - skillDir, - { - sshExecImpl: (_ctx, command) => ({ - // Fail only the mirror command; session refresh still succeeds. - status: command.includes("$HOME/.openclaw/skills") ? 1 : 0, - stdout: "", - stderr: "", - }), - }, - ); + const result = await postInstall(controlContext, paths, skillDir, { + execImpl: async (_ctx, command) => ({ + // Fail only the mirror command; session refresh still succeeds. + status: command.includes("$HOME/.openclaw/skills") ? 1 : 0, + stdout: "", + stderr: "", + }), + }); expect(result.success).toBe(true); expect(result.messages.some((m) => m.startsWith("Warning:") && m.includes("mirror"))).toBe( @@ -337,14 +340,14 @@ describe("postInstall", () => { }); describe("verifyInstall", () => { - it("requires SKILL.md in the OpenClaw home mirror, not only the upload dir (#4819)", () => { + it("requires SKILL.md in the OpenClaw home mirror, not only the upload dir (#4819)", async () => { // The agent loads skills from the home mirror, so an install whose mirror // copy failed must NOT verify as installed — otherwise the CLI reports // success while the skill stays invisible to the agent. const paths = resolveSkillPaths(null, "report-writer"); const commands: string[] = []; - const ok = verifyInstall({ configFile: "/tmp/ssh-config", sandboxName: "alpha" }, paths, { - sshExecImpl: (_ctx, command) => { + const ok = await verifyInstall(controlContext, paths, { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "EXISTS", stderr: "" }; }, @@ -357,14 +360,38 @@ describe("verifyInstall", () => { ).toBe(true); }); - it("returns false when the upload dir has SKILL.md but the home mirror does not", () => { + it("returns false when the upload dir has SKILL.md but the home mirror does not", async () => { const paths = resolveSkillPaths(null, "report-writer"); - const ok = verifyInstall({ configFile: "/tmp/ssh-config", sandboxName: "alpha" }, paths, { + const ok = await verifyInstall(controlContext, paths, { // A combined `test -f A && test -f B` shell command fails (non-zero, // no EXISTS) when the mirror file is absent. - sshExecImpl: () => ({ status: 1, stdout: "", stderr: "" }), + execImpl: async () => ({ status: 1, stdout: "", stderr: "" }), }); expect(ok).toBe(false); }); }); + +describe("uploadFile", () => { + it("sends file bytes through sandbox exec stdin", async () => { + const dir = mkdtempSync(join(tmpdir(), "skill-upload-")); + const localPath = join(dir, "binary.dat"); + const input = Buffer.from([0, 255, 10]); + writeFileSync(localPath, input); + let observedInput: string | Buffer | undefined; + try { + const result = await uploadFile(controlContext, localPath, "/sandbox/skill", "binary.dat", { + execImpl: async (_ctx, command, options) => { + expect(command).toBe("mkdir -p '/sandbox/skill' && cat > '/sandbox/skill/binary.dat'"); + observedInput = options?.input; + return { status: 0, stdout: "", stderr: "" }; + }, + }); + + expect(result?.status).toBe(0); + expect(observedInput).toEqual(input); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/lib/skill-install.ts b/src/lib/skill-install.ts index ffdcaf06e70..f6f5a6d7724 100644 --- a/src/lib/skill-install.ts +++ b/src/lib/skill-install.ts @@ -3,7 +3,7 @@ // // Skill install/remove logic for `nemoclaw skill install ` // and `nemoclaw skill remove `. -// Validates a local SKILL.md, uploads it to the sandbox via SSH, and +// Validates a local SKILL.md, uploads it through OpenShell sandbox exec, and // performs agent-specific post-install steps (session refresh for // OpenClaw). Non-OpenClaw agents get a "restart gateway" hint until a // generic refresh contract is defined in the manifest schema. @@ -16,18 +16,19 @@ import YAML from "yaml"; import { isObjectRecord } from "./core/json-types"; import { validateSkillName } from "./skill-name"; -import type { SshContext, SshResult } from "./skill-remote"; -import { shellQuote, sshExec } from "./skill-remote"; +import type { SandboxCommandResult, SandboxControlContext, SandboxExecImpl } from "./skill-remote"; +import { sandboxExec, shellQuote } from "./skill-remote"; export { validateSkillName } from "./skill-name"; export { checkExisting, type RemoveResult, removeSkill, - type SshContext, - type SshResult, + type SandboxCommandResult, + type SandboxControlContext, + type SandboxExecImpl, + sandboxExec, shellQuote, - sshExec, verifyRemove, } from "./skill-remote"; @@ -146,19 +147,20 @@ export function validateRelativePath(rel: string): boolean { // ── Upload helpers ─────────────────────────────────────────────── /** - * Upload a file to the sandbox by piping its content through SSH stdin. + * Upload a file to the sandbox through the selected OpenShell control plane. * Creates the target directory and writes the file in a single remote command. */ -export function uploadFile( - ctx: SshContext, +export async function uploadFile( + ctx: SandboxControlContext, localPath: string, remoteDir: string, remoteFilename: string, -): SshResult | null { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise { const content = fs.readFileSync(localPath); const remotePath = `${remoteDir}/${remoteFilename}`; const script = `mkdir -p ${shellQuote(remoteDir)} && cat > ${shellQuote(remotePath)}`; - return sshExec(ctx, script, { input: content }); + return (opts.execImpl ?? sandboxExec)(ctx, script, { input: content }); } export interface CollectedFiles { @@ -171,7 +173,7 @@ export interface CollectedFiles { * Collect files under `dir` recursively, returning paths relative to `dir`. * Dotfiles (names starting with `.`) are excluded by default and reported * separately so the caller can warn. Paths with unsafe characters are - * rejected to prevent shell injection when interpolated into SSH commands. + * rejected to prevent shell injection when interpolated into remote commands. */ export function collectFiles(dir: string): CollectedFiles { const files: string[] = []; @@ -204,11 +206,17 @@ export function collectFiles(dir: string): CollectedFiles { * Upload an entire skill directory to the sandbox, preserving subdirectory * structure. Rejects files with unsafe path characters and skips dotfiles. */ -export function uploadDirectory( - ctx: SshContext, +export async function uploadDirectory( + ctx: SandboxControlContext, localDir: string, remoteDir: string, -): { uploaded: number; failed: string[]; skippedDotfiles: string[]; unsafePaths: string[] } { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise<{ + uploaded: number; + failed: string[]; + skippedDotfiles: string[]; + unsafePaths: string[]; +}> { const { files, skippedDotfiles, unsafePaths } = collectFiles(localDir); if (unsafePaths.length > 0) { return { uploaded: 0, failed: unsafePaths, skippedDotfiles, unsafePaths }; @@ -217,7 +225,7 @@ export function uploadDirectory( for (const rel of files) { const localFile = path.join(localDir, rel); const remoteSubdir = rel.includes("/") ? `${remoteDir}/${path.dirname(rel)}` : remoteDir; - const result = uploadFile(ctx, localFile, remoteSubdir, path.basename(rel)); + const result = await uploadFile(ctx, localFile, remoteSubdir, path.basename(rel), opts); if (!result || result.status !== 0) { failed.push(rel); } @@ -229,17 +237,17 @@ export function uploadDirectory( * Run post-install steps: session refresh for OpenClaw, or * non-OpenClaw restart hint. */ -export function postInstall( - ctx: SshContext, +export async function postInstall( + ctx: SandboxControlContext, paths: SkillPaths, _localSkillDir: string, opts: { skipRefresh?: boolean; - sshExecImpl?: typeof sshExec; + execImpl?: SandboxExecImpl; } = {}, -): { success: boolean; messages: string[] } { +): Promise<{ success: boolean; messages: string[] }> { const messages: string[] = []; - const runSsh = opts.sshExecImpl ?? sshExec; + const run = opts.execImpl ?? sandboxExec; if (paths.isOpenClaw) { // Mirror the uploaded skill into the agent's home dir @@ -259,7 +267,7 @@ export function postInstall( // restricted to [A-Za-z0-9._-] by parseFrontmatter / the name regex. const dst = `"${paths.mirrorDir}"`; const mirrorParent = `"${paths.mirrorDir.slice(0, paths.mirrorDir.lastIndexOf("/"))}"`; - const mirrorResult = runSsh( + const mirrorResult = await run( ctx, `[ ${src} -ef ${dst} ] || { mkdir -p ${mirrorParent} && rm -rf ${dst} && cp -a ${src} ${dst}; }`, ); @@ -273,7 +281,7 @@ export function postInstall( // Clear sessions.json so OpenClaw re-discovers skills on the next // session even after an in-place skill update. if (paths.sessionFile && !opts.skipRefresh) { - const refreshResult = runSsh(ctx, `printf '{}' > ${shellQuote(paths.sessionFile)}`); + const refreshResult = await run(ctx, `printf '{}' > ${shellQuote(paths.sessionFile)}`); if (!refreshResult || refreshResult.status !== 0) { messages.push("Warning: failed to clear sessions (agent may need manual restart)"); } @@ -294,11 +302,11 @@ export function postInstall( * otherwise the CLI reports success while the skill stays invisible to the * agent. This mirrors verifyRemove(), which already checks both paths. */ -export function verifyInstall( - ctx: SshContext, +export async function verifyInstall( + ctx: SandboxControlContext, paths: SkillPaths, - opts: { sshExecImpl?: typeof sshExec } = {}, -): boolean { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise { const checks = [`test -f ${shellQuote(`${paths.uploadDir}/SKILL.md`)}`]; if (paths.isOpenClaw && paths.mirrorDir) { // mirrorDir contains $HOME, which must expand on the remote shell, so we @@ -306,7 +314,6 @@ export function verifyInstall( // restricted to [A-Za-z0-9._-]. checks.push(`test -f "${paths.mirrorDir}/SKILL.md"`); } - const runSsh = opts.sshExecImpl ?? sshExec; - const result = runSsh(ctx, `${checks.join(" && ")} && echo EXISTS`); + const result = await (opts.execImpl ?? sandboxExec)(ctx, `${checks.join(" && ")} && echo EXISTS`); return result !== null && result.stdout === "EXISTS"; } diff --git a/src/lib/skill-remote.test.ts b/src/lib/skill-remote.test.ts index 729514f657d..9792fe8fd65 100644 --- a/src/lib/skill-remote.test.ts +++ b/src/lib/skill-remote.test.ts @@ -1,76 +1,99 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxControl } from "./adapters/openshell/sandbox-control"; import { resolveSkillPaths } from "./skill-install"; import { validateSkillName } from "./skill-name"; -import { checkExisting, removeSkill, verifyRemove } from "./skill-remote"; +import { + checkExisting, + removeSkill, + sandboxExec, + type SandboxControlContext, + verifyRemove, +} from "./skill-remote"; + +function context( + exec: OpenShellSandboxControl["exec"] = vi.fn(async () => { + throw new Error("unreachable"); + }), +): SandboxControlContext { + return { control: { exec }, sandboxName: "test-sandbox" }; +} describe("validateSkillName", () => { - it("accepts valid skill names", () => { - expect(validateSkillName("my-skill")).toBe(true); - expect(validateSkillName("my_skill")).toBe(true); - expect(validateSkillName("my.skill")).toBe(true); - expect(validateSkillName("MySkill123")).toBe(true); - expect(validateSkillName("digicon-zeiss-ai-strategy")).toBe(true); - }); - - it("rejects empty string", () => { - expect(validateSkillName("")).toBe(false); - }); - - it("rejects names with spaces", () => { - expect(validateSkillName("my skill")).toBe(false); - }); - - it("rejects names with shell metacharacters", () => { - expect(validateSkillName("my;skill")).toBe(false); - expect(validateSkillName("my$skill")).toBe(false); - expect(validateSkillName("my/skill")).toBe(false); - expect(validateSkillName("../escape")).toBe(false); - expect(validateSkillName("my`skill`")).toBe(false); - }); + it.each([ + "my-skill", + "my_skill", + "my.skill", + "MySkill123", + "digicon-zeiss-ai-strategy", + ])("accepts %s", (name) => expect(validateSkillName(name)).toBe(true)); + + it.each([ + "", + "my skill", + "my;skill", + "my$skill", + "my/skill", + "../escape", + "my`skill`", + ".", + "..", + ])("rejects %s", (name) => expect(validateSkillName(name)).toBe(false)); +}); - it("rejects dot and double-dot to prevent directory traversal on rm -rf", () => { - expect(validateSkillName(".")).toBe(false); - expect(validateSkillName("..")).toBe(false); +describe("sandboxExec", () => { + it("runs one shell command through the selected control without transport retry", async () => { + const exec = vi.fn(async () => ({ status: 0, stdout: "ok\n", stderr: " warning\n" })); + const ctx = context(exec); + + await expect( + sandboxExec(ctx, "cat > /tmp/file", { input: Buffer.from("body") }), + ).resolves.toEqual({ + status: 0, + stdout: "ok", + stderr: "warning", + }); + expect(exec).toHaveBeenCalledOnce(); + expect(exec).toHaveBeenCalledWith({ + sandboxName: "test-sandbox", + command: ["sh", "-lc", "cat > /tmp/file"], + stdin: Buffer.from("body"), + timeoutMs: 30_000, + }); }); }); -describe("removeSkill (unit — no SSH)", () => { - it("returns success=false and a warning when sshExec returns null (sandbox unreachable)", () => { - const paths = resolveSkillPaths(null, "test-skill"); - - const ctx = { configFile: "/nonexistent/ssh.conf", sandboxName: "test-sandbox" }; - const result = removeSkill(ctx, paths); +describe("removeSkill", () => { + it("returns failure and warnings when sandbox execution is unavailable", async () => { + const result = await removeSkill(context(), resolveSkillPaths(null, "test-skill")); expect(result.success).toBe(false); expect(result.removedUploadDir).toBe(false); - expect(result.messages.some((m) => m.startsWith("Warning:"))).toBe(true); + expect(result.messages.some((message) => message.startsWith("Warning:"))).toBe(true); }); - it("success is false for OpenClaw when mirrorDir removal fails even if uploadDir was removed", () => { - const ctx = { configFile: "/tmp/ssh.conf", sandboxName: "test-sandbox" }; - const paths = resolveSkillPaths(null, "test-skill"); - const result = removeSkill(ctx, paths, { - sshExecImpl: (_ctx, command) => ({ + it("fails when the OpenClaw mirror removal fails after upload removal", async () => { + const result = await removeSkill(context(), resolveSkillPaths(null, "test-skill"), { + execImpl: async (_ctx, command) => ({ status: command.includes("$HOME/.openclaw/skills") ? 1 : 0, stdout: "", stderr: "", }), }); - expect(result.removedUploadDir).toBe(true); - expect(result.removedMirrorDir).toBe(false); - expect(result.success).toBe(false); + expect(result).toMatchObject({ + removedUploadDir: true, + removedMirrorDir: false, + success: false, + }); }); - it("removes OpenClaw upload and mirror dirs, then clears sessions", () => { - const ctx = { configFile: "/tmp/ssh.conf", sandboxName: "test-sandbox" }; - const paths = resolveSkillPaths(null, "test-skill"); + it("removes OpenClaw upload and mirror dirs, then clears sessions", async () => { const commands: string[] = []; - const result = removeSkill(ctx, paths, { - sshExecImpl: (_ctx, command) => { + const result = await removeSkill(context(), resolveSkillPaths(null, "test-skill"), { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "", stderr: "" }; }, @@ -86,28 +109,17 @@ describe("removeSkill (unit — no SSH)", () => { }); }); -describe("verifyRemove (unit — no SSH)", () => { - it("returns false when SSH is unreachable (conservative — treat failure as not-gone)", () => { - const paths = resolveSkillPaths(null, "test-skill"); - const ctx = { configFile: "/nonexistent/ssh.conf", sandboxName: "test-sandbox" }; - expect(verifyRemove(ctx, paths)).toBe(false); - }); - - it("returns false for non-OpenClaw paths when SSH is unreachable", () => { - const paths = resolveSkillPaths( - { name: "hermes", configPaths: { dir: "/sandbox/.hermes" } }, - "test-skill", +describe("verifyRemove", () => { + it("fails conservatively when sandbox execution is unavailable", async () => { + await expect(verifyRemove(context(), resolveSkillPaths(null, "test-skill"))).resolves.toBe( + false, ); - const ctx = { configFile: "/nonexistent/ssh.conf", sandboxName: "test-sandbox" }; - expect(verifyRemove(ctx, paths)).toBe(false); }); - it("verifies both OpenClaw skill directories are gone", () => { - const paths = resolveSkillPaths(null, "test-skill"); - const ctx = { configFile: "/tmp/ssh.conf", sandboxName: "test-sandbox" }; + it("verifies both OpenClaw skill directories are gone", async () => { const commands: string[] = []; - const gone = verifyRemove(ctx, paths, { - sshExecImpl: (_ctx, command) => { + const gone = await verifyRemove(context(), resolveSkillPaths(null, "test-skill"), { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "GONE", stderr: "" }; }, @@ -120,28 +132,17 @@ describe("verifyRemove (unit — no SSH)", () => { }); }); -describe("checkExisting (unit — no SSH)", () => { - it("returns null when SSH is unreachable for OpenClaw paths", () => { - const paths = resolveSkillPaths(null, "test-skill"); - const ctx = { configFile: "/nonexistent/ssh.conf", sandboxName: "test-sandbox" }; - expect(checkExisting(ctx, paths)).toBeNull(); - }); - - it("returns null when SSH is unreachable for non-OpenClaw paths", () => { - const paths = resolveSkillPaths( - { name: "hermes", configPaths: { dir: "/sandbox/.hermes" } }, - "test-skill", - ); - const ctx = { configFile: "/nonexistent/ssh.conf", sandboxName: "test-sandbox" }; - expect(checkExisting(ctx, paths)).toBeNull(); +describe("checkExisting", () => { + it("returns null when sandbox execution is unavailable", async () => { + await expect( + checkExisting(context(), resolveSkillPaths(null, "test-skill")), + ).resolves.toBeNull(); }); - it("probes skill directories so removal can clean partial uploads", () => { - const paths = resolveSkillPaths(null, "test-skill"); - const ctx = { configFile: "/tmp/ssh.conf", sandboxName: "test-sandbox" }; + it("probes directories so removal can clean partial uploads", async () => { const commands: string[] = []; - const exists = checkExisting(ctx, paths, { - sshExecImpl: (_ctx, command) => { + const exists = await checkExisting(context(), resolveSkillPaths(null, "test-skill"), { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "EXISTS", stderr: "" }; }, diff --git a/src/lib/skill-remote.ts b/src/lib/skill-remote.ts index 8b19d1780a7..7ebaf5c296a 100644 --- a/src/lib/skill-remote.ts +++ b/src/lib/skill-remote.ts @@ -1,61 +1,46 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; - +import type { OpenShellSandboxControl } from "./adapters/openshell/sandbox-control"; import { shellQuote } from "./core/shell-quote"; import type { SkillPaths } from "./skill-install"; export { shellQuote }; -export interface SshContext { - configFile: string; +export interface SandboxControlContext { + control: OpenShellSandboxControl; sandboxName: string; } -export interface SshResult { - status: number; +export interface SandboxCommandResult { + status: number | null; stdout: string; stderr: string; } -/** - * Run a command on the sandbox via SSH with optional stdin content. - * Uses the same SSH flags as executeSandboxCommand in sandbox-process-recovery-action.ts. - */ -export function sshExec( - ctx: SshContext, +export type SandboxExecImpl = ( + ctx: SandboxControlContext, + command: string, + opts?: { input?: string | Buffer; timeout?: number }, +) => Promise; + +/** Execute one shell command through the selected OpenShell control plane. */ +export async function sandboxExec( + ctx: SandboxControlContext, command: string, opts: { input?: string | Buffer; timeout?: number } = {}, -): SshResult | null { +): Promise { try { - const result = spawnSync( - "ssh", - [ - "-F", - ctx.configFile, - "-o", - "StrictHostKeyChecking=no", - "-o", - "UserKnownHostsFile=/dev/null", - "-o", - "ConnectTimeout=10", - "-o", - "LogLevel=ERROR", - `openshell-${ctx.sandboxName}`, - command, - ], - { - encoding: "utf-8", - stdio: [opts.input !== undefined ? "pipe" : "ignore", "pipe", "pipe"], - input: opts.input, - timeout: opts.timeout ?? 30_000, - }, - ); + const result = await ctx.control.exec({ + sandboxName: ctx.sandboxName, + command: ["sh", "-lc", command], + stdin: opts.input, + timeoutMs: opts.timeout ?? 30_000, + }); return { - status: result.status ?? 1, - stdout: (result.stdout || "").trim(), - stderr: (result.stderr || "").trim(), + status: result.status, + stdout: result.stdout.trim(), + stderr: result.stderr.trim(), }; } catch { return null; @@ -63,30 +48,22 @@ export function sshExec( } /** - * Check whether a skill directory already exists on the sandbox at the upload - * path or (for OpenClaw) the mirror path. Probing directories instead of only - * SKILL.md lets `skill remove` clean up partial uploads whose manifest write - * failed after the directory was created. - * - * Returns: - * true — skill exists - * false — skill is absent - * null — SSH probe failed; existence could not be determined + * Check whether a skill directory already exists at the upload path or, for + * OpenClaw, the mirror path. Directory probes let removal clean partial + * uploads whose manifest write failed. */ -export function checkExisting( - ctx: SshContext, +export async function checkExisting( + ctx: SandboxControlContext, paths: SkillPaths, - opts: { sshExecImpl?: typeof sshExec } = {}, -): boolean | null { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise { const checks = [`test -e ${shellQuote(paths.uploadDir)}`]; - if (paths.isOpenClaw && paths.mirrorDir) { - checks.push(`test -e "${paths.mirrorDir}"`); - } - const runSsh = opts.sshExecImpl ?? sshExec; - const result = runSsh(ctx, `{ ${checks.join(" || ")}; } && echo EXISTS || echo ABSENT`); - if (result === null || result.status !== 0) { - return null; - } + if (paths.isOpenClaw && paths.mirrorDir) checks.push(`test -e "${paths.mirrorDir}"`); + const result = await (opts.execImpl ?? sandboxExec)( + ctx, + `{ ${checks.join(" || ")}; } && echo EXISTS || echo ABSENT`, + ); + if (result === null || result.status !== 0) return null; if (result.stdout === "EXISTS") return true; if (result.stdout === "ABSENT") return false; return null; @@ -100,48 +77,33 @@ export interface RemoveResult { messages: string[]; } -/** - * Remove a skill from the sandbox by name. - * Deletes the immutable upload directory, the OpenClaw mirror directory - * (if applicable), and clears sessions.json so the agent re-discovers - * the remaining skills on the next session. - * - * Only the named skill directory is deleted — other skills are untouched. - */ -export function removeSkill( - ctx: SshContext, +/** Remove one named skill and clear OpenClaw's session index. */ +export async function removeSkill( + ctx: SandboxControlContext, paths: SkillPaths, - opts: { sshExecImpl?: typeof sshExec } = {}, -): RemoveResult { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise { const messages: string[] = []; - const runSsh = opts.sshExecImpl ?? sshExec; + const run = opts.execImpl ?? sandboxExec; - // 1. Remove the immutable upload directory (/sandbox/.openclaw/skills//) - const uploadDir = shellQuote(paths.uploadDir); - const removeUpload = runSsh(ctx, `rm -rf ${uploadDir}`); + const removeUpload = await run(ctx, `rm -rf ${shellQuote(paths.uploadDir)}`); const removedUploadDir = removeUpload !== null && removeUpload.status === 0; if (!removedUploadDir) { messages.push(`Warning: failed to remove upload directory ${paths.uploadDir}`); } - // 2. Remove the OpenClaw mirror ($HOME/.openclaw/skills//) - // mirrorDir contains $HOME which must expand on the remote shell, so we - // use double quotes (not shellQuote). This is safe because skill names - // are restricted to [A-Za-z0-9._-] by parseFrontmatter / the name - // validation regex, so $HOME expansion is the only variable substitution. let removedMirrorDir = false; if (paths.isOpenClaw && paths.mirrorDir) { - const removeMirror = runSsh(ctx, `rm -rf "${paths.mirrorDir}"`); + const removeMirror = await run(ctx, `rm -rf "${paths.mirrorDir}"`); removedMirrorDir = removeMirror !== null && removeMirror.status === 0; if (!removedMirrorDir) { messages.push(`Warning: failed to remove mirror directory ${paths.mirrorDir}`); } } - // 3. Clear sessions.json so the agent re-discovers the remaining skills. let clearedSessions = false; if (paths.isOpenClaw && paths.sessionFile) { - const clearResult = runSsh(ctx, `printf '{}' > ${shellQuote(paths.sessionFile)}`); + const clearResult = await run(ctx, `printf '{}' > ${shellQuote(paths.sessionFile)}`); clearedSessions = clearResult !== null && clearResult.status === 0; if (!clearedSessions) { messages.push("Warning: failed to clear sessions (agent may need manual restart)"); @@ -159,20 +121,17 @@ export function removeSkill( }; } -/** - * Verify the skill directory no longer exists on the sandbox. - * For OpenClaw sandboxes, both the upload dir and the mirror dir must be gone. - */ -export function verifyRemove( - ctx: SshContext, +/** Verify that both managed skill directories are absent. */ +export async function verifyRemove( + ctx: SandboxControlContext, paths: SkillPaths, - opts: { sshExecImpl?: typeof sshExec } = {}, -): boolean { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise { const checks = [`test ! -e ${shellQuote(paths.uploadDir)}`]; - if (paths.isOpenClaw && paths.mirrorDir) { - checks.push(`test ! -e "${paths.mirrorDir}"`); - } - const runSsh = opts.sshExecImpl ?? sshExec; - const result = runSsh(ctx, `${checks.join(" && ")} && echo GONE || echo EXISTS`); + if (paths.isOpenClaw && paths.mirrorDir) checks.push(`test ! -e "${paths.mirrorDir}"`); + const result = await (opts.execImpl ?? sandboxExec)( + ctx, + `${checks.join(" && ")} && echo GONE || echo EXISTS`, + ); return result !== null && result.stdout === "GONE"; } From b433f69e0b62639162af0a901da15f3486ecd46a Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 16:07:30 -0700 Subject: [PATCH 03/13] test(rebuild): cover awaited sandbox probe ordering Signed-off-by: Aaron Erickson --- .../sandbox/rebuild-destroy-phase.test.ts | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts b/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts index b7dbe99098c..047e8b02faf 100644 --- a/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-destroy-phase.test.ts @@ -70,4 +70,38 @@ describe("rebuild destroy validation diagnostics", () => { expect(mocks.reattachMcpAfterDeleteFailure).toHaveBeenCalledOnce(); expect(relockShieldsIfNeeded).toHaveBeenCalledWith(true); }); + + it("waits for the user-managed-file probe before final validation", async () => { + let resolveProbe: () => void = () => undefined; + const probe = new Promise((resolve) => { + resolveProbe = resolve; + }); + mocks.warnUnpreservedUserManagedFiles.mockReturnValue(probe); + const validateAfterMcpPreparation = vi.fn(async () => ({ + ok: false as const, + message: "validation blocked deletion", + })); + const bail = vi.fn((message: string): never => { + throw new Error(message); + }); + + const phase = runRebuildDestroyPhase({ + sandboxName: "alpha", + sandboxEntry: { name: "alpha", agent: "langchain-deepagents-code" }, + staleRecovery: false, + backupManifest: null, + log: vi.fn(), + bail, + relockShieldsIfNeeded: vi.fn(() => true), + validateAfterMcpPreparation, + onDeleted: vi.fn(), + }); + + await vi.waitFor(() => expect(mocks.warnUnpreservedUserManagedFiles).toHaveBeenCalledOnce()); + expect(validateAfterMcpPreparation).not.toHaveBeenCalled(); + + resolveProbe(); + await expect(phase).rejects.toThrow("validation blocked deletion"); + expect(validateAfterMcpPreparation).toHaveBeenCalledOnce(); + }); }); From c50f9740b48477e25dac6fa7bfeab17719ae7583 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 21:08:51 -0700 Subject: [PATCH 04/13] test(openshell): cover retried skill removal Signed-off-by: Aaron Erickson --- src/lib/skill-remote.test.ts | 54 +++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/src/lib/skill-remote.test.ts b/src/lib/skill-remote.test.ts index 9792fe8fd65..fb160a7082d 100644 --- a/src/lib/skill-remote.test.ts +++ b/src/lib/skill-remote.test.ts @@ -8,8 +8,8 @@ import { validateSkillName } from "./skill-name"; import { checkExisting, removeSkill, - sandboxExec, type SandboxControlContext, + sandboxExec, verifyRemove, } from "./skill-remote"; @@ -90,6 +90,58 @@ describe("removeSkill", () => { }); }); + it("converges when retried after removing only the upload directory", async () => { + const paths = resolveSkillPaths(null, "test-skill"); + const mirrorDir = paths.mirrorDir!; + const unrelatedPath = "/sandbox/.openclaw/skills/other-skill"; + const existingPaths = new Set([paths.uploadDir, mirrorDir, unrelatedPath]); + const commands: string[] = []; + let mirrorAttempts = 0; + const execImpl = vi.fn(async (_ctx: SandboxControlContext, command: string) => { + commands.push(command); + if (command === `rm -rf '${paths.uploadDir}'`) { + existingPaths.delete(paths.uploadDir); + return { status: 0, stdout: "", stderr: "" }; + } + if (command === `rm -rf "${mirrorDir}"`) { + mirrorAttempts += 1; + if (mirrorAttempts === 1) return { status: 1, stdout: "", stderr: "failed" }; + existingPaths.delete(mirrorDir); + return { status: 0, stdout: "", stderr: "" }; + } + if (command.startsWith("printf '{}' >")) { + return { status: 0, stdout: "", stderr: "" }; + } + if (command.startsWith("test ! -e")) { + return { + status: 0, + stdout: + existingPaths.has(paths.uploadDir) || existingPaths.has(mirrorDir) ? "EXISTS" : "GONE", + stderr: "", + }; + } + return { status: 1, stdout: "", stderr: `unexpected command: ${command}` }; + }); + + await expect(removeSkill(context(), paths, { execImpl })).resolves.toMatchObject({ + removedUploadDir: true, + removedMirrorDir: false, + success: false, + }); + await expect(removeSkill(context(), paths, { execImpl })).resolves.toMatchObject({ + clearedSessions: true, + removedMirrorDir: true, + removedUploadDir: true, + success: true, + }); + await expect(verifyRemove(context(), paths, { execImpl })).resolves.toBe(true); + + expect(existingPaths.has(paths.uploadDir)).toBe(false); + expect(existingPaths.has(mirrorDir)).toBe(false); + expect(existingPaths.has(unrelatedPath)).toBe(true); + expect(commands.every((command) => !command.includes(unrelatedPath))).toBe(true); + }); + it("removes OpenClaw upload and mirror dirs, then clears sessions", async () => { const commands: string[] = []; const result = await removeSkill(context(), resolveSkillPaths(null, "test-skill"), { From 85cfd575215d4deea1160b0d80ad8f71fe688f48 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 22:54:39 -0700 Subject: [PATCH 05/13] docs(openshell): extend reviewed read-only routing scope Signed-off-by: Aaron Erickson --- .../openshell/sandbox-control-routing.ts | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index 1ce48eb7f4c..c93fc0152af 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -70,17 +70,18 @@ export function selectOpenShellSandboxControlForMutation( } /** - * Prefer direct gRPC for the OpenClaw session-list read and retry through the - * OpenShell CLI only when configuration or sandbox lookup fails before Exec is - * dispatched. OpenShell v0.0.72 can persist `auth_mode: "cloudflare_jwt"`; - * only its CLI can establish that OpenShell-owned edge tunnel and manage the - * associated credential lifecycle, so NemoClaw cannot replace that path here. + * Prefer direct gRPC for explicitly reviewed read-only probes and retry through + * the OpenShell CLI only when configuration or sandbox lookup fails before + * Exec is dispatched. OpenShell v0.0.72 can persist + * `auth_mode: "cloudflare_jwt"`; only its CLI can establish that + * OpenShell-owned edge tunnel and manage the associated credential lifecycle, + * so NemoClaw cannot replace that path here. * - * This is a migration compatibility contract for the single current caller, - * `runSessionsPassthrough`, not a general routing policy. Remove the CLI - * fallback when OpenShell's public client or bindings support the edge-tunnel - * auth and credential-refresh lifecycle. Do not reuse it for another command - * without reviewing that command's replay semantics; mutations must select one + * This migration contract is limited to the reviewed read-only callers (the + * session list and rebuild file probe at this slice), not a general routing + * policy. Remove the CLI fallback when OpenShell's public client or bindings + * support the edge-tunnel auth and credential-refresh lifecycle. Every added + * caller requires a replay-semantics review; mutations must select one * transport before dispatch and must never be replayed automatically. */ export async function execSandboxReadOnlyWithGrpcFallback( From b5fb4ae6908e98debc122e04241b31befd662b60 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 23:24:24 -0700 Subject: [PATCH 06/13] test(openshell): script skill removal retry Signed-off-by: Aaron Erickson --- src/lib/skill-remote.test.ts | 62 +++++++++++++++++++----------------- 1 file changed, 32 insertions(+), 30 deletions(-) diff --git a/src/lib/skill-remote.test.ts b/src/lib/skill-remote.test.ts index fb160a7082d..b97cbd6a43c 100644 --- a/src/lib/skill-remote.test.ts +++ b/src/lib/skill-remote.test.ts @@ -94,33 +94,38 @@ describe("removeSkill", () => { const paths = resolveSkillPaths(null, "test-skill"); const mirrorDir = paths.mirrorDir!; const unrelatedPath = "/sandbox/.openclaw/skills/other-skill"; - const existingPaths = new Set([paths.uploadDir, mirrorDir, unrelatedPath]); - const commands: string[] = []; - let mirrorAttempts = 0; + const clearSessions = `printf '{}' > '${paths.sessionFile}'`; + const verifyGone = `test ! -e '${paths.uploadDir}' && test ! -e "${mirrorDir}" && echo GONE || echo EXISTS`; + const scriptedResults = [ + { + command: `rm -rf '${paths.uploadDir}'`, + result: { status: 0, stdout: "", stderr: "" }, + }, + { + command: `rm -rf "${mirrorDir}"`, + result: { status: 1, stdout: "", stderr: "failed" }, + }, + { command: clearSessions, result: { status: 0, stdout: "", stderr: "" } }, + { + command: `rm -rf '${paths.uploadDir}'`, + result: { status: 0, stdout: "", stderr: "" }, + }, + { + command: `rm -rf "${mirrorDir}"`, + result: { status: 0, stdout: "", stderr: "" }, + }, + { command: clearSessions, result: { status: 0, stdout: "", stderr: "" } }, + { + command: verifyGone, + result: { status: 0, stdout: "GONE", stderr: "" }, + }, + ]; const execImpl = vi.fn(async (_ctx: SandboxControlContext, command: string) => { - commands.push(command); - if (command === `rm -rf '${paths.uploadDir}'`) { - existingPaths.delete(paths.uploadDir); - return { status: 0, stdout: "", stderr: "" }; - } - if (command === `rm -rf "${mirrorDir}"`) { - mirrorAttempts += 1; - if (mirrorAttempts === 1) return { status: 1, stdout: "", stderr: "failed" }; - existingPaths.delete(mirrorDir); - return { status: 0, stdout: "", stderr: "" }; - } - if (command.startsWith("printf '{}' >")) { - return { status: 0, stdout: "", stderr: "" }; - } - if (command.startsWith("test ! -e")) { - return { - status: 0, - stdout: - existingPaths.has(paths.uploadDir) || existingPaths.has(mirrorDir) ? "EXISTS" : "GONE", - stderr: "", - }; - } - return { status: 1, stdout: "", stderr: `unexpected command: ${command}` }; + const next = scriptedResults.shift(); + expect(next).toBeDefined(); + expect(command).toBe(next!.command); + expect(command).not.toContain(unrelatedPath); + return next!.result; }); await expect(removeSkill(context(), paths, { execImpl })).resolves.toMatchObject({ @@ -136,10 +141,7 @@ describe("removeSkill", () => { }); await expect(verifyRemove(context(), paths, { execImpl })).resolves.toBe(true); - expect(existingPaths.has(paths.uploadDir)).toBe(false); - expect(existingPaths.has(mirrorDir)).toBe(false); - expect(existingPaths.has(unrelatedPath)).toBe(true); - expect(commands.every((command) => !command.includes(unrelatedPath))).toBe(true); + expect(scriptedResults).toEqual([]); }); it("removes OpenClaw upload and mirror dirs, then clears sessions", async () => { From cbfc62b026ec9afa2a3f91f3090e75e3619fd03a Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 23:34:12 -0700 Subject: [PATCH 07/13] fix(openshell): fail closed on skill probe errors Signed-off-by: Aaron Erickson --- src/lib/actions/sandbox/skill-install.test.ts | 26 +++++++++++++++---- src/lib/actions/sandbox/skill-install.ts | 16 +++++------- src/lib/skill-remote.test.ts | 10 ++++++- src/lib/skill-remote.ts | 4 ++- 4 files changed, 40 insertions(+), 16 deletions(-) diff --git a/src/lib/actions/sandbox/skill-install.test.ts b/src/lib/actions/sandbox/skill-install.test.ts index e34e58b56af..cde0d6302ae 100644 --- a/src/lib/actions/sandbox/skill-install.test.ts +++ b/src/lib/actions/sandbox/skill-install.test.ts @@ -201,11 +201,11 @@ describe("sandbox skill action orchestration", () => { expect(skillInstall.uploadDirectory).not.toHaveBeenCalled(); }); - it("continues skill install when the existence probe is unknown because upload plus verify are authoritative", async () => { + it("fails skill install before upload when the existence probe is inconclusive", async () => { const skillDir = makeSkillDir(); skillInstall.checkExisting.mockResolvedValue(null); const error = vi.spyOn(console, "error").mockImplementation(() => undefined); - const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + vi.spyOn(console, "log").mockImplementation(() => undefined); try { await installSandboxSkill("alpha", { command: "install", path: skillDir }); @@ -214,10 +214,26 @@ describe("sandbox skill action orchestration", () => { } expect(error).toHaveBeenCalledWith( - expect.stringContaining( - "Warning: could not check sandbox for existing skill — treating as fresh install.", - ), + " Could not check if skill 'demo-skill' exists — sandbox may be unreachable. No files were uploaded.", ); + expect(skillInstall.uploadDirectory).not.toHaveBeenCalled(); + expect(skillInstall.postInstall).not.toHaveBeenCalled(); + expect(skillInstall.verifyInstall).not.toHaveBeenCalled(); + expect(closeControl).toHaveBeenCalledOnce(); + expect(process.exitCode).toBe(1); + }); + + it("installs when the existence probe confirms the skill is absent", async () => { + const skillDir = makeSkillDir(); + skillInstall.checkExisting.mockResolvedValue(false); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + + try { + await installSandboxSkill("alpha", { command: "install", path: skillDir }); + } finally { + fs.rmSync(skillDir, { recursive: true, force: true }); + } + expect(skillInstall.uploadDirectory).toHaveBeenCalledWith( { control, sandboxName: "alpha" }, skillDir, diff --git a/src/lib/actions/sandbox/skill-install.ts b/src/lib/actions/sandbox/skill-install.ts index e5720e808ef..6b81d099c20 100644 --- a/src/lib/actions/sandbox/skill-install.ts +++ b/src/lib/actions/sandbox/skill-install.ts @@ -285,19 +285,17 @@ export async function installSandboxSkill( try { const ctx = { control: selected.control, sandboxName }; - // 5. Check if skill already exists (update vs fresh install). This probe is - // advisory for install only: transient control-plane or remote shell - // failures can make the stat probe inconclusive even when a - // subsequent upload succeeds. Upload plus verifyInstall() remain the - // source of truth for install success; remove keeps null fatal because it - // is destructive. Once OpenShell exposes a typed stat API or exec probe - // failures are reliably distinguishable from absent dirs across supported - // versions, remove this fallback and fail before upload. + // 5. Check if skill already exists (update vs fresh install). A successful + // sentinel response distinguishes absence from an existing directory; + // an inconclusive control result is an execution failure, not absence. + // Fail closed before upload so a probe failure cannot precede mutation. const existingCheck = await skillInstall.checkExisting(ctx, paths); if (existingCheck === null) { console.error( - ` ${YW}Warning: could not check sandbox for existing skill — treating as fresh install.${R}`, + ` Could not check if skill '${frontmatter.name}' exists — sandbox may be unreachable. No files were uploaded.`, ); + process.exitCode = 1; + return; } const isUpdate = existingCheck === true; diff --git a/src/lib/skill-remote.test.ts b/src/lib/skill-remote.test.ts index b97cbd6a43c..8a45b2a9f42 100644 --- a/src/lib/skill-remote.test.ts +++ b/src/lib/skill-remote.test.ts @@ -187,12 +187,20 @@ describe("verifyRemove", () => { }); describe("checkExisting", () => { - it("returns null when sandbox execution is unavailable", async () => { + it("maps a selected-control execution failure to an inconclusive result", async () => { await expect( checkExisting(context(), resolveSkillPaths(null, "test-skill")), ).resolves.toBeNull(); }); + it("maps a successful absence sentinel to false", async () => { + const execImpl = vi.fn(async () => ({ status: 0, stdout: "ABSENT", stderr: "" })); + + await expect( + checkExisting(context(), resolveSkillPaths(null, "test-skill"), { execImpl }), + ).resolves.toBe(false); + }); + it("probes directories so removal can clean partial uploads", async () => { const commands: string[] = []; const exists = await checkExisting(context(), resolveSkillPaths(null, "test-skill"), { diff --git a/src/lib/skill-remote.ts b/src/lib/skill-remote.ts index 7ebaf5c296a..73ddbd16f88 100644 --- a/src/lib/skill-remote.ts +++ b/src/lib/skill-remote.ts @@ -50,7 +50,9 @@ export async function sandboxExec( /** * Check whether a skill directory already exists at the upload path or, for * OpenClaw, the mirror path. Directory probes let removal clean partial - * uploads whose manifest write failed. + * uploads whose manifest write failed. A recognized sentinel from a + * successful command maps to true or false. Transport errors, nonzero status, + * and malformed output map to null so callers can fail before mutation. */ export async function checkExisting( ctx: SandboxControlContext, From 04a7156f01b2fc94940dfc8fa670381cbf5abd17 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 04:04:41 -0700 Subject: [PATCH 08/13] test(openshell): freeze read-only fallback callers Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 37 ++++++++++++++++----- test/legacy-sandbox-transports.test.ts | 30 ++++++++++++++++- 2 files changed, 57 insertions(+), 10 deletions(-) diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index 1246934c896..fd9d9117ff0 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -3,9 +3,10 @@ /** * Freezes the statically recognizable direct host-to-sandbox transport surface - * while NemoClaw moves to OpenShell's gRPC API. Literal calls and same-file - * immutable aliases must be removed or re-reviewed explicitly. This check is a - * review tripwire, not a general-purpose data-flow analysis. + * and the reviewed gRPC-to-CLI read-only fallback importers while NemoClaw + * moves to OpenShell's gRPC API. Literal calls, same-file immutable aliases, + * and fallback importers must be removed or re-reviewed explicitly. This check + * is a review tripwire, not a general-purpose data-flow analysis. */ import { existsSync, readdirSync, readFileSync } from "node:fs"; @@ -16,6 +17,7 @@ import ts from "typescript"; export type LegacySandboxTransportKind = | "docker-exec-command" | "docker-exec-builder" + | "grpc-cli-read-only-fallback" | "openshell-ssh-config" | "privileged-sandbox-exec" | "ssh-command" @@ -35,6 +37,7 @@ type ReviewedSiteTuple = readonly [string, LegacySandboxTransportKind, number]; const REVIEWED_SITE_TUPLES = [ ["src/lib/actions/dns/index.ts", "docker-exec-command", 4], ["src/lib/actions/sandbox/host-aliases.ts", "docker-exec-command", 1], + ["src/lib/actions/sandbox/sessions/passthrough.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/actions/sandbox/process-recovery.ts", "openshell-ssh-config", 1], ["src/lib/actions/sandbox/process-recovery.ts", "privileged-sandbox-exec", 2], ["src/lib/actions/sandbox/process-recovery.ts", "ssh-command", 1], @@ -62,6 +65,7 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/state/sandbox.ts", "ssh-command", 8], ["src/lib/state/sandbox.ts", "ssh-temp-config", 2], ["src/lib/state/state-file-restore.ts", "ssh-command", 1], + ["src/lib/state/user-managed-files-probe.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/tunnel/sandbox-gateway-stop.ts", "docker-exec-command", 2], ] as const satisfies readonly ReviewedSiteTuple[]; @@ -204,6 +208,21 @@ function scanSource( const bindings = collectConstBindings(sourceFile); function visit(node: ts.Node): void { + if ( + ts.isImportDeclaration(node) && + ts.isStringLiteral(node.moduleSpecifier) && + /(?:^|\/)sandbox-control-routing(?:\.js)?$/u.test(node.moduleSpecifier.text) && + node.importClause?.namedBindings && + ts.isNamedImports(node.importClause.namedBindings) && + node.importClause.namedBindings.elements.some( + (specifier) => + (specifier.propertyName?.text ?? specifier.name.text) === + "execSandboxReadOnlyWithGrpcFallback", + ) + ) { + increment(counts, "grpc-cli-read-only-fallback"); + } + if (ts.isArrayLiteralExpression(node)) { const first = literalText(node.elements[0]); const second = literalText(node.elements[1]); @@ -276,17 +295,15 @@ export function auditLegacySandboxTransports( const key = siteKey(reviewed); const current = discovered.get(key); if (!current) { - violations.push(`${key}: reviewed legacy transport is gone; remove this allowlist entry`); + violations.push(`${key}: reviewed transport use is gone; remove this allowlist entry`); } else if (current.calls !== reviewed.calls) { - violations.push( - `${key}: expected ${reviewed.calls} reviewed call(s), found ${current.calls}`, - ); + violations.push(`${key}: expected ${reviewed.calls} reviewed use(s), found ${current.calls}`); } discovered.delete(key); } for (const site of discovered.values()) { - violations.push(`${siteKey(site)}: found ${site.calls} unreviewed legacy transport call(s)`); + violations.push(`${siteKey(site)}: found ${site.calls} unreviewed transport use(s)`); } return violations; @@ -302,5 +319,7 @@ if (isEntrypoint) { process.exit(1); } - console.log("Legacy sandbox SSH, SSHFS, and Docker-exec sites match the reviewed inventory."); + console.log( + "Legacy sandbox transports and gRPC-to-CLI fallback importers match the reviewed inventory.", + ); } diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index efecf82b062..4268f288f7e 100644 --- a/test/legacy-sandbox-transports.test.ts +++ b/test/legacy-sandbox-transports.test.ts @@ -84,6 +84,34 @@ describe("legacy sandbox transport inventory", () => { ]); }); + it("tracks reviewed read-only fallback importers, including aliased imports", () => { + const root = fixtureRepo({ + "src/read-only-probe.ts": [ + 'import { execSandboxReadOnlyWithGrpcFallback as execReadOnly } from "./lib/adapters/openshell/sandbox-control-routing.js";', + 'execReadOnly("gateway", request);', + ].join("\n"), + }); + + expect(discoverLegacySandboxTransportSites(root)).toEqual([ + { + relativePath: "src/read-only-probe.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + ]); + }); + + it("fails closed when a new production file imports the read-only fallback", () => { + const root = fixtureRepo({ + "src/unreviewed-probe.ts": + 'import { execSandboxReadOnlyWithGrpcFallback } from "./lib/adapters/openshell/sandbox-control-routing";', + }); + + expect(auditLegacySandboxTransports(root, [])).toEqual([ + "src/unreviewed-probe.ts:grpc-cli-read-only-fallback: found 1 unreviewed transport use(s)", + ]); + }); + it("ignores comments, inert strings, tests, and non-sandbox SSH workflows", () => { const root = fixtureRepo({ "src/safe.ts": [ @@ -105,7 +133,7 @@ describe("legacy sandbox transport inventory", () => { }); expect(auditLegacySandboxTransports(root, [])).toEqual([ - "src/new-path.ts:ssh-command: found 1 unreviewed legacy transport call(s)", + "src/new-path.ts:ssh-command: found 1 unreviewed transport use(s)", ]); }); }); From b17c47282358ceff0df472eafac1259fbe5aec56 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 04:09:27 -0700 Subject: [PATCH 09/13] fix(openshell): scope mutation fallback to gateway Signed-off-by: Aaron Erickson --- src/lib/adapters/openshell/sandbox-control-routing.test.ts | 7 +++++-- src/lib/adapters/openshell/sandbox-control-routing.ts | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index c87a263beb0..f542089fe8c 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -33,6 +33,7 @@ function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: Sandbox const debug = vi.fn(); return { close, + cli, grpcExec, cliExec, createCli, @@ -244,7 +245,8 @@ describe("mutating OpenShell sandbox control routing", () => { const selected = selectOpenShellSandboxControlForMutation("nemoclaw", test.deps); expect(selected).toMatchObject({ control: expect.any(Object), transport: "grpc" }); - expect(selected.control).not.toBe(test.deps.cli); + expect(selected.control).not.toBe(test.cli); + expect(test.createCli).not.toHaveBeenCalled(); selected.close(); expect(test.close).toHaveBeenCalledOnce(); }); @@ -258,10 +260,11 @@ describe("mutating OpenShell sandbox control routing", () => { const selected = selectOpenShellSandboxControlForMutation("edge", test.deps); expect(selected).toEqual({ - control: test.deps.cli, + control: test.cli, transport: "cli-edge-tunnel", close: expect.any(Function), }); + expect(test.createCli).toHaveBeenCalledWith("edge"); selected.close(); expect(test.close).not.toHaveBeenCalled(); }); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index 1e5edfe1602..413b0f85f3c 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -65,7 +65,7 @@ export function selectOpenShellSandboxControlForMutation( } catch (error) { if (!(error instanceof OpenShellGrpcEdgeTunnelRequiredError)) throw error; return { - control: dependencies.cli, + control: dependencies.createCli(gatewayName), transport: "cli-edge-tunnel", close: () => {}, }; From 346a124498bb537a373c2c758b92554c8b793794 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 04:18:13 -0700 Subject: [PATCH 10/13] test(openshell): guard mutation fallback endpoint Signed-off-by: Aaron Erickson --- .../openshell/sandbox-control-routing.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index 71a765976ee..e315d2ab41b 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -304,6 +304,22 @@ describe("mutating OpenShell sandbox control routing", () => { expect(test.close).not.toHaveBeenCalled(); }); + it("fails closed when the mutation CLI factory refuses an endpoint override", () => { + const refusal = new Error("Unset OPENSHELL_GATEWAY_ENDPOINT and retry"); + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + test.createGrpc.mockImplementation(() => { + throw new OpenShellGrpcEdgeTunnelRequiredError(); + }); + test.createCli.mockImplementation(() => { + throw refusal; + }); + + expect(() => selectOpenShellSandboxControlForMutation("edge", test.deps)).toThrow(refusal); + + expect(test.createCli).toHaveBeenCalledWith("edge"); + expect(test.cliExec).not.toHaveBeenCalled(); + }); + it("does not turn a completed mutation into failure when the client cannot close", () => { const test = dependencies({ status: 0, stdout: "grpc", stderr: "" }); const error = new Error("close failed"); From 8d9d8f8b2a7e9376be9f0b596b47cdb7ac1e6d75 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 04:28:57 -0700 Subject: [PATCH 11/13] test(openshell): harden fallback importer guard Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 30 +++++++++++++--- test/legacy-sandbox-transports.test.ts | 38 +++++++++++++++++++++ 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index fd9d9117ff0..9076bce6a28 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -212,12 +212,34 @@ function scanSource( ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && /(?:^|\/)sandbox-control-routing(?:\.js)?$/u.test(node.moduleSpecifier.text) && - node.importClause?.namedBindings && - ts.isNamedImports(node.importClause.namedBindings) && - node.importClause.namedBindings.elements.some( + node.importClause && + !node.importClause.isTypeOnly && + ((node.importClause.namedBindings && ts.isNamespaceImport(node.importClause.namedBindings)) || + (node.importClause.namedBindings && + ts.isNamedImports(node.importClause.namedBindings) && + node.importClause.namedBindings.elements.some( + (specifier) => + !specifier.isTypeOnly && + (specifier.propertyName?.text ?? specifier.name.text) === + "execSandboxReadOnlyWithGrpcFallback", + ))) + ) { + increment(counts, "grpc-cli-read-only-fallback"); + } + + if ( + ts.isExportDeclaration(node) && + !node.isTypeOnly && + node.moduleSpecifier && + ts.isStringLiteral(node.moduleSpecifier) && + /(?:^|\/)sandbox-control-routing(?:\.js)?$/u.test(node.moduleSpecifier.text) && + node.exportClause && + ts.isNamedExports(node.exportClause) && + node.exportClause.elements.some( (specifier) => + !specifier.isTypeOnly && (specifier.propertyName?.text ?? specifier.name.text) === - "execSandboxReadOnlyWithGrpcFallback", + "execSandboxReadOnlyWithGrpcFallback", ) ) { increment(counts, "grpc-cli-read-only-fallback"); diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index 4268f288f7e..eb900d6d692 100644 --- a/test/legacy-sandbox-transports.test.ts +++ b/test/legacy-sandbox-transports.test.ts @@ -101,6 +101,44 @@ describe("legacy sandbox transport inventory", () => { ]); }); + it("tracks namespace imports and direct or aliased named re-exports", () => { + const root = fixtureRepo({ + "src/namespace-import.ts": + 'import * as routing from "./lib/adapters/openshell/sandbox-control-routing.js";\nrouting.execSandboxReadOnlyWithGrpcFallback("gateway", request);', + "src/re-export.ts": [ + 'export { execSandboxReadOnlyWithGrpcFallback } from "./lib/adapters/openshell/sandbox-control-routing.js";', + 'export { execSandboxReadOnlyWithGrpcFallback as execReadOnly } from "./lib/adapters/openshell/sandbox-control-routing.js";', + ].join("\n"), + }); + + expect(discoverLegacySandboxTransportSites(root)).toEqual([ + { + relativePath: "src/namespace-import.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + { + relativePath: "src/re-export.ts", + kind: "grpc-cli-read-only-fallback", + calls: 2, + }, + ]); + }); + + it("ignores type-only fallback imports and re-exports", () => { + const root = fixtureRepo({ + "src/type-only.ts": [ + 'import type { execSandboxReadOnlyWithGrpcFallback } from "./lib/adapters/openshell/sandbox-control-routing.js";', + 'import { type execSandboxReadOnlyWithGrpcFallback as ExecReadOnly } from "./lib/adapters/openshell/sandbox-control-routing.js";', + 'import type * as Routing from "./lib/adapters/openshell/sandbox-control-routing.js";', + 'export type { execSandboxReadOnlyWithGrpcFallback } from "./lib/adapters/openshell/sandbox-control-routing.js";', + 'export { type execSandboxReadOnlyWithGrpcFallback as ExecReadOnlyExport } from "./lib/adapters/openshell/sandbox-control-routing.js";', + ].join("\n"), + }); + + expect(discoverLegacySandboxTransportSites(root)).toEqual([]); + }); + it("fails closed when a new production file imports the read-only fallback", () => { const root = fixtureRepo({ "src/unreviewed-probe.ts": From 3558412226650c76ad9033c2144ad2cf3b87c5d3 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 19 Jul 2026 04:29:35 -0700 Subject: [PATCH 12/13] fix(openshell): guard rebuild probe routing Co-authored-by: Aaron Erickson Signed-off-by: Apurv Kumaria --- scripts/checks/legacy-sandbox-transports.ts | 24 +++++++++++++++---- .../state/user-managed-files-probe.test.ts | 23 ++++++++++++++++++ src/lib/state/user-managed-files-probe.ts | 7 ++++-- test/legacy-sandbox-transports.test.ts | 22 +++++++++++++++++ 4 files changed, 69 insertions(+), 7 deletions(-) diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index 9076bce6a28..aec9e909d9c 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -101,6 +101,15 @@ const DOCKER_COMMAND_CALLS = new Set([ ]); const NON_SANDBOX_SSH_ROOTS = ["src/lib/actions/dns/", "src/lib/deploy/"] as const; +const SANDBOX_CONTROL_ROUTING_MODULE_RE = /(?:^|\/)sandbox-control-routing(?:\.js)?$/u; + +function isSandboxControlRoutingModule(node: ts.Node | undefined): boolean { + return ( + node !== undefined && + (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) && + SANDBOX_CONTROL_ROUTING_MODULE_RE.test(node.text) + ); +} function productionTypeScriptFiles(directory: string): string[] { if (!existsSync(directory)) return []; @@ -210,8 +219,7 @@ function scanSource( function visit(node: ts.Node): void { if ( ts.isImportDeclaration(node) && - ts.isStringLiteral(node.moduleSpecifier) && - /(?:^|\/)sandbox-control-routing(?:\.js)?$/u.test(node.moduleSpecifier.text) && + isSandboxControlRoutingModule(node.moduleSpecifier) && node.importClause && !node.importClause.isTypeOnly && ((node.importClause.namedBindings && ts.isNamespaceImport(node.importClause.namedBindings)) || @@ -230,9 +238,7 @@ function scanSource( if ( ts.isExportDeclaration(node) && !node.isTypeOnly && - node.moduleSpecifier && - ts.isStringLiteral(node.moduleSpecifier) && - /(?:^|\/)sandbox-control-routing(?:\.js)?$/u.test(node.moduleSpecifier.text) && + isSandboxControlRoutingModule(node.moduleSpecifier) && node.exportClause && ts.isNamedExports(node.exportClause) && node.exportClause.elements.some( @@ -257,6 +263,14 @@ function scanSource( } if (ts.isCallExpression(node)) { + const loadsSandboxControlRoutingAtRuntime = + (node.expression.kind === ts.SyntaxKind.ImportKeyword || + (ts.isIdentifier(node.expression) && node.expression.text === "require")) && + isSandboxControlRoutingModule(node.arguments[0]); + if (loadsSandboxControlRoutingAtRuntime) { + increment(counts, "grpc-cli-read-only-fallback"); + } + const name = resolvedExpressionName(node.expression, bindings); const helperKind = name ? HELPER_KINDS.get(name) : undefined; if (helperKind) increment(counts, helperKind); diff --git a/src/lib/state/user-managed-files-probe.test.ts b/src/lib/state/user-managed-files-probe.test.ts index 6049083c81e..c1cb0bbb26f 100644 --- a/src/lib/state/user-managed-files-probe.test.ts +++ b/src/lib/state/user-managed-files-probe.test.ts @@ -50,6 +50,16 @@ describe("probeUserManagedFiles", () => { }); }); + it("fails before dispatch when the sandbox is not registered", async () => { + getSandbox.mockReturnValue(undefined); + + await expect(probeUserManagedFiles("alpha")).rejects.toThrow( + "user-managed file probe failed: sandbox 'alpha' is not registered", + ); + expect(loadAgent).not.toHaveBeenCalled(); + expect(execReadOnly).not.toHaveBeenCalled(); + }); + it("supports nested and shell-quoted declared paths", async () => { loadAgent.mockReturnValue({ userManagedFiles: [".hermes/.env", "user's.env"] }); execReadOnly.mockResolvedValue({ status: 0, stdout: ".hermes/.env\n", stderr: "" }); @@ -84,6 +94,19 @@ describe("probeUserManagedFiles", () => { ); }); + it("rejects partial output when the transport did not complete", async () => { + execReadOnly.mockResolvedValue({ + status: null, + stdout: ".env\n", + stderr: "transport interrupted", + error: new Error("UNAVAILABLE"), + }); + + await expect(probeUserManagedFiles("alpha")).rejects.toThrow( + "user-managed file probe failed: transport interrupted", + ); + }); + it("preserves partial successful output from a nonzero remote command", async () => { execReadOnly.mockResolvedValue({ status: 1, stdout: ".env\n", stderr: "partial" }); diff --git a/src/lib/state/user-managed-files-probe.ts b/src/lib/state/user-managed-files-probe.ts index 7597d9db869..e46b9d71d40 100644 --- a/src/lib/state/user-managed-files-probe.ts +++ b/src/lib/state/user-managed-files-probe.ts @@ -22,7 +22,10 @@ function _log(msg: string): void { export async function probeUserManagedFiles(sandboxName: string): Promise { const sb = registry.getSandbox(sandboxName); - const agentName = sb?.agent || "openclaw"; + if (!sb) { + throw new Error(`user-managed file probe failed: sandbox '${sandboxName}' is not registered`); + } + const agentName = sb.agent || "openclaw"; const declared = [...(loadAgent(agentName).userManagedFiles ?? [])]; if (declared.length === 0) return { declared, existing: [] }; @@ -42,7 +45,7 @@ export async function probeUserManagedFiles(sandboxName: string): Promise { ]); }); + it("tracks runtime imports of the read-only fallback module", () => { + const root = fixtureRepo({ + "src/dynamic-import.ts": + 'async function load() { return import("./lib/adapters/openshell/sandbox-control-routing.js"); }', + "src/require-import.ts": + 'const routing = require("./lib/adapters/openshell/sandbox-control-routing");', + }); + + expect(discoverLegacySandboxTransportSites(root)).toEqual([ + { + relativePath: "src/dynamic-import.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + { + relativePath: "src/require-import.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + ]); + }); + it("ignores type-only fallback imports and re-exports", () => { const root = fixtureRepo({ "src/type-only.ts": [ From cf6f1a04dd318000126b9f8461041c5f8c462b70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aaron=20Erickson=20=F0=9F=A6=9E?= Date: Mon, 20 Jul 2026 13:50:54 -0700 Subject: [PATCH 13/13] refactor(openshell): remove diagnostic SSH transport (#6798) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Moves in-sandbox debug and diagnostic reads from SSH to the supported OpenShell control boundary. This is PR 6 of 21 in the OpenShell gRPC migration stack. ## Changes - Route diagnostic commands through read-only gRPC control. - Preserve bounded output and best-effort diagnostic behavior. - Remove diagnostic SSH argument construction. ## Stack - Stack index: https://github.com/NVIDIA/NemoClaw/pull/6790 - Depends on: https://github.com/NVIDIA/NemoClaw/pull/6797 - Review this PR against base branch `refactor/openshell-grpc-rebuild-probe/ae` to see only this slice. ## Type of Change - [x] Code change (feature, bug fix, or refactor) - [ ] Code change with doc updates - [ ] Doc only (prose changes, no code sample modifications) - [ ] Doc only (includes code sample changes) ## Quality Gates - [x] Tests added or updated for changed behavior - [ ] Existing tests cover changed behavior — justification: - [ ] Tests not applicable — justification: - [x] Docs not applicable — justification: this slice changes only internal transport implementation or tests. - [x] Sensitive paths changed (security, policy, credentials, preflight, onboarding, inference, runner, sandbox, or messaging) - [x] Sensitive-path review completed or maintainer-approved waiver recorded — reviewer/approval link/justification: transport-boundary self-review completed; mutations select one transport before dispatch and are never replayed automatically. - [ ] Non-success, skipped, or missing CI check accepted by maintainer — check name, approval link, and follow-up issue: ## Verification - [x] PR description includes the DCO sign-off declaration and every commit appears as `Verified` in GitHub - [x] Normal `pre-commit`, `commit-msg`, and `pre-push` hooks passed, or `npm run check:diff` passed when hooks were skipped or unavailable - [x] Targeted behavior tests pass for the current change set, or tests are marked not applicable above — debug command and diagnostic collection tests passed - [ ] Applicable broad gate passed — targeted and changed-graph tests were used; CI will run the repository-required broad gates - [x] Quality Gates section completed with required justifications or waivers - [x] No secrets, API keys, or credentials committed - [ ] `npm run docs` builds without warnings (doc changes only) — not applicable - [ ] Doc pages follow the [style guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md) (doc changes only) - [ ] New doc pages include SPDX header and frontmatter (new pages only) --- Signed-off-by: Aaron Erickson --------- Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 3 +- src/commands/debug.ts | 17 +- .../simple-global-oclif-adapters.test.ts | 9 +- .../openshell/sandbox-control-routing.ts | 11 +- src/lib/diagnostics/debug-command.test.ts | 67 ++++++-- src/lib/diagnostics/debug-command.ts | 11 +- .../debug-sandbox-internals.test.ts | 155 ++++++++++++++++++ src/lib/diagnostics/debug.ts | 110 +++++++------ test/legacy-sandbox-transports.test.ts | 25 +++ 9 files changed, 319 insertions(+), 89 deletions(-) create mode 100644 src/lib/diagnostics/debug-sandbox-internals.test.ts diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index aec9e909d9c..a94832ccf05 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -46,8 +46,7 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/adapters/docker/container.ts", "docker-exec-command", 1], ["src/lib/adapters/openshell/client.ts", "openshell-ssh-config", 1], ["src/lib/adapters/openshell/runtime.ts", "openshell-ssh-config", 1], - ["src/lib/diagnostics/debug.ts", "openshell-ssh-config", 1], - ["src/lib/diagnostics/debug.ts", "ssh-command", 4], + ["src/lib/diagnostics/debug.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/onboard.ts", "docker-exec-builder", 1], ["src/lib/resources-cmd.ts", "docker-exec-command", 1], ["src/lib/sandbox/config.ts", "privileged-sandbox-exec", 2], diff --git a/src/commands/debug.ts b/src/commands/debug.ts index ba1bfb36d61..6cd25b487e6 100644 --- a/src/commands/debug.ts +++ b/src/commands/debug.ts @@ -2,19 +2,18 @@ // SPDX-License-Identifier: Apache-2.0 import { Flags } from "@oclif/core"; -import { NemoClawCommand } from "../lib/cli/nemoclaw-oclif-command"; - +import type { CaptureOpenshellResult } from "../lib/adapters/openshell/client"; +import { captureOpenshellCommand } from "../lib/adapters/openshell/client"; +import { resolveOpenshell } from "../lib/adapters/openshell/resolve"; +import { OPENSHELL_PROBE_TIMEOUT_MS } from "../lib/adapters/openshell/timeouts"; import { CLI_NAME } from "../lib/cli/branding"; -import { runDebug } from "../lib/diagnostics/debug"; +import { NemoClawCommand } from "../lib/cli/nemoclaw-oclif-command"; import type { DebugOptions } from "../lib/diagnostics/debug"; +import { runDebug } from "../lib/diagnostics/debug"; import type { RunDebugCommandDeps } from "../lib/diagnostics/debug-command"; import { runDebugCommandWithOptions } from "../lib/diagnostics/debug-command"; -import type { CaptureOpenshellResult } from "../lib/adapters/openshell/client"; -import { captureOpenshellCommand } from "../lib/adapters/openshell/client"; -import { OPENSHELL_PROBE_TIMEOUT_MS } from "../lib/adapters/openshell/timeouts"; -import * as registry from "../lib/state/registry"; -import { resolveOpenshell } from "../lib/adapters/openshell/resolve"; import { parseLiveSandboxNames } from "../lib/runtime-recovery"; +import * as registry from "../lib/state/registry"; const useColor = !process.env.NO_COLOR && !!process.stderr.isTTY; const B = useColor ? "\x1b[1m" : ""; @@ -99,6 +98,6 @@ export default class DebugCliCommand extends NemoClawCommand { if (flags.quick) options.quick = true; if (flags.output) options.output = flags.output; if (flags.sandbox) options.sandboxName = flags.sandbox; - runDebugCommandWithOptions(options, buildDebugCommandDeps(this.config.root)); + await runDebugCommandWithOptions(options, buildDebugCommandDeps(this.config.root)); } } diff --git a/src/commands/simple-global-oclif-adapters.test.ts b/src/commands/simple-global-oclif-adapters.test.ts index 450f4b73de0..304e302ee38 100644 --- a/src/commands/simple-global-oclif-adapters.test.ts +++ b/src/commands/simple-global-oclif-adapters.test.ts @@ -36,7 +36,7 @@ const mocks = vi.hoisted(() => { captureOpenshellCommand: vi.fn(() => ({ status: 0, output: "alpha\n" })), listSandboxes: vi.fn(() => ({ sandboxes: [] })), resolveOpenshell: vi.fn(() => "/usr/bin/openshell"), - runDebugCommandWithOptions: vi.fn(), + runDebugCommandWithOptions: vi.fn().mockResolvedValue(undefined), runDeployAction: vi.fn().mockResolvedValue(undefined), runDashboardUrlCommand: vi.fn(() => undefined), runGatewayTokenCommand: vi.fn(() => undefined), @@ -145,6 +145,13 @@ describe("simple global oclif adapters", () => { expect(configure).not.toHaveBeenCalledWith({ debug: false, quiet: true }); }); + it("propagates a rejected debug action through the CLI boundary", async () => { + const failure = new Error("diagnostic collection failed"); + mocks.runDebugCommandWithOptions.mockRejectedValueOnce(failure); + + await expect(DebugCliCommand.run(["--quick"], rootDir)).rejects.toBe(failure); + }); + it("builds debug defaults from the sandbox registry and OpenShell liveness", async () => { mocks.listSandboxes.mockReturnValue({ defaultSandbox: "alpha", diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index 1883f8d085d..66d0c18b95b 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -81,11 +81,12 @@ export function selectOpenShellSandboxControlForMutation( * so NemoClaw cannot replace that path here. * * This migration contract is limited to the reviewed read-only callers (the - * session list and rebuild file probe at this slice), not a general routing - * policy. Remove the CLI fallback when OpenShell's public client or bindings - * support the edge-tunnel auth and credential-refresh lifecycle. Every added - * caller requires a replay-semantics review; mutations must select one - * transport before dispatch and must never be replayed automatically. + * session list, rebuild file probe, and debug diagnostic probes at this + * slice), not a general routing policy. Remove the CLI fallback when + * OpenShell's public client or bindings support the edge-tunnel auth and + * credential-refresh lifecycle. Every added caller requires a replay-semantics + * review; mutations must select one transport before dispatch and must never + * be replayed automatically. */ export async function execSandboxReadOnlyWithGrpcFallback( gatewayName: string, diff --git a/src/lib/diagnostics/debug-command.test.ts b/src/lib/diagnostics/debug-command.test.ts index e46c88738f6..3079f8b88ac 100644 --- a/src/lib/diagnostics/debug-command.test.ts +++ b/src/lib/diagnostics/debug-command.test.ts @@ -6,9 +6,9 @@ import { describe, expect, it, vi } from "vitest"; import { runDebugCommandWithOptions } from "./debug-command"; describe("debug command", () => { - it("runs parsed debug options and falls back to the default sandbox", () => { - const runDebug = vi.fn(); - runDebugCommandWithOptions( + it("runs parsed debug options and falls back to the default sandbox", async () => { + const runDebug = vi.fn().mockResolvedValue(undefined); + await runDebugCommandWithOptions( { quick: true, output: "/tmp/out.tgz" }, { getDefaultSandbox: () => "alpha", @@ -23,10 +23,10 @@ describe("debug command", () => { }); }); - it("accepts an explicit --sandbox name that is registered", () => { - const runDebug = vi.fn(); + it("accepts an explicit --sandbox name that is registered", async () => { + const runDebug = vi.fn().mockResolvedValue(undefined); const isSandboxKnown = vi.fn().mockReturnValue(true); - runDebugCommandWithOptions( + await runDebugCommandWithOptions( { sandboxName: "alpha" }, { getDefaultSandbox: () => undefined, @@ -38,6 +38,43 @@ describe("debug command", () => { expect(runDebug).toHaveBeenCalledWith({ sandboxName: "alpha" }); }); + it("returns the debug operation completion promise", async () => { + let resolveDebug!: () => void; + const debugCompletion = new Promise((resolve) => { + resolveDebug = resolve; + }); + const runDebug = vi.fn(() => debugCompletion); + + const completion = runDebugCommandWithOptions( + { quick: true }, + { + getDefaultSandbox: () => "alpha", + isSandboxKnown: () => true, + runDebug, + }, + ); + + expect(completion).toBe(debugCompletion); + resolveDebug(); + await expect(completion).resolves.toBeUndefined(); + }); + + it("propagates a rejected debug operation", async () => { + const failure = new Error("diagnostic collection failed"); + const runDebug = vi.fn().mockRejectedValue(failure); + + await expect( + runDebugCommandWithOptions( + { quick: true }, + { + getDefaultSandbox: () => "alpha", + isSandboxKnown: () => true, + runDebug, + }, + ), + ).rejects.toBe(failure); + }); + it("rejects an explicit --sandbox name that is not registered, exits non-zero, skips runDebug", () => { const runDebug = vi.fn(); const errorLines: string[] = []; @@ -88,10 +125,10 @@ describe("debug command", () => { expect(errorLines[0]).toContain("NEMOCLAW_SANDBOX_NAME"); }); - it("prefers NEMOCLAW_SANDBOX_NAME over NEMOCLAW_SANDBOX and SANDBOX_NAME", () => { - const runDebug = vi.fn(); + it("prefers NEMOCLAW_SANDBOX_NAME over NEMOCLAW_SANDBOX and SANDBOX_NAME", async () => { + const runDebug = vi.fn().mockResolvedValue(undefined); const isSandboxKnown = vi.fn().mockReturnValue(true); - runDebugCommandWithOptions( + await runDebugCommandWithOptions( {}, { env: { @@ -108,10 +145,10 @@ describe("debug command", () => { expect(runDebug).toHaveBeenCalledWith({ sandboxName: "primary" }); }); - it("flag overrides env vars when both are present", () => { - const runDebug = vi.fn(); + it("flag overrides env vars when both are present", async () => { + const runDebug = vi.fn().mockResolvedValue(undefined); const isSandboxKnown = vi.fn().mockReturnValue(true); - runDebugCommandWithOptions( + await runDebugCommandWithOptions( { sandboxName: "alpha" }, { env: { NEMOCLAW_SANDBOX: "beta" } as NodeJS.ProcessEnv, @@ -125,10 +162,10 @@ describe("debug command", () => { expect(runDebug).toHaveBeenCalledWith({ sandboxName: "alpha" }); }); - it("falls back to getDefaultSandbox when neither flag nor env is set", () => { - const runDebug = vi.fn(); + it("falls back to getDefaultSandbox when neither flag nor env is set", async () => { + const runDebug = vi.fn().mockResolvedValue(undefined); const isSandboxKnown = vi.fn(); - runDebugCommandWithOptions( + await runDebugCommandWithOptions( {}, { env: {} as NodeJS.ProcessEnv, diff --git a/src/lib/diagnostics/debug-command.ts b/src/lib/diagnostics/debug-command.ts index 841efb00f34..b43f4bd30ee 100644 --- a/src/lib/diagnostics/debug-command.ts +++ b/src/lib/diagnostics/debug-command.ts @@ -6,7 +6,7 @@ import type { DebugOptions } from "./debug"; export interface RunDebugCommandDeps { getDefaultSandbox: () => string | undefined; isSandboxKnown: (name: string) => boolean; - runDebug: (options: DebugOptions) => void; + runDebug: (options: DebugOptions) => Promise; env?: NodeJS.ProcessEnv; errorLine?: (message: string) => void; exit?: (code: number) => never; @@ -31,7 +31,10 @@ function resolveExplicitName( return null; } -export function runDebugCommandWithOptions(options: DebugOptions, deps: RunDebugCommandDeps): void { +export function runDebugCommandWithOptions( + options: DebugOptions, + deps: RunDebugCommandDeps, +): Promise { const opts = { ...options }; const env = deps.env ?? process.env; const errorLine = deps.errorLine ?? ((msg: string) => console.error(msg)); @@ -49,12 +52,12 @@ export function runDebugCommandWithOptions(options: DebugOptions, deps: RunDebug errorLine(`Error: Sandbox '${explicit.name}'${sourceLabel} is not registered.`); errorLine(" Run `nemoclaw list` to see available sandboxes."); exit(1); - return; + return Promise.resolve(); } opts.sandboxName = explicit.name; } else { opts.sandboxName = deps.getDefaultSandbox(); } - deps.runDebug(opts); + return deps.runDebug(opts); } diff --git a/src/lib/diagnostics/debug-sandbox-internals.test.ts b/src/lib/diagnostics/debug-sandbox-internals.test.ts new file mode 100644 index 00000000000..2f6191b43f2 --- /dev/null +++ b/src/lib/diagnostics/debug-sandbox-internals.test.ts @@ -0,0 +1,155 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const { execSandbox, getSandbox, listSandboxes } = vi.hoisted(() => ({ + execSandbox: vi.fn(), + getSandbox: vi.fn(), + listSandboxes: vi.fn(), +})); + +const { execFileSync } = vi.hoisted(() => ({ execFileSync: vi.fn() })); + +vi.mock("../adapters/openshell/sandbox-control-routing", () => ({ + execSandboxReadOnlyWithGrpcFallback: execSandbox, +})); +vi.mock("../state/registry", () => ({ getSandbox, listSandboxes })); +vi.mock("node:child_process", async (importOriginal) => ({ + ...(await importOriginal()), + execFileSync, +})); + +import { collectSandboxInternals } from "./debug"; + +describe("collectSandboxInternals", () => { + let collectDir: string; + + beforeEach(() => { + collectDir = mkdtempSync(join(tmpdir(), "nemoclaw-debug-sandbox-")); + execFileSync.mockReturnValue(Buffer.alloc(0)); + getSandbox.mockReturnValue({ gatewayPort: 19080 }); + execSandbox.mockResolvedValue({ status: 0, stdout: "ok", stderr: "" }); + }); + + afterEach(() => { + rmSync(collectDir, { force: true, recursive: true }); + vi.clearAllMocks(); + }); + + it("collects the quick command set through the sandbox's named gateway", async () => { + await collectSandboxInternals(collectDir, "alpha", true); + + expect(execSandbox.mock.calls).toEqual([ + ["nemoclaw-19080", { sandboxName: "alpha", command: ["ps", "-ef"], timeoutMs: 30_000 }], + ["nemoclaw-19080", { sandboxName: "alpha", command: ["free", "-m"], timeoutMs: 30_000 }], + ]); + expect(readFileSync(join(collectDir, "sandbox-ps.txt"), "utf8")).toBe("ok\n"); + }); + + it("adds top and gateway-log collection outside quick mode and redacts output", async () => { + execSandbox.mockResolvedValue({ + status: 0, + stdout: "API_KEY=secret-value", + stderr: "", + }); + + await collectSandboxInternals(collectDir, "alpha", false); + + expect(execSandbox.mock.calls.map((call) => call[1].command)).toEqual([ + ["ps", "-ef"], + ["free", "-m"], + ["top", "-b", "-n", "1"], + ["tail", "-200", "/tmp/gateway.log"], + ]); + expect(readFileSync(join(collectDir, "sandbox-gateway-log.txt"), "utf8")).toBe( + "API_KEY=\n", + ); + }); + + it("keeps missing CLI and unregistered targets nonfatal", async () => { + execFileSync.mockImplementationOnce(() => { + throw new Error("not found"); + }); + await expect(collectSandboxInternals(collectDir, "alpha", true)).resolves.toBeUndefined(); + expect(execSandbox).not.toHaveBeenCalled(); + + execFileSync.mockReturnValue(Buffer.alloc(0)); + getSandbox.mockReturnValue(undefined); + await expect(collectSandboxInternals(collectDir, "alpha", true)).resolves.toBeUndefined(); + expect(execSandbox).not.toHaveBeenCalled(); + }); + + it("redacts credential-shaped invalid gateway bindings from terminal warnings", async () => { + const secret = ["sk-proj", "debugregistrycredential"].join("-"); + getSandbox.mockReturnValue({ gatewayName: secret }); + const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined); + + try { + await collectSandboxInternals(collectDir, "alpha", true); + + const terminalOutput = consoleLog.mock.calls.flat().join("\n"); + expect(terminalOutput).not.toContain(secret); + expect(terminalOutput).toContain(""); + expect(execSandbox).not.toHaveBeenCalled(); + } finally { + consoleLog.mockRestore(); + } + }); + + it("records one routing failure and continues collecting", async () => { + execSandbox + .mockRejectedValueOnce(new Error("API_KEY=secret-value")) + .mockResolvedValue({ status: 0, stdout: "free-ok", stderr: "" }); + + await collectSandboxInternals(collectDir, "alpha", true); + + expect(execSandbox).toHaveBeenCalledTimes(2); + expect(readFileSync(join(collectDir, "sandbox-ps.txt"), "utf8")).toBe( + " (sandbox command failed: API_KEY=)\n", + ); + expect(readFileSync(join(collectDir, "sandbox-free.txt"), "utf8")).toBe("free-ok\n"); + }); + + it("records resolved transport errors with partial output and continues collecting", async () => { + execSandbox + .mockResolvedValueOnce({ + status: null, + stdout: "partial output", + stderr: "partial warning", + error: new Error("API_KEY=secret-value"), + }) + .mockResolvedValue({ status: 0, stdout: "free-ok", stderr: "" }); + + await collectSandboxInternals(collectDir, "alpha", true); + + expect(execSandbox).toHaveBeenCalledTimes(2); + expect(readFileSync(join(collectDir, "sandbox-ps.txt"), "utf8")).toBe( + [ + "partial output", + "partial warning", + " (sandbox command failed; detail follows)", + "API_KEY=", + "", + ].join("\n"), + ); + expect(readFileSync(join(collectDir, "sandbox-free.txt"), "utf8")).toBe("free-ok\n"); + }); + + it("redacts credentials split across stdout and stderr as one stream", async () => { + execSandbox.mockResolvedValue({ + status: 0, + stdout: "Authorization: Bearer", + stderr: " secret-value", + }); + + await collectSandboxInternals(collectDir, "alpha", true); + + expect(readFileSync(join(collectDir, "sandbox-ps.txt"), "utf8")).toBe( + "Authorization: ", + ); + }); +}); diff --git a/src/lib/diagnostics/debug.ts b/src/lib/diagnostics/debug.ts index a41e70d98b5..00006f55aef 100644 --- a/src/lib/diagnostics/debug.ts +++ b/src/lib/diagnostics/debug.ts @@ -7,8 +7,10 @@ import { platform, tmpdir } from "node:os"; import { join } from "node:path"; import { dockerExecFileSync } from "../adapters/docker/exec"; +import { execSandboxReadOnlyWithGrpcFallback } from "../adapters/openshell/sandbox-control-routing"; import { DASHBOARD_PORT } from "../core/ports"; -import { listSandboxes } from "../state/registry"; +import { resolveSandboxGatewayName } from "../onboard/gateway-binding"; +import { getSandbox, listSandboxes } from "../state/registry"; import { createTarball as createDiagnosticsTarball } from "./tarball"; // --------------------------------------------------------------------------- @@ -367,63 +369,65 @@ function collectOpenshell(collectDir: string, sandboxName: string, quick: boolea } } -function collectSandboxInternals(collectDir: string, sandboxName: string, quick: boolean): void { +export async function collectSandboxInternals( + collectDir: string, + sandboxName: string, + quick: boolean, +): Promise { if (!commandExists("openshell")) return; - - // Check if sandbox exists. OpenShell ssh-config may succeed for unknown - // names, so verify the live sandbox first. - try { - execFileSync("openshell", ["sandbox", "get", sandboxName], { - encoding: "utf-8", - timeout: 10_000, - stdio: ["ignore", "pipe", "ignore"], - }); - } catch { - return; - } - section("Sandbox Internals"); - // Generate temporary SSH config in a private directory. - const sshConfigDir = mkdtempSync(join(tmpdir(), "nemoclaw-ssh-")); - const sshConfigPath = join(sshConfigDir, "config"); + let gatewayName: string; try { - const sshResult = spawnSync("openshell", ["sandbox", "ssh-config", sandboxName], { - timeout: TIMEOUT_MS, - stdio: ["ignore", "pipe", "ignore"], - encoding: "utf-8", - }); - if (sshResult.status !== 0) { - warn(`Could not generate SSH config for sandbox '${sandboxName}', skipping internals`); + const sandbox = getSandbox(sandboxName); + if (!sandbox) { + warn(`Sandbox '${sandboxName}' has no registered gateway binding, skipping internals`); return; } - writeFileSync(sshConfigPath, sshResult.stdout ?? ""); - - const sshHost = `openshell-${sandboxName}`; - const sshBase = [ - "-F", - sshConfigPath, - "-o", - "StrictHostKeyChecking=no", - "-o", - "ConnectTimeout=10", - sshHost, - ]; - - // Use collect() with array args — no shell interpolation of sandboxName - collect(collectDir, "sandbox-ps", "ssh", [...sshBase, "ps", "-ef"]); - collect(collectDir, "sandbox-free", "ssh", [...sshBase, "free", "-m"]); - if (!quick) { - collect(collectDir, "sandbox-top", "ssh", [...sshBase, "top", "-b", "-n", "1"]); - collect(collectDir, "sandbox-gateway-log", "ssh", [ - ...sshBase, - "tail", - "-200", - "/tmp/gateway.log", - ]); + gatewayName = resolveSandboxGatewayName(sandbox); + } catch (cause) { + warn( + redact( + `Could not resolve the gateway for sandbox '${sandboxName}', skipping internals: ${cause instanceof Error ? cause.message : String(cause)}`, + ), + ); + return; + } + + const commands: ReadonlyArray = [ + ["sandbox-ps", ["ps", "-ef"]], + ["sandbox-free", ["free", "-m"]], + ...(!quick + ? ([ + ["sandbox-top", ["top", "-b", "-n", "1"]], + ["sandbox-gateway-log", ["tail", "-200", "/tmp/gateway.log"]], + ] as const) + : []), + ]; + for (const [label, command] of commands) { + try { + const result = await execSandboxReadOnlyWithGrpcFallback(gatewayName, { + sandboxName, + command, + timeoutMs: TIMEOUT_MS, + }); + let raw = `${result.stdout}\n${result.stderr}`; + if (result.error) { + if (result.stdout.length === 0 && result.stderr.length === 0) raw = ""; + if (raw.length > 0 && !raw.endsWith("\n")) raw += "\n"; + raw += ` (sandbox command failed; detail follows)\n${result.error.message}`; + if (!raw.endsWith("\n")) raw += "\n"; + } + const redacted = redact(raw); + writeFileSync(join(collectDir, `${label}.txt`), redacted); + console.log(redacted.trimEnd()); + if (result.status !== 0 && !result.error) { + console.log(" (command exited with non-zero status)"); + } + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + writeCollectedMessage(collectDir, label, ` (sandbox command failed: ${redact(detail)})`); } - } finally { - rmSync(sshConfigDir, { force: true, recursive: true }); } } @@ -524,7 +528,7 @@ export function getDebugCompletionMessages(output?: string): string[] { * Collect local and sandbox diagnostics for a NemoClaw environment and * optionally bundle the results into a tarball for issue reporting. */ -export function runDebug(opts: DebugOptions = {}): void { +export async function runDebug(opts: DebugOptions = {}): Promise { const quick = opts.quick ?? false; const output = opts.output ?? ""; // Compiled location: dist/lib/diagnostics/debug.js → repo root is 3 levels up @@ -555,7 +559,7 @@ export function runDebug(opts: DebugOptions = {}): void { collectDocker(collectDir, quick); collectOpenshell(collectDir, sandboxName, quick); collectOnboardSession(collectDir, repoDir); - collectSandboxInternals(collectDir, sandboxName, quick); + await collectSandboxInternals(collectDir, sandboxName, quick); if (!quick) { collectNetwork(collectDir); diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index fbeda855774..cf2e2e05073 100644 --- a/test/legacy-sandbox-transports.test.ts +++ b/test/legacy-sandbox-transports.test.ts @@ -7,6 +7,7 @@ import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { + REVIEWED_LEGACY_SANDBOX_TRANSPORT_SITES, auditLegacySandboxTransports, discoverLegacySandboxTransportSites, } from "../scripts/checks/legacy-sandbox-transports"; @@ -161,6 +162,30 @@ describe("legacy sandbox transport inventory", () => { expect(discoverLegacySandboxTransportSites(root)).toEqual([]); }); + it("keeps every reviewed read-only fallback importer explicit", () => { + expect( + REVIEWED_LEGACY_SANDBOX_TRANSPORT_SITES.filter( + (site) => site.kind === "grpc-cli-read-only-fallback", + ), + ).toEqual([ + { + relativePath: "src/lib/actions/sandbox/sessions/passthrough.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + { + relativePath: "src/lib/diagnostics/debug.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + { + relativePath: "src/lib/state/user-managed-files-probe.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + ]); + }); + it("fails closed when a new production file imports the read-only fallback", () => { const root = fixtureRepo({ "src/unreviewed-probe.ts":