diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index 9076bce6a28..723a37d610a 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -46,14 +46,11 @@ 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], - ["src/lib/sandbox/version.ts", "openshell-ssh-config", 1], - ["src/lib/sandbox/version.ts", "ssh-command", 1], - ["src/lib/sandbox/version.ts", "ssh-temp-config", 1], + ["src/lib/sandbox/version.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/share-command-deps.ts", "openshell-ssh-config", 1], ["src/lib/share-command.ts", "sshfs-command", 1], ["src/lib/shields/index.ts", "privileged-sandbox-exec", 4], @@ -61,8 +58,9 @@ const REVIEWED_SITE_TUPLES = [ ["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], + ["src/lib/state/sandbox.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/state/sandbox.ts", "openshell-ssh-config", 1], - ["src/lib/state/sandbox.ts", "ssh-command", 8], + ["src/lib/state/sandbox.ts", "ssh-command", 7], ["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], 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/actions/maintenance.ts b/src/lib/actions/maintenance.ts index e1d8446022e..a73a0272a8d 100644 --- a/src/lib/actions/maintenance.ts +++ b/src/lib/actions/maintenance.ts @@ -84,7 +84,7 @@ export async function backupAll(): Promise { try { result = startedForBackup ? await backupStartedSandboxState(sb.name) - : sandboxState.backupSandboxState(sb.name); + : await sandboxState.backupSandboxState(sb.name); } catch (err: unknown) { // Source-of-truth review (#5734 / #5819): // diff --git a/src/lib/actions/sandbox/connect-route-repair-inconclusive.test.ts b/src/lib/actions/sandbox/connect-route-repair-inconclusive.test.ts index f50a8e24ea6..54f4cddbf20 100644 --- a/src/lib/actions/sandbox/connect-route-repair-inconclusive.test.ts +++ b/src/lib/actions/sandbox/connect-route-repair-inconclusive.test.ts @@ -6,6 +6,7 @@ import type { SandboxEntry } from "../../state/registry"; vi.mock("../../adapters/openshell/runtime", () => ({ captureOpenshell: vi.fn(() => ({ status: 0, output: "" })), + captureOpenshellBinary: vi.fn(), getOpenshellBinary: vi.fn(() => "openshell"), runOpenshell: vi.fn(() => ({ status: 0 })), })); diff --git a/src/lib/actions/sandbox/connect-route-repair.test.ts b/src/lib/actions/sandbox/connect-route-repair.test.ts index c6092b14e35..c2318a49e3e 100644 --- a/src/lib/actions/sandbox/connect-route-repair.test.ts +++ b/src/lib/actions/sandbox/connect-route-repair.test.ts @@ -6,6 +6,7 @@ import type { SandboxEntry } from "../../state/registry"; vi.mock("../../adapters/openshell/runtime", () => ({ captureOpenshell: vi.fn(() => ({ status: 0, output: "" })), + captureOpenshellBinary: vi.fn(), getOpenshellBinary: vi.fn(() => "openshell"), runOpenshell: vi.fn(() => ({ status: 0 })), })); diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 648474a76c9..cd28afc296f 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -974,7 +974,7 @@ export async function connectSandbox( // Version staleness check — warn but don't block try { - const versionCheck = sandboxVersion.checkAgentVersion(sandboxName); + const versionCheck = await sandboxVersion.checkAgentVersion(sandboxName); if (versionCheck.isStale) { for (const line of sandboxVersion.formatStalenessWarning(sandboxName, versionCheck)) { console.error(line); diff --git a/src/lib/actions/sandbox/doctor-flow.test.ts b/src/lib/actions/sandbox/doctor-flow.test.ts index d1a105a5f2c..0ac4efea655 100644 --- a/src/lib/actions/sandbox/doctor-flow.test.ts +++ b/src/lib/actions/sandbox/doctor-flow.test.ts @@ -132,7 +132,7 @@ function createDoctorHarness(): { }); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ name: "openclaw" }); vi.spyOn(agentRuntime, "getAgentDisplayName").mockReturnValue("OpenClaw"); - vi.spyOn(sandboxVersion, "checkAgentVersion").mockReturnValue({ + vi.spyOn(sandboxVersion, "checkAgentVersion").mockResolvedValue({ sandboxVersion: "0.1.0", expectedVersion: "0.2.0", isStale: true, diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index b6abbbde3a5..17497e7b195 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -292,9 +292,9 @@ function resolveInferenceRoute( }; } -function agentVersionDoctorCheck(sandboxName: string): DoctorCheck { +async function agentVersionDoctorCheck(sandboxName: string): Promise { try { - const version = sandboxVersion.checkAgentVersion(sandboxName); + const version = await sandboxVersion.checkAgentVersion(sandboxName); const agentName = agentRuntime.getAgentDisplayName(agentRuntime.getSessionAgent(sandboxName)); if (version.isStale) { return { @@ -352,14 +352,14 @@ function shieldsDoctorCheck(sandboxName: string): DoctorCheck { }; } -function collectRegisteredSandboxChecks( +async function collectRegisteredSandboxChecks( sandboxName: string, sb: SandboxEntry | null | undefined, wantsFix: boolean, sandboxReachable: boolean, -): DoctorCheck[] { +): Promise { if (!sb) return []; - const checks = [agentVersionDoctorCheck(sandboxName), shieldsDoctorCheck(sandboxName)]; + const checks = [await agentVersionDoctorCheck(sandboxName), shieldsDoctorCheck(sandboxName)]; const permsCheck = buildConfigPermsCheck(sandboxName, wantsFix, { inspect: shields.inspectMutableConfigPerms, repair: shields.repairMutableConfigPerms, @@ -402,7 +402,7 @@ async function collectDoctorChecks( ...gateway.checks, ...sandbox.checks, ...(await collectInferenceChecks(sandboxName, route, sandbox.reachable)), - ...collectRegisteredSandboxChecks(sandboxName, sb, intent.wantsFix, sandbox.reachable), + ...(await collectRegisteredSandboxChecks(sandboxName, sb, intent.wantsFix, sandbox.reachable)), ...collectToolScopeChecks(sandboxName, sb, sandbox.reachable, intent.wantsFix), ollamaDoctorCheck(route.provider), cloudflaredDoctorCheck(sandboxName), diff --git a/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts b/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts index 0f22a8a9126..dcb92cba67f 100644 --- a/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts +++ b/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts @@ -16,6 +16,7 @@ vi.mock("node:child_process", async (importOriginal) => { vi.mock("../../adapters/openshell/runtime", () => ({ captureOpenshell: vi.fn(), + captureOpenshellBinary: vi.fn(), captureOpenshellForStatus: vi.fn(), captureSandboxSshConfig, getOpenshellBinary: vi.fn(() => "openshell"), diff --git a/src/lib/actions/sandbox/rebuild-backup-phase.test.ts b/src/lib/actions/sandbox/rebuild-backup-phase.test.ts index 5f33475e81a..14f94200251 100644 --- a/src/lib/actions/sandbox/rebuild-backup-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-backup-phase.test.ts @@ -65,8 +65,8 @@ describe("rebuild web-search policy normalization", () => { ).toEqual(["npm"]); }); - it("keeps a finalized custom-only built-in selection empty instead of resetting it", () => { - const result = runRebuildBackupPhase({ + it("keeps a finalized custom-only built-in selection empty instead of resetting it", async () => { + const result = await runRebuildBackupPhase({ sandboxName: "alpha", sandboxEntry: { name: "alpha", @@ -94,10 +94,10 @@ describe("rebuild web-search policy normalization", () => { expect(result?.backupWasForceSkipped).toBe(false); }); - it("records when --force skips a total backup failure", () => { + it("records when --force skips a total backup failure", async () => { vi.spyOn(console, "warn").mockImplementation(() => undefined); vi.spyOn(console, "log").mockImplementation(() => undefined); - vi.spyOn(sandboxState, "backupSandboxState").mockReturnValue({ + vi.spyOn(sandboxState, "backupSandboxState").mockResolvedValue({ success: false, backedUpDirs: [], backedUpFiles: [], @@ -105,7 +105,7 @@ describe("rebuild web-search policy normalization", () => { failedFiles: ["openclaw.json"], }); - const result = runRebuildBackupPhase({ + const result = await runRebuildBackupPhase({ sandboxName: "alpha", sandboxEntry: { name: "alpha", agent: "openclaw", policies: [] }, staleRecovery: false, @@ -227,12 +227,12 @@ describe("custom OpenClaw plugin provenance rebuild guard (#6108)", () => { } as RebuildBackupPhaseInput; } - it("blocks a live custom image with missing registry provenance before backup", () => { + it("blocks a live custom image with missing registry provenance before backup", async () => { const backupStateForRebuild = vi.fn(); const input = customOpenClawInput(); const errorLog = vi.spyOn(console, "error").mockImplementation(() => undefined); - expect(() => runRebuildBackupPhase(input, backupStateForRebuild)).toThrow( + await expect(runRebuildBackupPhase(input, backupStateForRebuild)).rejects.toThrow( "Custom-image OpenClaw plugin provenance is unavailable.", ); @@ -245,17 +245,17 @@ describe("custom OpenClaw plugin provenance rebuild guard (#6108)", () => { errorLog.mockRestore(); }); - it("uses a marked prepared manifest when registry provenance is missing", () => { + it("uses a marked prepared manifest when registry provenance is missing", async () => { const backupStateForRebuild = vi.fn(); const input = customOpenClawInput({ preparedRecoveryManifest: completeMarkedManifest }); - const result = runRebuildBackupPhase(input, backupStateForRebuild); + const result = await runRebuildBackupPhase(input, backupStateForRebuild); expect(result?.backupManifest).toBe(completeMarkedManifest); expect(backupStateForRebuild).not.toHaveBeenCalled(); }); - it("blocks an unmarked legacy prepared manifest before deletion", () => { + it("blocks an unmarked legacy prepared manifest before deletion", async () => { const backupStateForRebuild = vi.fn(); const input = customOpenClawInput({ preparedRecoveryManifest: { @@ -266,15 +266,15 @@ describe("custom OpenClaw plugin provenance rebuild guard (#6108)", () => { }, }); - expect(() => runRebuildBackupPhase(input, backupStateForRebuild)).toThrow( + await expect(runRebuildBackupPhase(input, backupStateForRebuild)).rejects.toThrow( "Custom-image OpenClaw plugin provenance is unavailable.", ); expect(backupStateForRebuild).not.toHaveBeenCalled(); }); - it("revalidates a newly generated backup manifest before deletion", () => { - const backupStateForRebuild = vi.fn(() => ({ + it("revalidates a newly generated backup manifest before deletion", async () => { + const backupStateForRebuild = vi.fn(async () => ({ agentType: "openclaw", dir: "/sandbox/.openclaw", backupPath: "/tmp/incomplete-custom-openclaw-backup", @@ -289,7 +289,7 @@ describe("custom OpenClaw plugin provenance rebuild guard (#6108)", () => { }, }); - expect(() => runRebuildBackupPhase(input, backupStateForRebuild as never)).toThrow( + await expect(runRebuildBackupPhase(input, backupStateForRebuild as never)).rejects.toThrow( "Custom-image OpenClaw plugin provenance is unavailable.", ); diff --git a/src/lib/actions/sandbox/rebuild-backup-phase.ts b/src/lib/actions/sandbox/rebuild-backup-phase.ts index 8bb24655873..d3aca1d68bd 100644 --- a/src/lib/actions/sandbox/rebuild-backup-phase.ts +++ b/src/lib/actions/sandbox/rebuild-backup-phase.ts @@ -20,7 +20,7 @@ import type { RebuildBail, RebuildLog } from "./rebuild-credential-preflight"; import { backupSandboxStateForRebuild, type RebuildSandboxEntry } from "./rebuild-flow-helpers"; export type RebuildBackupManifest = Exclude< - ReturnType, + Awaited>, undefined >; @@ -144,10 +144,10 @@ export function normalizeRebuildTargetPolicyPresets( ); } -export function runRebuildBackupPhase( +export async function runRebuildBackupPhase( input: RebuildBackupPhaseInput, backupStateForRebuild: typeof backupSandboxStateForRebuild = backupSandboxStateForRebuild, -): RebuildBackupPhaseResult | null { +): Promise { const customOpenClaw = Boolean(input.sandboxEntry.fromDockerfile) && (!input.sandboxEntry.agent || input.sandboxEntry.agent === "openclaw"); @@ -174,7 +174,7 @@ export function runRebuildBackupPhase( } const backupManifest = preparedRecoveryManifest ?? - backupStateForRebuild( + (await backupStateForRebuild( input.sandboxName, input.sandboxEntry, input.staleRecovery, @@ -182,7 +182,7 @@ export function runRebuildBackupPhase( input.relockShieldsIfNeeded, input.bail, { force: input.force }, - ); + )); if (backupManifest === undefined) return null; if ( backupManifest && diff --git a/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts index 5e39bc84ffa..77470656d66 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts @@ -16,7 +16,7 @@ import { warnUnpreservedUserManagedFiles, } from "./rebuild-flow-helpers"; -function makeBackupResult(): ReturnType { +function makeBackupResult(): Awaited> { return { success: true, backedUpDirs: [".state"], @@ -38,7 +38,7 @@ function makeBackupResult(): ReturnType blueprintDigest: null, policyPresets: [], customPolicies: [], - } as ReturnType["manifest"], + } as Awaited>["manifest"], }; } @@ -227,8 +227,8 @@ describe("backupSandboxStateForRebuild with --force", () => { vi.restoreAllMocks(); }); - it("returns null (skip) when backup fails completely and force is set", () => { - backupSpy.mockReturnValue({ + it("returns null (skip) when backup fails completely and force is set", async () => { + backupSpy.mockResolvedValue({ success: false, backedUpDirs: [], backedUpFiles: [], @@ -236,7 +236,7 @@ describe("backupSandboxStateForRebuild with --force", () => { failedFiles: ["config.toml"], manifest: null, }); - const result = backupSandboxStateForRebuild( + const result = await backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), false, @@ -251,8 +251,8 @@ describe("backupSandboxStateForRebuild with --force", () => { expect(warnLines.some((line: string) => line.includes("--force was specified"))).toBe(true); }); - it("aborts with hint when backup fails completely without force", () => { - backupSpy.mockReturnValue({ + it("aborts with hint when backup fails completely without force", async () => { + backupSpy.mockResolvedValue({ success: false, backedUpDirs: [], backedUpFiles: [], @@ -260,7 +260,7 @@ describe("backupSandboxStateForRebuild with --force", () => { failedFiles: [], manifest: null, }); - expect(() => + await expect( backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), @@ -269,14 +269,14 @@ describe("backupSandboxStateForRebuild with --force", () => { () => true, makeBail(), ), - ).toThrow("bail: Failed to back up sandbox state."); + ).rejects.toThrow("bail: Failed to back up sandbox state."); const errorLines = errorSpy.mock.calls.map((args: unknown[]) => String(args[0])); expect(errorLines.some((line: string) => line.includes("rebuild --force"))).toBe(true); }); - it("aborts without force even when force option is explicitly false", () => { - backupSpy.mockReturnValue({ + it("aborts without force even when force option is explicitly false", async () => { + backupSpy.mockResolvedValue({ success: false, backedUpDirs: [], backedUpFiles: [], @@ -284,7 +284,7 @@ describe("backupSandboxStateForRebuild with --force", () => { failedFiles: [], manifest: null, }); - expect(() => + await expect( backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), @@ -294,7 +294,7 @@ describe("backupSandboxStateForRebuild with --force", () => { makeBail(), { force: false }, ), - ).toThrow("bail: Failed to back up sandbox state."); + ).rejects.toThrow("bail: Failed to back up sandbox state."); }); }); @@ -310,7 +310,7 @@ describe("warnUnpreservedUserManagedFiles", () => { logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - backupSpy = vi.spyOn(sandboxState, "backupSandboxState").mockReturnValue(makeBackupResult()); + backupSpy = vi.spyOn(sandboxState, "backupSandboxState").mockResolvedValue(makeBackupResult()); probeSpy = vi.spyOn(userManagedFilesProbe, "probeUserManagedFiles").mockResolvedValue({ declared: [], existing: [], @@ -365,8 +365,8 @@ describe("warnUnpreservedUserManagedFiles", () => { expect(warnLines.some((line: string) => line.includes("will not be preserved"))).toBe(false); }); - it("skips probe when staleRecovery short-circuits the backup", () => { - const result = backupSandboxStateForRebuild( + it("skips probe when staleRecovery short-circuits the backup", async () => { + const result = await backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), true, @@ -380,8 +380,8 @@ describe("warnUnpreservedUserManagedFiles", () => { expect(probeSpy).not.toHaveBeenCalled(); }); - it("does not probe during backup before managed MCP adapter entries are scrubbed", () => { - const result = backupSandboxStateForRebuild( + it("does not probe during backup before managed MCP adapter entries are scrubbed", async () => { + const result = await backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), false, @@ -414,8 +414,8 @@ describe("warnUnpreservedUserManagedFiles", () => { expect(errorSpy).not.toHaveBeenCalled(); }); - it("surfaces the backup failure reason before aborting", () => { - backupSpy.mockReturnValue({ + it("surfaces the backup failure reason before aborting", async () => { + backupSpy.mockResolvedValue({ ...makeBackupResult(), success: false, backedUpDirs: [], @@ -425,7 +425,7 @@ describe("warnUnpreservedUserManagedFiles", () => { error: "Pre-backup audit rejected an unsafe symlink", }); - expect(() => + await expect( backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), @@ -434,7 +434,7 @@ describe("warnUnpreservedUserManagedFiles", () => { () => true, makeBail(), ), - ).toThrow("bail: Failed to back up sandbox state."); + ).rejects.toThrow("bail: Failed to back up sandbox state."); const errorLines = errorSpy.mock.calls.map((args: unknown[]) => String(args[0])); expect(errorLines).toContain(" Reason: Pre-backup audit rejected an unsafe symlink"); diff --git a/src/lib/actions/sandbox/rebuild-flow-helpers.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.ts index d6a5be57b43..ed12a2821d5 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.ts @@ -258,7 +258,7 @@ export function pinRebuildAgentBaseImageForRecreate( }; } -export function backupSandboxStateForRebuild( +export async function backupSandboxStateForRebuild( sandboxName: string, sb: RebuildSandboxEntry, staleRecovery: boolean, @@ -266,12 +266,12 @@ export function backupSandboxStateForRebuild( relockShieldsIfNeeded: (sandboxStillExists: boolean) => boolean, bail: (msg: string, code?: number) => never, options?: { force?: boolean }, -): sandboxState.RebuildManifest | null | undefined { +): Promise { if (staleRecovery) return null; console.log(" Backing up sandbox state..."); log(`Agent type: ${sb.agent || "openclaw"}, stateDirs from manifest`); - const backup = sandboxState.backupSandboxState(sandboxName); + const backup = await sandboxState.backupSandboxState(sandboxName); log( `Backup result: success=${backup.success}, backed=${backup.backedUpDirs.join(",")}; files=${backup.backedUpFiles.join(",")}, failed=${backup.failedDirs.join(",")}; failedFiles=${backup.failedFiles.join(",")}`, ); diff --git a/src/lib/actions/sandbox/rebuild-pipeline.ts b/src/lib/actions/sandbox/rebuild-pipeline.ts index c3c2a87042c..20e5e57eaf9 100644 --- a/src/lib/actions/sandbox/rebuild-pipeline.ts +++ b/src/lib/actions/sandbox/rebuild-pipeline.ts @@ -150,7 +150,7 @@ async function rebuildSandboxUnlocked( recoveryManifest = preDeleteRecovery.manifest; recoveryRegistrySnapshot = preDeleteRecovery.registrySnapshot; - const backup = runRebuildBackupPhase({ + const backup = await runRebuildBackupPhase({ sandboxName, // The requested observability bit is replacement intent, not a // preflight mutation of the old registry row. Use a copy only for diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts index bd4551354a3..58ad7c9dcce 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts @@ -40,7 +40,7 @@ export interface RebuildPostRestorePhaseInput { recoveryRecreate: boolean; preparedBackupRecovery: boolean; staleSandboxWasLocked: boolean; - versionCheck: ReturnType; + versionCheck: Awaited>; relockShieldsIfNeeded: (sandboxStillExists: boolean) => boolean; log: RebuildLog; bail: RebuildBail; diff --git a/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts b/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts index b842451388a..ea16be0b80d 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts @@ -5,12 +5,17 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import * as openshellResolve from "../../adapters/openshell/resolve"; import { redact } from "../../security/redact"; import * as sandboxSession from "../../state/sandbox-session"; +import type { RebuildSandboxEntry } from "./rebuild-flow-helpers"; import { confirmSandboxRebuildIfNeeded, countActiveSandboxSessionsForRebuild, createRebuildCommandContext, + type RebuildVersionCheck, } from "./rebuild-preflight-confirmation"; -import { isSingleAgentRebuildSupported } from "./rebuild-preflight-guards"; +import { + expectedRebuildEntryAfterVersionCheck, + isSingleAgentRebuildSupported, +} from "./rebuild-preflight-guards"; afterEach(() => { vi.restoreAllMocks(); @@ -167,6 +172,61 @@ describe("createRebuildCommandContext bail behaviour (#6376)", () => { }); describe("rebuild preflight guards", () => { + it("allows only the sandbox-exec agent-version cache write after confirmation", () => { + const confirmedEntry: RebuildSandboxEntry = { + name: "alpha", + agent: "openclaw", + agentVersion: null, + policies: ["npm"], + gatewayName: "nemoclaw", + }; + const confirmedEntrySnapshot = JSON.stringify(confirmedEntry); + const concurrentlyChangedEntry = { ...confirmedEntry, gatewayName: "other-gateway" }; + const versionCheck: RebuildVersionCheck = { + sandboxVersion: "2026.7.14", + expectedVersion: "2026.7.14", + isStale: false, + verificationFailed: false, + detectionMethod: "sandbox-exec", + }; + + const expectedEntry = expectedRebuildEntryAfterVersionCheck( + concurrentlyChangedEntry, + confirmedEntrySnapshot, + versionCheck, + ); + + expect(expectedEntry).toStrictEqual({ ...confirmedEntry, agentVersion: "2026.7.14" }); + expect(expectedEntry).not.toBe(concurrentlyChangedEntry); + }); + + it.each([ + ["registry", "2026.7.14"], + ["unknown", null], + ["sandbox-exec", null], + ] as const)("returns the original entry for %s detection with sandbox version %s", (detectionMethod, sandboxVersion) => { + const confirmedEntry: RebuildSandboxEntry = { + name: "alpha", + agent: "openclaw", + agentVersion: null, + }; + const versionCheck: RebuildVersionCheck = { + sandboxVersion, + expectedVersion: "2026.7.14", + isStale: false, + verificationFailed: sandboxVersion === null, + detectionMethod, + }; + + expect( + expectedRebuildEntryAfterVersionCheck( + confirmedEntry, + JSON.stringify(confirmedEntry), + versionCheck, + ), + ).toBe(confirmedEntry); + }); + it("rejects a multi-agent sandbox before later rebuild work", () => { const error = vi.spyOn(console, "error").mockImplementation(() => undefined); const bail = (message: string): never => { diff --git a/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts b/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts index 32681c85997..8024f2496e6 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts @@ -21,7 +21,7 @@ import { type RebuildBail, type RebuildLog } from "./rebuild-credential-prefligh import { printRebuildPreflightFailure } from "./rebuild-preflight-error"; import { ensureRebuildUsageNoticeAccepted } from "./rebuild-usage-notice"; -export type RebuildVersionCheck = ReturnType; +export type RebuildVersionCheck = Awaited>; export function createRebuildCommandContext( options: string[] | RebuildSandboxOptions, @@ -158,7 +158,7 @@ export async function confirmRebuildIntent( bail: RebuildBail, requestedDcodeAutoApprovalMode?: DcodeAutoApprovalMode, ): Promise { - const versionCheck = sandboxVersion.checkAgentVersion(sandboxName); + const versionCheck = await sandboxVersion.checkAgentVersion(sandboxName); console.log(""); console.log(` ${B}Rebuild sandbox '${sandboxName}'${R}`); if (versionCheck.sandboxVersion) { diff --git a/src/lib/actions/sandbox/rebuild-preflight-guards.ts b/src/lib/actions/sandbox/rebuild-preflight-guards.ts index 02ee2e61a8e..aa398cb4045 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-guards.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-guards.ts @@ -98,7 +98,7 @@ export function expectedRebuildEntryAfterVersionCheck( confirmedEntrySnapshot: string, versionCheck: RebuildVersionCheck, ): RebuildSandboxEntry { - if (versionCheck.detectionMethod !== "ssh-exec" || versionCheck.sandboxVersion === null) { + if (versionCheck.detectionMethod !== "sandbox-exec" || versionCheck.sandboxVersion === null) { return confirmedEntry; } const expectedEntry = JSON.parse(confirmedEntrySnapshot) as RebuildSandboxEntry; diff --git a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts index d62699c6fac..48b12249577 100644 --- a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts +++ b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts @@ -134,7 +134,7 @@ describe("rebuild resume snapshot repair", () => { detected: false, sessions: [], }), - vi.spyOn(sandboxVersion, "checkAgentVersion").mockReturnValue({ + vi.spyOn(sandboxVersion, "checkAgentVersion").mockResolvedValue({ expectedVersion: "0.1.0", sandboxVersion: "0.0.1", } as never), diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index 903eadee680..52b189a727b 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -199,6 +199,7 @@ vi.mock("../../shields", () => ({ vi.mock("../../shields/timer-bound-lock", () => ({ withTimerBoundShieldsMutationLock: lifecycleMock.withTimerBoundMock, + withTimerBoundShieldsMutationLockAsync: lifecycleMock.withTimerBoundMock, })); vi.mock("../../shields/timer-control", () => ({ @@ -346,39 +347,39 @@ describe("runSandboxSnapshot", () => { ); }); - it("creates a named snapshot after gateway, liveness, and shields checks pass", async () => { - const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {}); - const manifest = { - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - name: "before-upgrade", - }; - backupSandboxStateMock.mockReturnValue({ + it("keeps a named snapshot and its shields lock pending until backup completes", async () => { + const manifest = { ...latestBackupFixture, name: "before-upgrade" }; + const backupResult = { success: true, backedUpDirs: ["workspace"], backedUpFiles: ["openclaw.json"], failedDirs: [], failedFiles: [], manifest, - }); - findBackupMock.mockReturnValue({ - match: { ...manifest, snapshotVersion: 7, name: "before-upgrade" }, - }); + }; + let resolveBackup!: (result: typeof backupResult) => void; + backupSandboxStateMock.mockReturnValue( + new Promise((resolve) => { + resolveBackup = resolve; + }), + ); const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { + const snapshotPromise = runSandboxSnapshot("alpha", { kind: "create", name: "before-upgrade", }); - + const lockCallbackPromise = lifecycleMock.withTimerBoundMock.mock.results[0] + ?.value as Promise; + const settled = vi.fn(); + void snapshotPromise.then(() => settled("snapshot")); + void lockCallbackPromise.then(() => settled("lock callback")); + await Promise.resolve(); + expect(settled).not.toHaveBeenCalled(); + resolveBackup(backupResult); + await Promise.all([snapshotPromise, lockCallbackPromise]); expect(backupSandboxStateMock).toHaveBeenCalledWith("alpha", { name: "before-upgrade", }); - expect(findBackupMock).toHaveBeenCalledWith("alpha", manifest.timestamp); - const output = consoleLog.mock.calls.flat().join("\n"); - expect(output).toContain("Creating snapshot of 'alpha' (--name before-upgrade)"); - expect(output).toContain("Snapshot v7 name=before-upgrade created"); - expect(output).toContain("/tmp/backup-alpha"); }); it("refuses snapshot creation before backup when a dcode task is active", async () => { diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 13f4d003979..f48fe61d496 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -46,7 +46,10 @@ import { ROOT, run, validateName } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; import { streamSandboxCreate } from "../../sandbox/create-stream"; import * as shields from "../../shields"; -import { withTimerBoundShieldsMutationLock } from "../../shields/timer-bound-lock"; +import { + withTimerBoundShieldsMutationLock, + withTimerBoundShieldsMutationLockAsync, +} from "../../shields/timer-bound-lock"; import { readTimerMarker } from "../../shields/timer-control"; import { isSandboxReady } from "../../state/gateway"; import { withSandboxMutationLock } from "../../state/mcp-lifecycle-lock"; @@ -553,10 +556,10 @@ function isSnapshotCreationAllowedByDcodeActivity(sandboxName: string): boolean return false; } -function runSnapshotCreate( +async function runSnapshotCreate( sandboxName: string, request: Extract, -): void { +): Promise { const liveNames = requireLiveSandboxesOnSandboxGateway( sandboxName, " Failed to query live sandbox state from OpenShell.", @@ -565,50 +568,54 @@ function runSnapshotCreate( console.error(` Sandbox '${sandboxName}' is not running. Cannot create snapshot.`); snapshotExit(1); } - return withTimerBoundShieldsMutationLock(sandboxName, "create sandbox snapshot", () => { - // Keep the shields check and backup in one timer-bound interval. Normal - // auto-restore waits; at the absolute deadline it may preempt this process - // and reclaim the token rather than changing policy/config mid-copy. - if (!isSnapshotCreationAllowedByShields(sandboxName)) { - console.error(" Cannot create snapshot while shields are up."); - console.error(` Run \`${CLI_NAME} ${sandboxName} shields down\` first, then retry.`); - snapshotExit(1); - } - if ( - shouldCheckDcodeActivity(sandboxName) && - !isSnapshotCreationAllowedByDcodeActivity(sandboxName) - ) { - snapshotExit(1); - } - const label = request.name ? ` (--name ${request.name})` : ""; - console.log(` Creating snapshot of '${sandboxName}'${label}...`); - const result = sandboxState.backupSandboxState(sandboxName, { - name: request.name ?? null, - }); - if (result.success) { - const manifest = result.manifest!; - const entry = sandboxState.findBackup(sandboxName, manifest.timestamp).match ?? manifest; - const v = formatSnapshotVersion(entry); - const nameSuffix = entry.name ? ` name=${entry.name}` : ""; - const itemSummary = `${result.backedUpDirs.length} directories, ${result.backedUpFiles.length} files`; - console.log(` ${G}✓${R} Snapshot ${v}${nameSuffix} created (${itemSummary})`); - console.log(` ${manifest.backupPath}`); - return; - } - if (result.error) { - console.error(` ${result.error}`); - } else { - console.error(" Snapshot failed."); - if (result.failedDirs.length > 0) { - const failedDirs = formatFailedBackupItems(result.failedDirs, result.failedDirReasons); - console.error(` Failed directories: ${failedDirs}`); + return withTimerBoundShieldsMutationLockAsync( + sandboxName, + "create sandbox snapshot", + async () => { + // Keep the shields check and backup in one timer-bound interval. Normal + // auto-restore waits; at the absolute deadline it may preempt this process + // and reclaim the token rather than changing policy/config mid-copy. + if (!isSnapshotCreationAllowedByShields(sandboxName)) { + console.error(" Cannot create snapshot while shields are up."); + console.error(` Run \`${CLI_NAME} ${sandboxName} shields down\` first, then retry.`); + snapshotExit(1); } - if (result.failedFiles.length > 0) { - console.error(` Failed files: ${result.failedFiles.join(", ")}`); + if ( + shouldCheckDcodeActivity(sandboxName) && + !isSnapshotCreationAllowedByDcodeActivity(sandboxName) + ) { + snapshotExit(1); } - } - snapshotExit(1); - }); + const label = request.name ? ` (--name ${request.name})` : ""; + console.log(` Creating snapshot of '${sandboxName}'${label}...`); + const result = await sandboxState.backupSandboxState(sandboxName, { + name: request.name ?? null, + }); + if (result.success) { + const manifest = result.manifest!; + const entry = sandboxState.findBackup(sandboxName, manifest.timestamp).match ?? manifest; + const v = formatSnapshotVersion(entry); + const nameSuffix = entry.name ? ` name=${entry.name}` : ""; + const itemSummary = `${result.backedUpDirs.length} directories, ${result.backedUpFiles.length} files`; + console.log(` ${G}✓${R} Snapshot ${v}${nameSuffix} created (${itemSummary})`); + console.log(` ${manifest.backupPath}`); + return; + } + if (result.error) { + console.error(` ${result.error}`); + } else { + console.error(" Snapshot failed."); + if (result.failedDirs.length > 0) { + const failedDirs = formatFailedBackupItems(result.failedDirs, result.failedDirReasons); + console.error(` Failed directories: ${failedDirs}`); + } + if (result.failedFiles.length > 0) { + console.error(` Failed files: ${result.failedFiles.join(", ")}`); + } + } + snapshotExit(1); + }, + ); } function repairRestoredOpenClawConfigPerms( @@ -1107,7 +1114,7 @@ export async function runSandboxSnapshot( ) { switch (request.kind) { case "create": { - runSnapshotCreate(sandboxName, request); + await runSnapshotCreate(sandboxName, request); break; } case "list": { diff --git a/src/lib/actions/sandbox/status-text.ts b/src/lib/actions/sandbox/status-text.ts index 68307b0b40e..34cba859bec 100644 --- a/src/lib/actions/sandbox/status-text.ts +++ b/src/lib/actions/sandbox/status-text.ts @@ -211,11 +211,14 @@ function printShieldsPosture(sandboxName: string): void { console.log(` Permissions: ${detail}`); } -function printAgentVersion(context: SandboxStatusTextContext, sandbox: SandboxEntry): void { +async function printAgentVersion( + context: SandboxStatusTextContext, + sandbox: SandboxEntry, +): Promise { try { const { lookup, sandboxName, statusAgent } = context; const shouldProbe = shouldProbeSandboxRuntimeVersion(lookup, sandbox, statusAgent.agentRuntime); - const versionCheck = sandboxVersion.checkAgentVersion(sandboxName, { + const versionCheck = await sandboxVersion.checkAgentVersion(sandboxName, { forceProbe: shouldProbe, skipProbe: !shouldProbe, }); @@ -275,7 +278,9 @@ function printInferenceRouteDrift( } /** Render registry-backed sandbox details and return any non-fatal degraded outcome. */ -export function printSandboxDetails(context: SandboxStatusTextContext): SandboxStatusTextOutcome { +export async function printSandboxDetails( + context: SandboxStatusTextContext, +): Promise { const { sb, currentModel, currentProvider, sandboxName } = context; if (!sb) return { exitCode: null }; @@ -295,7 +300,7 @@ export function printSandboxDetails(context: SandboxStatusTextContext): SandboxS const agentExitCode = printAgentHarness(context); printActiveSessions(sandboxName); printShieldsPosture(sandboxName); - printAgentVersion(context, sb); + await printAgentVersion(context, sb); return { exitCode: inferenceExitCode ?? agentExitCode }; } diff --git a/src/lib/actions/sandbox/status.ts b/src/lib/actions/sandbox/status.ts index 0bb69da0791..941ed4624fe 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -111,7 +111,7 @@ export async function showSandboxStatus(sandboxName: string): Promise { terminalRuntimeHealth, statusAgent, }; - const textOutcome = printSandboxDetails(textContext); + const textOutcome = await printSandboxDetails(textContext); if (textOutcome.exitCode && (!process.exitCode || process.exitCode === 0)) { process.exitCode = textOutcome.exitCode; } diff --git a/src/lib/actions/sandbox/stopped-sandbox-backup.test.ts b/src/lib/actions/sandbox/stopped-sandbox-backup.test.ts index b52442fd3ff..b41137a3109 100644 --- a/src/lib/actions/sandbox/stopped-sandbox-backup.test.ts +++ b/src/lib/actions/sandbox/stopped-sandbox-backup.test.ts @@ -2,6 +2,15 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import type { BackupResult } from "../../state/sandbox"; + +function deferred() { + let resolve!: (value: T | PromiseLike) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} vi.mock("../../state/registry", () => ({ getSandbox: vi.fn(), @@ -136,58 +145,108 @@ describe("returnSandboxContainerToStopped", () => { }); describe("backupStartedSandboxState", () => { - const ok = { + const ok: BackupResult = { success: true, backedUpDirs: [], failedDirs: [], backedUpFiles: [], failedFiles: [], }; - const unreachable = { ...ok, success: false, unreachable: true }; - const denied = { ...ok, success: false }; + const unreachable: BackupResult = { ...ok, success: false, unreachable: true }; + const denied: BackupResult = { ...ok, success: false }; it("retries while the just-started container's SSH endpoint is unreachable (#6500)", async () => { + const first = deferred(); + const second = deferred(); + const third = deferred(); const backup = vi .fn() - .mockReturnValueOnce(unreachable) - .mockReturnValueOnce(unreachable) - .mockReturnValueOnce(ok); + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise) + .mockReturnValueOnce(third.promise); const sleep = vi.fn().mockResolvedValue(undefined); - const result = await backupStartedSandboxState("my-sb", { + const resultPromise = backupStartedSandboxState("my-sb", { backup, sleep, attempts: 5, delayMs: 1, }); + + expect(backup).toHaveBeenCalledTimes(1); + expect(sleep).not.toHaveBeenCalled(); + first.resolve(unreachable); + await vi.waitFor(() => expect(backup).toHaveBeenCalledTimes(2)); + expect(sleep).toHaveBeenCalledTimes(1); + second.resolve(unreachable); + await vi.waitFor(() => expect(backup).toHaveBeenCalledTimes(3)); + expect(sleep).toHaveBeenCalledTimes(2); + const settled = vi.fn(); + void resultPromise.then(settled); + await Promise.resolve(); + expect(settled).not.toHaveBeenCalled(); + third.resolve(ok); + + const result = await resultPromise; expect(result.success).toBe(true); expect(backup).toHaveBeenCalledTimes(3); expect(sleep).toHaveBeenCalledTimes(2); }); it("returns a non-transport failure without retrying", async () => { - const backup = vi.fn().mockReturnValue(denied); + const pending = deferred(); + const backup = vi.fn().mockReturnValue(pending.promise); const sleep = vi.fn().mockResolvedValue(undefined); - const result = await backupStartedSandboxState("my-sb", { + const resultPromise = backupStartedSandboxState("my-sb", { backup, sleep, attempts: 5, delayMs: 1, }); + + const settled = vi.fn(); + void resultPromise.then(settled); + await Promise.resolve(); + expect(settled).not.toHaveBeenCalled(); + expect(sleep).not.toHaveBeenCalled(); + pending.resolve(denied); + + const result = await resultPromise; expect(result.success).toBe(false); expect(backup).toHaveBeenCalledTimes(1); expect(sleep).not.toHaveBeenCalled(); }); it("gives up after the attempt budget while still unreachable", async () => { - const backup = vi.fn().mockReturnValue(unreachable); + const first = deferred(); + const second = deferred(); + const third = deferred(); + const backup = vi + .fn() + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise) + .mockReturnValueOnce(third.promise); const sleep = vi.fn().mockResolvedValue(undefined); - const result = await backupStartedSandboxState("my-sb", { + const resultPromise = backupStartedSandboxState("my-sb", { backup, sleep, attempts: 3, delayMs: 1, }); + + expect(backup).toHaveBeenCalledTimes(1); + first.resolve(unreachable); + await vi.waitFor(() => expect(backup).toHaveBeenCalledTimes(2)); + second.resolve(unreachable); + await vi.waitFor(() => expect(backup).toHaveBeenCalledTimes(3)); + const settled = vi.fn(); + void resultPromise.then(settled); + await Promise.resolve(); + expect(settled).not.toHaveBeenCalled(); + third.resolve(unreachable); + + const result = await resultPromise; expect(result.unreachable).toBe(true); expect(backup).toHaveBeenCalledTimes(3); + expect(sleep).toHaveBeenCalledTimes(2); }); }); diff --git a/src/lib/actions/sandbox/stopped-sandbox-backup.ts b/src/lib/actions/sandbox/stopped-sandbox-backup.ts index 04fef0e7bcb..9766eea635b 100644 --- a/src/lib/actions/sandbox/stopped-sandbox-backup.ts +++ b/src/lib/actions/sandbox/stopped-sandbox-backup.ts @@ -104,7 +104,7 @@ export function returnSandboxContainerToStopped( } interface BackupRetryDeps { - backup: (name: string) => sandboxState.BackupResult; + backup: (name: string) => Promise; sleep: (ms: number) => Promise; attempts: number; delayMs: number; @@ -129,14 +129,14 @@ export async function backupStartedSandboxState( depsOverride: Partial = {}, ): Promise { const deps: BackupRetryDeps = { ...defaultBackupRetryDeps, ...depsOverride }; - let result = deps.backup(sandboxName); + let result = await deps.backup(sandboxName); for ( let attempt = 1; attempt < deps.attempts && !result.success && result.unreachable; attempt++ ) { await deps.sleep(deps.delayMs); - result = deps.backup(sandboxName); + result = await deps.backup(sandboxName); } return result; } diff --git a/src/lib/actions/sandbox/upload.test.ts b/src/lib/actions/sandbox/upload.test.ts index ae26fcd4049..02f8de0974a 100644 --- a/src/lib/actions/sandbox/upload.test.ts +++ b/src/lib/actions/sandbox/upload.test.ts @@ -8,6 +8,10 @@ vi.mock("./gateway-state", () => ({ ensureLiveSandboxOrExit: vi.fn(async () => undefined), })); +vi.mock("./gateway-target", () => ({ + getSandboxTargetGatewayName: vi.fn(() => "nemoclaw-9090"), +})); + vi.mock("../../adapters/openshell/runtime", () => ({ runOpenshell: vi.fn(), })); @@ -25,6 +29,7 @@ beforeEach(() => { }); afterEach(() => { + vi.unstubAllEnvs(); vi.restoreAllMocks(); }); @@ -39,7 +44,16 @@ describe("uploadToSandbox", () => { const expectedHostPath = path.resolve(process.cwd(), "SOUL.md"); expect(ensureMock).toHaveBeenCalledWith("alpha", { allowNonReadyPhase: true }); expect(runMock).toHaveBeenCalledWith( - ["sandbox", "upload", "alpha", expectedHostPath, "/sandbox/.openclaw/workspace/SOUL.md"], + [ + "sandbox", + "upload", + "-g", + "nemoclaw-9090", + "--", + "alpha", + expectedHostPath, + "/sandbox/.openclaw/workspace/SOUL.md", + ], expect.objectContaining({ stdio: "inherit" }), ); expect(result).toEqual({ @@ -61,7 +75,7 @@ describe("uploadToSandbox", () => { sandboxDest: "/sandbox/etc/", }); const args = runMock.mock.calls[0]?.[0]; - expect(args?.[3]).toBe("/etc/hosts"); + expect(args?.[6]).toBe("/etc/hosts"); }); it("preserves a trailing separator on a relative host directory source", async () => { @@ -71,11 +85,33 @@ describe("uploadToSandbox", () => { sandboxDest: "/sandbox/work/", }); const args = runMock.mock.calls[0]?.[0]; - const hostPath = args?.[3] as string; + const hostPath = args?.[6] as string; expect(hostPath.endsWith(path.sep) || hostPath.endsWith("/")).toBe(true); expect(hostPath.slice(0, -1)).toBe(path.resolve(process.cwd(), "src")); }); + it("keeps a flag-shaped sandbox destination after the option terminator", async () => { + await uploadToSandbox({ + sandboxName: "alpha", + hostPath: "./SOUL.md", + sandboxDest: "--gateway-endpoint=https://other-gateway.example.test", + }); + + expect(runMock).toHaveBeenCalledWith( + [ + "sandbox", + "upload", + "-g", + "nemoclaw-9090", + "--", + "alpha", + path.resolve(process.cwd(), "SOUL.md"), + "--gateway-endpoint=https://other-gateway.example.test", + ], + expect.objectContaining({ stdio: "inherit" }), + ); + }); + it("throws (does not exit) when no host path is given", async () => { await expect(uploadToSandbox({ sandboxName: "alpha", hostPath: "" })).rejects.toThrow( /No host path provided/, @@ -83,4 +119,15 @@ describe("uploadToSandbox", () => { expect(ensureMock).not.toHaveBeenCalled(); expect(runMock).not.toHaveBeenCalled(); }); + + it("fails closed before liveness or upload when an endpoint override is set", async () => { + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://other-gateway.example.test"); + + await expect(uploadToSandbox({ sandboxName: "alpha", hostPath: "./SOUL.md" })).rejects.toThrow( + /Unset OPENSHELL_GATEWAY_ENDPOINT/, + ); + + expect(ensureMock).not.toHaveBeenCalled(); + expect(runMock).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/actions/sandbox/upload.ts b/src/lib/actions/sandbox/upload.ts index a861931f68b..fd803d67223 100644 --- a/src/lib/actions/sandbox/upload.ts +++ b/src/lib/actions/sandbox/upload.ts @@ -3,7 +3,9 @@ import { runOpenshell } from "../../adapters/openshell/runtime"; import { CLI_NAME } from "../../cli/branding"; +import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; import { ensureLiveSandboxOrExit } from "./gateway-state"; +import { getSandboxTargetGatewayName } from "./gateway-target"; import { resolveHostPathFromCwd } from "./host-path"; export interface SandboxUploadOptions { @@ -25,6 +27,11 @@ export async function uploadToSandbox(opts: SandboxUploadOptions): Promise [sandbox-dest]`, ); } + // The upload is a host-to-sandbox mutation. An ambient endpoint override can + // redirect both the liveness check and the upload away from the gateway the + // registry binds this sandbox to, so reject it before either command runs. + assertNoOpenShellGatewayEndpointOverride(); + const gatewayName = getSandboxTargetGatewayName(opts.sandboxName); const hostPath = resolveHostPathFromCwd(trimmedHostPath); const sandboxDest = (opts.sandboxDest ?? "").trim() || "/sandbox/"; @@ -32,9 +39,12 @@ export async function uploadToSandbox(opts: SandboxUploadOptions): Promise { + vi.spyOn(sandboxVersion, "checkAgentVersion").mockImplementation(async (...args: unknown[]) => { const name = String(args[0]); return { sandboxVersion: options.staleNames?.includes(name) === true ? "2026.5.26" : "2026.5.27", @@ -417,7 +417,7 @@ describe("upgrade-sandboxes prepared backup recovery (#6114)", () => { liveOutput: "other-box Ready", }); vi.stubEnv("NEMOCLAW_RESTORE_LATEST_BACKUP_ON_RECREATE", "0"); - vi.spyOn(sandboxVersion, "checkAgentVersion").mockReturnValue({ + vi.spyOn(sandboxVersion, "checkAgentVersion").mockResolvedValue({ sandboxVersion: null, expectedVersion: "2026.5.27", isStale: false, diff --git a/src/lib/actions/upgrade-sandboxes.ts b/src/lib/actions/upgrade-sandboxes.ts index e75c83458f1..13e87f2c6a6 100644 --- a/src/lib/actions/upgrade-sandboxes.ts +++ b/src/lib/actions/upgrade-sandboxes.ts @@ -51,10 +51,10 @@ export const upgradeSandboxesDependencies = { /** * Checks the sandbox agent version with a live probe when the sandbox is running. */ -function checkAgentVersionForUpgrade( +async function checkAgentVersionForUpgrade( sandboxName: string, liveNames: Set, -): sandboxVersion.VersionCheckResult { +): Promise { return sandboxVersion.checkAgentVersion( sandboxName, liveNames.has(sandboxName) ? { forceProbe: true } : undefined, @@ -245,10 +245,14 @@ export async function upgradeSandboxes( // Classify sandboxes as stale, unknown, or current. Pass the running NemoClaw // build so a NemoClaw image/build change is detected even when the agent // version is unchanged (#5026). + const versionChecks = new Map(); + for (const sandbox of sandboxes) { + versionChecks.set(sandbox.name, await checkAgentVersionForUpgrade(sandbox.name, liveNames)); + } const { stale, unknown } = classifyUpgradeableSandboxes( sandboxes, liveNames, - (name) => checkAgentVersionForUpgrade(name, liveNames), + (name) => versionChecks.get(name)!, { currentNemoclawVersion: resolveCurrentNemoclawVersion() }, ); diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 0663702cdd9..081a121f12d 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -244,6 +244,44 @@ describe("gRPC OpenShell sandbox control", () => { expect(fake.close).toHaveBeenCalledOnce(); }); + it("treats a present exit frame with an omitted proto3 default scalar as status zero", async () => { + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { stdout: { data: Buffer.from("ok") } }); + stream.emit("data", { exit: {} }); + stream.emit("end"); + }, + }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + await expect(control.exec({ sandboxName: "alpha", command: ["true"] })).resolves.toEqual({ + status: 0, + stdout: "ok", + stderr: "", + }); + }); + + it("does not treat a malformed null exit code as the proto3 default zero", async () => { + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { exit: { exitCode: null } }); + stream.emit("end"); + }, + }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + const result = await control.exec({ sandboxName: "alpha", command: ["true"] }); + + expect(result.status).toBeNull(); + expect(result.error?.message).toBe("OpenShell gRPC exec stream ended without an exit status"); + }); + it("executes against the pinned OpenShell service definition", async () => { const protoFile = path.resolve( __dirname, @@ -275,14 +313,16 @@ describe("gRPC OpenShell sandbox control", () => { { stdout?: { data: Buffer }; stderr?: { data: Buffer }; - exit?: { exitCode: number }; + exit?: { exitCode?: number }; } >, ) { requests.push(call.request); call.write({ stdout: { data: Buffer.from("wire stdout") } }); call.write({ stderr: { data: Buffer.from("wire stderr") } }); - call.write({ exit: { exitCode: 0 } }); + // Rust/prost does not encode the default proto3 int32 value. Exercise + // the exact successful exit event emitted by the v0.0.72 gateway. + call.write({ exit: {} }); call.end(); }, }); @@ -316,6 +356,35 @@ describe("gRPC OpenShell sandbox control", () => { } }); + it("preserves binary stdout without UTF-8 replacement", async () => { + const bytes = Buffer.from([0, 255, 128, 10]); + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { stdout: { data: bytes.subarray(0, 2) } }); + stream.emit("data", { stdout: { data: bytes.subarray(2) } }); + stream.emit("data", { exit: { exitCode: 0 } }); + stream.emit("end"); + }, + }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + await expect( + control.exec({ + sandboxName: "alpha", + command: ["tar", "-cf", "-", "workspace"], + stdoutEncoding: "buffer", + }), + ).resolves.toEqual({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "", + }); + }); + it("returns lookup failures without starting exec", async () => { const error = serviceError("gateway unavailable"); const fake = fakeApi({ getError: error }); diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts index 8806e7c91c1..1bfaf8d95e5 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -4,7 +4,6 @@ import type { EventEmitter } from "node:events"; import { isIP } from "node:net"; import path from "node:path"; -import { StringDecoder } from "node:string_decoder"; import * as grpc from "@grpc/grpc-js"; import * as protoLoader from "@grpc/proto-loader"; @@ -236,10 +235,8 @@ function execute( metadata, options, ); - const stdoutDecoder = new StringDecoder("utf8"); - const stderrDecoder = new StringDecoder("utf8"); - let stdout = ""; - let stderr = ""; + const stdoutChunks: Buffer[] = []; + const stderrChunks: Buffer[] = []; let retainedBytes = 0; let status: number | null = null; let settled = false; @@ -247,9 +244,11 @@ function execute( const finish = (error?: Error) => { if (settled) return; settled = true; - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); + const stdoutBytes = Buffer.concat(stdoutChunks); + const stdout = request.stdoutEncoding === "buffer" ? "" : stdoutBytes.toString("utf8"); + const stderr = Buffer.concat(stderrChunks).toString("utf8"); const result: SandboxExecResult = { status, stdout, stderr }; + if (request.stdoutEncoding === "buffer") result.stdoutBytes = stdoutBytes; if (error) result.error = error; resolve(result); }; @@ -258,8 +257,8 @@ function execute( const remaining = maxOutputBytes - retainedBytes; const retained = data.subarray(0, Math.max(0, remaining)); retainedBytes += retained.length; - if (destination === "stdout") stdout += stdoutDecoder.write(retained); - else stderr += stderrDecoder.write(retained); + if (destination === "stdout") stdoutChunks.push(retained); + else stderrChunks.push(retained); if (retained.length < data.length) { finish(new OpenShellExecOutputLimitError(maxOutputBytes)); stream.cancel(); @@ -270,8 +269,13 @@ function execute( if (settled) return; if (event.stdout) append("stdout", asBuffer(event.stdout.data)); else if (event.stderr) append("stderr", asBuffer(event.stderr.data)); - else if (event.exit && Number.isInteger(event.exit.exitCode)) { - status = event.exit.exitCode as number; + else if (event.exit) { + // Rust/prost omits a proto3 scalar whose value is the default zero, so + // a successful command arrives through proto-loader as `exit: {}`. + // The enclosing oneof message is the exit-status signal; a missing + // scalar inside that present message therefore means exit code 0. + const exitCode = event.exit.exitCode === undefined ? 0 : event.exit.exitCode; + if (Number.isInteger(exitCode)) status = exitCode; } }); stream.on("error", (error: Error) => finish(error)); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index f7ed4427781..a48592259ce 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it, vi } from "vitest"; import { OpenShellGrpcEdgeTunnelRequiredError } from "./grpc-gateway-config"; import { type GrpcOpenShellSandboxControl, + OpenShellGrpcOutputLimitError, OpenShellGrpcPreDispatchError, } from "./grpc-sandbox-control"; import { @@ -188,6 +189,52 @@ describe("read-only OpenShell sandbox control routing", () => { expect(test.close).toHaveBeenCalledOnce(); }); + it("preserves binary stdout across the direct route", async () => { + const bytes = Buffer.from([0, 255, 128, 10]); + const result = { status: 0, stdout: "", stdoutBytes: bytes, stderr: "" }; + const test = dependencies(result); + const stdin = "import sqlite3, sys\nsrc, dst = sys.argv[1], sys.argv[2]"; + const binaryRequest = { ...request, stdin, stdoutEncoding: "buffer" as const }; + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", binaryRequest, test.deps), + ).resolves.toEqual(result); + expect(test.grpcExec).toHaveBeenCalledWith({ + ...binaryRequest, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + }); + + it("preserves stdin and binary stdout across the pre-dispatch CLI fallback", async () => { + const stdin = "import sqlite3, sys\nsrc, dst = sys.argv[1], sys.argv[2]"; + const bytes = Buffer.from([0, 255, 128, 10]); + const grpcError = new Error("UNAVAILABLE"); + const cliResult = { status: 0, stdout: "", stdoutBytes: bytes, stderr: "" }; + const test = dependencies( + { + status: null, + stdout: "", + stderr: "", + error: new OpenShellGrpcPreDispatchError(grpcError), + }, + cliResult, + ); + const binaryRequest = { ...request, stdin, stdoutEncoding: "buffer" as const }; + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", binaryRequest, test.deps), + ).resolves.toEqual(cliResult); + + expect(test.grpcExec).toHaveBeenCalledWith({ + ...binaryRequest, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + expect(test.cliExec).toHaveBeenCalledWith({ + ...binaryRequest, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + }); + it("does not replay a completed non-zero command through the CLI", async () => { const result = { status: 2, stdout: "", stderr: "unknown flag" }; const test = dependencies(result); @@ -199,6 +246,22 @@ describe("read-only OpenShell sandbox control routing", () => { expect(test.cliExec).not.toHaveBeenCalled(); }); + it("does not replay a signaled command through the CLI", async () => { + const result = { + status: null, + stdout: "partial", + stderr: "terminated", + signal: "SIGTERM" as NodeJS.Signals, + }; + const test = dependencies(result); + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", request, test.deps), + ).resolves.toEqual(result); + + expect(test.cliExec).not.toHaveBeenCalled(); + }); + it("retries a pre-dispatch gRPC lookup failure with the same bounded deadline", async () => { const grpcError = new Error("UNAVAILABLE"); const cliResult = { status: 0, stdout: "cli", stderr: "" }; @@ -242,6 +305,18 @@ describe("read-only OpenShell sandbox control routing", () => { expect(test.cliExec).not.toHaveBeenCalled(); }); + it("does not replay a local gRPC output-limit failure", async () => { + const error = new OpenShellGrpcOutputLimitError(4096); + const result = { status: null, stdout: "partial", stderr: "", error }; + const test = dependencies(result); + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", request, test.deps), + ).resolves.toEqual(result); + + expect(test.cliExec).not.toHaveBeenCalled(); + }); + it("uses the CLI when gateway configuration cannot create a gRPC client", async () => { const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); const error = new Error("edge tunnel required"); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index 1883f8d085d..b59aa8274bb 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, debug diagnostic probes, version probe, + * and state-file backup reads 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/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 0a5e3762fdc..55131e2ce1a 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -259,6 +259,38 @@ describe("CLI OpenShell sandbox control", () => { }); }); + it("projects raw stdout from the single bounded CLI capture", async () => { + const bytes = Buffer.from([0, 255, 128, 10]); + const capture = vi.fn( + (): CaptureOpenshellBinaryResult => ({ + status: 0, + stdout: bytes, + stderr: Buffer.from("warning"), + }), + ); + const control = createCliOpenShellSandboxControl(capture); + + await expect( + control.exec({ + sandboxName: "alpha", + command: ["tar", "-cf", "-", "workspace"], + stdin: "archive request", + maxOutputBytes: 1024, + stdoutEncoding: "buffer", + timeoutMs: 120_000, + }), + ).resolves.toEqual({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "warning", + }); + expect(capture).toHaveBeenCalledWith( + ["sandbox", "exec", "--name", "alpha", "--", "tar", "-cf", "-", "workspace"], + { input: "archive request", maxBuffer: 1024, timeout: 120_000 }, + ); + }); + it("preserves transport failures without throwing", async () => { const error = Object.assign(new Error("spawnSync openshell EIO"), { code: "EIO", diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index b4b1fe0d4cb..7f1d41177b2 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -17,11 +17,15 @@ export interface SandboxExecRequest { maxOutputBytes?: number; /** End-to-end lookup and execution deadline. Zero means no deadline. */ timeoutMs?: number; + /** Preserve stdout bytes instead of decoding them as UTF-8. */ + stdoutEncoding?: "utf8" | "buffer"; } export interface SandboxExecResult { status: number | null; stdout: string; + /** Present when stdoutEncoding is `buffer`; stdout remains an empty string. */ + stdoutBytes?: Buffer; stderr: string; error?: Error; signal?: NodeJS.Signals | null; @@ -312,14 +316,17 @@ function retainCombinedOutput( function normalizeExecResult( result: CaptureOpenshellBinaryResult, maxOutputBytes: number, + stdoutEncoding: SandboxExecRequest["stdoutEncoding"], ): SandboxExecResult { const retained = retainCombinedOutput(result.stdout, result.stderr, maxOutputBytes); - const stdout = retained.stdout.toString("utf8"); + const stdout = stdoutEncoding === "buffer" ? "" : retained.stdout.toString("utf8"); const stderr = retained.stderr.toString("utf8"); + const stdoutBytes = stdoutEncoding === "buffer" ? { stdoutBytes: retained.stdout } : {}; if (retained.truncated || isOutputLimitError(result.error)) { return { status: null, stdout, + ...stdoutBytes, stderr, error: new OpenShellExecOutputLimitError(maxOutputBytes), ...(result.signal !== undefined ? { signal: result.signal } : {}), @@ -328,6 +335,7 @@ function normalizeExecResult( const normalized: SandboxExecResult = { status: result.status, stdout, + ...stdoutBytes, stderr, }; if (result.error) normalized.error = result.error; @@ -366,7 +374,7 @@ function createCliSandboxControl( timeout: request.timeoutMs, }, ); - return normalizeExecResult(result, maxOutputBytes); + return normalizeExecResult(result, maxOutputBytes, request.stdoutEncoding); }, }; } 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/src/lib/onboard.ts b/src/lib/onboard.ts index 2b197d9abfc..f8c8d01b2a8 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2574,7 +2574,7 @@ async function createSandboxWithBaseImageResolution( console.log(` Messaging credential(s) rotated: ${rotatedNames}`); console.log(" Rebuilding sandbox to propagate new credentials to the L7 proxy..."); if (!shouldSkipPreRecreateBackup(process.env)) { - const result = recreateProtection.backup(); + const result = await recreateProtection.backup(); if (!result.ok) { console.error( " Set NEMOCLAW_RECREATE_WITHOUT_BACKUP=1 to recreate without preserving state.", @@ -2642,7 +2642,7 @@ async function createSandboxWithBaseImageResolution( !shouldSkipPreRecreateBackup(process.env) ) { note(" Backing up workspace state before recreating sandbox..."); - const result = recreateProtection.backup(); + const result = await recreateProtection.backup(); if (!result.ok) { console.error( " Set NEMOCLAW_RECREATE_WITHOUT_BACKUP=1 to recreate without preserving state.", diff --git a/src/lib/onboard/sandbox-backup-on-recreate.test.ts b/src/lib/onboard/sandbox-backup-on-recreate.test.ts index 060e9443835..51c33300dc6 100644 --- a/src/lib/onboard/sandbox-backup-on-recreate.test.ts +++ b/src/lib/onboard/sandbox-backup-on-recreate.test.ts @@ -24,11 +24,11 @@ function makeBackup(overrides: Partial = {}): BackupResult { } describe("backupSandboxBeforeRecreate", () => { - it("returns ok with backup result on success", () => { + it("returns ok with backup result on success", async () => { const backup = makeBackup(); - const backupImpl = vi.fn().mockReturnValue(backup); + const backupImpl = vi.fn().mockResolvedValue(backup); const log = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", backupImpl, log, @@ -41,16 +41,16 @@ describe("backupSandboxBeforeRecreate", () => { expect(log).toHaveBeenCalledWith(expect.stringContaining("State backed up")); }); - it("rejects an unmarked custom OpenClaw backup before recreate deletion (#6108)", () => { + it("rejects an unmarked custom OpenClaw backup before recreate deletion (#6108)", async () => { const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", sandboxEntry: { name: "my-assistant", agent: "openclaw", fromDockerfile: "/tmp/Dockerfile.custom", }, - backupImpl: () => makeBackup(), + backupImpl: async () => makeBackup(), log: vi.fn(), errorLog, }); @@ -62,13 +62,13 @@ describe("backupSandboxBeforeRecreate", () => { ); }); - it("rejects an unmarked backup for an orphan custom OpenClaw target (#6108)", () => { + it("rejects an unmarked backup for an orphan custom OpenClaw target (#6108)", async () => { const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "orphan", sandboxEntry: null, requireOpenClawImagePluginProvenance: true, - backupImpl: () => makeBackup(), + backupImpl: async () => makeBackup(), log: vi.fn(), errorLog, }); @@ -81,7 +81,7 @@ describe("backupSandboxBeforeRecreate", () => { ); }); - it("returns ok:false with failureKind=partial when some entries failed", () => { + it("returns ok:false with failureKind=partial when some entries failed", async () => { const backup = makeBackup({ success: false, backedUpDirs: ["workspace"], @@ -90,9 +90,9 @@ describe("backupSandboxBeforeRecreate", () => { failedFiles: ["bad.bin"], }); const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", - backupImpl: () => backup, + backupImpl: async () => backup, log: vi.fn(), errorLog, }); @@ -103,19 +103,19 @@ describe("backupSandboxBeforeRecreate", () => { expect(errorLog).toHaveBeenCalledWith(expect.stringContaining("Aborting recreate")); }); - it("rejects backup result missing manifest backupPath", () => { + it("rejects backup result missing manifest backupPath", async () => { const backup = makeBackup({ manifest: undefined }); const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", - backupImpl: () => backup, + backupImpl: async () => backup, log: vi.fn(), errorLog, }); expect(result.ok).toBe(false); }); - it("returns ok:false with failureKind=empty when nothing was backed up", () => { + it("returns ok:false with failureKind=empty when nothing was backed up", async () => { const backup = makeBackup({ success: false, backedUpDirs: [], @@ -125,9 +125,9 @@ describe("backupSandboxBeforeRecreate", () => { error: "Pre-backup audit rejected an unsafe symlink", }); const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", - backupImpl: () => backup, + backupImpl: async () => backup, errorLog, log: vi.fn(), }); @@ -138,11 +138,11 @@ describe("backupSandboxBeforeRecreate", () => { expect(errorLog).toHaveBeenCalledWith(" Reason: Pre-backup audit rejected an unsafe symlink"); }); - it("returns ok:false with failureKind=threw when backup throws", () => { + it("returns ok:false with failureKind=threw when backup throws", async () => { const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", - backupImpl: () => { + backupImpl: async () => { throw new Error("disk full"); }, errorLog, diff --git a/src/lib/onboard/sandbox-backup-on-recreate.ts b/src/lib/onboard/sandbox-backup-on-recreate.ts index bbbfda4dd99..b5102cd2058 100644 --- a/src/lib/onboard/sandbox-backup-on-recreate.ts +++ b/src/lib/onboard/sandbox-backup-on-recreate.ts @@ -5,7 +5,7 @@ import type { SandboxEntry } from "../state/registry"; import type { BackupResult } from "../state/sandbox"; import * as sandboxState from "../state/sandbox"; -export type SandboxBackupImpl = (sandboxName: string) => BackupResult; +export type SandboxBackupImpl = (sandboxName: string) => Promise; export interface PreRecreateBackupOptions { sandboxName: string; @@ -30,9 +30,9 @@ export interface PreRecreateBackupResult { errorMessage?: string; } -export function backupSandboxBeforeRecreate( +export async function backupSandboxBeforeRecreate( opts: PreRecreateBackupOptions, -): PreRecreateBackupResult { +): Promise { const log = opts.log ?? ((m: string) => console.log(m)); const errorLog = opts.errorLog ?? ((m: string) => console.error(m)); const backupImpl = opts.backupImpl ?? sandboxState.backupSandboxState; @@ -42,7 +42,7 @@ export function backupSandboxBeforeRecreate( (Boolean(sandboxEntry?.fromDockerfile) && (!sandboxEntry?.agent || sandboxEntry.agent === "openclaw")); try { - const backup = backupImpl(opts.sandboxName); + const backup = await backupImpl(opts.sandboxName); if (backup.success && backup.manifest?.backupPath) { if ( (customOpenClaw || backup.manifest.reconcileOpenClawImagePluginProvenance === true) && diff --git a/src/lib/onboard/sandbox-recreate-protection.test.ts b/src/lib/onboard/sandbox-recreate-protection.test.ts index 6da8b2b806f..de46c6a8429 100644 --- a/src/lib/onboard/sandbox-recreate-protection.test.ts +++ b/src/lib/onboard/sandbox-recreate-protection.test.ts @@ -5,7 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { createSandboxRecreateProtection } from "./sandbox-recreate-protection"; describe("createSandboxRecreateProtection", () => { - it("forwards one custom-image protection context to every recreation path (#6108)", () => { + it("forwards one custom-image protection context to every recreation path (#6108)", async () => { const note = vi.fn(); const sandboxEntry = { name: "my-assistant", @@ -22,7 +22,7 @@ describe("createSandboxRecreateProtection", () => { backup: null, failureKind: "none" as const, }; - const backupSandboxBeforeRecreate = vi.fn(() => backupResult); + const backupSandboxBeforeRecreate = vi.fn(async () => backupResult); const protection = createSandboxRecreateProtection( { sandboxName: "my-assistant", @@ -53,7 +53,7 @@ describe("createSandboxRecreateProtection", () => { }); expect(resolveNotReadyOutcome).toHaveBeenCalledWith("my-assistant", note, sandboxEntry, true); - expect(protection.backup()).toBe(backupResult); + await expect(protection.backup()).resolves.toBe(backupResult); expect(backupSandboxBeforeRecreate).toHaveBeenCalledWith({ sandboxName: "my-assistant", sandboxEntry, diff --git a/src/lib/onboard/sandbox-recreate-protection.ts b/src/lib/onboard/sandbox-recreate-protection.ts index 94df005ab27..0e632230055 100644 --- a/src/lib/onboard/sandbox-recreate-protection.ts +++ b/src/lib/onboard/sandbox-recreate-protection.ts @@ -48,7 +48,7 @@ export function createSandboxRecreateProtection( resolveNotReadyOutcome(): notReadyRecreate.NonInteractiveNotReadyOutcome { return deps.resolveNotReadyOutcome(sandboxName, note, sandboxEntry, customOpenClawImage); }, - backup(): PreRecreateBackupResult { + backup(): Promise { return deps.backupSandboxBeforeRecreate({ sandboxName, sandboxEntry, diff --git a/src/lib/sandbox/version.test.ts b/src/lib/sandbox/version.test.ts index 3211f4b7494..afa4d2345e7 100644 --- a/src/lib/sandbox/version.test.ts +++ b/src/lib/sandbox/version.test.ts @@ -1,14 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { basename, dirname, join } from "node:path"; +import { dirname, join } from "node:path"; import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -// Mock heavy dependencies that pull in the full module graph -vi.mock("../adapters/openshell/resolve.js", () => ({ - resolveOpenshell: vi.fn(() => "/usr/local/bin/openshell"), +const { execSandbox } = vi.hoisted(() => ({ execSandbox: vi.fn() })); + +vi.mock("../adapters/openshell/sandbox-control-routing.js", () => ({ + execSandboxReadOnlyWithGrpcFallback: execSandbox, })); vi.mock("../adapters/openshell/client.js", () => ({ @@ -32,7 +33,6 @@ vi.mock("../adapters/openshell/client.js", () => ({ } return true; }, - captureSandboxSshConfigCommand: vi.fn(), })); const { EXPECTED_VERSION_BY_AGENT } = vi.hoisted(() => ({ @@ -55,15 +55,6 @@ vi.mock("../agent/defs.js", () => ({ })), })); -vi.mock("child_process", async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, spawnSync: vi.fn() }; -}); - -import { spawnSync } from "child_process"; -import { captureSandboxSshConfigCommand } from "../adapters/openshell/client.js"; -import { OPENSHELL_PROBE_TIMEOUT_MS } from "../adapters/openshell/timeouts.js"; - // state/registry captures the registry path at module scope, so HOME must be // redirected before it loads. Static ESM imports are hoisted above this // assignment, hence the dynamic imports below; reassigning HOME from @@ -89,7 +80,7 @@ afterAll(() => { }); describe("registry isolation", () => { - it("resolves the registry inside the test HOME, never the real one (#6553)", () => { + it("resolves the registry inside the test HOME, never the real one (#6553)", async () => { expect(registry.REGISTRY_FILE).toBe(TEST_REGISTRY_FILE); expect(registry.REGISTRY_FILE.startsWith(TEST_HOME)).toBe(true); }); @@ -98,264 +89,245 @@ describe("registry isolation", () => { describe("checkAgentVersion", () => { beforeEach(() => { resetTestRegistry(); + execSandbox.mockReset().mockResolvedValue({ status: 1, stdout: "", stderr: "failed" }); }); afterEach(() => { vi.restoreAllMocks(); }); - it("fast path: uses cached agentVersion from registry", () => { + it("fast path: uses cached agentVersion from registry", async () => { registry.registerSandbox({ name: "test-sb", agent: null, agentVersion: "2026.5.27", }); - const result = checkAgentVersion("test-sb"); + const result = await checkAgentVersion("test-sb"); expect(result.detectionMethod).toBe("registry"); expect(result.sandboxVersion).toBe("2026.5.27"); expect(result.isStale).toBe(false); }); - it("fast path: detects stale version from registry", () => { + it("fast path: detects stale version from registry", async () => { registry.registerSandbox({ name: "test-sb", agent: null, agentVersion: "2026.3.11", }); - const result = checkAgentVersion("test-sb"); + const result = await checkAgentVersion("test-sb"); expect(result.detectionMethod).toBe("registry"); expect(result.sandboxVersion).toBe("2026.3.11"); expect(result.isStale).toBe(true); }); - it("fast path: same version is not stale", () => { + it("fast path: same version is not stale", async () => { registry.registerSandbox({ name: "test-sb", agent: null, agentVersion: "2026.5.27", }); - const result = checkAgentVersion("test-sb"); + const result = await checkAgentVersion("test-sb"); expect(result.isStale).toBe(false); }); - it("slow path: probes via SSH when no cached version", () => { - registry.registerSandbox({ name: "test-sb", agent: null }); - - vi.mocked(captureSandboxSshConfigCommand).mockReturnValue({ - status: 0, - output: "Host openshell-test-sb\n HostName 127.0.0.1\n", - }); + it("slow path: probes through sandbox exec when no cached version", async () => { + registry.registerSandbox({ name: "test-sb", agent: null, gatewayPort: 19080 }); - vi.mocked(spawnSync).mockReturnValue({ + execSandbox.mockResolvedValue({ status: 0, stdout: "OpenClaw 2026.5.27 (abc123)\n", stderr: "", - pid: 1234, - output: [], - signal: null, }); - const result = checkAgentVersion("test-sb"); - expect(result.detectionMethod).toBe("ssh-exec"); + const result = await checkAgentVersion("test-sb"); + expect(result.detectionMethod).toBe("sandbox-exec"); expect(result.sandboxVersion).toBe("2026.5.27"); expect(result.isStale).toBe(false); - expect(captureSandboxSshConfigCommand).toHaveBeenCalledWith( - "/usr/local/bin/openshell", - "test-sb", - { ignoreError: true, timeout: OPENSHELL_PROBE_TIMEOUT_MS }, - ); - const sshArgs = vi.mocked(spawnSync).mock.calls[0]?.[1] as string[]; - const configFile = sshArgs[sshArgs.indexOf("-F") + 1]; - const configDir = dirname(configFile); - expect(configDir).not.toBe(tmpdir()); - expect(basename(configDir)).toMatch(/^nemoclaw-ver-/); - expect(basename(configFile)).toBe("ssh_config"); - expect(existsSync(configDir)).toBe(false); + expect(execSandbox).toHaveBeenCalledWith("nemoclaw-19080", { + sandboxName: "test-sb", + command: ["sh", "-c", "openclaw --version"], + maxOutputBytes: 64 * 1024, + timeoutMs: 15_000, + }); // Should have cached the version in registry const updated = registry.getSandbox("test-sb"); expect(updated?.agentVersion).toBe("2026.5.27"); }); - it("returns an unknown verdict when SSH config fails so callers do not read isStale as verified current", () => { + it("returns an unknown verdict when sandbox exec fails so callers do not read isStale as verified current", async () => { registry.registerSandbox({ name: "test-sb", agent: null }); - vi.mocked(captureSandboxSshConfigCommand).mockReturnValue({ - status: 1, - output: "", + const result = await checkAgentVersion("test-sb"); + expect(result.detectionMethod).toBe("unknown"); + expect(result.unavailableReason).toBe("probe-failed"); + expect(result.isStale).toBe(false); + }); + + it("treats a returned sandbox exec error as an unknown probe without caching output", async () => { + registry.registerSandbox({ name: "test-sb", agent: null, gatewayPort: 19080 }); + execSandbox.mockResolvedValue({ + status: null, + stdout: "OpenClaw 2026.5.27\n", + stderr: "", + error: new Error("output limit exceeded"), }); - const result = checkAgentVersion("test-sb"); + const result = await checkAgentVersion("test-sb"); + expect(result.detectionMethod).toBe("unknown"); expect(result.unavailableReason).toBe("probe-failed"); - expect(result.isStale).toBe(false); + expect(registry.getSandbox("test-sb")?.agentVersion).toBeNull(); }); - it("can skip live probing when no cached version is available", () => { + it("can skip live probing when no cached version is available", async () => { registry.registerSandbox({ name: "test-sb", agent: null }); - vi.mocked(captureSandboxSshConfigCommand).mockClear(); - vi.mocked(spawnSync).mockClear(); - const result = checkAgentVersion("test-sb", { skipProbe: true }); + const result = await checkAgentVersion("test-sb", { skipProbe: true }); expect(result.detectionMethod).toBe("unavailable"); expect(result.sandboxVersion).toBeNull(); expect(result.isStale).toBe(false); - expect(captureSandboxSshConfigCommand).not.toHaveBeenCalled(); - expect(spawnSync).not.toHaveBeenCalled(); + expect(execSandbox).not.toHaveBeenCalled(); }); - it("force probe bypasses cached version", () => { + it("force probe bypasses cached version", async () => { registry.registerSandbox({ name: "test-sb", agent: null, agentVersion: "2026.3.11", }); - vi.mocked(captureSandboxSshConfigCommand).mockReturnValue({ - status: 0, - output: "Host openshell-test-sb\n HostName 127.0.0.1\n", - }); - - vi.mocked(spawnSync).mockReturnValue({ + execSandbox.mockResolvedValue({ status: 0, stdout: "OpenClaw 2026.5.27 (abc123)\n", stderr: "", - pid: 1234, - output: [], - signal: null, }); - const result = checkAgentVersion("test-sb", { forceProbe: true }); - expect(result.detectionMethod).toBe("ssh-exec"); + const result = await checkAgentVersion("test-sb", { forceProbe: true }); + expect(result.detectionMethod).toBe("sandbox-exec"); expect(result.sandboxVersion).toBe("2026.5.27"); }); - it("force probe returns unknown when the live probe fails so cached metadata cannot silently mask drift", () => { + it("force probe returns unknown when the live probe fails so cached metadata cannot silently mask drift", async () => { registry.registerSandbox({ name: "test-sb", agent: null, agentVersion: "2026.5.18", }); - vi.mocked(captureSandboxSshConfigCommand).mockReturnValue({ - status: 0, - output: "", - }); - vi.mocked(spawnSync).mockClear(); - - const result = checkAgentVersion("test-sb", { forceProbe: true }); + const result = await checkAgentVersion("test-sb", { forceProbe: true }); expect(result.detectionMethod).toBe("unknown"); expect(result.unavailableReason).toBe("probe-failed"); expect(result.sandboxVersion).toBeNull(); expect(result.isStale).toBe(false); - expect(spawnSync).not.toHaveBeenCalled(); + expect(execSandbox).toHaveBeenCalledOnce(); }); - it("does not flag an update for a hermes runtime that matches the expected semver", () => { + it("does not flag an update for a hermes runtime that matches the expected semver", async () => { registry.registerSandbox({ name: "hermes-sb", agent: "hermes", agentVersion: "0.17.0", }); - const result = checkAgentVersion("hermes-sb"); + const result = await checkAgentVersion("hermes-sb"); expect(result.detectionMethod).toBe("registry"); expect(result.sandboxVersion).toBe("0.17.0"); expect(result.isStale).toBe(false); }); - it("flags a hermes runtime that is behind the expected semver", () => { + it("flags a hermes runtime that is behind the expected semver", async () => { registry.registerSandbox({ name: "hermes-sb", agent: "hermes", agentVersion: "0.16.9", }); - const result = checkAgentVersion("hermes-sb"); + const result = await checkAgentVersion("hermes-sb"); expect(result.sandboxVersion).toBe("0.16.9"); expect(result.isStale).toBe(true); }); - it("flags a scheme-mismatched cached version as stale so the rebuild flow realigns runtime and manifest (#6049)", () => { + it("flags a scheme-mismatched cached version as stale so the rebuild flow realigns runtime and manifest (#6049)", async () => { registry.registerSandbox({ name: "hermes-sb", agent: "hermes-calendar-pin", agentVersion: "0.17.0", }); - const result = checkAgentVersion("hermes-sb"); + const result = await checkAgentVersion("hermes-sb"); expect(result.detectionMethod).toBe("registry"); expect(result.sandboxVersion).toBe("0.17.0"); expect(result.schemeMismatch).toBe(true); expect(result.isStale).toBe(true); }); - it("treats a semver with a four-digit major that does not start with 20 as semver, not calendar (#6049)", () => { + it("treats a semver with a four-digit major that does not start with 20 as semver, not calendar (#6049)", async () => { registry.registerSandbox({ name: "high-major-sb", agent: "high-major-semver", agentVersion: "1000.0.0", }); - const result = checkAgentVersion("high-major-sb"); + const result = await checkAgentVersion("high-major-sb"); expect(result.detectionMethod).toBe("registry"); expect(result.sandboxVersion).toBe("1000.0.0"); expect(result.verificationFailed).toBe(false); expect(result.isStale).toBe(false); }); - it("flags a same-scheme semver when the sandbox trails a four-digit-major expected pin (#6049)", () => { + it("flags a same-scheme semver when the sandbox trails a four-digit-major expected pin (#6049)", async () => { registry.registerSandbox({ name: "high-major-sb", agent: "high-major-semver", agentVersion: "999.9.8", }); - const result = checkAgentVersion("high-major-sb"); + const result = await checkAgentVersion("high-major-sb"); expect(result.verificationFailed).toBe(false); expect(result.isStale).toBe(true); }); - it("treats a semver with a pre-2020 four-digit major as semver, not calendar (#6049)", () => { + it("treats a semver with a pre-2020 four-digit major as semver, not calendar (#6049)", async () => { registry.registerSandbox({ name: "low-year-sb", agent: "low-year-semver", agentVersion: "2010.0.0", }); - const result = checkAgentVersion("low-year-sb"); + const result = await checkAgentVersion("low-year-sb"); expect(result.detectionMethod).toBe("registry"); expect(result.sandboxVersion).toBe("2010.0.0"); expect(result.schemeMismatch).toBeFalsy(); expect(result.isStale).toBe(false); }); - it("without a manifest version_scheme, falls back to shape classification so a matching-shape cached value is treated as current (#6049)", () => { + it("without a manifest version_scheme, falls back to shape classification so a matching-shape cached value is treated as current (#6049)", async () => { registry.registerSandbox({ name: "openclaw-sb", agent: null, agentVersion: "2026.5.27" }); - const result = checkAgentVersion("openclaw-sb"); + const result = await checkAgentVersion("openclaw-sb"); expect(result.detectionMethod).toBe("registry"); expect(result.sandboxVersion).toBe("2026.5.27"); expect(result.schemeMismatch).toBeFalsy(); expect(result.isStale).toBe(false); }); - it("flags a calendar-manifest agent with a semver runtime as scheme-mismatched and stale (#6049)", () => { + it("flags a calendar-manifest agent with a semver runtime as scheme-mismatched and stale (#6049)", async () => { registry.registerSandbox({ name: "openclaw-sb", agent: "openclaw", agentVersion: "1.2.3" }); - const result = checkAgentVersion("openclaw-sb"); + const result = await checkAgentVersion("openclaw-sb"); expect(result.detectionMethod).toBe("registry"); expect(result.sandboxVersion).toBe("1.2.3"); expect(result.schemeMismatch).toBe(true); expect(result.isStale).toBe(true); }); - it("emits a structured JSON payload to stderr when a scheme mismatch is detected (#6049)", () => { + it("emits a structured JSON payload to stderr when a scheme mismatch is detected (#6049)", async () => { registry.registerSandbox({ name: "hermes-warn-sb", agent: "hermes-calendar-pin", @@ -369,7 +341,7 @@ describe("checkAgentVersion", () => { return true; }) as typeof process.stderr.write; try { - checkAgentVersion("hermes-warn-sb"); + await checkAgentVersion("hermes-warn-sb"); } finally { process.stderr.write = originalWrite; } @@ -386,56 +358,42 @@ describe("checkAgentVersion", () => { }); }); - it("flags a scheme mismatch discovered during an ssh probe as stale (#6049)", () => { + it("flags a scheme mismatch discovered during a sandbox probe as stale (#6049)", async () => { registry.registerSandbox({ name: "hermes-sb", agent: "hermes-calendar-pin" }); - vi.mocked(captureSandboxSshConfigCommand).mockReturnValue({ - status: 0, - output: "Host openshell-hermes-sb\n HostName 127.0.0.1\n", - }); - vi.mocked(spawnSync).mockReturnValue({ + execSandbox.mockResolvedValue({ status: 0, stdout: "hermes 0.17.0\n", stderr: "", - pid: 4321, - output: [], - signal: null, }); - const result = checkAgentVersion("hermes-sb"); - expect(result.detectionMethod).toBe("ssh-exec"); + const result = await checkAgentVersion("hermes-sb"); + expect(result.detectionMethod).toBe("sandbox-exec"); expect(result.sandboxVersion).toBe("0.17.0"); expect(result.schemeMismatch).toBe(true); expect(result.isStale).toBe(true); }); - it("surfaces the reason when checkAgentVersion cannot inspect the sandbox", () => { + it("surfaces the reason when checkAgentVersion cannot inspect the sandbox", async () => { registry.registerSandbox({ name: "test-sb", agent: null }); - const result = checkAgentVersion("test-sb", { skipProbe: true }); + const result = await checkAgentVersion("test-sb", { skipProbe: true }); expect(result.detectionMethod).toBe("unavailable"); expect(result.unavailableReason).toBe("skip-probe"); }); - it("probes a hermes runtime over ssh and does not flag a matching semver", () => { + it("probes a hermes runtime through sandbox exec and does not flag a matching semver", async () => { registry.registerSandbox({ name: "hermes-sb", agent: "hermes" }); - vi.mocked(captureSandboxSshConfigCommand).mockReturnValue({ - status: 0, - output: "Host openshell-hermes-sb\n HostName 127.0.0.1\n", - }); - vi.mocked(spawnSync).mockReturnValue({ + execSandbox.mockResolvedValue({ status: 0, stdout: "hermes 0.17.0\n", stderr: "", - pid: 4321, - output: [], - signal: null, }); - const result = checkAgentVersion("hermes-sb"); - expect(result.detectionMethod).toBe("ssh-exec"); + const result = await checkAgentVersion("hermes-sb"); + expect(result.detectionMethod).toBe("sandbox-exec"); expect(result.sandboxVersion).toBe("0.17.0"); expect(result.isStale).toBe(false); }); @@ -447,7 +405,7 @@ describe("formatStalenessWarning", () => { registry.registerSandbox({ name: "my-sb", agent: null }); }); - it("includes sandbox name, versions, and rebuild hint", () => { + it("includes sandbox name, versions, and rebuild hint", async () => { const lines = formatStalenessWarning("my-sb", { sandboxVersion: "2026.3.11", expectedVersion: "2026.5.27", diff --git a/src/lib/sandbox/version.ts b/src/lib/sandbox/version.ts index 59e535c6229..000127d0dbb 100644 --- a/src/lib/sandbox/version.ts +++ b/src/lib/sandbox/version.ts @@ -5,22 +5,18 @@ // // Compares the agent version running inside a sandbox against the version // this NemoClaw release was built for. Two code paths: -// Fast: registry lookup (no SSH, used when agentVersion is already cached) -// Slow: SSH exec into sandbox, run version_command, cache result in registry +// Fast: registry lookup (used when agentVersion is already cached) +// Slow: sandbox exec, run version_command, cache result in registry -import { spawnSync } from "child_process"; - -import { - captureSandboxSshConfigCommand, - parseVersionFromText, -} from "../adapters/openshell/client.js"; -import { resolveOpenshell } from "../adapters/openshell/resolve.js"; -import { OPENSHELL_PROBE_TIMEOUT_MS } from "../adapters/openshell/timeouts.js"; +import { parseVersionFromText } from "../adapters/openshell/client.js"; +import { execSandboxReadOnlyWithGrpcFallback } from "../adapters/openshell/sandbox-control-routing.js"; import { loadAgent } from "../agent/defs.js"; +import { resolveSandboxGatewayName } from "../onboard/gateway-binding.js"; import * as registry from "../state/registry.js"; -import { createTempSshConfig } from "./temp-ssh-config.js"; import { evaluateStaleness } from "./version-scheme.js"; +const VERSION_PROBE_MAX_OUTPUT_BYTES = 64 * 1024; + export interface VersionCheckResult { sandboxVersion: string | null; expectedVersion: string | null; @@ -40,7 +36,7 @@ export interface VersionCheckResult { verificationFailed: boolean; /** * How the staleness verdict was reached. - * - `"registry"` / `"ssh-exec"`: `isStale` is authoritative for this sandbox + * - `"registry"` / `"sandbox-exec"`: `isStale` is authoritative for this sandbox * as long as `verificationFailed` is `false`. * - `"unavailable"`: no staleness check was attempted (missing expected * version, or the caller opted out of probing). @@ -48,7 +44,7 @@ export interface VersionCheckResult { * inspected — callers should treat this as "unable to verify", not * "verified current". */ - detectionMethod: "registry" | "ssh-exec" | "unavailable" | "unknown"; + detectionMethod: "registry" | "sandbox-exec" | "unavailable" | "unknown"; /** * `true` when the runtime and expected versions use different schemes * (semver vs calendar). In that case `isStale` is forced to `true` so the @@ -80,48 +76,25 @@ function resolveAgentForSandbox(sandboxName: string): ReturnType { const agent = resolveAgentForSandbox(sandboxName); - - const openshellBinary = resolveOpenshell(); - if (!openshellBinary) return null; - - const sshConfigResult = captureSandboxSshConfigCommand(openshellBinary, sandboxName, { - ignoreError: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }); - if (sshConfigResult.status !== 0) return null; - if (!sshConfigResult.output.trim()) return null; - - const tmpSshConfig = createTempSshConfig(sshConfigResult.output, "nemoclaw-ver-"); try { - const result = spawnSync( - "ssh", - [ - "-F", - tmpSshConfig.file, - "-o", - "StrictHostKeyChecking=no", - "-o", - "UserKnownHostsFile=/dev/null", - "-o", - "ConnectTimeout=5", - "-o", - "LogLevel=ERROR", - `openshell-${sandboxName}`, - agent.versionCommand, - ], - { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], timeout: 15000 }, + const result = await execSandboxReadOnlyWithGrpcFallback( + resolveSandboxGatewayName(registry.getSandbox(sandboxName)), + { + sandboxName, + command: ["sh", "-c", agent.versionCommand], + maxOutputBytes: VERSION_PROBE_MAX_OUTPUT_BYTES, + timeoutMs: 15_000, + }, ); - if (result.status !== 0) return null; + if (result.status !== 0 || result.error) return null; return parseVersionFromText(result.stdout, agent.versionCommand); } catch { return null; - } finally { - tmpSshConfig.cleanup(); } } @@ -129,12 +102,12 @@ export function probeAgentVersion(sandboxName: string): string | null { * Check whether a sandbox is running an outdated agent version. * * Fast path: compare registry.agentVersion against manifest expected_version. - * Slow path: SSH into sandbox, run version_command, cache result in registry. + * Slow path: run version_command through sandbox exec and cache the result. */ -export function checkAgentVersion( +export async function checkAgentVersion( sandboxName: string, opts?: VersionCheckOptions, -): VersionCheckResult { +): Promise { const agent = resolveAgentForSandbox(sandboxName); const expectedVersion = agent.expectedVersion; @@ -186,8 +159,8 @@ export function checkAgentVersion( }; } - // Slow path: SSH exec into sandbox - const probed = probeAgentVersion(sandboxName); + // Slow path: sandbox exec + const probed = await probeAgentVersion(sandboxName); if (probed && sb) { // Cache for future fast-path lookups registry.updateSandbox(sandboxName, { agentVersion: probed }); @@ -215,7 +188,7 @@ export function checkAgentVersion( expectedVersion, isStale: verdict.isStale, verificationFailed: false, - detectionMethod: "ssh-exec", + detectionMethod: "sandbox-exec", schemeMismatch: verdict.schemeMismatch, }; } diff --git a/src/lib/state/sandbox-state-file-backup.test.ts b/src/lib/state/sandbox-state-file-backup.test.ts new file mode 100644 index 00000000000..bed1677fba1 --- /dev/null +++ b/src/lib/state/sandbox-state-file-backup.test.ts @@ -0,0 +1,221 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { findMultilineExecArg } from "../actions/sandbox/exec"; + +const execReadOnly = vi.hoisted(() => vi.fn()); +const getSandbox = vi.hoisted(() => vi.fn()); +const loadAgent = vi.hoisted(() => vi.fn()); + +vi.mock("../adapters/openshell/sandbox-control-routing.js", () => ({ + execSandboxReadOnlyWithGrpcFallback: execReadOnly, +})); +vi.mock("./registry.js", () => ({ getSandbox })); +vi.mock("../agent/defs.js", () => ({ loadAgent })); + +const ORIGINAL_HOME = process.env.HOME; +const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-file-backup-")); +process.env.HOME = TMP_HOME; + +const { + backupSandboxState, + buildStateFileBackupExecRequest, + classifyStateFileBackupExecResult, + isSandboxExecTransportFailure, + SQLITE_BACKUP_PY, +} = await import("./sandbox"); + +afterAll(() => { + ORIGINAL_HOME === undefined + ? Reflect.deleteProperty(process.env, "HOME") + : Reflect.set(process.env, "HOME", ORIGINAL_HOME); + fs.rmSync(TMP_HOME, { force: true, recursive: true }); +}); + +beforeEach(() => { + vi.clearAllMocks(); + fs.rmSync(path.join(TMP_HOME, ".nemoclaw"), { force: true, recursive: true }); + getSandbox.mockReturnValue({ + name: "hermes", + agent: "hermes", + policies: [], + gatewayName: "nemoclaw", + }); + loadAgent.mockReturnValue({ + configPaths: { dir: "/sandbox/.hermes" }, + expectedVersion: null, + stateDirs: [], + stateFiles: [{ path: "runtime/state.db", strategy: "copy" }], + }); +}); + +describe("state-file backup exec request", () => { + it("streams the SQLite program through stdin and keeps every command argument single-line", () => { + const request = buildStateFileBackupExecRequest("hermes", "/sandbox/.hermes", { + path: "runtime/state.db", + strategy: "sqlite_backup", + }); + + expect(request.command).toEqual([ + "sh", + "-c", + expect.stringContaining('python3 - "$src" "$tmp"'), + ]); + expect(request.command.every((argument) => !/[\r\n]/.test(argument))).toBe(true); + expect(findMultilineExecArg(request.command)).toBe(-1); + expect(request.command.join("\n")).not.toContain("sqlite3.connect"); + expect(request.command.join("\n")).toContain('python3 - "$src" "$tmp" || exit $?'); + expect(request.stdin).toBe(SQLITE_BACKUP_PY); + expect(SQLITE_BACKUP_PY).toContain("sqlite3.connect"); + expect(SQLITE_BACKUP_PY).toContain("src_conn.backup(dst_conn)"); + expect(SQLITE_BACKUP_PY).toContain("PRAGMA quick_check"); + expect(request).toMatchObject({ + sandboxName: "hermes", + timeoutMs: 120_000, + maxOutputBytes: 256 * 1024 * 1024, + stdoutEncoding: "buffer", + }); + }); + + it("does not attach the SQLite program to copy requests", () => { + const request = buildStateFileBackupExecRequest("hermes", "/sandbox/.hermes", { + path: "SOUL.md", + strategy: "copy", + }); + + expect(request.command).toEqual(["sh", "-c", expect.stringContaining('cat -- "$src"')]); + expect(request).not.toHaveProperty("stdin"); + }); + + it("does not emit a temporary database when the streamed Python backup fails", () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-sqlite-backup-failure-")); + try { + fs.writeFileSync(path.join(tempDir, "state.db"), "source"); + const request = buildStateFileBackupExecRequest("hermes", tempDir, { + path: "state.db", + strategy: "sqlite_backup", + }); + const failingProgram = [ + "import pathlib, sys", + "pathlib.Path(sys.argv[2]).write_bytes(b'partial-backup')", + "raise SystemExit(41)", + ].join("\n"); + + const result = spawnSync("sh", request.command.slice(1), { + encoding: "utf8", + input: failingProgram, + }); + + expect(result.status).toBe(41); + expect(result.stdout).toBe(""); + expect(result.stderr).toBe(""); + } finally { + fs.rmSync(tempDir, { force: true, recursive: true }); + } + }); + + it("accepts only an error-free binary result as a completed backup", () => { + const bytes = Buffer.from([0, 255, 128, 10]); + expect( + classifyStateFileBackupExecResult({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "", + }), + ).toBe("backed_up"); + expect( + classifyStateFileBackupExecResult({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "", + error: new Error("stream failed"), + }), + ).toBe("failed"); + expect( + classifyStateFileBackupExecResult({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "", + signal: "SIGTERM", + }), + ).toBe("failed"); + expect( + classifyStateFileBackupExecResult({ + status: 2, + stdout: "", + stderr: "", + error: new Error("lookup failed"), + }), + ).toBe("failed"); + expect(classifyStateFileBackupExecResult({ status: 0, stdout: "", stderr: "" })).toBe("failed"); + }); + + it("does not classify terminal local validation and output limits as unreachable", () => { + const outputLimit = Object.assign(new Error("output limit"), { code: "ENOBUFS" }); + const invalidRequest = Object.assign(new Error("invalid request"), { + code: "OPENSHELL_EXEC_INVALID_ARGUMENT", + }); + + expect(isSandboxExecTransportFailure({ status: null, error: outputLimit })).toBe(false); + expect(isSandboxExecTransportFailure({ status: null, error: invalidRequest })).toBe(false); + expect(isSandboxExecTransportFailure({ status: null, error: new Error("UNAVAILABLE") })).toBe( + true, + ); + expect(isSandboxExecTransportFailure({ status: null, signal: "SIGKILL" })).toBe(true); + }); + + it("persists binary state-file bytes with private mode and complete backup bookkeeping", async () => { + const bytes = Buffer.from([0x53, 0x51, 0x4c, 0x00, 0xff, 0xfe, 0x80, 0x0a]); + execReadOnly.mockResolvedValue({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "", + }); + + const result = await backupSandboxState("hermes", { name: "binary-state" }); + + expect(result).toMatchObject({ + success: true, + backedUpDirs: [], + failedDirs: [], + backedUpFiles: ["runtime/state.db"], + failedFiles: [], + }); + expect(result.manifest?.stateFiles).toEqual([{ path: "runtime/state.db", strategy: "copy" }]); + const persistedPath = path.join(result.manifest!.backupPath, "runtime", "state.db"); + expect(fs.readFileSync(persistedPath)).toEqual(bytes); + expect(fs.statSync(persistedPath).mode & 0o777).toBe(0o600); + expect(execReadOnly).toHaveBeenCalledWith( + "nemoclaw", + expect.objectContaining({ + sandboxName: "hermes", + stdoutEncoding: "buffer", + }), + ); + }); + + it("fails closed when a successful state-file exec omits binary stdout", async () => { + execReadOnly.mockResolvedValue({ status: 0, stdout: "", stderr: "" }); + + const result = await backupSandboxState("hermes", { name: "missing-binary-state" }); + + expect(result).toMatchObject({ + success: false, + backedUpFiles: [], + failedFiles: ["runtime/state.db"], + unreachable: false, + }); + expect(fs.existsSync(path.join(result.manifest!.backupPath, "runtime", "state.db"))).toBe( + false, + ); + }); +}); diff --git a/src/lib/state/sandbox.ts b/src/lib/state/sandbox.ts index 09aa0c7d5e7..57afb3085ca 100644 --- a/src/lib/state/sandbox.ts +++ b/src/lib/state/sandbox.ts @@ -27,6 +27,11 @@ import { spawnSync } from "child_process"; import { captureSandboxSshConfigCommand } from "../adapters/openshell/client.js"; import { resolveOpenshell } from "../adapters/openshell/resolve.js"; +import type { + SandboxExecRequest, + SandboxExecResult, +} from "../adapters/openshell/sandbox-control.js"; +import { execSandboxReadOnlyWithGrpcFallback } from "../adapters/openshell/sandbox-control-routing.js"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../adapters/openshell/timeouts.js"; import type { AgentStateFile } from "../agent/defs.js"; import { loadAgent } from "../agent/defs.js"; @@ -35,6 +40,7 @@ import { BACKUP_FAILURE_ABSENT_AFTER_EXTRACTION, classifyFailedDirsFromTarStderr, } from "../domain/backup-failure.js"; +import { resolveSandboxGatewayName } from "../onboard/gateway-binding.js"; import { shellQuote } from "../runner.js"; import { createTempSshConfig } from "../sandbox/temp-ssh-config.js"; import { isSensitiveFile, sanitizeConfigFile } from "../security/credential-filter.js"; @@ -743,7 +749,8 @@ function stateFileRemotePath(dir: string, filePath: string): string { return `${dir.replace(/\/+$/, "")}/${filePath}`; } -const SQLITE_BACKUP_PY = [ +/** @internal Exported so the transport-boundary test can pin the exact stdin payload. */ +export const SQLITE_BACKUP_PY = [ "import sqlite3, sys", "src, dst = sys.argv[1], sys.argv[2]", "src_conn = sqlite3.connect('file:' + src + '?mode=ro', uri=True, timeout=30)", @@ -771,7 +778,7 @@ function buildStateFileBackupCommand(dir: string, spec: StateFileSpec): string { '[ "${hardlink_count:-0}" = "0" ] || { echo "hard-linked sqlite state file rejected: $src" >&2; exit 11; }', 'tmp="$(mktemp /tmp/nemoclaw-sqlite-backup.XXXXXX)"', "trap 'rm -f \"$tmp\"' EXIT", - `python3 -c ${shellQuote(SQLITE_BACKUP_PY)} "$src" "$tmp"`, + 'python3 - "$src" "$tmp" || exit $?', 'cat -- "$tmp"', ].join("; "); } @@ -786,41 +793,83 @@ function buildStateFileBackupCommand(dir: string, spec: StateFileSpec): string { ].join("; "); } -type StateFileBackupOutcome = "backed_up" | "missing" | "failed"; +/** @internal Exported to pin the state-file transport contract in focused tests. */ +export function buildStateFileBackupExecRequest( + sandboxName: string, + dir: string, + spec: StateFileSpec, +): SandboxExecRequest { + return { + sandboxName, + command: ["sh", "-c", buildStateFileBackupCommand(dir, spec)], + ...(spec.strategy === "sqlite_backup" ? { stdin: SQLITE_BACKUP_PY } : {}), + timeoutMs: 120_000, + maxOutputBytes: 256 * 1024 * 1024, + stdoutEncoding: "buffer", + }; +} + +export type StateFileBackupOutcome = "backed_up" | "missing" | "failed"; interface StateFileBackupResult { outcome: StateFileBackupOutcome; - // Set on "failed" when the SSH probe itself failed at the transport level - // (exit 255, signal-killed, spawn error). The caller (backupSandboxState) - // propagates this into BackupResult.unreachable so that + // Set on "failed" when sandbox exec itself failed at the transport level. + // The caller propagates this into BackupResult.unreachable so that // NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1 activates for state-file // failures too, not only the initial dir probe. See #6188. unreachable: boolean; } -function backupStateFile( - configFile: string, +/** @internal Distinguish remote reachability failures from terminal local request failures. */ +export function isSandboxExecTransportFailure(result: { + status: number | null; + error?: Error; + signal?: NodeJS.Signals | null; +}): boolean { + const code = (result.error as NodeJS.ErrnoException | undefined)?.code; + // Both transports use ENOBUFS for the shared raw-output cap. The canonical + // request validator uses OPENSHELL_EXEC_INVALID_ARGUMENT. Neither can be + // repaired by retrying or by treating the sandbox as unreachable. + if (code === "ENOBUFS" || code === "OPENSHELL_EXEC_INVALID_ARGUMENT") return false; + return Boolean(result.error || result.signal || result.status === null); +} + +/** @internal Pin the binary state-file result contract independently of filesystem writes. */ +export function classifyStateFileBackupExecResult( + result: SandboxExecResult, +): StateFileBackupOutcome { + if (result.error || result.signal) return "failed"; + if (result.status === 2) return "missing"; + if (result.status !== 0 || !result.stdoutBytes) return "failed"; + return "backed_up"; +} + +async function backupStateFile( + gatewayName: string, sandboxName: string, dir: string, spec: StateFileSpec, backupPath: string, -): StateFileBackupResult { - const command = buildStateFileBackupCommand(dir, spec); +): Promise { _log(`Backing up state file ${spec.path} (${spec.strategy})`); - const result = spawnSync("ssh", [...sshArgs(configFile, sandboxName), command], { - stdio: ["ignore", "pipe", "pipe"], - timeout: 120000, - maxBuffer: 256 * 1024 * 1024, - }); + const result = await execSandboxReadOnlyWithGrpcFallback( + gatewayName, + buildStateFileBackupExecRequest(sandboxName, dir, spec), + ); - if (result.status === 2) return { outcome: "missing", unreachable: false }; - if (result.status !== 0 || result.error || result.signal || !result.stdout) { + const outcome = classifyStateFileBackupExecResult(result); + if (outcome === "missing") return { outcome, unreachable: false }; + if (outcome === "failed") { const detail = - (result.stderr?.toString() || "").trim() || + result.stderr.trim() || result.error?.message || - (result.signal ? `signal ${result.signal}` : `exit ${String(result.status)}`); + (result.signal + ? `signal ${result.signal}` + : result.status === 0 + ? "binary stdout was not preserved" + : `exit ${String(result.status)}`); _log(`FAILED: state file backup ${spec.path}: ${detail.substring(0, 200)}`); - return { outcome: "failed", unreachable: isSshTransportFailure(result) }; + return { outcome: "failed", unreachable: isSandboxExecTransportFailure(result) }; } const localPath = path.join(backupPath, spec.path); @@ -828,7 +877,12 @@ function backupStateFile( rejectSymlinksOnPath(parent); mkdirSync(parent, { recursive: true, mode: 0o700 }); rejectSymlinksOnPath(localPath); - writeFileSync(localPath, result.stdout); + const stdoutBytes = result.stdoutBytes; + if (!stdoutBytes) { + _log(`FAILED: state file backup ${spec.path}: binary stdout was not preserved`); + return { outcome: "failed", unreachable: false }; + } + writeFileSync(localPath, stdoutBytes); chmodSync(localPath, 0o600); return { outcome: "backed_up", unreachable: false }; } @@ -846,7 +900,10 @@ export { buildStateFileRestoreCommand } from "./state-file-restore.js"; // module. Prefer importing directly from ./ssh-transport in new code. export { isSshTransportFailure }; -export function backupSandboxState(sandboxName: string, options: BackupOptions = {}): BackupResult { +export async function backupSandboxState( + sandboxName: string, + options: BackupOptions = {}, +): Promise { const sb = registry.getSandbox(sandboxName); const agentName = sb?.agent || "openclaw"; const agent = loadAgent(agentName); @@ -969,31 +1026,52 @@ export function backupSandboxState(sandboxName: string, options: BackupOptions = return { success: true, manifest, backedUpDirs, failedDirs, backedUpFiles, failedFiles }; } - // SSH+tar single-roundtrip download - _log("Getting SSH config via openshell sandbox ssh-config"); - const sshConfig = getSshConfig(sandboxName); - if (!sshConfig) { - _log("FAILED: Could not get SSH config"); - // For a sandbox the registry reported as running, an unreachable - // `openshell sandbox ssh-config` lookup is a transport-level failure — - // treat it the same as the initial dir probe and propagate `unreachable` - // so NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1 can activate. (#6188) - return { - success: false, - manifest, - backedUpDirs, - failedDirs: [...stateDirs], - backedUpFiles, - failedFiles: stateFiles.map((f) => f.path), - unreachable: true, - }; + let stateFileGatewayName: string | undefined; + if (stateFiles.length > 0) { + try { + stateFileGatewayName = resolveSandboxGatewayName(sb); + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + _log(`FAILED: Could not resolve sandbox gateway for state-file backup: ${detail}`); + return { + success: false, + manifest, + backedUpDirs, + failedDirs: [...stateDirs], + backedUpFiles, + failedFiles: stateFiles.map((file) => file.path), + error: detail, + }; + } } - _log(`SSH config obtained (${sshConfig.length} bytes)`); - const tempSshConfig = createTempSshConfig(sshConfig, "nemoclaw-state-"); - const configFile = tempSshConfig.file; - try { - if (stateDirs.length > 0) { + // State-directory backup remains on the existing SSH+tar path until the + // next migration layer moves its probe, audit, and archive download together. + if (stateDirs.length > 0) { + // SSH+tar single-roundtrip download + _log("Getting SSH config via openshell sandbox ssh-config"); + const sshConfig = getSshConfig(sandboxName); + if (!sshConfig) { + _log("FAILED: Could not get SSH config"); + // For a sandbox the registry reported as running, an unreachable + // `openshell sandbox ssh-config` lookup is a transport-level failure — + // treat it the same as the initial dir probe and propagate `unreachable` + // so NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1 can activate. (#6188) + return { + success: false, + manifest, + backedUpDirs, + failedDirs: [...stateDirs], + backedUpFiles, + failedFiles: stateFiles.map((f) => f.path), + unreachable: true, + }; + } + _log(`SSH config obtained (${sshConfig.length} bytes)`); + + const tempSshConfig = createTempSshConfig(sshConfig, "nemoclaw-state-"); + const configFile = tempSshConfig.file; + try { // Build tar command that only includes existing directories. // First, check which declared state dirs actually exist in the sandbox, // then additionally discover per-agent `workspace-*` directories produced @@ -1210,10 +1288,24 @@ export function backupSandboxState(sandboxName: string, options: BackupOptions = failedDirs.push(...existingDirs); } } + } finally { + try { + tempSshConfig.cleanup(); + } catch { + /* ignore */ + } } + } + if (stateFileGatewayName !== undefined) { for (const spec of stateFiles) { - const result = backupStateFile(configFile, sandboxName, dir, spec, backupPath); + const result = await backupStateFile( + stateFileGatewayName, + sandboxName, + dir, + spec, + backupPath, + ); if (result.outcome === "backed_up") { backedUpFiles.push(spec.path); } else if (result.outcome === "failed") { @@ -1224,12 +1316,6 @@ export function backupSandboxState(sandboxName: string, options: BackupOptions = if (result.unreachable) unreachable = true; } } - } finally { - try { - tempSshConfig.cleanup(); - } catch { - /* ignore */ - } } // SECURITY: Strip credentials from the local backup diff --git a/test/cli/list-share-live-inference.test.ts b/test/cli/list-share-live-inference.test.ts index 7ddac87d89a..44cc3d72741 100644 --- a/test/cli/list-share-live-inference.test.ts +++ b/test/cli/list-share-live-inference.test.ts @@ -24,6 +24,9 @@ const HEALTHY_DEFAULT_GATEWAY_STUB = [ "fi", ]; +const GATEWAY_SCOPED_SANDBOX_EXEC_STUB = + 'if [ "$1" = "--gateway" ] && [ "$2" = "nemoclaw" ] && [ "$3" = "sandbox" ] && [ "$4" = "exec" ] && [ "$5" = "--name" ] && [ "$6" = "my-agent" ]; then'; + function createShareTestEnv(prefix: string): Record { const home = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); const localBin = path.join(home, "bin"); @@ -257,9 +260,8 @@ describe("list shows live gateway inference", () => { " echo 'Sandbox: my-agent'", " exit 0", "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "ssh-config" ] && [ "$3" = "my-agent" ]; then', - " echo 'Host openshell-my-agent'", - " echo ' HostName 127.0.0.1'", + GATEWAY_SCOPED_SANDBOX_EXEC_STUB, + " echo 'OpenClaw 2026.3.11 (old)'", " exit 0", "fi", 'if [ "$1" = "--version" ]; then', @@ -270,12 +272,6 @@ describe("list shows live gateway inference", () => { ].join("\n"), { mode: 0o755 }, ); - fs.writeFileSync( - path.join(localBin, "ssh"), - ["#!/usr/bin/env bash", "echo 'OpenClaw 2026.3.11 (old)'", "exit 0"].join("\n"), - { mode: 0o755 }, - ); - const r = runWithEnv("upgrade-sandboxes --check 2>&1", { HOME: home, PATH: `${localBin}:${process.env.PATH || ""}`, @@ -331,9 +327,8 @@ describe("list shows live gateway inference", () => { " echo 'Sandbox: my-agent'", " exit 0", "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "ssh-config" ] && [ "$3" = "my-agent" ]; then', - " echo 'Host openshell-my-agent'", - " echo ' HostName 127.0.0.1'", + GATEWAY_SCOPED_SANDBOX_EXEC_STUB, + " echo 'OpenClaw 9999.12.31 (new)'", " exit 0", "fi", 'if [ "$1" = "--version" ]; then', @@ -344,12 +339,6 @@ describe("list shows live gateway inference", () => { ].join("\n"), { mode: 0o755 }, ); - fs.writeFileSync( - path.join(localBin, "ssh"), - ["#!/usr/bin/env bash", "echo 'OpenClaw 9999.12.31 (new)'", "exit 0"].join("\n"), - { mode: 0o755 }, - ); - const r = runWithEnv("upgrade-sandboxes --check 2>&1", { HOME: home, PATH: `${localBin}:${process.env.PATH || ""}`, @@ -405,9 +394,8 @@ describe("list shows live gateway inference", () => { ' echo "my-agent Running openclaw"', " exit 0", "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "ssh-config" ] && [ "$3" = "my-agent" ]; then', - " echo 'Host openshell-my-agent'", - " echo ' HostName 127.0.0.1'", + GATEWAY_SCOPED_SANDBOX_EXEC_STUB, + ` echo 'OpenClaw ${OPENCLAW_EXPECTED_VERSION}'`, " exit 0", "fi", 'if [ "$1" = "--version" ]; then', @@ -418,15 +406,6 @@ describe("list shows live gateway inference", () => { ].join("\n"), { mode: 0o755 }, ); - // Live probe reports the CURRENT agent version, so agent-version is NOT stale. - fs.writeFileSync( - path.join(localBin, "ssh"), - ["#!/usr/bin/env bash", `echo 'OpenClaw ${OPENCLAW_EXPECTED_VERSION}'`, "exit 0"].join( - "\n", - ), - { mode: 0o755 }, - ); - const r = runWithEnv("upgrade-sandboxes --check 2>&1", { HOME: home, PATH: `${localBin}:${process.env.PATH || ""}`, @@ -482,21 +461,14 @@ describe("list shows live gateway inference", () => { " echo 'Sandbox: my-agent'", " exit 0", "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "ssh-config" ] && [ "$3" = "my-agent" ]; then', - " echo 'Host openshell-my-agent'", - " echo ' HostName 127.0.0.1'", + GATEWAY_SCOPED_SANDBOX_EXEC_STUB, + " echo 'OpenClaw 2026.3.11 (old)'", " exit 0", "fi", "exit 0", ].join("\n"), { mode: 0o755 }, ); - fs.writeFileSync( - path.join(localBin, "ssh"), - ["#!/usr/bin/env bash", "echo 'OpenClaw 2026.3.11 (old)'", "exit 0"].join("\n"), - { mode: 0o755 }, - ); - const r = runWithEnv("upgrade-sandboxes --check 2>&1", { HOME: home, PATH: `${localBin}:${process.env.PATH || ""}`, diff --git a/test/helpers/rebuild-flow-harness.ts b/test/helpers/rebuild-flow-harness.ts index d10a4cd8085..63b837374f7 100644 --- a/test/helpers/rebuild-flow-harness.ts +++ b/test/helpers/rebuild-flow-harness.ts @@ -382,7 +382,7 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): detected: false, sessions: [], }); - vi.spyOn(sandboxVersion, "checkAgentVersion").mockReturnValue({ + vi.spyOn(sandboxVersion, "checkAgentVersion").mockResolvedValue({ expectedVersion: "0.2.0", sandboxVersion: "0.1.0", }); diff --git a/test/helpers/rebuild-flow-lifecycle-cases.ts b/test/helpers/rebuild-flow-lifecycle-cases.ts index 8a0c57c2c5d..01ddba4a410 100644 --- a/test/helpers/rebuild-flow-lifecycle-cases.ts +++ b/test/helpers/rebuild-flow-lifecycle-cases.ts @@ -134,7 +134,7 @@ export function registerRebuildFlowLifecycleTests(): void { expectedVersion: "0.2.0", isStale: false, verificationFailed: false, - detectionMethod: "ssh-exec", + detectionMethod: "sandbox-exec", }, }); @@ -158,7 +158,7 @@ export function registerRebuildFlowLifecycleTests(): void { expectedVersion: "0.2.0", isStale: false, verificationFailed: false, - detectionMethod: "ssh-exec", + detectionMethod: "sandbox-exec", }, }); @@ -182,7 +182,7 @@ export function registerRebuildFlowLifecycleTests(): void { expectedVersion: "0.2.0", isStale: false, verificationFailed: false, - detectionMethod: "ssh-exec", + detectionMethod: "sandbox-exec", }, }); diff --git a/test/helpers/rebuild-flow-test-harness.ts b/test/helpers/rebuild-flow-test-harness.ts index c4a16dda1eb..2f0bb756930 100644 --- a/test/helpers/rebuild-flow-test-harness.ts +++ b/test/helpers/rebuild-flow-test-harness.ts @@ -293,7 +293,7 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): detected: false, sessions: [], }); - vi.spyOn(sandboxVersion, "checkAgentVersion").mockImplementation(() => { + vi.spyOn(sandboxVersion, "checkAgentVersion").mockImplementation(async () => { Object.assign(currentSandboxEntry, overrides.entryUpdatesAfterVersionCheck ?? {}); return ( overrides.versionCheck ?? { diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index eb900d6d692..5f49b2327bd 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"; @@ -139,6 +140,40 @@ 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/sandbox/version.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + { + relativePath: "src/lib/state/sandbox.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": diff --git a/test/openclaw-config-snapshot.test.ts b/test/openclaw-config-snapshot.test.ts index c3ea863f892..ca46258751d 100644 --- a/test/openclaw-config-snapshot.test.ts +++ b/test/openclaw-config-snapshot.test.ts @@ -4,8 +4,38 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; -import { afterAll, describe, expect, it } from "vitest"; +import { afterAll, describe, expect, it, vi } from "vitest"; + +vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => ({ + execSandboxReadOnlyWithGrpcFallback: async ( + _gatewayName: string, + request: { + command: readonly string[]; + stdin?: string | Buffer; + maxOutputBytes?: number; + timeoutMs?: number; + stdoutEncoding?: "utf8" | "buffer"; + }, + ) => { + const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: request.stdoutEncoding === "buffer" ? undefined : "utf8", + }); + const binary = request.stdoutEncoding === "buffer"; + return { + status: result.status, + stdout: binary ? "" : String(result.stdout ?? ""), + ...(binary ? { stdoutBytes: Buffer.from(result.stdout ?? "") } : {}), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), + }; + }, +})); // sandbox-state computes its backup root from HOME at module load time. const ORIGINAL_HOME = process.env.HOME; @@ -167,7 +197,7 @@ describe("OpenClaw durable config file (#5027)", () => { process.env.NEMOCLAW_OPENSHELL_BIN = path.join(binDir, "openshell"); process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); expect(backup.backedUpFiles).toEqual(["openclaw.json"]); expect(backup.manifest?.stateFiles).toEqual([{ path: "openclaw.json", strategy: "copy" }]); @@ -298,7 +328,7 @@ describe("OpenClaw durable config file (#5027)", () => { process.env.NEMOCLAW_OPENSHELL_BIN = path.join(binDir, "openshell"); process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); // Local backup keeps non-secret tuning + mcp.servers; secrets are stripped. diff --git a/test/sandbox-download-upload-cli.test.ts b/test/sandbox-download-upload-cli.test.ts index 322ff1229e6..24ecf6fb641 100644 --- a/test/sandbox-download-upload-cli.test.ts +++ b/test/sandbox-download-upload-cli.test.ts @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { describe, expect, it } from "vitest"; import { runWithEnv, writeSandboxRegistry } from "./cli/helpers"; @@ -91,7 +91,7 @@ describe("sandbox download/upload CLI wrappers", () => { const calls = fs.readFileSync(openshellLog, "utf8"); const expectedHostPath = path.resolve(process.cwd(), "SOUL.md"); expect(calls).toContain( - `sandbox upload alpha ${expectedHostPath} /sandbox/.openclaw/workspace/SOUL.md`, + `sandbox upload -g nemoclaw -- alpha ${expectedHostPath} /sandbox/.openclaw/workspace/SOUL.md`, ); } finally { fs.rmSync(home, { recursive: true, force: true }); @@ -113,7 +113,7 @@ describe("sandbox download/upload CLI wrappers", () => { const calls = fs.readFileSync(openshellLog, "utf8"); const expectedHostPath = path.resolve(process.cwd(), "x"); - expect(calls).toContain(`sandbox upload alpha ${expectedHostPath} /sandbox/`); + expect(calls).toContain(`sandbox upload -g nemoclaw -- alpha ${expectedHostPath} /sandbox/`); } finally { fs.rmSync(home, { recursive: true, force: true }); } diff --git a/test/snapshot-gateway-guard.test.ts b/test/snapshot-gateway-guard.test.ts index 856c61fa731..8db7f94c3f0 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -121,10 +121,11 @@ function makeHealthyVmGatewayEnv(prefix: string): Record { // VM-driver snapshots should trust gateway metadata, not the legacy cluster // container probe. writeExecutable(path.join(localBin, "openshell"), [ + 'if [ "$1 $2 $3 $4" = "--gateway nemoclaw sandbox exec" ]; then shift 2; fi', 'case "$1 $2" in', ' "gateway info") printf "Gateway Info\\n\\nGateway: nemoclaw\\nGateway endpoint: https://127.0.0.1:8080/\\n"; exit 0 ;;', ' "sandbox list") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "sandbox exec") printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n"; exit 0 ;;', + ' "sandbox exec") case "$*" in *NEMOCLAW_DCODE_PROBE*) printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n" ;; *openclaw.json*) printf "{\\"gateway\\":{\\"auth\\":{\\"token\\":\\"fresh\\"}}}" ;; esac; exit 0 ;;', ' "sandbox ssh-config") printf "Host openshell-alpha\\n HostName 127.0.0.1\\n User sandbox\\n"; exit 0 ;;', "esac", 'if [ "$1" = "status" ]; then exit 0; fi', @@ -160,11 +161,12 @@ function makeVmRestoreToEnv( const cloneReadyMarker = path.join(home, "clone-1-ready"); writeExecutable(path.join(localBin, "openshell"), [ + 'if [ "$1 $2 $3 $4" = "--gateway nemoclaw sandbox exec" ]; then shift 2; fi', 'case "$1 $2" in', ' "gateway info") printf "Gateway Info\\n\\nGateway: nemoclaw\\nGateway endpoint: https://127.0.0.1:8080/\\n"; exit 0 ;;', ' "sandbox get") printf "{\\"name\\":\\"%s\\"}\\n" "$3"; exit 0 ;;', ` "sandbox list") if [ -f ${JSON.stringify(cloneReadyMarker)} ]; then printf "NAME STATUS\\nalpha Ready\\nclone-1 Ready\\n"; else printf "NAME STATUS\\nalpha Ready\\n"; fi; exit 0 ;;`, - ' "sandbox exec") printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n"; exit 0 ;;', + ' "sandbox exec") case "$*" in *NEMOCLAW_DCODE_PROBE*) printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n" ;; *openclaw.json*) printf "{\\"gateway\\":{\\"auth\\":{\\"token\\":\\"fresh\\"}}}" ;; esac; exit 0 ;;', ' "sandbox ssh-config") printf "Host openshell-alpha\\n HostName 127.0.0.1\\n User sandbox\\n"; exit 0 ;;', ` "sandbox create") touch ${JSON.stringify(cloneReadyMarker)}; printf "created clone-1\\n"; exit 0 ;;`, "esac", diff --git a/test/snapshot.test.ts b/test/snapshot.test.ts index 12fcec71749..a4a009aa2a2 100644 --- a/test/snapshot.test.ts +++ b/test/snapshot.test.ts @@ -8,8 +8,38 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; -import { afterAll, beforeEach, describe, expect, it } from "vitest"; +import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => ({ + execSandboxReadOnlyWithGrpcFallback: async ( + _gatewayName: string, + request: { + command: readonly string[]; + stdin?: string | Buffer; + maxOutputBytes?: number; + timeoutMs?: number; + stdoutEncoding?: "utf8" | "buffer"; + }, + ) => { + const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: request.stdoutEncoding === "buffer" ? undefined : "utf8", + }); + const binary = request.stdoutEncoding === "buffer"; + return { + status: result.status, + stdout: binary ? "" : String(result.stdout ?? ""), + ...(binary ? { stdoutBytes: Buffer.from(result.stdout ?? "") } : {}), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), + }; + }, +})); // Override HOME BEFORE importing sandbox-state — it reads process.env.HOME // at module-load time to compute REBUILD_BACKUPS_DIR. Captured original is @@ -441,12 +471,12 @@ describe("parseRestoreArgs", () => { }); describe("sandbox directory backup semantics", () => { - it("rejects a custom OpenClaw backup with missing image-plugin provenance (#6108)", () => { + it("rejects a custom OpenClaw backup with missing image-plugin provenance (#6108)", async () => { writeOpenClawRegistry("custom-openclaw", { fromDockerfile: "/tmp/Dockerfile.custom", }); - const backup = sandboxState.backupSandboxState("custom-openclaw"); + const backup = await sandboxState.backupSandboxState("custom-openclaw"); expect(backup.success).toBe(false); expect(backup.manifest).toBeUndefined(); @@ -454,7 +484,7 @@ describe("sandbox directory backup semantics", () => { expect(fs.existsSync(path.join(BACKUPS_ROOT, "custom-openclaw"))).toBe(false); }); - it("treats empty state directories as backed up when tar exits cleanly", () => { + it("treats empty state directories as backed up when tar exits cleanly", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-empty-dirs-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -505,7 +535,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}${path.delimiter}${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); expect(backup.failedDirs).toEqual([]); expect(backup.backedUpDirs).toEqual(existingDirs); @@ -523,7 +553,7 @@ process.exit(0); } }); - it("classifies tar-failed directories and excludes them from the restorable manifest", () => { + it("classifies tar-failed directories and excludes them from the restorable manifest", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-partial-tar-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -590,7 +620,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.failedDirs).toEqual(["agents", "workspace"]); expect(backup.failedDirReasons).toEqual({ @@ -628,7 +658,7 @@ process.exit(0); } }); - it("accepts built-in and custom OpenClaw peer links during the pre-backup audit", () => { + it("accepts built-in and custom OpenClaw peer links during the pre-backup audit", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-whitelist-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -677,7 +707,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); expect(backup.backedUpDirs).toEqual(existingDirs); expect(backup.error).toBeUndefined(); @@ -692,7 +722,7 @@ process.exit(0); } }); - it("accepts extension npm .bin symlinks that resolve inside node_modules", () => { + it("accepts extension npm .bin symlinks that resolve inside node_modules", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-npm-bin-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -741,7 +771,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); expect(backup.error).toBeUndefined(); } finally { @@ -755,7 +785,7 @@ process.exit(0); } }); - it("rejects extension npm .bin symlinks that escape node_modules", () => { + it("rejects extension npm .bin symlinks that escape node_modules", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-npm-bin-escape-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -792,7 +822,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.error).toMatch(/node_modules\/\.bin\/leak/); expect(backup.error).toMatch(/openclaw\.json/); @@ -807,7 +837,7 @@ process.exit(0); } }); - it("still rejects non-whitelisted symlinks alongside whitelisted ones", () => { + it("still rejects non-whitelisted symlinks alongside whitelisted ones", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-mixed-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -845,7 +875,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.error).toMatch(/workspace\/leak/); expect(backup.error).not.toMatch(/openclaw-weixin/); @@ -863,7 +893,7 @@ process.exit(0); it.each([ "weather", "slack", - ])("rejects a generic %s OpenClaw peer link with a tampered target", (extensionName) => { + ])("rejects a generic %s OpenClaw peer link with a tampered target", async (extensionName) => { // The generic peer path is valid, but its target must remain the exact // global OpenClaw install rather than an arbitrary absolute path. const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-target-tampered-")); @@ -902,7 +932,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.error).toContain(`extensions/${extensionName}`); expect(backup.error).toMatch(/\/etc\/passwd/); @@ -917,7 +947,7 @@ process.exit(0); } }); - it("marks non-attributed directories failed when they are missing from partial extraction", () => { + it("marks non-attributed directories failed when they are missing from partial extraction", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-missing-partial-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -962,7 +992,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.backedUpDirs).toEqual(["extensions"]); expect(backup.failedDirs).toEqual(["agents", "workspace"]); @@ -983,7 +1013,7 @@ process.exit(0); } }); - it("treats audit-find exit 1 with empty stdout as a successful audit", () => { + it("treats audit-find exit 1 with empty stdout as a successful audit", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-perm-denied-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -1040,7 +1070,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); expect(backup.error).toBeUndefined(); expect(backup.backedUpDirs).toEqual(existingDirs); @@ -1055,7 +1085,7 @@ process.exit(0); } }); - it("still rejects violations from readable dirs even if a sibling find exits non-zero", () => { + it("still rejects violations from readable dirs even if a sibling find exits non-zero", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-mixed-perm-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -1102,7 +1132,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.error).toMatch(/workspace\/leak/); } finally { @@ -1118,7 +1148,7 @@ process.exit(0); }); describe("Deep Agents Code durable state files", () => { - it("backs up manifest-declared state while excluding credential-bearing files", () => { + it("backs up manifest-declared state while excluding credential-bearing files", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-deepagents-snapshot-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -1218,7 +1248,9 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}${path.delimiter}${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("deepagents", { name: "deepagents-state" }); + const backup = await sandboxState.backupSandboxState("deepagents", { + name: "deepagents-state", + }); expect(backup.success).toBe(true); expect(backup.backedUpDirs).toEqual([".state", "skills", "agent/skills"]); expect(backup.backedUpFiles).toEqual(["config.toml"]); @@ -1270,7 +1302,7 @@ process.exit(0); }); describe("Hermes durable state files", () => { - it("backs up and restores SOUL.md plus the SQLite state database without credential files", () => { + it("backs up and restores SOUL.md plus the SQLite state database without credential files", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-snapshot-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -1280,11 +1312,12 @@ describe("Hermes durable state files", () => { const hermesDir = path.join(fakeRoot, ".hermes"); const runtimeDir = path.join(hermesDir, "runtime"); const sshLog = path.join(fixture, "ssh-log.jsonl"); + const stateDbBytes = Buffer.from([0x53, 0x51, 0x4c, 0x00, 0xff, 0xfe, 0x80, 0x0a]); fs.mkdirSync(binDir, { recursive: true }); fs.mkdirSync(runtimeDir, { recursive: true }); fs.writeFileSync(path.join(hermesDir, "SOUL.md"), "original soul\n"); fs.writeFileSync(path.join(hermesDir, ".hermes_history"), "original history\n"); - fs.writeFileSync(path.join(runtimeDir, "state.db"), "original sqlite backup\n"); + fs.writeFileSync(path.join(runtimeDir, "state.db"), stateDbBytes); fs.writeFileSync(path.join(hermesDir, "config.yaml"), "token: should-not-copy\n"); fs.writeFileSync(path.join(hermesDir, ".env"), "API_TOKEN=should-not-copy\n"); fs.writeFileSync(path.join(hermesDir, "auth.json"), '{"token":"should-not-copy"}\n'); @@ -1326,6 +1359,10 @@ if (cmd.includes("[ -d ")) { process.exit(0); } if (cmd.includes("nemoclaw-sqlite-backup")) { + if (readStdin().toString("utf8") !== ${JSON.stringify(sandboxState.SQLITE_BACKUP_PY)}) { + process.stderr.write("unexpected sqlite backup script on stdin\\n"); + process.exit(97); + } process.stdout.write(fs.readFileSync(path.join(hermesDir, "runtime", "state.db"))); process.exit(0); } @@ -1375,7 +1412,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("hermes", { name: "hermes-state" }); + const backup = await sandboxState.backupSandboxState("hermes", { name: "hermes-state" }); expect(backup.success).toBe(true); expect(backup.backedUpFiles).toEqual(["SOUL.md", ".hermes_history", "runtime/state.db"]); expect(backup.failedFiles).toEqual([]); @@ -1391,8 +1428,8 @@ process.exit(0); fs.readFileSync(path.join(backup.manifest!.backupPath, ".hermes_history"), "utf-8"), ).toBe("original history\n"); expect( - fs.readFileSync(path.join(backup.manifest!.backupPath, "runtime", "state.db"), "utf-8"), - ).toBe("original sqlite backup\n"); + fs.readFileSync(path.join(backup.manifest!.backupPath, "runtime", "state.db")), + ).toEqual(stateDbBytes); expect(fs.existsSync(path.join(backup.manifest!.backupPath, "config.yaml"))).toBe(false); expect(fs.existsSync(path.join(backup.manifest!.backupPath, ".env"))).toBe(false); expect(fs.existsSync(path.join(backup.manifest!.backupPath, "auth.json"))).toBe(false); @@ -1407,14 +1444,10 @@ process.exit(0); expect(fs.readFileSync(path.join(hermesDir, ".hermes_history"), "utf-8")).toBe( "original history\n", ); - expect(fs.readFileSync(path.join(runtimeDir, "state.db"), "utf-8")).toBe( - "original sqlite backup\n", - ); + expect(fs.readFileSync(path.join(runtimeDir, "state.db"))).toEqual(stateDbBytes); const loggedCommands = fs.readFileSync(sshLog, "utf-8"); - expect(loggedCommands).toContain("sqlite3.connect"); - expect(loggedCommands).toContain("src_conn.backup(dst_conn)"); - expect(loggedCommands).toContain("PRAGMA quick_check"); + expect(loggedCommands).toContain('python3 - \\"$src\\" \\"$tmp\\"'); } finally { if (oldOpenshell === undefined) { delete process.env.NEMOCLAW_OPENSHELL_BIN; diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 63b4ef79edf..0b405f0453a 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -170,7 +170,14 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne detected: true, sessions: [{ pid: 1 }, { pid: 2 }], }); - vi.spyOn(sandboxVersion, "checkAgentVersion").mockReturnValue({ isStale: false }); + vi.spyOn(sandboxVersion, "checkAgentVersion").mockResolvedValue({ + sandboxVersion: null, + expectedVersion: null, + isStale: false, + verificationFailed: true, + detectionMethod: "unknown", + unavailableReason: "probe-failed", + }); vi.spyOn(sandboxVersion, "formatStalenessWarning").mockReturnValue([]); const checkAndRecoverSpy = vi .spyOn(processRecovery, "checkAndRecoverSandboxProcesses") diff --git a/test/support/status-flow-test-harness.ts b/test/support/status-flow-test-harness.ts index 2147abe284d..4e07b6147fc 100644 --- a/test/support/status-flow-test-harness.ts +++ b/test/support/status-flow-test-harness.ts @@ -183,12 +183,12 @@ export function createStatusFlowHarness(options: StatusFlowHarnessOptions = {}): container: null, }); vi.spyOn(nim, "shouldShowNimLine").mockReturnValue(true); - const checkAgentVersionSpy = vi.spyOn(sandboxVersion, "checkAgentVersion").mockReturnValue( + const checkAgentVersionSpy = vi.spyOn(sandboxVersion, "checkAgentVersion").mockResolvedValue( options.versionCheck ?? { sandboxVersion: "0.1.0", expectedVersion: "0.2.0", isStale: true, - detectionMethod: "runtime", + detectionMethod: "sandbox-exec", }, ); vi.spyOn(shields, "getShieldsPosture").mockReturnValue(