Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
9 changes: 9 additions & 0 deletions src/commands/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,17 @@ function buildDebugCommandDeps(rootDir: string): RunDebugCommandDeps {
return defaultSandbox;
};

const isSandboxKnown = (name: string): boolean => {
const { sandboxes } = registry.listSandboxes();
if (sandboxes.find((sandbox) => sandbox.name === name)) return true;
const liveList = captureOpenshell(rootDir, ["sandbox", "list"]);
if (liveList.status === 0 && parseLiveSandboxNames(liveList.output).has(name)) return true;
return false;
};

return {
getDefaultSandbox,
isSandboxKnown,
runDebug,
};
}
Expand Down
118 changes: 118 additions & 0 deletions src/lib/diagnostics/debug-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ describe("debug command", () => {
{ quick: true, output: "/tmp/out.tgz" },
{
getDefaultSandbox: () => "alpha",
isSandboxKnown: () => true,
runDebug,
},
);
Expand All @@ -21,4 +22,121 @@ describe("debug command", () => {
sandboxName: "alpha",
});
});

it("accepts an explicit --sandbox name that is registered", () => {
const runDebug = vi.fn();
const isSandboxKnown = vi.fn().mockReturnValue(true);
runDebugCommandWithOptions(
{ sandboxName: "alpha" },
{
getDefaultSandbox: () => undefined,
isSandboxKnown,
runDebug,
},
);
expect(isSandboxKnown).toHaveBeenCalledWith("alpha");
expect(runDebug).toHaveBeenCalledWith({ sandboxName: "alpha" });
});

it("rejects an explicit --sandbox name that is not registered, exits non-zero, skips runDebug", () => {
const runDebug = vi.fn();
const errorLines: string[] = [];
const exit = vi.fn(() => {
throw new Error("exit");
}) as unknown as (code: number) => never;
expect(() =>
runDebugCommandWithOptions(
{ sandboxName: "does-not-exist", output: "/tmp/out.tgz" },
{
getDefaultSandbox: () => "alpha",
isSandboxKnown: () => false,
runDebug,
errorLine: (msg) => errorLines.push(msg),
exit,
},
),
).toThrow("exit");
expect(exit).toHaveBeenCalledWith(1);
expect(runDebug).not.toHaveBeenCalled();
expect(errorLines[0]).toContain("does-not-exist");
expect(errorLines[0]).toContain("not registered");
expect(errorLines.join("\n")).toContain("nemoclaw list");
});

it("validates an env-sourced sandbox name and reports the env source on failure", () => {
const runDebug = vi.fn();
const errorLines: string[] = [];
const exit = vi.fn(() => {
throw new Error("exit");
}) as unknown as (code: number) => never;
expect(() =>
runDebugCommandWithOptions(
{},
{
env: { NEMOCLAW_SANDBOX_NAME: "ghost" } as NodeJS.ProcessEnv,
getDefaultSandbox: () => "alpha",
isSandboxKnown: () => false,
runDebug,
errorLine: (msg) => errorLines.push(msg),
exit,
},
),
).toThrow("exit");
expect(runDebug).not.toHaveBeenCalled();
expect(errorLines[0]).toContain("ghost");
expect(errorLines[0]).toContain("NEMOCLAW_SANDBOX_NAME");
});

it("prefers NEMOCLAW_SANDBOX_NAME over NEMOCLAW_SANDBOX and SANDBOX_NAME", () => {
const runDebug = vi.fn();
const isSandboxKnown = vi.fn().mockReturnValue(true);
runDebugCommandWithOptions(
{},
{
env: {
NEMOCLAW_SANDBOX_NAME: "primary",
NEMOCLAW_SANDBOX: "secondary",
SANDBOX_NAME: "tertiary",
} as NodeJS.ProcessEnv,
getDefaultSandbox: () => undefined,
isSandboxKnown,
runDebug,
},
);
expect(isSandboxKnown).toHaveBeenCalledWith("primary");
expect(runDebug).toHaveBeenCalledWith({ sandboxName: "primary" });
});

it("flag overrides env vars when both are present", () => {
const runDebug = vi.fn();
const isSandboxKnown = vi.fn().mockReturnValue(true);
runDebugCommandWithOptions(
{ sandboxName: "alpha" },
{
env: { NEMOCLAW_SANDBOX: "beta" } as NodeJS.ProcessEnv,
getDefaultSandbox: () => undefined,
isSandboxKnown,
runDebug,
},
);
expect(isSandboxKnown).toHaveBeenCalledWith("alpha");
expect(isSandboxKnown).not.toHaveBeenCalledWith("beta");
expect(runDebug).toHaveBeenCalledWith({ sandboxName: "alpha" });
});

it("falls back to getDefaultSandbox when neither flag nor env is set", () => {
const runDebug = vi.fn();
const isSandboxKnown = vi.fn();
runDebugCommandWithOptions(
{},
{
env: {} as NodeJS.ProcessEnv,
getDefaultSandbox: () => "alpha",
isSandboxKnown,
runDebug,
},
);
expect(isSandboxKnown).not.toHaveBeenCalled();
expect(runDebug).toHaveBeenCalledWith({ sandboxName: "alpha" });
});
});
41 changes: 40 additions & 1 deletion src/lib/diagnostics/debug-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,52 @@ import type { DebugOptions } from "./debug";

export interface RunDebugCommandDeps {
getDefaultSandbox: () => string | undefined;
isSandboxKnown: (name: string) => boolean;
runDebug: (options: DebugOptions) => void;
env?: NodeJS.ProcessEnv;
errorLine?: (message: string) => void;
exit?: (code: number) => never;
}

const SANDBOX_NAME_ENV_VARS = ["NEMOCLAW_SANDBOX_NAME", "NEMOCLAW_SANDBOX", "SANDBOX_NAME"] as const;

function resolveExplicitName(
options: DebugOptions,
env: NodeJS.ProcessEnv,
): { name: string; source: "flag" | "env"; envVar?: string } | null {
const flagName = options.sandboxName?.trim();
if (flagName) return { name: flagName, source: "flag" };
for (const envVar of SANDBOX_NAME_ENV_VARS) {
const value = env[envVar]?.trim();
if (value) return { name: value, source: "env", envVar };
}
return null;
}

export function runDebugCommandWithOptions(options: DebugOptions, deps: RunDebugCommandDeps): void {
const opts = { ...options };
if (!opts.sandboxName) {
const env = deps.env ?? process.env;
const errorLine = deps.errorLine ?? ((msg: string) => console.error(msg));
const exit =
deps.exit ??
((code: number) => {
process.exit(code);
});

const explicit = resolveExplicitName(opts, env);
if (explicit) {
if (!deps.isSandboxKnown(explicit.name)) {
const sourceLabel =
explicit.source === "env" && explicit.envVar ? ` (from ${explicit.envVar})` : "";
errorLine(`Error: Sandbox '${explicit.name}'${sourceLabel} is not registered.`);
errorLine(" Run `nemoclaw list` to see available sandboxes.");
exit(1);
return;
}
opts.sandboxName = explicit.name;
} else {
opts.sandboxName = deps.getDefaultSandbox();
}

deps.runDebug(opts);
}
16 changes: 16 additions & 0 deletions src/lib/diagnostics/debug.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,22 @@ describe("createTarball", () => {
expect(process.exitCode).toBe(1);
});

it("removes any partial tarball when tar fails", () => {
tempDir = mkdtempSync(join(tmpdir(), "debug-test-"));
writeFileSync(join(tempDir, "payload.txt"), "test data");
outputDir = mkdtempSync(join(tmpdir(), "debug-test-out-"));
const output = join(outputDir, "partial.tar.gz");
// Pre-create a stub file so createTarball can prove it removed a partial.
writeFileSync(output, "stub partial tarball");
// Removing the source dir forces tar to fail without racing in-progress
// collection.
rmSync(tempDir, { recursive: true, force: true });
const ok = createTarball(tempDir, output);
expect(ok).toBe(false);
expect(process.exitCode).toBe(1);
expect(existsSync(output)).toBe(false);
});

it("creates tarball successfully and returns true for valid output path", () => {
tempDir = mkdtempSync(join(tmpdir(), "debug-test-"));
writeFileSync(join(tempDir, "dummy.txt"), "test data");
Expand Down
15 changes: 13 additions & 2 deletions src/lib/diagnostics/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,11 @@ export function createTarball(collectDir: string, output: string): boolean {
? `killed by signal ${result.signal}`
: `exited with code ${result.status ?? "unknown"}`;
error(`Failed to create tarball at ${output} (tar ${reason})`);
try {
rmSync(output, { force: true });
} catch {
/* best-effort cleanup of partial tarball */
}
process.exitCode = 1;
return false;
}
Expand Down Expand Up @@ -558,9 +563,15 @@ export function runDebug(opts: DebugOptions = {}): void {
// Compiled location: dist/lib/diagnostics/debug.js → repo root is 3 levels up
const repoDir = join(__dirname, "..", "..", "..");

// Resolve sandbox name
// Resolve sandbox name. Precedence matches the documented services + debug
// contract in docs/reference/commands.mdx: explicit option > NEMOCLAW_SANDBOX_NAME
// > NEMOCLAW_SANDBOX > SANDBOX_NAME.
let sandboxName =
opts.sandboxName ?? process.env.NEMOCLAW_SANDBOX ?? process.env.SANDBOX_NAME ?? "";
opts.sandboxName ??
process.env.NEMOCLAW_SANDBOX_NAME ??
process.env.NEMOCLAW_SANDBOX ??
process.env.SANDBOX_NAME ??
"";
if (!sandboxName) {
sandboxName = detectSandboxName();
}
Expand Down
55 changes: 52 additions & 3 deletions test/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,11 +279,34 @@ function createCloudflaredServiceDir(prefix: string): { sandboxName: string; ser
return { sandboxName, serviceDir };
}

function createDebugCommandTestEnv(prefix: string): Record<string, string> {
function createDebugCommandTestEnv(
prefix: string,
options: { extraSandboxNames?: string[] } = {},
): Record<string, string> {
const home = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
const localBin = path.join(home, "bin");
const sandboxName = `${prefix}${process.pid.toString(36)}-${Date.now().toString(36)}`;
fs.mkdirSync(localBin, { recursive: true });
// Register the env-sourced sandbox plus any extra names supplied via the
// --sandbox flag so the validation gate accepts them.
writeSandboxRegistry(home, sandboxName);
if (options.extraSandboxNames && options.extraSandboxNames.length > 0) {
const registryPath = path.join(home, ".nemoclaw", "sandboxes.json");
const current = JSON.parse(fs.readFileSync(registryPath, "utf-8")) as {
sandboxes: Record<string, unknown>;
defaultSandbox?: string | null;
};
for (const extra of options.extraSandboxNames) {
current.sandboxes[extra] = {
name: extra,
model: "test-model",
provider: "nvidia-prod",
gpuEnabled: false,
policies: [],
};
}
fs.writeFileSync(registryPath, JSON.stringify(current), { mode: 0o600 });
}
fs.writeFileSync(
path.join(localBin, "openshell"),
[
Expand Down Expand Up @@ -1489,13 +1512,28 @@ describe("CLI dispatch", () => {
it("debug --sandbox NAME targets the specified sandbox", testTimeoutOptions(30_000), () => {
const r = runWithEnv(
"debug --quick --sandbox mybox",
createDebugCommandTestEnv("nemoclaw-cli-debug-sandbox-"),
createDebugCommandTestEnv("nemoclaw-cli-debug-sandbox-", { extraSandboxNames: ["mybox"] }),
30000,
);
expect(r.code).toBe(0);
expect(r.out).toContain("Collecting diagnostics for sandbox 'mybox'");
});

it("debug --sandbox NAME rejects an unregistered name and exits non-zero", () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-debug-unknown-"));
writeSandboxRegistry(home);
const tarball = path.join(home, "out.tar.gz");
const r = runWithEnv(
`debug --sandbox does-not-exist --output ${tarball} 2>&1`,
{ HOME: home },
30000,
);
expect(r.code).not.toBe(0);
expect(r.out).toContain("does-not-exist");
expect(r.out).toContain("not registered");
expect(fs.existsSync(tarball)).toBe(false);
});

it("debug --sandbox without a name exits 1", () => {
const r = run("debug --sandbox");
expect(r.code).not.toBe(0);
Expand All @@ -1522,7 +1560,18 @@ describe("CLI dispatch", () => {
fs.mkdirSync(path.join(home, ".nemoclaw"), { recursive: true });
fs.writeFileSync(
path.join(home, ".nemoclaw", "sandboxes.json"),
JSON.stringify({ sandboxes: {}, defaultSandbox: "ghost" }),
JSON.stringify({
sandboxes: {
mybox: {
name: "mybox",
model: "test-model",
provider: "nvidia-prod",
gpuEnabled: false,
policies: [],
},
},
defaultSandbox: "ghost",
}),
{ mode: 0o600 },
);
const r = runWithEnv("debug --quick --sandbox mybox 2>&1", { HOME: home }, 30000);
Expand Down
Loading
Loading