Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
8c2a1bb
feat(core): add NEMOCLAW_INSTANCE primitive for multi-instance host s…
laitingsheng Jun 11, 2026
0092c8e
fix(core): reject port-like instance segments, migrate local-adapter …
laitingsheng Jun 11, 2026
29e29c8
docs(core): document default and port-based instance fallback chain
laitingsheng Jun 11, 2026
9c7081e
fix(core): default instance name is nemoclaw, not synthetic sentinel
laitingsheng Jun 11, 2026
d9944e8
merge: bring in latest main
laitingsheng Jun 11, 2026
cc75f2b
fix(inference): instance-aware Ollama proxy token reader, restore tes…
laitingsheng Jun 11, 2026
7de390b
docs(core): align instance scope inventory, reformat env-var section …
laitingsheng Jun 11, 2026
36a351a
test(core): runtime call-site coverage for migrated instance surfaces…
laitingsheng Jun 11, 2026
2efd8cb
fix: import downstream exports in runtime tests, narrow scope claim, …
laitingsheng Jun 11, 2026
27e1a98
Merge branch 'main' into feat/3053-nemoclaw-instance-identity
cv Jun 11, 2026
815111f
refactor(gateway): centralise gateway-name literal, resolve per-sandb…
laitingsheng Jun 11, 2026
bf23f79
merge: latest remote feat branch
laitingsheng Jun 11, 2026
fd4ed73
merge: latest main
laitingsheng Jun 11, 2026
7b76a22
refactor(gateway): drop unrelated cleanup, keep sandbox-scoped fix
laitingsheng Jun 11, 2026
7dc3c67
fix(sandbox): route gateway commands to sandbox's registered gateway
laitingsheng Jun 11, 2026
cfde925
fix(sandbox): extract gateway routing, validate persisted names, rout…
laitingsheng Jun 11, 2026
56ec87b
fix(sandbox): honor sandbox gateway during recovery
cv Jun 12, 2026
7890e56
refactor(onboard): extract gateway recovery module
cv Jun 12, 2026
3d93eee
Merge remote-tracking branch 'origin/main' into feat/3053-nemoclaw-in…
cv Jun 12, 2026
b99fb20
fix(sandbox): fail closed for cross-gateway restore
cv Jun 12, 2026
7fc6891
fix(sandbox): select persisted gateway before destroy
cv Jun 12, 2026
05b097c
refactor(sandbox): extract destroy gateway helpers
cv Jun 12, 2026
506e45e
fix(sandbox): fail closed on snapshot gateway selection
cv Jun 12, 2026
a85b005
fix(sandbox): fail closed on invalid gateway bindings, dedupe dashboa…
laitingsheng Jun 12, 2026
3a43504
Merge remote-tracking branch 'origin/main' into feat/3053-nemoclaw-in…
laitingsheng Jun 12, 2026
a1ce42c
style(sandbox): apply biome formatting to recovery state list
laitingsheng Jun 12, 2026
507a3a5
fix(sandbox): route per-sandbox gateway through hints and recovery st…
laitingsheng Jun 12, 2026
3c17076
fix(sandbox): respect post-select lifecycle, per-port host PID, sandb…
laitingsheng Jun 12, 2026
618de7e
refactor(onboard): extract dashboard-port reservation helper
laitingsheng Jun 12, 2026
3c3c120
Merge remote-tracking branch 'origin/main' into feat/3053-nemoclaw-in…
laitingsheng Jun 12, 2026
bd9e8b8
test(e2e): surface captured onboard output in phase diagnostics
laitingsheng Jun 12, 2026
4b38352
style(sandbox): apply biome formatting to rebuild-gateway-drift test
laitingsheng Jun 12, 2026
b4e1379
revert(onboard): drop multi-instance dashboard-port reservation
laitingsheng Jun 13, 2026
56d641e
Merge branch 'main' into feat/3053-nemoclaw-instance-identity
cv Jun 13, 2026
aef283d
fix(sandbox): resolve gateway via persisted port default and fail clo…
laitingsheng Jun 13, 2026
71230da
Merge remote-tracking branch 'origin/main' into feat/3053-nemoclaw-in…
laitingsheng Jun 13, 2026
2ac0045
test(onboard): stub Linux Docker-driver flag in gateway recovery tests
laitingsheng Jun 13, 2026
428f20b
style(onboard): apply biome formatting to gateway-recovery test
laitingsheng Jun 13, 2026
36499bd
Merge remote-tracking branch 'origin/main' into feat/3053-nemoclaw-in…
laitingsheng Jun 13, 2026
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
14 changes: 12 additions & 2 deletions src/lib/actions/gateway-drift-preflight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,12 @@ describe("gateway drift preflight for maintenance actions", () => {
await backupAll();

expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({
recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable"],
recoverableStates: [
"missing_named",
"named_unhealthy",
"named_unreachable",
"connected_other",
],
});
expect(captureOpenshellSpy).toHaveBeenCalledTimes(2);
expect(captureOpenshellSpy).toHaveBeenNthCalledWith(1, ["sandbox", "list"]);
Expand Down Expand Up @@ -258,7 +263,12 @@ describe("gateway drift preflight for maintenance actions", () => {
await upgradeSandboxes({ check: true });

expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({
recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable"],
recoverableStates: [
"missing_named",
"named_unhealthy",
"named_unreachable",
"connected_other",
],
});
expect(captureOpenshellSpy).toHaveBeenCalledTimes(2);
expect(classifyUpgradeableSandboxesSpy).toHaveBeenCalledWith(
Expand Down
13 changes: 8 additions & 5 deletions src/lib/actions/sandbox/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import {
import { findReachableOllamaHost, probeLocalProviderHealth } from "../../inference/local";
import { ensureOllamaAuthProxy, probeOllamaAuthProxyHealth } from "../../inference/ollama/proxy";
import { LOCAL_INFERENCE_TIMEOUT_SECS } from "../../onboard/env";
import { resolveSandboxGatewayName } from "../../onboard/gateway-binding";
import { getSandboxTargetGatewayName } from "./gateway-target";
import { isWsl } from "../../platform";
import { ROOT } from "../../runner";
import * as sandboxVersion from "../../sandbox/version";
Expand Down Expand Up @@ -54,8 +56,6 @@ import { ensureLiveSandboxOrExit, printGatewayLifecycleHint } from "./gateway-st
import { checkAndRecoverSandboxProcesses } from "./process-recovery";
import { applyOpenShellVmDnsMonkeypatch, shouldApplyVmDnsMonkeypatch } from "./vm-dns-monkeypatch";

const NEMOCLAW_GATEWAY_NAME = "nemoclaw";

export type SandboxConnectOptions = {
probeOnly?: boolean;
};
Expand Down Expand Up @@ -253,7 +253,9 @@ function failConnectReadinessGatewayUnavailable(sandboxName: string, detailOutpu
printGatewayLifecycleHint(detailOutput, sandboxName, console.error);
}
console.error(" Recovery:");
console.error(" 1. Run: openshell gateway start --name nemoclaw");
console.error(
` 1. Run: openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}`,
);
console.error(` 2. If the gateway cannot be restarted, run: ${CLI_NAME} onboard`);
console.error(` 3. Retry: ${CLI_NAME} ${sandboxName} connect`);
process.exit(1);
Expand All @@ -273,7 +275,8 @@ function failConnectReadinessDockerRuntimeDown(sandboxName: string): never {
}

function failIfGatewayBlocksConnectReadiness(sandboxName: string): void {
const lifecycle = getNamedGatewayLifecycleState();
const sb = registry.getSandbox(sandboxName);
const lifecycle = getNamedGatewayLifecycleState(resolveSandboxGatewayName(sb));
if (isBlockingGatewayLifecycle(lifecycle)) {
failConnectReadinessGatewayUnavailable(
sandboxName,
Expand Down Expand Up @@ -512,7 +515,7 @@ function repairSandboxInferenceRouteIfNeeded(
reapplyVmInferenceRoute,
repairLegacyDnsProxy: (name, isQuiet) =>
runSetupDnsProxy(
{ gatewayName: NEMOCLAW_GATEWAY_NAME, sandboxName: name },
{ gatewayName: resolveSandboxGatewayName(sb), sandboxName: name },
{ log: isQuiet ? () => undefined : console.log },
),
},
Expand Down
117 changes: 117 additions & 0 deletions src/lib/actions/sandbox/destroy-gateway.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import os from "node:os";
import path from "node:path";

import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts";
import { DASHBOARD_PORT } from "../../core/ports";
import {
resolveGatewayPortFromName,
resolveGatewayStateDirName,
} from "../../onboard/gateway-binding";
import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process";
import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup";

export type DestroyRunOpenshell = (
args: string[],
opts?: Record<string, unknown>,
) => { status: number | null; stdout?: string; stderr?: string };

const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT);

// Compute the Docker-driver gateway state directory that belongs to
// `gatewayName`. `stopHostGatewayProcesses` defaults to the bare leaf
// `openshell-docker-gateway`, so without this override a destroy of a
// `nemoclaw-<port>` sandbox would read the default instance's pid file and
// stop the wrong host gateway process. Returns null when the gateway name is
// outside the NemoClaw namespace (the caller then keeps the defaults).
function resolvePerGatewayStateDir(gatewayName: string): string | null {
const port = resolveGatewayPortFromName(gatewayName);
if (port === null) return null;
const configured = process.env.NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR;
if (configured && configured.trim()) {
return path.resolve(configured.trim());
}
return path.join(os.homedir(), ".local", "state", "nemoclaw", resolveGatewayStateDirName(port));
}

export function selectGatewayForSandboxDestroy(
sandboxName: string,
gatewayName: string,
runOpenshell: DestroyRunOpenshell,
): void {
const result = runOpenshell(["gateway", "select", gatewayName], {
ignoreError: true,
stdio: ["ignore", "pipe", "pipe"],
timeout: OPENSHELL_OPERATION_TIMEOUT_MS,
});
if (result.status === 0) return;

const output = [result.stdout, result.stderr].filter(Boolean).join("\n").trim();
if (output) {
console.error(` ${output}`);
}
console.error(
` Failed to select gateway '${gatewayName}' before destroying sandbox '${sandboxName}'.`,
);
process.exit(result.status || 1);
}

export function cleanupGatewayAfterLastSandbox(
gatewayName: string,
runOpenshell?: DestroyRunOpenshell,
): void {
const openshell =
runOpenshell ??
(require("../../adapters/openshell/runtime") as { runOpenshell: DestroyRunOpenshell })
.runOpenshell;
const { dockerRemoveVolumesByPrefix } = require("../../adapters/docker") as {
dockerRemoveVolumesByPrefix: (prefix: string, opts?: { ignoreError?: boolean }) => void;
};

openshell(["forward", "stop", DASHBOARD_FORWARD_PORT], {
ignoreError: true,
stdio: ["ignore", "ignore", "ignore"],
});
// After the cooperative forward-stop, sweep the dashboard port range for
// stale host-side gateway-forward processes. The forward-stop above releases
// ports the live openshell tracks; this catches orphans whose openshell
// record was lost across upgrades or failed onboards.
stopStaleDashboardListeners();
if (process.platform === "linux") {
// Sandbox destroy is conservative: only stop the host gateway whose PID
// file we wrote during onboard. Disable the pgrep sweep so a stray
// openshell-gateway under another user/project on the same host (rare but
// possible on shared hosts) is not torn down by a NemoClaw `destroy`.
// The uninstall path keeps the broader sweep on (run-plan.ts). The state
// dir is per-gateway-name so a destroy of `nemoclaw-<port>` reads the
// per-port pid file rather than defaulting to the bare instance's.
const perGatewayStateDir = resolvePerGatewayStateDir(gatewayName);
const stopOptions: { usePgrepFallback: false; stateDir?: string; pidFile?: string } = {
usePgrepFallback: false,
};
if (perGatewayStateDir) {
stopOptions.stateDir = perGatewayStateDir;
stopOptions.pidFile = path.join(perGatewayStateDir, "openshell-gateway.pid");
}
stopHostGatewayProcesses({}, stopOptions);
const removeResult = openshell(["gateway", "remove", gatewayName], {
ignoreError: true,
stdio: ["ignore", "pipe", "pipe"],
});
if (removeResult.status !== 0) {
openshell(["gateway", "destroy", "-g", gatewayName], {
ignoreError: true,
stdio: ["ignore", "pipe", "pipe"],
});
}
} else {
openshell(["gateway", "destroy", "-g", gatewayName], {
ignoreError: true,
});
}
dockerRemoveVolumesByPrefix(`openshell-cluster-${gatewayName}`, {
ignoreError: true,
});
}
75 changes: 18 additions & 57 deletions src/lib/actions/sandbox/destroy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { resolveOpenshell } from "../../adapters/openshell/resolve";
import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts";
import { CLI_NAME } from "../../cli/branding";
import { G, R, YW } from "../../cli/terminal-style";
import { DASHBOARD_PORT } from "../../core/ports";
import { prompt as askPrompt } from "../../credentials/store";
import {
type DestroySandboxOptions,
Expand All @@ -19,8 +18,6 @@ import {
shouldCleanupGatewayAfterDestroy,
shouldStopHostServicesAfterDestroy,
} from "../../domain/sandbox/destroy";
import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup";
import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process";
import {
SANDBOX_PROVIDER_SUFFIXES,
emitProviderDetachResidualHint,
Expand All @@ -37,6 +34,12 @@ import {
createSystemDeps as createSessionDeps,
getActiveSandboxSessions,
} from "../../state/sandbox-session";
import {
cleanupGatewayAfterLastSandbox,
type DestroyRunOpenshell,
selectGatewayForSandboxDestroy,
} from "./destroy-gateway";
import { getSandboxTargetGatewayName } from "./gateway-target";

type DockerRmi = (tag: string, opts?: { ignoreError?: boolean }) => { status: number | null };

Expand Down Expand Up @@ -76,53 +79,6 @@ type RemoveShieldsStateDeps = {
warn?: (message: string) => void;
};

const NEMOCLAW_GATEWAY_NAME = "nemoclaw";
const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT);

function cleanupGatewayAfterLastSandbox(): void {
const { runOpenshell } = require("../../adapters/openshell/runtime") as {
runOpenshell: (args: string[], opts?: Record<string, unknown>) => { status: number | null };
};
const { dockerRemoveVolumesByPrefix } = require("../../adapters/docker") as {
dockerRemoveVolumesByPrefix: (prefix: string, opts?: { ignoreError?: boolean }) => void;
};

runOpenshell(["forward", "stop", DASHBOARD_FORWARD_PORT], {
ignoreError: true,
stdio: ["ignore", "ignore", "ignore"],
});
// After the cooperative forward-stop, sweep the dashboard port range for
// stale host-side gateway-forward processes (#3397, #3398). The forward-stop
// above releases ports the live openshell tracks; this catches orphans whose
// openshell record was lost across upgrades or failed onboards.
stopStaleDashboardListeners();
if (process.platform === "linux") {
// Sandbox destroy is conservative: only stop the host gateway whose PID
// file we wrote during onboard. Disable the pgrep sweep so a stray
// openshell-gateway under another user/project on the same host (rare but
// possible on shared hosts) is not torn down by a NemoClaw `destroy`.
// The uninstall path keeps the broader sweep on (run-plan.ts).
stopHostGatewayProcesses({}, { usePgrepFallback: false });
const removeResult = runOpenshell(["gateway", "remove", NEMOCLAW_GATEWAY_NAME], {
ignoreError: true,
stdio: ["ignore", "pipe", "pipe"],
});
if (removeResult.status !== 0) {
runOpenshell(["gateway", "destroy", "-g", NEMOCLAW_GATEWAY_NAME], {
ignoreError: true,
stdio: ["ignore", "pipe", "pipe"],
});
}
} else {
runOpenshell(["gateway", "destroy", "-g", NEMOCLAW_GATEWAY_NAME], {
ignoreError: true,
});
}
dockerRemoveVolumesByPrefix(`openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`, {
ignoreError: true,
});
}

// Mirrors the body of `isNonInteractive()` in src/lib/onboard.ts. Duplicated
// here to avoid an awkward sibling-action -> onboard import; the canonical
// helper should be lifted to src/lib/core/ so this and the lazy requires in
Expand Down Expand Up @@ -403,11 +359,13 @@ export async function destroySandbox(

console.log(` Deleting sandbox '${sandboxName}'...`);
const { runOpenshell } = require("../../adapters/openshell/runtime") as {
runOpenshell: (
args: string[],
opts?: Record<string, unknown>,
) => { status: number | null; stdout?: string; stderr?: string };
runOpenshell: DestroyRunOpenshell;
};
// Capture and select the sandbox's gateway before any destructive OpenShell
// operation. Provider cleanup and sandbox delete must address the gateway
// recorded for this sandbox, not whichever gateway happens to be active.
const cleanupGatewayName = getSandboxTargetGatewayName(sandboxName);
selectGatewayForSandboxDestroy(sandboxName, cleanupGatewayName, runOpenshell);
const detachOutcome = runSandboxProviderPreDeleteCleanup(sandboxName, {
runOpenshell,
redact,
Expand Down Expand Up @@ -437,6 +395,9 @@ export async function destroySandbox(
stopHostServices: shouldStopHostServices,
});
cleanupShieldsDestroyArtifacts(sandboxName);
// The sandbox's gateway was captured before the registry entry is removed —
// post-removal lookups return null and would collapse the cleanup target
// back to the default gateway.
const removed = removeSandboxRegistryEntry(sandboxName);
const session = onboardSession.loadSession();
if (session && session.sandboxName === sandboxName) {
Expand All @@ -455,12 +416,12 @@ export async function destroySandbox(
) {
const shouldCleanupGateway = await resolveCleanupGatewayDecision(normalized);
if (shouldCleanupGateway) {
cleanupGatewayAfterLastSandbox();
cleanupGatewayAfterLastSandbox(cleanupGatewayName, runOpenshell);
} else {
const gatewayRemovalHint =
process.platform === "linux"
? `openshell gateway remove ${NEMOCLAW_GATEWAY_NAME}`
: `openshell gateway destroy -g ${NEMOCLAW_GATEWAY_NAME}`;
? `openshell gateway remove ${cleanupGatewayName}`
: `openshell gateway destroy -g ${cleanupGatewayName}`;
console.log(
` Shared NemoClaw gateway preserved. Re-run '${gatewayRemovalHint}' to remove it,`,
);
Expand Down
1 change: 1 addition & 0 deletions src/lib/actions/sandbox/doctor-gateway-fallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { captureHostCommand, type CommandCapture } from "./doctor-host-command";

export type GatewayInspectOptions = {
namedGatewayConnected?: boolean;
gatewayName?: string;
};

type LocalGatewayProbe = {
Expand Down
19 changes: 11 additions & 8 deletions src/lib/actions/sandbox/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { recoverNamedGatewayRuntime } from "../../gateway-runtime-action";
import { parseGatewayInference } from "../../inference/config";
import { type ProviderHealthStatus, probeProviderHealth } from "../../inference/health";
import { isLinuxDockerDriverGatewayEnabled } from "../../onboard/docker-driver-platform";
import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding";
import { executeSandboxCommandForVerification } from "../../onboard/sandbox-verification-exec";
import { ROOT } from "../../runner";
import { parseLiveSandboxNames } from "../../runtime-recovery";
Expand All @@ -37,8 +38,6 @@ import { captureHostCommand } from "./doctor-host-command";
import { buildToolScopeChecks } from "./doctor-tool-scope";
import { probeSandboxInferenceGatewayHealth } from "./process-recovery";

const NEMOCLAW_GATEWAY_NAME = "nemoclaw";

type DoctorStatus = "ok" | "warn" | "fail" | "info";

export type DoctorCheck = {
Expand Down Expand Up @@ -193,7 +192,7 @@ function dockerInspectGateway(
detail: `${containerName} ${running ? "running" : "stopped"} (${health}; ${image})`,
hint: running
? undefined
: "restart the gateway with `openshell gateway start --name nemoclaw`",
: `restart the gateway with \`openshell gateway start --name ${options.gatewayName ?? "nemoclaw"}\``,
});

const port = captureHostCommand("docker", ["port", containerName, "30051/tcp"], 5000);
Expand Down Expand Up @@ -550,6 +549,7 @@ export async function runSandboxDoctor(
}

const sb = registry.getSandbox(sandboxName);
const gatewayName = sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT);
const checks: DoctorCheck[] = [];
// Tracks whether the named sandbox is present-and-Ready, so live-only probes
// (e.g. the #4616 dashboard tool-scope diagnostic) only run when they can
Expand Down Expand Up @@ -594,7 +594,7 @@ export async function runSandboxDoctor(

let openshellConnected = false;
if (openshellBin) {
const recovery = await recoverNamedGatewayRuntime();
const recovery = await recoverNamedGatewayRuntime({ gatewayName });
const lifecycle = recovery.after || recovery.before;
const cleanStatus = stripAnsi(lifecycle?.status || "");
openshellConnected = lifecycle?.state === "healthy_named";
Expand All @@ -603,16 +603,19 @@ export async function runSandboxDoctor(
label: "OpenShell status",
status: openshellConnected ? "ok" : "fail",
detail: openshellConnected
? "connected to nemoclaw"
: oneLine(cleanStatus || lifecycle?.gatewayInfo || "not connected to nemoclaw"),
hint: openshellConnected ? undefined : "run `openshell gateway select nemoclaw` and retry",
? `connected to ${gatewayName}`
: oneLine(cleanStatus || lifecycle?.gatewayInfo || `not connected to ${gatewayName}`),
hint: openshellConnected
? undefined
: `run \`openshell gateway select ${gatewayName}\` and retry`,
});
}

if (shouldInspectLegacyGatewayContainer(sb)) {
checks.push(
...dockerInspectGateway(`openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`, {
...dockerInspectGateway(`openshell-cluster-${gatewayName}`, {
namedGatewayConnected: openshellConnected,
gatewayName,
}),
);
}
Expand Down
Loading
Loading