Skip to content
Merged
63 changes: 59 additions & 4 deletions src/lib/policy/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ const YAML = require("yaml");
const { ROOT, run, runCapture } = require("../runner");
const registry = require("../state/registry");
const { loadAgent } = require("../agent/defs");
// Late-binding access via the module exports so tests can spy on
// resolveOpenshell without rewiring requires.
const openshellResolveModule = require("../adapters/openshell/resolve");

const PRESETS_DIR = path.join(ROOT, "nemoclaw-blueprint", "policies", "presets");

Expand Down Expand Up @@ -323,20 +326,67 @@ function parseCurrentPolicy(raw: string | null | undefined): string {
return candidate;
}

/**
* Resolve the openshell binary, preferring an absolute path so spawnSync does
* not raise ENOENT in non-interactive shells where ~/.local/bin/ is absent
* from PATH (issue #4224). Falls back to the literal "openshell" so callers
* that build argv at module scope (or in tests that only check argv shape)
* don't side-effect on a missing binary; command entry points call
* `assertOpenshellResolvable()` before invoking openshell to surface the
* actionable diagnostic.
*/
function resolveOpenshellBinary(): string {
return openshellResolveModule.resolveOpenshell() ?? "openshell";
}

/**
* Pre-spawn check used at command entry points before any
* `run(buildPolicy*Command(...))`. If the binary cannot be resolved, prints
* every location checked and an install hint, then exits nonzero — instead
* of letting the spawn surface as the opaque `spawnSync openshell ENOENT`
* (issue #4224).
*/
function assertOpenshellResolvable(): void {
if (openshellResolveModule.resolveOpenshell()) return;

const home = process.env.HOME;
const override = process.env.NEMOCLAW_OPENSHELL_BIN;
const currentPath = process.env.PATH;
const checked: string[] = [];
if (override) checked.push(`NEMOCLAW_OPENSHELL_BIN=${override}`);
// Log the concrete PATH so bug reports name what was actually searched.
// The whole point of #4224 is that non-interactive shells drop ~/.local/bin
// from PATH; the value is the most actionable single piece of context.
checked.push(
currentPath
? `PATH=${currentPath} (via \`command -v openshell\`)`
: "PATH=<unset> (via `command -v openshell`)",
);
if (home?.startsWith("/")) checked.push(`${home}/.local/bin/openshell`);
checked.push("/usr/local/bin/openshell", "/usr/bin/openshell");

console.error(" openshell binary not found. Checked:");
for (const location of checked) {
console.error(` - ${location}`);
}
console.error(
" Install OpenShell (https://github.com/NVIDIA/OpenShell) or set NEMOCLAW_OPENSHELL_BIN to an absolute, executable path.",
);
process.exit(1);
}

/**
* Build the openshell policy set command as an argv array.
*/
function buildPolicySetCommand(policyFile: string, sandboxName: string): string[] {
const binary = process.env.NEMOCLAW_OPENSHELL_BIN || "openshell";
return [binary, "policy", "set", "--policy", policyFile, "--wait", sandboxName];
return [resolveOpenshellBinary(), "policy", "set", "--policy", policyFile, "--wait", sandboxName];
}

/**
* Build the openshell policy get command as an argv array.
*/
function buildPolicyGetCommand(sandboxName: string): string[] {
const binary = process.env.NEMOCLAW_OPENSHELL_BIN || "openshell";
return [binary, "policy", "get", "--full", sandboxName];
return [resolveOpenshellBinary(), "policy", "get", "--full", sandboxName];
}

/**
Expand Down Expand Up @@ -604,6 +654,7 @@ function removePreset(sandboxName: string, presetName: string): boolean {
fs.writeFileSync(tmpFile, updated, { encoding: "utf-8", mode: 0o600 });

try {
assertOpenshellResolvable();
run(buildPolicySetCommand(tmpFile, sandboxName));
console.log(` Removed preset: ${presetName}`);
} finally {
Expand Down Expand Up @@ -742,6 +793,7 @@ function applyPresetContent(
fs.writeFileSync(tmpFile, merged, { encoding: "utf-8", mode: 0o600 });

try {
assertOpenshellResolvable();
run(buildPolicySetCommand(tmpFile, sandboxName));

console.log(` Applied preset: ${presetName}`);
Expand Down Expand Up @@ -855,6 +907,7 @@ function applyPresets(sandboxName: string, presetNames: string[]): boolean {
fs.writeFileSync(tmpFile, merged, { encoding: "utf-8", mode: 0o600 });

try {
assertOpenshellResolvable();
run(buildPolicySetCommand(tmpFile, sandboxName));

for (const presetName of uniquePresetNames) {
Expand Down Expand Up @@ -1204,6 +1257,7 @@ function applyPermissivePolicy(sandboxName: string): void {
}

console.log(" Applying permissive policy...");
assertOpenshellResolvable();
run(buildPolicySetCommand(policyPath, sandboxName));
console.log(" Applied permissive policy.");
}
Expand All @@ -1223,6 +1277,7 @@ export {
parseCurrentPolicy,
buildPolicySetCommand,
buildPolicyGetCommand,
assertOpenshellResolvable,
mergePresetIntoPolicy,
mergePresetNamesIntoPolicy,
removePresetFromPolicy,
Expand Down
138 changes: 131 additions & 7 deletions test/policies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import os from "node:os";
import path from "node:path";
import { createRequire } from "node:module";
import type { Interface as ReadlineInterface } from "node:readline";
import { afterEach, describe, it, expect, vi } from "vitest";
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import { spawnSync } from "node:child_process";
import * as policies from "../dist/lib/policy";
import { execTimeout } from "./helpers/timeouts";
Expand All @@ -15,6 +15,9 @@ const requireForTest = createRequire(import.meta.url);
const readline = requireForTest("node:readline") as typeof import("node:readline");
const YAML = requireForTest("yaml");
const REPO_ROOT = path.join(import.meta.dirname, "..");
const resolveOpenshellModule = requireForTest(
path.join(REPO_ROOT, "dist", "lib", "adapters", "openshell", "resolve.js"),
) as { resolveOpenshell: (...args: unknown[]) => string | null };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const CLI_PATH = JSON.stringify(path.join(REPO_ROOT, "dist", "nemoclaw.js"));
const CREDENTIALS_PATH = JSON.stringify(path.join(REPO_ROOT, "dist", "lib", "credentials", "store.js"));
const POLICIES_PATH = JSON.stringify(path.join(REPO_ROOT, "dist", "lib", "policy", "index.js"));
Expand Down Expand Up @@ -778,8 +781,10 @@ exit 1
describe("buildPolicySetCommand", () => {
it("returns an argv array with sandbox name as a separate element", () => {
const cmd = policies.buildPolicySetCommand("/tmp/policy.yaml", "my-assistant");
expect(cmd).toEqual([
"openshell",
// The binary is resolved via resolveOpenshell() so it may be an absolute
// path; assert the openshell tail and the rest of the argv shape.
expect(cmd[0]).toMatch(/openshell$/);
expect(cmd.slice(1)).toEqual([
"policy",
"set",
"--policy",
Expand All @@ -803,11 +808,15 @@ exit 1
});

it("uses the resolved openshell binary when provided by the installer path", () => {
process.env.NEMOCLAW_OPENSHELL_BIN = "/tmp/fake path/openshell";
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-bin-"));
const override = path.join(tmpDir, "openshell");
fs.writeFileSync(override, "#!/bin/sh\nexit 0\n", { mode: 0o755 });
const prev = process.env.NEMOCLAW_OPENSHELL_BIN;
process.env.NEMOCLAW_OPENSHELL_BIN = override;
try {
const cmd = policies.buildPolicySetCommand("/tmp/policy.yaml", "my-assistant");
expect(cmd).toEqual([
"/tmp/fake path/openshell",
override,
"policy",
"set",
"--policy",
Expand All @@ -816,15 +825,130 @@ exit 1
"my-assistant",
]);
} finally {
delete process.env.NEMOCLAW_OPENSHELL_BIN;
if (prev === undefined) delete process.env.NEMOCLAW_OPENSHELL_BIN;
else process.env.NEMOCLAW_OPENSHELL_BIN = prev;
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
});

describe("buildPolicyGetCommand", () => {
it("returns an argv array with sandbox name as a separate element", () => {
const cmd = policies.buildPolicyGetCommand("my-assistant");
expect(cmd).toEqual(["openshell", "policy", "get", "--full", "my-assistant"]);
expect(cmd[0]).toMatch(/openshell$/);
expect(cmd.slice(1)).toEqual(["policy", "get", "--full", "my-assistant"]);
});
});

// Regression for issue #4224: when openshell is installed at ~/.local/bin/openshell
// (the installer's user-local location) but PATH from a non-interactive shell does
// not include ~/.local/bin/, buildPolicySetCommand / buildPolicyGetCommand must
// resolve openshell to an absolute path so spawnSync does not raise ENOENT.
describe("issue 4224: spawnSync openshell ENOENT in non-interactive shells", () => {
let tmpHome: string;
let fakeOpenshell: string;
let origHome: string | undefined;
let origPath: string | undefined;
let origBin: string | undefined;

beforeEach(() => {
tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-issue4224-"));
const localBin = path.join(tmpHome, ".local", "bin");
fs.mkdirSync(localBin, { recursive: true });
fakeOpenshell = path.join(localBin, "openshell");
fs.writeFileSync(fakeOpenshell, "#!/bin/sh\nexit 0\n", { mode: 0o755 });

origHome = process.env.HOME;
origPath = process.env.PATH;
origBin = process.env.NEMOCLAW_OPENSHELL_BIN;
// Simulate the non-interactive shell: openshell not on PATH, no override.
process.env.HOME = tmpHome;
process.env.PATH = "/nonexistent-nemoclaw-path";
delete process.env.NEMOCLAW_OPENSHELL_BIN;
});

afterEach(() => {
if (origHome === undefined) delete process.env.HOME;
else process.env.HOME = origHome;
if (origPath === undefined) delete process.env.PATH;
else process.env.PATH = origPath;
if (origBin === undefined) delete process.env.NEMOCLAW_OPENSHELL_BIN;
else process.env.NEMOCLAW_OPENSHELL_BIN = origBin;
fs.rmSync(tmpHome, { recursive: true, force: true });
});

it("buildPolicySetCommand resolves openshell to ~/.local/bin/openshell when PATH lacks it", () => {
const cmd = policies.buildPolicySetCommand("/tmp/policy.yaml", "my-assistant");
expect(cmd[0]).toBe(fakeOpenshell);
expect(cmd).toEqual([
fakeOpenshell,
"policy",
"set",
"--policy",
"/tmp/policy.yaml",
"--wait",
"my-assistant",
]);
});

it("buildPolicyGetCommand resolves openshell to ~/.local/bin/openshell when PATH lacks it", () => {
const cmd = policies.buildPolicyGetCommand("my-assistant");
expect(cmd[0]).toBe(fakeOpenshell);
expect(cmd).toEqual([fakeOpenshell, "policy", "get", "--full", "my-assistant"]);
});

it("assertOpenshellResolvable emits a diagnostic listing every checked location and exits nonzero when openshell cannot be resolved", () => {
const resolveSpy = vi
.spyOn(resolveOpenshellModule, "resolveOpenshell")
.mockReturnValue(null);
const errors: string[] = [];
const errSpy = vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => {
errors.push(args.map((a) => String(a)).join(" "));
});
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((_code?: number) => {
throw new Error("__test_exit__");
}) as never);

process.env.HOME = tmpHome;
process.env.PATH = "/nonexistent-nemoclaw-path";
process.env.NEMOCLAW_OPENSHELL_BIN = "/nonexistent/openshell";

try {
expect(() => policies.assertOpenshellResolvable()).toThrow(/__test_exit__/);
expect(exitSpy).toHaveBeenCalledWith(1);
const combined = errors.join("\n");
expect(combined).toMatch(/openshell binary not found/);
expect(combined).toMatch(/NEMOCLAW_OPENSHELL_BIN=\/nonexistent\/openshell/);
// PATH value should be logged verbatim so bug reports name what was searched.
expect(combined).toContain("PATH=/nonexistent-nemoclaw-path");
expect(combined).toContain(`${tmpHome}/.local/bin/openshell`);
expect(combined).toContain("/usr/local/bin/openshell");
expect(combined).toContain("/usr/bin/openshell");
expect(combined).toMatch(/Install OpenShell|NEMOCLAW_OPENSHELL_BIN/);
} finally {
resolveSpy.mockRestore();
errSpy.mockRestore();
exitSpy.mockRestore();
}
});

it("assertOpenshellResolvable is a noop when openshell resolves", () => {
const resolveSpy = vi
.spyOn(resolveOpenshellModule, "resolveOpenshell")
.mockReturnValue(fakeOpenshell);
const errSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((_code?: number) => {
throw new Error("should not exit");
}) as never);
try {
expect(() => policies.assertOpenshellResolvable()).not.toThrow();
expect(exitSpy).not.toHaveBeenCalled();
expect(errSpy).not.toHaveBeenCalled();
} finally {
resolveSpy.mockRestore();
errSpy.mockRestore();
exitSpy.mockRestore();
}
});
});

Expand Down
Loading