From c690f07bf3747b706acccfbd1c71db61bedbf035 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:32:40 -0700 Subject: [PATCH 1/7] refactor(openshell): remove diagnostic SSH transport Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 2 - src/commands/debug.ts | 17 ++- src/lib/diagnostics/debug-command.ts | 11 +- .../debug-sandbox-internals.test.ts | 99 +++++++++++++++++ src/lib/diagnostics/debug.ts | 100 ++++++++---------- 5 files changed, 161 insertions(+), 68 deletions(-) create mode 100644 src/lib/diagnostics/debug-sandbox-internals.test.ts diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index 8a758525053..7fc75a525be 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -42,8 +42,6 @@ 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/onboard.ts", "docker-exec-builder", 1], ["src/lib/resources-cmd.ts", "docker-exec-command", 1], ["src/lib/sandbox/config.ts", "privileged-sandbox-exec", 2], diff --git a/src/commands/debug.ts b/src/commands/debug.ts index ba1bfb36d61..6cd25b487e6 100644 --- a/src/commands/debug.ts +++ b/src/commands/debug.ts @@ -2,19 +2,18 @@ // SPDX-License-Identifier: Apache-2.0 import { Flags } from "@oclif/core"; -import { NemoClawCommand } from "../lib/cli/nemoclaw-oclif-command"; - +import type { CaptureOpenshellResult } from "../lib/adapters/openshell/client"; +import { captureOpenshellCommand } from "../lib/adapters/openshell/client"; +import { resolveOpenshell } from "../lib/adapters/openshell/resolve"; +import { OPENSHELL_PROBE_TIMEOUT_MS } from "../lib/adapters/openshell/timeouts"; import { CLI_NAME } from "../lib/cli/branding"; -import { runDebug } from "../lib/diagnostics/debug"; +import { NemoClawCommand } from "../lib/cli/nemoclaw-oclif-command"; import type { DebugOptions } from "../lib/diagnostics/debug"; +import { runDebug } from "../lib/diagnostics/debug"; import type { RunDebugCommandDeps } from "../lib/diagnostics/debug-command"; import { runDebugCommandWithOptions } from "../lib/diagnostics/debug-command"; -import type { CaptureOpenshellResult } from "../lib/adapters/openshell/client"; -import { captureOpenshellCommand } from "../lib/adapters/openshell/client"; -import { OPENSHELL_PROBE_TIMEOUT_MS } from "../lib/adapters/openshell/timeouts"; -import * as registry from "../lib/state/registry"; -import { resolveOpenshell } from "../lib/adapters/openshell/resolve"; import { parseLiveSandboxNames } from "../lib/runtime-recovery"; +import * as registry from "../lib/state/registry"; const useColor = !process.env.NO_COLOR && !!process.stderr.isTTY; const B = useColor ? "\x1b[1m" : ""; @@ -99,6 +98,6 @@ export default class DebugCliCommand extends NemoClawCommand { if (flags.quick) options.quick = true; if (flags.output) options.output = flags.output; if (flags.sandbox) options.sandboxName = flags.sandbox; - runDebugCommandWithOptions(options, buildDebugCommandDeps(this.config.root)); + await runDebugCommandWithOptions(options, buildDebugCommandDeps(this.config.root)); } } diff --git a/src/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..9a8159d3c58 --- /dev/null +++ b/src/lib/diagnostics/debug-sandbox-internals.test.ts @@ -0,0 +1,99 @@ +// 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("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"); + }); +}); diff --git a/src/lib/diagnostics/debug.ts b/src/lib/diagnostics/debug.ts index a41e70d98b5..52aa0f31852 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,55 @@ 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( + `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, + }); + const raw = `${result.stdout}\n${result.stderr}`; + const redacted = redact(raw); + writeFileSync(join(collectDir, `${label}.txt`), redacted); + console.log(redacted.trimEnd()); + if (result.status !== 0) 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 +518,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 +549,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); From e4f1bc037bb444380a3ceae82eeb265dc224432a Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 23:59:18 -0700 Subject: [PATCH 2/7] docs(openshell): include debug fallback caller Signed-off-by: Aaron Erickson --- src/lib/adapters/openshell/sandbox-control-routing.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index c93fc0152af..cae229d02e4 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -78,11 +78,12 @@ export function selectOpenShellSandboxControlForMutation( * so NemoClaw cannot replace that path here. * * This migration contract is limited to the reviewed read-only callers (the - * session list and rebuild file probe at this slice), not a general routing - * policy. Remove the CLI fallback when OpenShell's public client or bindings - * support the edge-tunnel auth and credential-refresh lifecycle. Every added - * caller requires a replay-semantics review; mutations must select one - * transport before dispatch and must never be replayed automatically. + * session list, rebuild file probe, and debug diagnostic probes at this + * slice), not a general routing policy. Remove the CLI fallback when + * OpenShell's public client or bindings support the edge-tunnel auth and + * credential-refresh lifecycle. Every added caller requires a replay-semantics + * review; mutations must select one transport before dispatch and must never + * be replayed automatically. */ export async function execSandboxReadOnlyWithGrpcFallback( gatewayName: string, From d171233752fe30abd2f9a54a86a39716f81e9de0 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 00:09:36 -0700 Subject: [PATCH 3/7] test(debug): cover async command completion Signed-off-by: Aaron Erickson --- .../simple-global-oclif-adapters.test.ts | 9 ++- src/lib/diagnostics/debug-command.test.ts | 67 ++++++++++++++----- 2 files changed, 60 insertions(+), 16 deletions(-) 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/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, From 9c1abfc291837aa9dc78453242859f84b468d236 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 04:07:53 -0700 Subject: [PATCH 4/7] fix(debug): preserve sandbox transport failures Signed-off-by: Aaron Erickson --- .../debug-sandbox-internals.test.ts | 24 +++++++++++++++++++ src/lib/diagnostics/debug.ts | 13 +++++++--- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/lib/diagnostics/debug-sandbox-internals.test.ts b/src/lib/diagnostics/debug-sandbox-internals.test.ts index 9a8159d3c58..1a541cf5261 100644 --- a/src/lib/diagnostics/debug-sandbox-internals.test.ts +++ b/src/lib/diagnostics/debug-sandbox-internals.test.ts @@ -96,4 +96,28 @@ describe("collectSandboxInternals", () => { ); 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: API_KEY=)", + "", + ].join("\n"), + ); + expect(readFileSync(join(collectDir, "sandbox-free.txt"), "utf8")).toBe("free-ok\n"); + }); }); diff --git a/src/lib/diagnostics/debug.ts b/src/lib/diagnostics/debug.ts index 52aa0f31852..f594d7d77c5 100644 --- a/src/lib/diagnostics/debug.ts +++ b/src/lib/diagnostics/debug.ts @@ -409,11 +409,18 @@ export async function collectSandboxInternals( command, timeoutMs: TIMEOUT_MS, }); - const raw = `${result.stdout}\n${result.stderr}`; - const redacted = redact(raw); + const outputParts = [result.stdout, result.stderr] + .filter((value) => value.length > 0) + .map((value) => redact(value)); + if (result.error) { + outputParts.push(` (sandbox command failed: ${redact(result.error.message)})`); + } + const redacted = `${outputParts.join("\n")}\n`; writeFileSync(join(collectDir, `${label}.txt`), redacted); console.log(redacted.trimEnd()); - if (result.status !== 0) console.log(" (command exited with non-zero status)"); + 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)})`); From d071ed4cdb2412dcfbbef789ac7300013da39db0 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 04:14:19 -0700 Subject: [PATCH 5/7] fix(debug): redact combined sandbox streams Signed-off-by: Aaron Erickson --- .../diagnostics/debug-sandbox-internals.test.ts | 17 ++++++++++++++++- src/lib/diagnostics/debug.ts | 11 ++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/lib/diagnostics/debug-sandbox-internals.test.ts b/src/lib/diagnostics/debug-sandbox-internals.test.ts index 1a541cf5261..123c43b622e 100644 --- a/src/lib/diagnostics/debug-sandbox-internals.test.ts +++ b/src/lib/diagnostics/debug-sandbox-internals.test.ts @@ -114,10 +114,25 @@ describe("collectSandboxInternals", () => { [ "partial output", "partial warning", - " (sandbox command failed: API_KEY=)", + " (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 f594d7d77c5..a83e7c4e171 100644 --- a/src/lib/diagnostics/debug.ts +++ b/src/lib/diagnostics/debug.ts @@ -409,13 +409,14 @@ export async function collectSandboxInternals( command, timeoutMs: TIMEOUT_MS, }); - const outputParts = [result.stdout, result.stderr] - .filter((value) => value.length > 0) - .map((value) => redact(value)); + let raw = `${result.stdout}\n${result.stderr}`; if (result.error) { - outputParts.push(` (sandbox command failed: ${redact(result.error.message)})`); + 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 = `${outputParts.join("\n")}\n`; + const redacted = redact(raw); writeFileSync(join(collectDir, `${label}.txt`), redacted); console.log(redacted.trimEnd()); if (result.status !== 0 && !result.error) { From a9297cb17929f66fd8c5803b878dd8623dcbc65c Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 04:29:27 -0700 Subject: [PATCH 6/7] test(checks): review debug gRPC fallback Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 1 + test/legacy-sandbox-transports.test.ts | 25 +++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index 3979a126cee..aeb6c114929 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -46,6 +46,7 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/adapters/docker/container.ts", "docker-exec-command", 1], ["src/lib/adapters/openshell/client.ts", "openshell-ssh-config", 1], ["src/lib/adapters/openshell/runtime.ts", "openshell-ssh-config", 1], + ["src/lib/diagnostics/debug.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/onboard.ts", "docker-exec-builder", 1], ["src/lib/resources-cmd.ts", "docker-exec-command", 1], ["src/lib/sandbox/config.ts", "privileged-sandbox-exec", 2], diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index 4268f288f7e..c9f9f9f10c8 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"; @@ -101,6 +102,30 @@ describe("legacy sandbox transport inventory", () => { ]); }); + it("keeps every reviewed read-only fallback importer explicit", () => { + expect( + REVIEWED_LEGACY_SANDBOX_TRANSPORT_SITES.filter( + (site) => site.kind === "grpc-cli-read-only-fallback", + ), + ).toEqual([ + { + relativePath: "src/lib/actions/sandbox/sessions/passthrough.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + { + relativePath: "src/lib/diagnostics/debug.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + { + relativePath: "src/lib/state/user-managed-files-probe.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + ]); + }); + it("fails closed when a new production file imports the read-only fallback", () => { const root = fixtureRepo({ "src/unreviewed-probe.ts": From 57b096ea3d560dd4e3c15fdbcfa4767b25ac38b0 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 10:34:17 -0700 Subject: [PATCH 7/7] fix(cli): redact debug gateway resolution errors Signed-off-by: Aaron Erickson --- .../diagnostics/debug-sandbox-internals.test.ts | 17 +++++++++++++++++ src/lib/diagnostics/debug.ts | 4 +++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/lib/diagnostics/debug-sandbox-internals.test.ts b/src/lib/diagnostics/debug-sandbox-internals.test.ts index 123c43b622e..2f6191b43f2 100644 --- a/src/lib/diagnostics/debug-sandbox-internals.test.ts +++ b/src/lib/diagnostics/debug-sandbox-internals.test.ts @@ -83,6 +83,23 @@ describe("collectSandboxInternals", () => { 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")) diff --git a/src/lib/diagnostics/debug.ts b/src/lib/diagnostics/debug.ts index a83e7c4e171..00006f55aef 100644 --- a/src/lib/diagnostics/debug.ts +++ b/src/lib/diagnostics/debug.ts @@ -387,7 +387,9 @@ export async function collectSandboxInternals( gatewayName = resolveSandboxGatewayName(sandbox); } catch (cause) { warn( - `Could not resolve the gateway for sandbox '${sandboxName}', skipping internals: ${cause instanceof Error ? cause.message : String(cause)}`, + redact( + `Could not resolve the gateway for sandbox '${sandboxName}', skipping internals: ${cause instanceof Error ? cause.message : String(cause)}`, + ), ); return; }