Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions src/lib/actions/sandbox/sandbox-exec-output.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { Buffer } from "node:buffer";
import { describe, expect, it } from "vitest";
import {
buildSandboxExecMarkedCommand,
extractSandboxExecCommandStdout,
SANDBOX_EXEC_STARTED_MARKER,
} from "./sandbox-exec-output";

describe("buildSandboxExecMarkedCommand", () => {
it("prints the sentinel before the command for ordinary scripts", () => {
const command = buildSandboxExecMarkedCommand("echo hi");
expect(command).toBe(`printf '%s\\n' '${SANDBOX_EXEC_STARTED_MARKER}'; echo hi`);
});

it("base64-encodes the hermes secret boundary script instead of inlining it", () => {
const script = "python3 validate-hermes-env-secret-boundary.py --check";
const command = buildSandboxExecMarkedCommand(script);

expect(command).toContain(`printf '%s\\n' '${SANDBOX_EXEC_STARTED_MARKER}'`);
expect(command).not.toContain(script);
const encoded = Buffer.from(script, "utf8").toString("base64");
expect(command).toContain(encoded);
});
});

describe("extractSandboxExecCommandStdout", () => {
it("returns null for empty output", () => {
expect(extractSandboxExecCommandStdout("")).toBeNull();
expect(extractSandboxExecCommandStdout(" \n ")).toBeNull();
});

it("returns null when the sentinel never appears", () => {
expect(extractSandboxExecCommandStdout("exec failed\n")).toBeNull();
});

it("extracts stdout after a raw, unframed sentinel", () => {
const output = `${SANDBOX_EXEC_STARTED_MARKER}\nNEMOCLAW_DCODE_PROBE=idle\n`;
expect(extractSandboxExecCommandStdout(output)).toBe("NEMOCLAW_DCODE_PROBE=idle");
});

it("strips the 'stdout: ' frame prefix", () => {
const output = `stdout: ${SANDBOX_EXEC_STARTED_MARKER}\nstdout: NEMOCLAW_DCODE_PROBE=idle\n`;
expect(extractSandboxExecCommandStdout(output)).toBe("NEMOCLAW_DCODE_PROBE=idle");
});

it("strips the '[stdout] ' frame prefix", () => {
const output = `[stdout] ${SANDBOX_EXEC_STARTED_MARKER}\n[stdout] NEMOCLAW_DCODE_PROBE=active\n`;
expect(extractSandboxExecCommandStdout(output)).toBe("NEMOCLAW_DCODE_PROBE=active");
});

it("strips stdout frame prefixes case-insensitively", () => {
const output = `STDOUT: ${SANDBOX_EXEC_STARTED_MARKER}\n[STDOUT] NEMOCLAW_DCODE_PROBE=idle\n`;
expect(extractSandboxExecCommandStdout(output)).toBe("NEMOCLAW_DCODE_PROBE=idle");
});

it("returns null when a preamble repeats the sentinel before the authentic boundary", () => {
const output = [
SANDBOX_EXEC_STARTED_MARKER,
"NEMOCLAW_DCODE_PROBE=idle",
`stdout: ${SANDBOX_EXEC_STARTED_MARKER}`,
"stdout: NEMOCLAW_DCODE_PROBE=active",
].join("\n");

expect(extractSandboxExecCommandStdout(output)).toBeNull();
});

it("returns null when child stdout repeats the sentinel after the authentic boundary", () => {
const output = [
SANDBOX_EXEC_STARTED_MARKER,
"NEMOCLAW_DCODE_PROBE=active",
`[stdout] ${SANDBOX_EXEC_STARTED_MARKER}`,
"[stdout] NEMOCLAW_DCODE_PROBE=idle",
].join("\n");

expect(extractSandboxExecCommandStdout(output)).toBeNull();
});

it("does not match a sentinel embedded in a preamble line as a substring", () => {
const output = `some login banner ${SANDBOX_EXEC_STARTED_MARKER} noise\n${SANDBOX_EXEC_STARTED_MARKER}\nNEMOCLAW_DCODE_PROBE=idle\n`;
expect(extractSandboxExecCommandStdout(output)).toBe("NEMOCLAW_DCODE_PROBE=idle");
});
});
27 changes: 19 additions & 8 deletions src/lib/actions/sandbox/sandbox-exec-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,30 @@ function parseSandboxExecStdoutFrame(line: string): { text: string; framed: bool
* stdout frame prefixes at this transport boundary so recovery, status, and
* Hermes boundary callers keep consuming plain command stdout.
*
* Security boundary: the sentinel must occupy its own stdout line after optional
* frame-prefix stripping. A preamble that merely contains the sentinel string is
* rejected so sandbox output cannot move the parser boundary forward. Remove
* this compatibility shim once OpenShell exposes a stable machine-readable exec
* output mode that preserves child stdout/stderr without human framing.
* Source-of-truth boundary (#6180): OpenShell owns the sandbox-exec transport,
* whose human-readable framing can make otherwise valid child stdout
* ambiguous. NemoClaw cannot change that transport here, so this shared parser
* normalizes its output for recovery, status, Hermes, and snapshot callers.
* The parser, process-recovery, and snapshot tests lock down that adaptation.
*
* Security boundary: accept exactly one exact sentinel line after optional
* frame-prefix stripping. A sentinel emitted before the command by a shell
* preamble or after it by child stdout makes the boundary ambiguous, so fail
* closed instead of choosing either marker. Remove this compatibility shim
* once supported OpenShell versions expose stable machine-readable exec output
* that preserves child stdout/stderr without human framing.
*/
export function extractSandboxExecCommandStdout(output: string): string | null {
const stdout = output.trim();
if (!stdout) return null;
const lines = stdout.split(/\r?\n/).map(parseSandboxExecStdoutFrame);
const exactMarkerIndex = lines.findIndex(
(line) => line.text.trim() === SANDBOX_EXEC_STARTED_MARKER,
);
let exactMarkerIndex = -1;
for (let i = 0; i < lines.length; i++) {
if (lines[i].text.trim() === SANDBOX_EXEC_STARTED_MARKER) {
if (exactMarkerIndex >= 0) return null;
exactMarkerIndex = i;
}
}
if (exactMarkerIndex >= 0) {
return lines
.slice(exactMarkerIndex + 1)
Expand Down
69 changes: 68 additions & 1 deletion src/lib/actions/sandbox/snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SANDBOX_EXEC_STARTED_MARKER } from "./sandbox-exec-output";

type OpenshellCaptureResult = {
status: number | null;
Expand All @@ -23,7 +24,11 @@ type SandboxRecord = {
type DcodeProbeState = "active" | "idle" | "unverifiable" | "no-runtime";

function dcodeProbeOutput(state: DcodeProbeState, extra = ""): string {
return `NEMOCLAW_DCODE_PROBE=${state}\n${extra}`;
return `${SANDBOX_EXEC_STARTED_MARKER}\nNEMOCLAW_DCODE_PROBE=${state}\n${extra}`;
}

function framedDcodeProbeOutput(state: DcodeProbeState, framePrefix = "stdout: "): string {
return `${framePrefix}${SANDBOX_EXEC_STARTED_MARKER}\n${framePrefix}NEMOCLAW_DCODE_PROBE=${state}\n`;
}

function openshellResponses(
Expand Down Expand Up @@ -404,6 +409,68 @@ describe("runSandboxSnapshot", () => {
expect(consoleLog.mock.calls.flat().join("\n")).toContain("Snapshot v8 name=idle created");
});

it("allows dcode snapshot creation when OpenShell frames the probe stdout", async () => {
getSandboxMock.mockReturnValue(dcodeSandboxEntry);
mockDcodeProbeResult({ status: 0, output: framedDcodeProbeOutput("idle") });
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {});
const manifest = {
timestamp: "2026-06-15T00:00:00.000Z",
backupPath: "/tmp/backup-alpha",
name: "framed-idle",
};
backupSandboxStateMock.mockReturnValue({
success: true,
backedUpDirs: ["workspace"],
backedUpFiles: ["config.toml"],
failedDirs: [],
failedFiles: [],
manifest,
});
findBackupMock.mockReturnValue({
match: { ...manifest, snapshotVersion: 9, name: "framed-idle" },
});
const { runSandboxSnapshot } = await import("./snapshot");

await runSandboxSnapshot("alpha", { kind: "create", name: "framed-idle" });

expect(backupSandboxStateMock).toHaveBeenCalledWith("alpha", { name: "framed-idle" });
expect(consoleLog.mock.calls.flat().join("\n")).toContain(
"Snapshot v9 name=framed-idle created",
);
});

it("refuses an active dcode task when OpenShell frames the probe stdout", async () => {
getSandboxMock.mockReturnValue(dcodeSandboxEntry);
mockDcodeProbeResult({ status: 0, output: framedDcodeProbeOutput("active", "[stdout] ") });
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const { runSandboxSnapshot } = await import("./snapshot");

await expect(runSandboxSnapshot("alpha", { kind: "create" })).rejects.toMatchObject({
exitCode: 1,
});

expect(backupSandboxStateMock).not.toHaveBeenCalled();
expect(consoleError.mock.calls.flat().join("\n")).toContain(
"Sandbox is actively running a dcode task. Please retry after the task completes.",
);
});

it("refuses an idle dcode snapshot when the exec wrapper reports a non-zero status", async () => {
getSandboxMock.mockReturnValue(dcodeSandboxEntry);
mockDcodeProbeResult({ status: 1, output: dcodeProbeOutput("idle") });
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const { runSandboxSnapshot } = await import("./snapshot");

await expect(runSandboxSnapshot("alpha", { kind: "create" })).rejects.toMatchObject({
exitCode: 1,
});

expect(backupSandboxStateMock).not.toHaveBeenCalled();
expect(consoleError.mock.calls.flat().join("\n")).toContain(
"Cannot verify whether sandbox 'alpha' is actively running a dcode task. Refusing to create snapshot.",
);
});

it("refuses registered dcode snapshots when raw status 1 has no idle sentinel", async () => {
getSandboxMock.mockReturnValue(dcodeSandboxEntry);
mockDcodeProbeResult({ status: 1, output: "exec failed" });
Expand Down
27 changes: 20 additions & 7 deletions src/lib/actions/sandbox/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ import type { SandboxEntry } from "../../state/registry";
import * as registry from "../../state/registry";
import * as sandboxState from "../../state/sandbox";
import { cleanupShieldsDestroyArtifacts, removeSandboxRegistryEntry } from "./destroy";
import {
buildSandboxExecMarkedCommand,
extractSandboxExecCommandStdout,
} from "./sandbox-exec-output";
import {
probeGatewayRunning,
selectSandboxGatewayIfRegistered,
Expand Down Expand Up @@ -426,23 +430,32 @@ function isSnapshotCreationAllowedByDcodeActivity(sandboxName: string): boolean
// when dcode exposes a wrapper-owned idle/active lock or equivalent snapshot
// quiescence signal and the backup path checks that source directly.
const probe = captureOpenshell(
["sandbox", "exec", "--name", sandboxName, "--", "sh", "-lc", DCODE_BUSY_PROBE_SCRIPT],
[
"sandbox",
"exec",
"--name",
sandboxName,
"--",
"sh",
"-lc",
buildSandboxExecMarkedCommand(DCODE_BUSY_PROBE_SCRIPT),
],
{
ignoreError: true,
includeStderr: true,
timeout: OPENSHELL_PROBE_TIMEOUT_MS,
},
);
const probeState = parseDcodeProbeState(probe.output || "");
const probeSucceeded = probe.status === 0 && !probe.error && !probe.signal;
const probeCompleted = probe.status === 0 && !probe.error && !probe.signal;
const commandStdout = probeCompleted ? extractSandboxExecCommandStdout(probe.output || "") : null;
const probeState = commandStdout === null ? null : parseDcodeProbeState(commandStdout);
if (
probeSucceeded &&
(probeState === DCODE_PROBE_STATE.idleDcodeRuntime ||
probeState === DCODE_PROBE_STATE.noDcodeRuntime)
probeState === DCODE_PROBE_STATE.idleDcodeRuntime ||
probeState === DCODE_PROBE_STATE.noDcodeRuntime
) {
return true;
}
if (probeSucceeded && probeState === DCODE_PROBE_STATE.active) {
if (probeState === DCODE_PROBE_STATE.active) {
console.error(
" Sandbox is actively running a dcode task. Please retry after the task completes.",
);
Expand Down
Loading