From 8c2a1bb681a81073f946779db4456d9ec0999042 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 13:18:52 +0000 Subject: [PATCH 01/29] feat(core): add NEMOCLAW_INSTANCE primitive for multi-instance host segregation Signed-off-by: Tinson Lai --- docs/reference/commands.mdx | 3 + src/lib/core/instance.test.ts | 72 ++++++++++++++++++++ src/lib/core/instance.ts | 67 +++++++++++++++++++ src/lib/credentials/store.ts | 12 +++- src/lib/onboard/gateway-binding.test.ts | 74 ++++++++++++++++++--- src/lib/onboard/gateway-binding.ts | 87 +++++++++++++++---------- src/lib/state/paths.test.ts | 58 ++++++++++++++++- src/lib/state/paths.ts | 30 ++++++++- src/lib/state/sandbox.ts | 10 ++- 9 files changed, 361 insertions(+), 52 deletions(-) create mode 100644 src/lib/core/instance.test.ts create mode 100644 src/lib/core/instance.ts diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 22270cafd6d..345eeb22db3 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1817,10 +1817,13 @@ All ports must be non-privileged integers between 1024 and 65535. | `NEMOCLAW_OLLAMA_PORT` | 11434 | Ollama inference | | `NEMOCLAW_OLLAMA_PROXY_PORT` | 11435 | Ollama auth proxy | | `NEMOCLAW_DASHBOARD_BIND` | *unset* (loopback) | Dashboard or API forward bind address. Set to `0.0.0.0` to opt in to remote bind for SSH-deployed hosts. | +| `NEMOCLAW_INSTANCE` | `default` | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | If a port value is not a valid integer or falls outside the allowed range, the CLI exits with an error. `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` values, NemoClaw derives a separate gateway name, state directory, and compatibility container name from the port so one gateway does not tear down another. + +`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). The default instance keeps the original `~/.nemoclaw` state root and `nemoclaw` gateway name verbatim, so existing single-instance deployments observe no change. Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` scopes the credentials directory, rebuild backups, and gateway binding to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Full per-instance segregation of registry, snapshots, and messaging is tracked separately as follow-up. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/src/lib/core/instance.test.ts b/src/lib/core/instance.test.ts new file mode 100644 index 00000000000..3e2183646cc --- /dev/null +++ b/src/lib/core/instance.test.ts @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + DEFAULT_NEMOCLAW_INSTANCE, + isDefaultInstance, + parseInstanceName, +} from "../../../dist/lib/core/instance"; + +describe("parseInstanceName", () => { + const ENV_KEY = "TEST_NEMOCLAW_INSTANCE"; + + beforeEach(() => { + delete process.env[ENV_KEY]; + }); + + afterEach(() => { + delete process.env[ENV_KEY]; + }); + + it.each([ + ["an unset env var", undefined, DEFAULT_NEMOCLAW_INSTANCE], + ["an empty env var", "", DEFAULT_NEMOCLAW_INSTANCE], + ["surrounding whitespace then empty", " ", DEFAULT_NEMOCLAW_INSTANCE], + ["a valid lower-case slug", "agent-a", "agent-a"], + ["a numeric tail", "tenant1", "tenant1"], + ["mixed case input is normalised", "Agent-B", "agent-b"], + ["trims surrounding whitespace", " primary ", "primary"], + ["a single character", "a", "a"], + ["the maximum length", "a".repeat(32), "a".repeat(32)], + ] as const)("parses %s", (_label, value, expected) => { + if (value !== undefined) { + process.env[ENV_KEY] = value; + } + + expect(parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE)).toBe(expected); + }); + + it.each([ + ["leading hyphen", "-foo"], + ["trailing hyphen", "foo-"], + ["double hyphen-only", "--"], + ["whitespace inside", "agent a"], + ["filesystem separator", "agent/a"], + ["dot separator", "agent.a"], + ["underscore", "agent_a"], + ["unicode", "agentü"], + ["overlong slug", "a".repeat(33)], + ] as const)("rejects %s", (_label, value) => { + process.env[ENV_KEY] = value; + expect(() => parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE)).toThrow( + /Invalid instance name/, + ); + }); + + it("falls back to a non-default fallback when the env var is unset", () => { + expect(parseInstanceName(ENV_KEY, "primary")).toBe("primary"); + }); +}); + +describe("isDefaultInstance", () => { + it("recognises the default instance", () => { + expect(isDefaultInstance(DEFAULT_NEMOCLAW_INSTANCE)).toBe(true); + }); + + it("rejects any other name", () => { + expect(isDefaultInstance("agent-a")).toBe(false); + expect(isDefaultInstance("")).toBe(false); + expect(isDefaultInstance("primary")).toBe(false); + }); +}); diff --git a/src/lib/core/instance.ts b/src/lib/core/instance.ts new file mode 100644 index 00000000000..d2ddb8a4110 --- /dev/null +++ b/src/lib/core/instance.ts @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * NemoClaw instance identity primitive. + * + * Historically NemoClaw treated the host-side installation as a process-global + * singleton: one gateway named `nemoclaw`, one state root at `~/.nemoclaw`, one + * registry/credentials/snapshot tree. Two NemoClaw-managed sandboxes on the + * same host therefore had to share that tree even when the user wanted full + * segregation (billing isolation, A/B model testing, multi-tenant POCs). + * + * `NEMOCLAW_INSTANCE` makes the instance identity configurable. The default + * instance keeps every existing on-disk path and gateway name verbatim so + * single-instance deployments are unaffected; a non-default instance gets a + * suffixed state root and gateway name so two instances never collide. + * + * This module is the single source of truth for resolving the active instance + * name; downstream callers (state root, gateway-name resolver, credentials + * store, rebuild-backups dir) thread the resolved value through their own + * paths rather than parsing the env var directly. + */ + +/** Reserved name representing today's singleton behaviour. */ +export const DEFAULT_NEMOCLAW_INSTANCE = "default"; + +/** + * Lower-case alphanumeric slug with internal `-`. Must start and end with an + * alphanumeric so it composes safely into filesystem names, gateway-name + * strings, and container names. + */ +const INSTANCE_NAME_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/; + +/** + * Validate an instance-name candidate. Returns the trimmed lower-case name if + * valid, or throws with a stable error message that callers can surface to the + * user verbatim. Empty input resolves to {@link DEFAULT_NEMOCLAW_INSTANCE} so + * `NEMOCLAW_INSTANCE=""` and an unset variable behave the same. + */ +export function parseInstanceName(envVar: string, fallback: string): string { + const raw = process.env[envVar]; + if (raw === undefined || raw === "") return fallback; + const trimmed = String(raw).trim().toLowerCase(); + if (trimmed === "") return fallback; + if (!INSTANCE_NAME_RE.test(trimmed)) { + throw new Error( + `Invalid instance name: ${envVar}="${raw}" — must be 1–32 lower-case ` + + `alphanumerics with internal '-' (e.g. "agent-a", "tenant1")`, + ); + } + return trimmed; +} + +/** Whether the supplied instance name refers to today's singleton tree. */ +export function isDefaultInstance(name: string): boolean { + return name === DEFAULT_NEMOCLAW_INSTANCE; +} + +/** + * Active NemoClaw instance name resolved at module load. Read from + * `NEMOCLAW_INSTANCE`; falls back to {@link DEFAULT_NEMOCLAW_INSTANCE}. + * + * Callers needing test-time overrides should call {@link parseInstanceName} + * directly against an explicit env-var name rather than re-reading this + * constant, since this value is captured once per process. + */ +export const NEMOCLAW_INSTANCE = parseInstanceName("NEMOCLAW_INSTANCE", DEFAULT_NEMOCLAW_INSTANCE); diff --git a/src/lib/credentials/store.ts b/src/lib/credentials/store.ts index 8464633e7cc..cd543b06377 100644 --- a/src/lib/credentials/store.ts +++ b/src/lib/credentials/store.ts @@ -15,6 +15,7 @@ import readline from "node:readline"; import { isErrnoException } from "../core/errno"; import { rejectSymlinksOnPath } from "../state/config-io"; +import { resolveNemoclawHomeDir } from "../state/paths"; const UNSAFE_HOME_PATHS = new Set(["/tmp", "/var/tmp", "/dev/shm", "/"]); @@ -117,15 +118,20 @@ let _cachedHome: string | null = null; let _credsDir: string | null = null; let _legacyCredsFile: string | null = null; -/** Return `~/.nemoclaw`, resolving and validating `HOME` once per process. */ +/** + * Return the active-instance NemoClaw home directory (e.g. `~/.nemoclaw` for + * the default instance, `~/.nemoclaw-` otherwise). The host-side + * gateway is the system of record for credentials; this path is retained only + * for the pre-migration plaintext credentials file the legacy stager reads. + */ export function getCredsDir(): string { const home = resolveHomeDir(); if (_cachedHome !== home) { _cachedHome = home; - _credsDir = path.join(home, ".nemoclaw"); + _credsDir = resolveNemoclawHomeDir(home); _legacyCredsFile = null; } - return _credsDir || path.join(home, ".nemoclaw"); + return _credsDir || resolveNemoclawHomeDir(home); } /** diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 3833cde0516..13d1ca42af7 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -24,26 +24,80 @@ import { } from "../../../dist/lib/onboard/gateway-binding"; describe("gateway-binding resolver (#4422)", () => { - it("keeps the bare nemoclaw names for the default gateway port", () => { - expect(resolveGatewayName(DEFAULT_GATEWAY_PORT)).toBe(BASE_GATEWAY_NAME); - expect(resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT)).toBe(BASE_GATEWAY_STATE_DIR_NAME); - expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT)).toBe( + const DEFAULT_INSTANCE = "default"; + + it("keeps the bare nemoclaw names for the default instance on the default gateway port", () => { + expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, DEFAULT_INSTANCE)).toBe(BASE_GATEWAY_NAME); + expect(resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT, DEFAULT_INSTANCE)).toBe( + BASE_GATEWAY_STATE_DIR_NAME, + ); + expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, DEFAULT_INSTANCE)).toBe( BASE_GATEWAY_COMPAT_CONTAINER_NAME, ); }); it("suffixes the name, state dir, and compat container for a non-default port", () => { - expect(resolveGatewayName(8081)).toBe("nemoclaw-8081"); - expect(resolveGatewayStateDirName(8081)).toBe("openshell-docker-gateway-8081"); - expect(resolveGatewayCompatContainerName(8081)).toBe("nemoclaw-openshell-gateway-8081"); + expect(resolveGatewayName(8081, DEFAULT_INSTANCE)).toBe("nemoclaw-8081"); + expect(resolveGatewayStateDirName(8081, DEFAULT_INSTANCE)).toBe( + "openshell-docker-gateway-8081", + ); + expect(resolveGatewayCompatContainerName(8081, DEFAULT_INSTANCE)).toBe( + "nemoclaw-openshell-gateway-8081", + ); }); it("derives distinct bindings for two different gateway ports", () => { const a = 8080; const b = 8081; - expect(resolveGatewayName(a)).not.toBe(resolveGatewayName(b)); - expect(resolveGatewayStateDirName(a)).not.toBe(resolveGatewayStateDirName(b)); - expect(resolveGatewayCompatContainerName(a)).not.toBe(resolveGatewayCompatContainerName(b)); + expect(resolveGatewayName(a, DEFAULT_INSTANCE)).not.toBe( + resolveGatewayName(b, DEFAULT_INSTANCE), + ); + expect(resolveGatewayStateDirName(a, DEFAULT_INSTANCE)).not.toBe( + resolveGatewayStateDirName(b, DEFAULT_INSTANCE), + ); + expect(resolveGatewayCompatContainerName(a, DEFAULT_INSTANCE)).not.toBe( + resolveGatewayCompatContainerName(b, DEFAULT_INSTANCE), + ); + }); +}); + +describe("gateway-binding resolver factors NEMOCLAW_INSTANCE (#3053)", () => { + const DEFAULT_INSTANCE = "default"; + + it("suffixes the gateway name with the instance for a non-default instance on the default port", () => { + expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, "agent-a")).toBe("nemoclaw-agent-a"); + expect(resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT, "agent-a")).toBe( + "openshell-docker-gateway-agent-a", + ); + expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, "agent-a")).toBe( + "nemoclaw-openshell-gateway-agent-a", + ); + }); + + it("composes instance and port suffixes when both are non-default", () => { + expect(resolveGatewayName(8081, "agent-a")).toBe("nemoclaw-agent-a-8081"); + expect(resolveGatewayStateDirName(8081, "agent-a")).toBe( + "openshell-docker-gateway-agent-a-8081", + ); + expect(resolveGatewayCompatContainerName(8081, "agent-a")).toBe( + "nemoclaw-openshell-gateway-agent-a-8081", + ); + }); + + it("segregates two non-default instances even on the same default port", () => { + expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, "agent-a")).not.toBe( + resolveGatewayName(DEFAULT_GATEWAY_PORT, "agent-b"), + ); + expect(resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT, "agent-a")).not.toBe( + resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT, "agent-b"), + ); + expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, "agent-a")).not.toBe( + resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, "agent-b"), + ); + }); + + it("preserves the bare nemoclaw names when the instance is left at default", () => { + expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, DEFAULT_INSTANCE)).toBe(BASE_GATEWAY_NAME); }); }); diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index d726947b61d..596e703689e 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 /** - * Per-gateway-port binding resolver. + * Per-instance / per-gateway-port binding resolver. * * Historically NemoClaw treated the OpenShell gateway as a process-global * singleton named `nemoclaw`, with a single Docker-driver state directory and @@ -12,59 +12,80 @@ * creating the second sandbox recreated/killed the first sandbox's gateway and * overwrote its runtime marker (#4422). * - * These pure resolvers derive a stable per-port binding. The default port - * keeps the original `nemoclaw` names verbatim so existing single-sandbox - * deployments and on-disk state are untouched; any non-default port gets a - * `-` suffixed name/dir/container so two sandboxes on distinct gateway - * ports never collide. + * These pure resolvers derive a stable per-binding identity along two + * independent axes: + * + * 1. **Gateway port** — the original `nemoclaw-` suffix introduced for + * `NEMOCLAW_GATEWAY_PORT` (#4422). The default port keeps the bare + * `nemoclaw` name verbatim for backward compatibility. + * 2. **NemoClaw instance** — the `NEMOCLAW_INSTANCE` identity that scopes the + * entire host-side install (state root, gateway name, lifecycle). The + * default instance keeps the bare `nemoclaw` name verbatim; any other + * instance is prefixed (`nemoclaw-` / `nemoclaw--`) + * so two instances never collide even on the default port. + * + * Both axes default to the singleton tree so existing single-instance, + * default-port deployments observe no name change. */ import { DEFAULT_GATEWAY_PORT } from "../core/ports"; +import { isDefaultInstance, NEMOCLAW_INSTANCE } from "../core/instance"; import type { GatewayReuseState } from "../state/gateway"; -/** Gateway registration name used for the default gateway port. */ +/** Gateway registration name used for the default instance and default port. */ export const BASE_GATEWAY_NAME = "nemoclaw"; -/** Docker-driver gateway state directory leaf name for the default port. */ +/** Docker-driver gateway state directory leaf name for the default binding. */ export const BASE_GATEWAY_STATE_DIR_NAME = "openshell-docker-gateway"; -/** Docker-driver gateway compatibility container name for the default port. */ +/** Docker-driver gateway compatibility container name for the default binding. */ export const BASE_GATEWAY_COMPAT_CONTAINER_NAME = "nemoclaw-openshell-gateway"; function isDefaultGatewayPort(port: number): boolean { return port === DEFAULT_GATEWAY_PORT; } +function bindingSuffix(port: number, instance: string): string { + const parts: string[] = []; + if (!isDefaultInstance(instance)) parts.push(instance); + if (!isDefaultGatewayPort(port)) parts.push(String(port)); + return parts.length === 0 ? "" : `-${parts.join("-")}`; +} + /** - * Resolve the OpenShell gateway registration name for a gateway port. The - * default port keeps the bare `nemoclaw` name for backward compatibility; any - * other port gets a `nemoclaw-` name so its lifecycle commands - * (add/select/remove/start/destroy) never target another sandbox's gateway. + * Resolve the OpenShell gateway registration name for a gateway port + active + * instance. The default instance on the default port keeps the bare `nemoclaw` + * name for backward compatibility; any other combination gets an + * `` / `` suffix so its lifecycle commands + * (add/select/remove/start/destroy) never target another instance's gateway. */ -export function resolveGatewayName(port: number): string { - return isDefaultGatewayPort(port) ? BASE_GATEWAY_NAME : `${BASE_GATEWAY_NAME}-${port}`; +export function resolveGatewayName(port: number, instance: string = NEMOCLAW_INSTANCE): string { + return `${BASE_GATEWAY_NAME}${bindingSuffix(port, instance)}`; } /** * Resolve the Docker-driver gateway state directory leaf name for a gateway - * port. The state dir holds the gateway pid file and runtime marker, so a - * per-port leaf keeps each sandbox's marker isolated — a second onboard cannot - * overwrite the first sandbox's marker or clobber its pid file. + * port + active instance. The state dir holds the gateway pid file and runtime + * marker, so a per-binding leaf keeps each sandbox's marker isolated — a + * second onboard cannot overwrite the first sandbox's marker or clobber its + * pid file. */ -export function resolveGatewayStateDirName(port: number): string { - return isDefaultGatewayPort(port) - ? BASE_GATEWAY_STATE_DIR_NAME - : `${BASE_GATEWAY_STATE_DIR_NAME}-${port}`; +export function resolveGatewayStateDirName( + port: number, + instance: string = NEMOCLAW_INSTANCE, +): string { + return `${BASE_GATEWAY_STATE_DIR_NAME}${bindingSuffix(port, instance)}`; } /** - * Resolve the Docker-driver gateway compatibility container name for a gateway - * port. A per-port container name prevents the second onboard's - * `docker run --name ...` (and the pre-launch `docker rm`) from tearing down - * the first sandbox's compat gateway container. + * Resolve the Docker-driver gateway compatibility container name for a + * gateway port + active instance. A per-binding container name prevents the + * second onboard's `docker run --name ...` (and the pre-launch `docker rm`) + * from tearing down the first sandbox's compat gateway container. */ -export function resolveGatewayCompatContainerName(port: number): string { - return isDefaultGatewayPort(port) - ? BASE_GATEWAY_COMPAT_CONTAINER_NAME - : `${BASE_GATEWAY_COMPAT_CONTAINER_NAME}-${port}`; +export function resolveGatewayCompatContainerName( + port: number, + instance: string = NEMOCLAW_INSTANCE, +): string { + return `${BASE_GATEWAY_COMPAT_CONTAINER_NAME}${bindingSuffix(port, instance)}`; } /** Gateway state classifiers from `state/gateway`, each bound to a gateway name. */ @@ -85,9 +106,9 @@ export interface GatewayNameBoundClassifiers { /** * Bind the gateway-name-aware health/reuse classifiers to a resolved gateway - * name so a non-default NEMOCLAW_GATEWAY_PORT (gateway `nemoclaw-`) is - * recognized as its own gateway rather than matched against the `nemoclaw` - * singleton (#4422). Kept out of onboard.ts to avoid growing that file. + * name so a non-default NEMOCLAW_GATEWAY_PORT or NEMOCLAW_INSTANCE is + * recognised as its own gateway rather than matched against the `nemoclaw` + * singleton. Kept out of onboard.ts to avoid growing that file. */ export function createGatewayNameBoundClassifiers( state: typeof import("../state/gateway"), diff --git a/src/lib/state/paths.test.ts b/src/lib/state/paths.test.ts index 268b5ccaef7..cd43c3f7dcf 100644 --- a/src/lib/state/paths.test.ts +++ b/src/lib/state/paths.test.ts @@ -5,7 +5,15 @@ import { existsSync } from "node:fs"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { ROOT, SCRIPTS } from "../../../dist/lib/state/paths"; +import { DEFAULT_NEMOCLAW_INSTANCE } from "../../../dist/lib/core/instance"; +import { + BASE_NEMOCLAW_HOME_DIR_NAME, + resolveNemoclawHomeDir, + resolveNemoclawHomeDirName, + resolveNemoclawStateDir, + ROOT, + SCRIPTS, +} from "../../../dist/lib/state/paths"; describe("paths", () => { it("resolves the repo root", () => { @@ -18,3 +26,51 @@ describe("paths", () => { expect(existsSync(join(SCRIPTS, "debug.sh"))).toBe(true); }); }); + +describe("resolveNemoclawHomeDirName", () => { + it("keeps the bare .nemoclaw leaf for the default instance", () => { + expect(resolveNemoclawHomeDirName(DEFAULT_NEMOCLAW_INSTANCE)).toBe(BASE_NEMOCLAW_HOME_DIR_NAME); + }); + + it("suffixes the leaf with the instance name for a non-default instance", () => { + expect(resolveNemoclawHomeDirName("agent-a")).toBe(".nemoclaw-agent-a"); + expect(resolveNemoclawHomeDirName("tenant1")).toBe(".nemoclaw-tenant1"); + }); + + it("derives distinct leaves for two different instances", () => { + const a = resolveNemoclawHomeDirName("agent-a"); + const b = resolveNemoclawHomeDirName("agent-b"); + expect(a).not.toBe(b); + }); +}); + +describe("resolveNemoclawHomeDir / resolveNemoclawStateDir", () => { + const home = "/tmp/nemoclaw-instance-fixture"; + + it("returns the bare ~/.nemoclaw path for the default instance", () => { + expect(resolveNemoclawHomeDir(home, DEFAULT_NEMOCLAW_INSTANCE)).toBe( + join(home, BASE_NEMOCLAW_HOME_DIR_NAME), + ); + expect(resolveNemoclawStateDir(home, DEFAULT_NEMOCLAW_INSTANCE)).toBe( + join(home, BASE_NEMOCLAW_HOME_DIR_NAME, "state"), + ); + }); + + it("returns the per-instance home and state dirs for a non-default instance", () => { + expect(resolveNemoclawHomeDir(home, "agent-a")).toBe( + join(home, `${BASE_NEMOCLAW_HOME_DIR_NAME}-agent-a`), + ); + expect(resolveNemoclawStateDir(home, "agent-a")).toBe( + join(home, `${BASE_NEMOCLAW_HOME_DIR_NAME}-agent-a`, "state"), + ); + }); + + it("segregates two instances under the same home dir", () => { + expect(resolveNemoclawHomeDir(home, "agent-a")).not.toBe( + resolveNemoclawHomeDir(home, "agent-b"), + ); + expect(resolveNemoclawStateDir(home, "agent-a")).not.toBe( + resolveNemoclawStateDir(home, "agent-b"), + ); + }); +}); diff --git a/src/lib/state/paths.ts b/src/lib/state/paths.ts index e92b72bac44..d167c2ae610 100644 --- a/src/lib/state/paths.ts +++ b/src/lib/state/paths.ts @@ -4,15 +4,39 @@ import os from "node:os"; import path from "node:path"; +import { DEFAULT_NEMOCLAW_INSTANCE, isDefaultInstance, NEMOCLAW_INSTANCE } from "../core/instance"; + export const ROOT = path.resolve(__dirname, "..", "..", ".."); export const SCRIPTS = path.join(ROOT, "scripts"); -export function resolveNemoclawHomeDir(homeDir: string = process.env.HOME ?? os.homedir()): string { - return path.join(homeDir, ".nemoclaw"); +/** Leaf directory name for today's singleton state root. */ +export const BASE_NEMOCLAW_HOME_DIR_NAME = ".nemoclaw"; + +/** + * Resolve the leaf directory name for the NemoClaw state root, derived from + * the active instance identity. The default instance keeps the bare + * `.nemoclaw` name verbatim so existing single-instance deployments and + * on-disk state are untouched; any non-default instance gets a + * `.nemoclaw-` leaf so two instances never share a state tree. + */ +export function resolveNemoclawHomeDirName(instance: string = NEMOCLAW_INSTANCE): string { + return isDefaultInstance(instance) + ? BASE_NEMOCLAW_HOME_DIR_NAME + : `${BASE_NEMOCLAW_HOME_DIR_NAME}-${instance}`; +} + +export function resolveNemoclawHomeDir( + homeDir: string = process.env.HOME ?? os.homedir(), + instance: string = NEMOCLAW_INSTANCE, +): string { + return path.join(homeDir, resolveNemoclawHomeDirName(instance)); } export function resolveNemoclawStateDir( homeDir: string = process.env.HOME ?? os.homedir(), + instance: string = NEMOCLAW_INSTANCE, ): string { - return path.join(resolveNemoclawHomeDir(homeDir), "state"); + return path.join(resolveNemoclawHomeDir(homeDir, instance), "state"); } + +export { DEFAULT_NEMOCLAW_INSTANCE, NEMOCLAW_INSTANCE }; diff --git a/src/lib/state/sandbox.ts b/src/lib/state/sandbox.ts index 55442b29de5..c6cf4f1f7b8 100644 --- a/src/lib/state/sandbox.ts +++ b/src/lib/state/sandbox.ts @@ -37,11 +37,12 @@ import { } from "./openclaw-config-restore-input.js"; import { shellQuote } from "../runner.js"; import { isSensitiveFile, sanitizeConfigFile } from "../security/credential-filter.js"; +import { resolveNemoclawHomeDir } from "./paths.js"; import * as registry from "./registry.js"; import { runTarListing } from "./tar-listing.js"; const HOME_DIR = path.resolve(process.env.HOME || os.homedir()); -const REBUILD_BACKUPS_DIR = path.join(HOME_DIR, ".nemoclaw", "rebuild-backups"); +const REBUILD_BACKUPS_DIR = path.join(resolveNemoclawHomeDir(HOME_DIR), "rebuild-backups"); const MANIFEST_VERSION = 1; @@ -478,7 +479,12 @@ function sshArgs(configFile: string, sandboxName: string): string[] { function computeBlueprintDigest(): string | null { // Look for blueprint.yaml relative to the agent-defs ROOT const candidates = [ - path.join(process.env.HOME || "/tmp", ".nemoclaw", "blueprints", "0.1.0", "blueprint.yaml"), + path.join( + resolveNemoclawHomeDir(process.env.HOME || "/tmp"), + "blueprints", + "0.1.0", + "blueprint.yaml", + ), path.join(__dirname, "..", "..", "nemoclaw-blueprint", "blueprint.yaml"), ]; for (const p of candidates) { From 0092c8e029b780776e05480c045c0216ec5c6b91 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 13:50:41 +0000 Subject: [PATCH 02/29] fix(core): reject port-like instance segments, migrate local-adapter state, sync docs Signed-off-by: Tinson Lai --- docs/reference/commands-nemohermes.mdx | 3 ++ docs/reference/commands.mdx | 2 +- src/lib/core/instance.test.ts | 22 +++++++++++++ src/lib/core/instance.ts | 34 +++++++++++++++++--- src/lib/inference/local-adapter-lifecycle.ts | 5 +-- src/lib/onboard/gateway-binding.test.ts | 14 ++++++++ 6 files changed, 73 insertions(+), 7 deletions(-) diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index 58c6ccb8d38..fb171d1fae3 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -1573,10 +1573,13 @@ All ports must be non-privileged integers between 1024 and 65535. | `NEMOCLAW_OLLAMA_PORT` | 11434 | Ollama inference | | `NEMOCLAW_OLLAMA_PROXY_PORT` | 11435 | Ollama auth proxy | | `NEMOCLAW_DASHBOARD_BIND` | *unset* (loopback) | Dashboard or API forward bind address. Set to `0.0.0.0` to opt in to remote bind for SSH-deployed hosts. | +| `NEMOCLAW_INSTANCE` | `default` | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | If a port value is not a valid integer or falls outside the allowed range, the CLI exits with an error. `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` values, NemoClaw derives a separate gateway name, state directory, and compatibility container name from the port so one gateway does not tear down another. + +`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). The default instance keeps the original `~/.nemoclaw` state root and `nemohermes` gateway name verbatim, so existing single-instance deployments observe no change. Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups, local inference adapter state, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, snapshot trees, and messaging configuration — continue to share state across instances; follow-up PRs migrate those surfaces. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 345eeb22db3..035585b7a9e 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1823,7 +1823,7 @@ If a port value is not a valid integer or falls outside the allowed range, the C `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` values, NemoClaw derives a separate gateway name, state directory, and compatibility container name from the port so one gateway does not tear down another. -`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). The default instance keeps the original `~/.nemoclaw` state root and `nemoclaw` gateway name verbatim, so existing single-instance deployments observe no change. Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` scopes the credentials directory, rebuild backups, and gateway binding to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Full per-instance segregation of registry, snapshots, and messaging is tracked separately as follow-up. +`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). The default instance keeps the original `~/.nemoclaw` state root and `nemoclaw` gateway name verbatim, so existing single-instance deployments observe no change. Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups, local inference adapter state, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, snapshot trees, and messaging configuration — continue to share state across instances; follow-up PRs migrate those surfaces. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/src/lib/core/instance.test.ts b/src/lib/core/instance.test.ts index 3e2183646cc..a4b8e56c250 100644 --- a/src/lib/core/instance.test.ts +++ b/src/lib/core/instance.test.ts @@ -54,6 +54,28 @@ describe("parseInstanceName", () => { ); }); + it.each([ + ["a pure-digit name", "8081"], + ["a port-like trailing segment", "agent-8081"], + ["a port-like leading segment", "8081-agent"], + ["a port-like middle segment", "agent-1-instance"], + ["a short numeric tail", "tenant-1"], + ] as const)("rejects %s as a port-suffix collision risk", (_label, value) => { + process.env[ENV_KEY] = value; + expect(() => parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE)).toThrow( + /hyphen-separated segments may not be purely numeric/, + ); + }); + + it.each([ + ["a name with a mixed alphanumeric segment", "agent-a1"], + ["a name leading with a digit", "1agent"], + ["a name with a number embedded in a segment", "tenant1"], + ] as const)("still accepts %s (no purely-numeric segment)", (_label, value) => { + process.env[ENV_KEY] = value; + expect(parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE)).toBe(value); + }); + it("falls back to a non-default fallback when the env var is unset", () => { expect(parseInstanceName(ENV_KEY, "primary")).toBe("primary"); }); diff --git a/src/lib/core/instance.ts b/src/lib/core/instance.ts index d2ddb8a4110..38b2c696235 100644 --- a/src/lib/core/instance.ts +++ b/src/lib/core/instance.ts @@ -13,12 +13,21 @@ * `NEMOCLAW_INSTANCE` makes the instance identity configurable. The default * instance keeps every existing on-disk path and gateway name verbatim so * single-instance deployments are unaffected; a non-default instance gets a - * suffixed state root and gateway name so two instances never collide. + * suffixed state root, credentials directory, rebuild-backups directory, + * local-adapter state directory, and gateway name so the migrated surfaces + * stay segregated. + * + * Scope of segregation in this groundwork: NemoClaw home directory, gateway + * binding (name, state dir, compat container), credentials store, rebuild + * backups, and local inference adapter state. Out of scope here and tracked + * as follow-up: the sandbox registry, onboard session state, messaging + * configuration, snapshot trees, and any module that still reads + * `~/.nemoclaw` directly. Callers that have not yet migrated to + * `resolveNemoclawHomeDir()` still share state across instances. * * This module is the single source of truth for resolving the active instance - * name; downstream callers (state root, gateway-name resolver, credentials - * store, rebuild-backups dir) thread the resolved value through their own - * paths rather than parsing the env var directly. + * name; downstream callers thread the resolved value through their own paths + * rather than parsing the env var directly. */ /** Reserved name representing today's singleton behaviour. */ @@ -31,6 +40,17 @@ export const DEFAULT_NEMOCLAW_INSTANCE = "default"; */ const INSTANCE_NAME_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/; +/** + * Pure-digit hyphen-separated segments are rejected so the instance name can + * never collide with the `-` suffix appended by the gateway-name + * resolver. Without this rule, `NEMOCLAW_INSTANCE=agent-a NEMOCLAW_GATEWAY_PORT=8081` + * and `NEMOCLAW_INSTANCE=agent-a-8081` (default port) would both compose + * `nemoclaw-agent-a-8081` and overwrite each other's gateway state. + */ +function hasNumericSegment(name: string): boolean { + return name.split("-").some((segment) => /^\d+$/.test(segment)); +} + /** * Validate an instance-name candidate. Returns the trimmed lower-case name if * valid, or throws with a stable error message that callers can surface to the @@ -48,6 +68,12 @@ export function parseInstanceName(envVar: string, fallback: string): string { `alphanumerics with internal '-' (e.g. "agent-a", "tenant1")`, ); } + if (hasNumericSegment(trimmed)) { + throw new Error( + `Invalid instance name: ${envVar}="${raw}" — hyphen-separated segments ` + + `may not be purely numeric (would collide with the gateway port suffix)`, + ); + } return trimmed; } diff --git a/src/lib/inference/local-adapter-lifecycle.ts b/src/lib/inference/local-adapter-lifecycle.ts index 05cb6a10725..b160273816c 100644 --- a/src/lib/inference/local-adapter-lifecycle.ts +++ b/src/lib/inference/local-adapter-lifecycle.ts @@ -5,9 +5,10 @@ import { spawn, type ChildProcess } from "node:child_process"; import crypto from "node:crypto"; import fs from "node:fs"; import http from "node:http"; -import os from "node:os"; import path from "node:path"; +import { resolveNemoclawHomeDir } from "../state/paths"; + export type JsonObject = Record; export type RunCaptureFn = ( @@ -20,7 +21,7 @@ export type RunFn = ( options?: { ignoreError?: boolean; suppressOutput?: boolean }, ) => unknown; -export const DEFAULT_LOCAL_ADAPTER_STATE_DIR = path.join(os.homedir(), ".nemoclaw"); +export const DEFAULT_LOCAL_ADAPTER_STATE_DIR = resolveNemoclawHomeDir(); export function ensureLocalAdapterStateDir(stateDir = DEFAULT_LOCAL_ADAPTER_STATE_DIR): void { if (!fs.existsSync(stateDir)) { diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 13d1ca42af7..5a050ed19a4 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -99,6 +99,20 @@ describe("gateway-binding resolver factors NEMOCLAW_INSTANCE (#3053)", () => { it("preserves the bare nemoclaw names when the instance is left at default", () => { expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, DEFAULT_INSTANCE)).toBe(BASE_GATEWAY_NAME); }); + + // Regression for the encoding ambiguity surfaced in review: instance + // "agent-a" composed with port 8081 produces the same gateway name as + // instance "agent-a-8081" composed with the default port. The instance + // parser rejects purely-numeric hyphen-segments to guarantee this never + // happens for env-derived values; the resolver itself stays a pure function + // so callers must validate first via parseInstanceName(). + it("composed names would collide if a port-like instance tail were permitted", () => { + const composed = resolveGatewayName(8081, "agent-a"); + const portLikeTail = resolveGatewayName(DEFAULT_GATEWAY_PORT, "agent-a-8081"); + expect(composed).toBe("nemoclaw-agent-a-8081"); + expect(portLikeTail).toBe("nemoclaw-agent-a-8081"); + // parseInstanceName() refuses "agent-a-8081" — see src/lib/core/instance.test.ts. + }); }); describe("docker-driver compat container is gateway-port scoped (#4422)", () => { From 29e29c85016de69cbdc4f44b7039699262e4d6a4 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 13:56:01 +0000 Subject: [PATCH 03/29] docs(core): document default and port-based instance fallback chain Signed-off-by: Tinson Lai --- docs/reference/commands-nemohermes.mdx | 6 ++- docs/reference/commands.mdx | 6 ++- src/lib/core/instance.ts | 23 ++++++--- src/lib/onboard/gateway-binding.test.ts | 64 ++++++++++++++++++++++++- 4 files changed, 90 insertions(+), 9 deletions(-) diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index fb171d1fae3..f16a9c55fce 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -1579,7 +1579,11 @@ If a port value is not a valid integer or falls outside the allowed range, the C `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` values, NemoClaw derives a separate gateway name, state directory, and compatibility container name from the port so one gateway does not tear down another. -`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). The default instance keeps the original `~/.nemoclaw` state root and `nemohermes` gateway name verbatim, so existing single-instance deployments observe no change. Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups, local inference adapter state, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, snapshot trees, and messaging configuration — continue to share state across instances; follow-up PRs migrate those surfaces. +`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). + +The default behaviour applies when `NEMOCLAW_INSTANCE` is unset or empty: the state root stays at `~/.nemoclaw` and the gateway name stays at `nemohermes`. Existing single-instance deployments therefore observe no change after upgrading. When the bare `nemohermes` gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. + +Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups, local inference adapter state, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, snapshot trees, and messaging configuration — continue to share state across instances; follow-up PRs migrate those surfaces. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 035585b7a9e..2ca30aa56fe 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1823,7 +1823,11 @@ If a port value is not a valid integer or falls outside the allowed range, the C `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` values, NemoClaw derives a separate gateway name, state directory, and compatibility container name from the port so one gateway does not tear down another. -`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). The default instance keeps the original `~/.nemoclaw` state root and `nemoclaw` gateway name verbatim, so existing single-instance deployments observe no change. Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups, local inference adapter state, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, snapshot trees, and messaging configuration — continue to share state across instances; follow-up PRs migrate those surfaces. +`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). + +The default behaviour applies when `NEMOCLAW_INSTANCE` is unset or empty: the state root stays at `~/.nemoclaw` and the gateway name stays at `nemoclaw`. Existing single-instance deployments therefore observe no change after upgrading. When the bare `nemoclaw` gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. + +Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups, local inference adapter state, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, snapshot trees, and messaging configuration — continue to share state across instances; follow-up PRs migrate those surfaces. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/src/lib/core/instance.ts b/src/lib/core/instance.ts index 38b2c696235..546fedea4c9 100644 --- a/src/lib/core/instance.ts +++ b/src/lib/core/instance.ts @@ -10,12 +10,23 @@ * same host therefore had to share that tree even when the user wanted full * segregation (billing isolation, A/B model testing, multi-tenant POCs). * - * `NEMOCLAW_INSTANCE` makes the instance identity configurable. The default - * instance keeps every existing on-disk path and gateway name verbatim so - * single-instance deployments are unaffected; a non-default instance gets a - * suffixed state root, credentials directory, rebuild-backups directory, - * local-adapter state directory, and gateway name so the migrated surfaces - * stay segregated. + * `NEMOCLAW_INSTANCE` makes the instance identity configurable. The fallback + * chain has two layers: + * + * 1. When `NEMOCLAW_INSTANCE` is unset or empty, the default instance is + * selected, every existing on-disk path resolves to `~/.nemoclaw`, and + * the gateway name stays at the bare `nemoclaw` — single-instance + * deployments observe no change after upgrading. + * 2. With the default instance still selected, a non-default + * `NEMOCLAW_GATEWAY_PORT` produces a `nemoclaw-` gateway that + * segregates from the bare default at the gateway-binding layer alone. + * This port-derived form is the implicit fallback identity when the + * bare `nemoclaw` gateway is already occupied. + * + * Setting `NEMOCLAW_INSTANCE` to a non-default value overrides both layers + * with a named instance: the state root, credentials directory, + * rebuild-backups directory, local-adapter state directory, and gateway name + * all gain an `` suffix so the migrated surfaces stay segregated. * * Scope of segregation in this groundwork: NemoClaw home directory, gateway * binding (name, state dir, compat container), credentials store, rebuild diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 5a050ed19a4..08d28c459a2 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -5,7 +5,8 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { DEFAULT_NEMOCLAW_INSTANCE, parseInstanceName } from "../../../dist/lib/core/instance"; import { DEFAULT_GATEWAY_PORT } from "../../../dist/lib/core/ports"; import { buildDockerDriverGatewayLaunch } from "../../../dist/lib/onboard/docker-driver-gateway-launch"; import { @@ -22,6 +23,10 @@ import { resolveGatewayName, resolveGatewayStateDirName, } from "../../../dist/lib/onboard/gateway-binding"; +import { + BASE_NEMOCLAW_HOME_DIR_NAME, + resolveNemoclawHomeDir, +} from "../../../dist/lib/state/paths"; describe("gateway-binding resolver (#4422)", () => { const DEFAULT_INSTANCE = "default"; @@ -115,6 +120,63 @@ describe("gateway-binding resolver factors NEMOCLAW_INSTANCE (#3053)", () => { }); }); +// Confirms the standing fallback contract: an unset NEMOCLAW_INSTANCE must +// resolve to the bare `nemoclaw` identity on the default gateway port, and +// to `nemoclaw-` when only NEMOCLAW_GATEWAY_PORT is supplied. The +// port-derived form is the implicit fallback identity when the bare default +// is already occupied — users opting out of the new env var still get a +// distinct gateway by varying the port alone. +describe("default and port-based fallback identity chain", () => { + const ENV_KEY = "TEST_NEMOCLAW_INSTANCE_FALLBACK"; + + beforeEach(() => { + delete process.env[ENV_KEY]; + }); + + afterEach(() => { + delete process.env[ENV_KEY]; + }); + + it("resolves bare nemoclaw names and the bare home dir when NEMOCLAW_INSTANCE is unset", () => { + const resolved = parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE); + expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); + expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, resolved)).toBe(BASE_GATEWAY_NAME); + expect(resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT, resolved)).toBe( + BASE_GATEWAY_STATE_DIR_NAME, + ); + expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, resolved)).toBe( + BASE_GATEWAY_COMPAT_CONTAINER_NAME, + ); + expect(resolveNemoclawHomeDir("/tmp/fixture", resolved)).toBe( + `/tmp/fixture/${BASE_NEMOCLAW_HOME_DIR_NAME}`, + ); + }); + + it("resolves the port-based fallback when NEMOCLAW_INSTANCE is unset and only the gateway port shifts", () => { + const resolved = parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE); + expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); + // The home dir stays at the bare default — port alone does not segregate + // host state, only the gateway binding. + expect(resolveNemoclawHomeDir("/tmp/fixture", resolved)).toBe( + `/tmp/fixture/${BASE_NEMOCLAW_HOME_DIR_NAME}`, + ); + // The gateway binding takes the port suffix so two default-instance + // sandboxes on distinct ports never share gateway state. + expect(resolveGatewayName(8081, resolved)).toBe("nemoclaw-8081"); + expect(resolveGatewayStateDirName(8081, resolved)).toBe("openshell-docker-gateway-8081"); + expect(resolveGatewayCompatContainerName(8081, resolved)).toBe( + "nemoclaw-openshell-gateway-8081", + ); + }); + + it("treats an empty env value the same as an unset env value", () => { + process.env[ENV_KEY] = ""; + const resolved = parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE); + expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); + expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, resolved)).toBe(BASE_GATEWAY_NAME); + }); +}); + describe("docker-driver compat container is gateway-port scoped (#4422)", () => { function withTempState( fn: (paths: { gatewayBin: string; sandboxBin: string; stateDir: string }) => T, From 9c7081ef44415dc270f7aa32938529c131a31ce2 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 14:07:04 +0000 Subject: [PATCH 04/29] fix(core): default instance name is nemoclaw, not synthetic sentinel Signed-off-by: Tinson Lai --- docs/reference/commands-nemohermes.mdx | 4 ++-- docs/reference/commands.mdx | 4 ++-- src/lib/core/instance.test.ts | 19 ++++++++++++++++++- src/lib/core/instance.ts | 23 +++++++++++++++-------- src/lib/onboard/gateway-binding.test.ts | 4 ++-- 5 files changed, 39 insertions(+), 15 deletions(-) diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index f16a9c55fce..9206dd04b81 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -1573,7 +1573,7 @@ All ports must be non-privileged integers between 1024 and 65535. | `NEMOCLAW_OLLAMA_PORT` | 11434 | Ollama inference | | `NEMOCLAW_OLLAMA_PROXY_PORT` | 11435 | Ollama auth proxy | | `NEMOCLAW_DASHBOARD_BIND` | *unset* (loopback) | Dashboard or API forward bind address. Set to `0.0.0.0` to opt in to remote bind for SSH-deployed hosts. | -| `NEMOCLAW_INSTANCE` | `default` | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | +| `NEMOCLAW_INSTANCE` | `nemohermes` | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default `nemohermes` instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | If a port value is not a valid integer or falls outside the allowed range, the CLI exits with an error. `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. @@ -1581,7 +1581,7 @@ When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` v `NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). -The default behaviour applies when `NEMOCLAW_INSTANCE` is unset or empty: the state root stays at `~/.nemoclaw` and the gateway name stays at `nemohermes`. Existing single-instance deployments therefore observe no change after upgrading. When the bare `nemohermes` gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. +The default instance name is `nemohermes` — the same identity NemoClaw has used historically. Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it to `nemohermes` explicitly all resolve to the same identity: the state root stays at `~/.nemoclaw` and the gateway name stays at `nemohermes`. Existing single-instance deployments therefore observe no change after upgrading. When the bare `nemohermes` gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups, local inference adapter state, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, snapshot trees, and messaging configuration — continue to share state across instances; follow-up PRs migrate those surfaces. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 2ca30aa56fe..a18a86df8df 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1817,7 +1817,7 @@ All ports must be non-privileged integers between 1024 and 65535. | `NEMOCLAW_OLLAMA_PORT` | 11434 | Ollama inference | | `NEMOCLAW_OLLAMA_PROXY_PORT` | 11435 | Ollama auth proxy | | `NEMOCLAW_DASHBOARD_BIND` | *unset* (loopback) | Dashboard or API forward bind address. Set to `0.0.0.0` to opt in to remote bind for SSH-deployed hosts. | -| `NEMOCLAW_INSTANCE` | `default` | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | +| `NEMOCLAW_INSTANCE` | `nemoclaw` | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default `nemoclaw` instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | If a port value is not a valid integer or falls outside the allowed range, the CLI exits with an error. `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. @@ -1825,7 +1825,7 @@ When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` v `NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). -The default behaviour applies when `NEMOCLAW_INSTANCE` is unset or empty: the state root stays at `~/.nemoclaw` and the gateway name stays at `nemoclaw`. Existing single-instance deployments therefore observe no change after upgrading. When the bare `nemoclaw` gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. +The default instance name is `nemoclaw` — the same identity NemoClaw has used historically. Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it to `nemoclaw` explicitly all resolve to the same identity: the state root stays at `~/.nemoclaw` and the gateway name stays at `nemoclaw`. Existing single-instance deployments therefore observe no change after upgrading. When the bare `nemoclaw` gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups, local inference adapter state, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, snapshot trees, and messaging configuration — continue to share state across instances; follow-up PRs migrate those surfaces. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. diff --git a/src/lib/core/instance.test.ts b/src/lib/core/instance.test.ts index a4b8e56c250..347ffc80049 100644 --- a/src/lib/core/instance.test.ts +++ b/src/lib/core/instance.test.ts @@ -79,10 +79,26 @@ describe("parseInstanceName", () => { it("falls back to a non-default fallback when the env var is unset", () => { expect(parseInstanceName(ENV_KEY, "primary")).toBe("primary"); }); + + it("treats an explicit NEMOCLAW_INSTANCE=nemoclaw as the default", () => { + process.env[ENV_KEY] = "nemoclaw"; + const resolved = parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE); + expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); + expect(isDefaultInstance(resolved)).toBe(true); + }); + + it("normalises uppercase NEMOCLAW to the default instance", () => { + process.env[ENV_KEY] = "NEMOCLAW"; + const resolved = parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE); + expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); + expect(isDefaultInstance(resolved)).toBe(true); + }); }); describe("isDefaultInstance", () => { - it("recognises the default instance", () => { + it("recognises the default instance name as `nemoclaw`", () => { + expect(DEFAULT_NEMOCLAW_INSTANCE).toBe("nemoclaw"); + expect(isDefaultInstance("nemoclaw")).toBe(true); expect(isDefaultInstance(DEFAULT_NEMOCLAW_INSTANCE)).toBe(true); }); @@ -90,5 +106,6 @@ describe("isDefaultInstance", () => { expect(isDefaultInstance("agent-a")).toBe(false); expect(isDefaultInstance("")).toBe(false); expect(isDefaultInstance("primary")).toBe(false); + expect(isDefaultInstance("default")).toBe(false); }); }); diff --git a/src/lib/core/instance.ts b/src/lib/core/instance.ts index 546fedea4c9..91f73c7e16a 100644 --- a/src/lib/core/instance.ts +++ b/src/lib/core/instance.ts @@ -10,13 +10,15 @@ * same host therefore had to share that tree even when the user wanted full * segregation (billing isolation, A/B model testing, multi-tenant POCs). * - * `NEMOCLAW_INSTANCE` makes the instance identity configurable. The fallback - * chain has two layers: + * `NEMOCLAW_INSTANCE` makes the instance identity configurable. The default + * instance name is the historical singleton identity `nemoclaw`, so the + * fallback chain has two layers without any synthetic sentinel name: * - * 1. When `NEMOCLAW_INSTANCE` is unset or empty, the default instance is - * selected, every existing on-disk path resolves to `~/.nemoclaw`, and - * the gateway name stays at the bare `nemoclaw` — single-instance - * deployments observe no change after upgrading. + * 1. When `NEMOCLAW_INSTANCE` is unset, empty, or set explicitly to + * `nemoclaw`, the default instance is selected, every existing on-disk + * path resolves to `~/.nemoclaw`, and the gateway name stays at the + * bare `nemoclaw` — single-instance deployments observe no change + * after upgrading. * 2. With the default instance still selected, a non-default * `NEMOCLAW_GATEWAY_PORT` produces a `nemoclaw-` gateway that * segregates from the bare default at the gateway-binding layer alone. @@ -41,8 +43,13 @@ * rather than parsing the env var directly. */ -/** Reserved name representing today's singleton behaviour. */ -export const DEFAULT_NEMOCLAW_INSTANCE = "default"; +/** + * Default instance name. Equals the historical singleton identity so the + * bare `nemoclaw` gateway name and `~/.nemoclaw` state root fall out of the + * resolvers without a synthetic sentinel. `NEMOCLAW_INSTANCE=nemoclaw` is + * therefore equivalent to leaving the variable unset. + */ +export const DEFAULT_NEMOCLAW_INSTANCE = "nemoclaw"; /** * Lower-case alphanumeric slug with internal `-`. Must start and end with an diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 08d28c459a2..93a278eee3d 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -29,7 +29,7 @@ import { } from "../../../dist/lib/state/paths"; describe("gateway-binding resolver (#4422)", () => { - const DEFAULT_INSTANCE = "default"; + const DEFAULT_INSTANCE = DEFAULT_NEMOCLAW_INSTANCE; it("keeps the bare nemoclaw names for the default instance on the default gateway port", () => { expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, DEFAULT_INSTANCE)).toBe(BASE_GATEWAY_NAME); @@ -67,7 +67,7 @@ describe("gateway-binding resolver (#4422)", () => { }); describe("gateway-binding resolver factors NEMOCLAW_INSTANCE (#3053)", () => { - const DEFAULT_INSTANCE = "default"; + const DEFAULT_INSTANCE = DEFAULT_NEMOCLAW_INSTANCE; it("suffixes the gateway name with the instance for a non-default instance on the default port", () => { expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, "agent-a")).toBe("nemoclaw-agent-a"); From cc75f2b01cd61040df32a3f56d8302c782cd99f7 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 14:41:49 +0000 Subject: [PATCH 05/29] fix(inference): instance-aware Ollama proxy token reader, restore test env, tighten doc claims Signed-off-by: Tinson Lai --- docs/reference/commands-nemohermes.mdx | 10 ++++----- docs/reference/commands.mdx | 10 ++++----- src/lib/core/instance.test.ts | 8 ++++++- src/lib/inference/local-adapter-lifecycle.ts | 2 +- src/lib/inference/local.ts | 15 +++++++------ src/lib/onboard/gateway-binding.test.ts | 22 ++++++++++++-------- src/lib/onboard/gateway-binding.ts | 2 +- src/lib/state/paths.test.ts | 2 +- src/lib/state/paths.ts | 14 ++++++++++++- src/lib/state/sandbox.ts | 4 ++-- 10 files changed, 57 insertions(+), 32 deletions(-) diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index 9206dd04b81..fa93e245896 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -1102,7 +1102,7 @@ If the registry is unreachable (offline or firewalled hosts), NemoClaw falls bac ### `nemohermes backup-all` -Back up all registered running sandboxes to `~/.nemoclaw/rebuild-backups/`. +Back up all registered running sandboxes to `~/.nemoclaw/rebuild-backups/` for the default instance, or `~/.nemoclaw-/rebuild-backups/` when `NEMOCLAW_INSTANCE` is set to a non-default value (see the Environment Variables section). Sandboxes that are not running are skipped. ```bash @@ -1114,7 +1114,7 @@ The installer calls `backup-all` automatically before onboarding to protect agai ### `nemohermes snapshot create` Create a timestamped snapshot of sandbox state. -Snapshots are stored in `~/.nemoclaw/rebuild-backups//`. +Snapshots are stored in `~/.nemoclaw/rebuild-backups//` for the default instance, or `~/.nemoclaw-/rebuild-backups//` when `NEMOCLAW_INSTANCE` is set to a non-default value. ```bash nemohermes my-assistant snapshot create @@ -1573,7 +1573,7 @@ All ports must be non-privileged integers between 1024 and 65535. | `NEMOCLAW_OLLAMA_PORT` | 11434 | Ollama inference | | `NEMOCLAW_OLLAMA_PROXY_PORT` | 11435 | Ollama auth proxy | | `NEMOCLAW_DASHBOARD_BIND` | *unset* (loopback) | Dashboard or API forward bind address. Set to `0.0.0.0` to opt in to remote bind for SSH-deployed hosts. | -| `NEMOCLAW_INSTANCE` | `nemohermes` | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default `nemohermes` instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | +| `NEMOCLAW_INSTANCE` | _historical default_ | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | If a port value is not a valid integer or falls outside the allowed range, the CLI exits with an error. `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. @@ -1581,9 +1581,9 @@ When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` v `NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). -The default instance name is `nemohermes` — the same identity NemoClaw has used historically. Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it to `nemohermes` explicitly all resolve to the same identity: the state root stays at `~/.nemoclaw` and the gateway name stays at `nemohermes`. Existing single-instance deployments therefore observe no change after upgrading. When the bare `nemohermes` gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. +The default instance name is the historical singleton identity NemoClaw has always used. Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it explicitly to that default value all resolve to the same identity: the state root stays at `~/.nemoclaw` and the OpenShell gateway keeps its bare historical name (`nemoclaw-` for non-default ports; no suffix on the default port). Existing single-instance deployments therefore observe no change after upgrading. When the bare default gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. -Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups, local inference adapter state, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, snapshot trees, and messaging configuration — continue to share state across instances; follow-up PRs migrate those surfaces. +Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state including the Ollama auth-proxy token, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, messaging configuration, host-side mount roots, the uninstall plan, and the `config-io` host-root permission healer — continue to share state across instances; follow-up PRs migrate those surfaces. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index a18a86df8df..eca10467b8a 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1328,7 +1328,7 @@ If the registry is unreachable (offline or firewalled hosts), NemoClaw falls bac ### `$$nemoclaw backup-all` -Back up all registered running sandboxes to `~/.nemoclaw/rebuild-backups/`. +Back up all registered running sandboxes to `~/.nemoclaw/rebuild-backups/` for the default instance, or `~/.nemoclaw-/rebuild-backups/` when `NEMOCLAW_INSTANCE` is set to a non-default value (see the Environment Variables section). Sandboxes that are not running are skipped. ```bash @@ -1340,7 +1340,7 @@ The installer calls `backup-all` automatically before onboarding to protect agai ### `$$nemoclaw snapshot create` Create a timestamped snapshot of sandbox state. -Snapshots are stored in `~/.nemoclaw/rebuild-backups//`. +Snapshots are stored in `~/.nemoclaw/rebuild-backups//` for the default instance, or `~/.nemoclaw-/rebuild-backups//` when `NEMOCLAW_INSTANCE` is set to a non-default value. ```bash $$nemoclaw my-assistant snapshot create @@ -1817,7 +1817,7 @@ All ports must be non-privileged integers between 1024 and 65535. | `NEMOCLAW_OLLAMA_PORT` | 11434 | Ollama inference | | `NEMOCLAW_OLLAMA_PROXY_PORT` | 11435 | Ollama auth proxy | | `NEMOCLAW_DASHBOARD_BIND` | *unset* (loopback) | Dashboard or API forward bind address. Set to `0.0.0.0` to opt in to remote bind for SSH-deployed hosts. | -| `NEMOCLAW_INSTANCE` | `nemoclaw` | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default `nemoclaw` instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | +| `NEMOCLAW_INSTANCE` | _historical default_ | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | If a port value is not a valid integer or falls outside the allowed range, the CLI exits with an error. `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. @@ -1825,9 +1825,9 @@ When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` v `NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). -The default instance name is `nemoclaw` — the same identity NemoClaw has used historically. Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it to `nemoclaw` explicitly all resolve to the same identity: the state root stays at `~/.nemoclaw` and the gateway name stays at `nemoclaw`. Existing single-instance deployments therefore observe no change after upgrading. When the bare `nemoclaw` gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. +The default instance name is the historical singleton identity NemoClaw has always used. Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it explicitly to that default value all resolve to the same identity: the state root stays at `~/.nemoclaw` and the OpenShell gateway keeps its bare historical name (`nemoclaw-` for non-default ports; no suffix on the default port). Existing single-instance deployments therefore observe no change after upgrading. When the bare default gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. -Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups, local inference adapter state, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, snapshot trees, and messaging configuration — continue to share state across instances; follow-up PRs migrate those surfaces. +Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state including the Ollama auth-proxy token, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, messaging configuration, host-side mount roots, the uninstall plan, and the `config-io` host-root permission healer — continue to share state across instances; follow-up PRs migrate those surfaces. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/src/lib/core/instance.test.ts b/src/lib/core/instance.test.ts index 347ffc80049..21b2dec5241 100644 --- a/src/lib/core/instance.test.ts +++ b/src/lib/core/instance.test.ts @@ -10,13 +10,19 @@ import { describe("parseInstanceName", () => { const ENV_KEY = "TEST_NEMOCLAW_INSTANCE"; + let previousEnvValue: string | undefined; beforeEach(() => { + previousEnvValue = process.env[ENV_KEY]; delete process.env[ENV_KEY]; }); afterEach(() => { - delete process.env[ENV_KEY]; + if (previousEnvValue === undefined) { + delete process.env[ENV_KEY]; + } else { + process.env[ENV_KEY] = previousEnvValue; + } }); it.each([ diff --git a/src/lib/inference/local-adapter-lifecycle.ts b/src/lib/inference/local-adapter-lifecycle.ts index b160273816c..45abf519faf 100644 --- a/src/lib/inference/local-adapter-lifecycle.ts +++ b/src/lib/inference/local-adapter-lifecycle.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawn, type ChildProcess } from "node:child_process"; +import { type ChildProcess, spawn } from "node:child_process"; import crypto from "node:crypto"; import fs from "node:fs"; import http from "node:http"; diff --git a/src/lib/inference/local.ts b/src/lib/inference/local.ts index 1ab0146c575..8b4490733e0 100644 --- a/src/lib/inference/local.ts +++ b/src/lib/inference/local.ts @@ -7,13 +7,13 @@ */ import fs from "node:fs"; -import os from "node:os"; import nodePath from "node:path"; -import type { CurlProbeResult } from "../adapters/http/probe"; import { buildValidatedCurlCommandArgs } from "../adapters/http/curl-args"; +import type { CurlProbeResult } from "../adapters/http/probe"; import { runCurlProbe } from "../adapters/http/probe"; import type { CaptureResult } from "../runner"; import { buildSubprocessEnv } from "../subprocess-env"; +import type { OllamaRuntimeModelStatus } from "./ollama-runtime-context"; import { applyOllamaRuntimeContextWindow as applyOllamaRuntimeContextWindowWithHost, MAX_AUTODETECTED_OLLAMA_CONTEXT_WINDOW, @@ -22,14 +22,15 @@ import { resetOllamaRuntimeContextWindowAutoState, resolveOllamaRuntimeContextWindow as resolveOllamaRuntimeContextWindowWithHost, } from "./ollama-runtime-context"; -import type { OllamaRuntimeModelStatus } from "./ollama-runtime-context"; import { applyVllmRuntimeContextWindow as applyVllmRuntimeContextWindowFromModels } from "./vllm-runtime-context"; + export type { OllamaRuntimeModelStatus } from "./ollama-runtime-context"; const { shellQuote, runCapture, runCaptureEx } = require("../runner"); import { OLLAMA_PORT, OLLAMA_PROXY_PORT, VLLM_PORT } from "../core/ports"; import { sleepSeconds } from "../core/wait"; +import { resolveNemoclawHomeDir } from "../state/paths"; import { anyRegistryModelFits, effectiveGpuMemoryMB, @@ -238,14 +239,16 @@ export interface LocalProviderHealthProbeOptions { skipOllamaAuthProxySubprobe?: boolean; /** * Reads the persisted Ollama auth-proxy bearer token. Injectable for tests. - * Default reads from `~/.nemoclaw/ollama-proxy-token` (written by - * inference/ollama/proxy.ts during onboard). + * Default reads from `/ollama-proxy-token` (written by + * inference/ollama/proxy.ts during onboard). The active NemoClaw home + * follows `NEMOCLAW_INSTANCE` so the reader and writer stay in sync for + * non-default instances. */ loadOllamaProxyTokenImpl?: () => string | null; } function defaultLoadOllamaProxyToken(): string | null { - const tokenPath = nodePath.join(os.homedir(), ".nemoclaw", "ollama-proxy-token"); + const tokenPath = nodePath.join(resolveNemoclawHomeDir(), "ollama-proxy-token"); try { if (fs.existsSync(tokenPath)) { const token = fs.readFileSync(tokenPath, "utf-8").trim(); diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 93a278eee3d..f02fdd38de6 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -23,10 +23,7 @@ import { resolveGatewayName, resolveGatewayStateDirName, } from "../../../dist/lib/onboard/gateway-binding"; -import { - BASE_NEMOCLAW_HOME_DIR_NAME, - resolveNemoclawHomeDir, -} from "../../../dist/lib/state/paths"; +import { BASE_NEMOCLAW_HOME_DIR_NAME, resolveNemoclawHomeDir } from "../../../dist/lib/state/paths"; describe("gateway-binding resolver (#4422)", () => { const DEFAULT_INSTANCE = DEFAULT_NEMOCLAW_INSTANCE; @@ -128,13 +125,20 @@ describe("gateway-binding resolver factors NEMOCLAW_INSTANCE (#3053)", () => { // distinct gateway by varying the port alone. describe("default and port-based fallback identity chain", () => { const ENV_KEY = "TEST_NEMOCLAW_INSTANCE_FALLBACK"; + const FIXTURE_HOME = path.join(os.tmpdir(), "nemoclaw-instance-fallback"); + let previousEnvValue: string | undefined; beforeEach(() => { + previousEnvValue = process.env[ENV_KEY]; delete process.env[ENV_KEY]; }); afterEach(() => { - delete process.env[ENV_KEY]; + if (previousEnvValue === undefined) { + delete process.env[ENV_KEY]; + } else { + process.env[ENV_KEY] = previousEnvValue; + } }); it("resolves bare nemoclaw names and the bare home dir when NEMOCLAW_INSTANCE is unset", () => { @@ -147,8 +151,8 @@ describe("default and port-based fallback identity chain", () => { expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, resolved)).toBe( BASE_GATEWAY_COMPAT_CONTAINER_NAME, ); - expect(resolveNemoclawHomeDir("/tmp/fixture", resolved)).toBe( - `/tmp/fixture/${BASE_NEMOCLAW_HOME_DIR_NAME}`, + expect(resolveNemoclawHomeDir(FIXTURE_HOME, resolved)).toBe( + path.join(FIXTURE_HOME, BASE_NEMOCLAW_HOME_DIR_NAME), ); }); @@ -157,8 +161,8 @@ describe("default and port-based fallback identity chain", () => { expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); // The home dir stays at the bare default — port alone does not segregate // host state, only the gateway binding. - expect(resolveNemoclawHomeDir("/tmp/fixture", resolved)).toBe( - `/tmp/fixture/${BASE_NEMOCLAW_HOME_DIR_NAME}`, + expect(resolveNemoclawHomeDir(FIXTURE_HOME, resolved)).toBe( + path.join(FIXTURE_HOME, BASE_NEMOCLAW_HOME_DIR_NAME), ); // The gateway binding takes the port suffix so two default-instance // sandboxes on distinct ports never share gateway state. diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index 596e703689e..e0220f6bc03 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -28,8 +28,8 @@ * default-port deployments observe no name change. */ -import { DEFAULT_GATEWAY_PORT } from "../core/ports"; import { isDefaultInstance, NEMOCLAW_INSTANCE } from "../core/instance"; +import { DEFAULT_GATEWAY_PORT } from "../core/ports"; import type { GatewayReuseState } from "../state/gateway"; /** Gateway registration name used for the default instance and default port. */ diff --git a/src/lib/state/paths.test.ts b/src/lib/state/paths.test.ts index cd43c3f7dcf..dc3495bf3f3 100644 --- a/src/lib/state/paths.test.ts +++ b/src/lib/state/paths.test.ts @@ -8,10 +8,10 @@ import { describe, expect, it } from "vitest"; import { DEFAULT_NEMOCLAW_INSTANCE } from "../../../dist/lib/core/instance"; import { BASE_NEMOCLAW_HOME_DIR_NAME, + ROOT, resolveNemoclawHomeDir, resolveNemoclawHomeDirName, resolveNemoclawStateDir, - ROOT, SCRIPTS, } from "../../../dist/lib/state/paths"; diff --git a/src/lib/state/paths.ts b/src/lib/state/paths.ts index d167c2ae610..2109fe24aed 100644 --- a/src/lib/state/paths.ts +++ b/src/lib/state/paths.ts @@ -17,7 +17,19 @@ export const BASE_NEMOCLAW_HOME_DIR_NAME = ".nemoclaw"; * the active instance identity. The default instance keeps the bare * `.nemoclaw` name verbatim so existing single-instance deployments and * on-disk state are untouched; any non-default instance gets a - * `.nemoclaw-` leaf so two instances never share a state tree. + * `.nemoclaw-` leaf so callers that route through this helper land + * in a per-instance tree. + * + * Migration is partial. Surfaces that route through this helper today: the + * credentials store (`credentials/store.ts`), rebuild backups + blueprint + * digest (`state/sandbox.ts`), the local-adapter state directory and Ollama + * auth-proxy token (`inference/local-adapter-lifecycle.ts`, `inference/local.ts`), + * and the gateway-name binding (`onboard/gateway-binding.ts`). Surfaces that + * still hard-code `.nemoclaw` — the sandbox registry (`state/registry.ts`), + * onboard session state (`state/onboard-session.ts`), messaging configuration, + * uninstall plan, host-side mount roots, and the `config-io` host-root + * permission healer — continue to share state across instances until + * follow-up PRs migrate them. */ export function resolveNemoclawHomeDirName(instance: string = NEMOCLAW_INSTANCE): string { return isDefaultInstance(instance) diff --git a/src/lib/state/sandbox.ts b/src/lib/state/sandbox.ts index c6cf4f1f7b8..d9ab5110ed7 100644 --- a/src/lib/state/sandbox.ts +++ b/src/lib/state/sandbox.ts @@ -31,12 +31,12 @@ import { OPENSHELL_PROBE_TIMEOUT_MS } from "../adapters/openshell/timeouts.js"; import type { AgentStateFile } from "../agent/defs.js"; import { loadAgent } from "../agent/defs.js"; import { isRecord, type UnknownRecord } from "../core/json-types.js"; +import { shellQuote } from "../runner.js"; +import { isSensitiveFile, sanitizeConfigFile } from "../security/credential-filter.js"; import { buildOpenClawConfigRestoreInputFromSandbox, shouldMergeOpenClawConfigStateFile, } from "./openclaw-config-restore-input.js"; -import { shellQuote } from "../runner.js"; -import { isSensitiveFile, sanitizeConfigFile } from "../security/credential-filter.js"; import { resolveNemoclawHomeDir } from "./paths.js"; import * as registry from "./registry.js"; import { runTarListing } from "./tar-listing.js"; From 7de390b1ed13f0573598a3222067aa215bb544c8 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 15:05:52 +0000 Subject: [PATCH 06/29] docs(core): align instance scope inventory, reformat env-var section per style guide Signed-off-by: Tinson Lai --- docs/reference/commands-nemohermes.mdx | 20 +++++++++++++++----- docs/reference/commands.mdx | 20 +++++++++++++++----- src/lib/core/instance.ts | 12 +++++++----- 3 files changed, 37 insertions(+), 15 deletions(-) diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index fa93e245896..05b9cda7b96 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -1579,11 +1579,21 @@ If a port value is not a valid integer or falls outside the allowed range, the C `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` values, NemoClaw derives a separate gateway name, state directory, and compatibility container name from the port so one gateway does not tear down another. -`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). - -The default instance name is the historical singleton identity NemoClaw has always used. Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it explicitly to that default value all resolve to the same identity: the state root stays at `~/.nemoclaw` and the OpenShell gateway keeps its bare historical name (`nemoclaw-` for non-default ports; no suffix on the default port). Existing single-instance deployments therefore observe no change after upgrading. When the bare default gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. - -Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state including the Ollama auth-proxy token, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, messaging configuration, host-side mount roots, the uninstall plan, and the `config-io` host-root permission healer — continue to share state across instances; follow-up PRs migrate those surfaces. +`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). +Hyphen-separated segments may not be purely numeric so the instance name cannot collide with the gateway port suffix. +Without this rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name. + +The default instance name is the historical singleton identity NemoClaw has always used. +Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it explicitly to that default value all resolve to the same identity. +The state root then stays at `~/.nemoclaw` and the OpenShell gateway keeps its bare historical name (`nemoclaw-` for non-default ports, with no suffix on the default port). +Existing single-instance deployments therefore observe no change after upgrading. +When the bare default gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE`. +The port suffix is the implicit fallback identity for the default instance. + +Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state (including the Ollama auth-proxy token), and gateway binding (name, state directory, compatibility container) to that instance. +Combine `NEMOCLAW_INSTANCE` with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). +Modules that still read `~/.nemoclaw` directly continue to share state across instances until follow-up PRs migrate them. +These remaining shared surfaces are the sandbox registry, onboard session state, messaging configuration, host-side mount roots, the uninstall plan, and the `config-io` host-root permission healer. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index eca10467b8a..24e1ff8e9dc 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1823,11 +1823,21 @@ If a port value is not a valid integer or falls outside the allowed range, the C `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` values, NemoClaw derives a separate gateway name, state directory, and compatibility container name from the port so one gateway does not tear down another. -`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). Hyphen-separated segments may not be purely numeric: this rules out collisions with the gateway port suffix (without the rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name). - -The default instance name is the historical singleton identity NemoClaw has always used. Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it explicitly to that default value all resolve to the same identity: the state root stays at `~/.nemoclaw` and the OpenShell gateway keeps its bare historical name (`nemoclaw-` for non-default ports; no suffix on the default port). Existing single-instance deployments therefore observe no change after upgrading. When the bare default gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE` — the port suffix is the implicit fallback identity for the default instance. - -Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state including the Ollama auth-proxy token, and gateway binding (name, state directory, compatibility container) to that instance; combine with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly — the sandbox registry, onboard session state, messaging configuration, host-side mount roots, the uninstall plan, and the `config-io` host-root permission healer — continue to share state across instances; follow-up PRs migrate those surfaces. +`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). +Hyphen-separated segments may not be purely numeric so the instance name cannot collide with the gateway port suffix. +Without this rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name. + +The default instance name is the historical singleton identity NemoClaw has always used. +Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it explicitly to that default value all resolve to the same identity. +The state root then stays at `~/.nemoclaw` and the OpenShell gateway keeps its bare historical name (`nemoclaw-` for non-default ports, with no suffix on the default port). +Existing single-instance deployments therefore observe no change after upgrading. +When the bare default gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE`. +The port suffix is the implicit fallback identity for the default instance. + +Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state (including the Ollama auth-proxy token), and gateway binding (name, state directory, compatibility container) to that instance. +Combine `NEMOCLAW_INSTANCE` with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). +Modules that still read `~/.nemoclaw` directly continue to share state across instances until follow-up PRs migrate them. +These remaining shared surfaces are the sandbox registry, onboard session state, messaging configuration, host-side mount roots, the uninstall plan, and the `config-io` host-root permission healer. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/src/lib/core/instance.ts b/src/lib/core/instance.ts index 91f73c7e16a..f9d43104c00 100644 --- a/src/lib/core/instance.ts +++ b/src/lib/core/instance.ts @@ -31,11 +31,13 @@ * all gain an `` suffix so the migrated surfaces stay segregated. * * Scope of segregation in this groundwork: NemoClaw home directory, gateway - * binding (name, state dir, compat container), credentials store, rebuild - * backups, and local inference adapter state. Out of scope here and tracked - * as follow-up: the sandbox registry, onboard session state, messaging - * configuration, snapshot trees, and any module that still reads - * `~/.nemoclaw` directly. Callers that have not yet migrated to + * binding (name, state dir, compat container), credentials store (including + * the legacy plaintext credentials file path), rebuild backups and the + * snapshot tree underneath, local inference adapter state, and the Ollama + * auth-proxy token reader/writer. Out of scope here and tracked as follow-up: + * the sandbox registry, onboard session state, messaging configuration, + * host-side mount roots, the uninstall plan, and the `config-io` host-root + * permission healer. Callers that have not yet migrated to * `resolveNemoclawHomeDir()` still share state across instances. * * This module is the single source of truth for resolving the active instance From 36a351a77a7896bfa558499bc95f51538461abea Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 15:27:55 +0000 Subject: [PATCH 07/29] test(core): runtime call-site coverage for migrated instance surfaces; document shields Signed-off-by: Tinson Lai --- docs/reference/commands-nemohermes.mdx | 2 +- docs/reference/commands.mdx | 2 +- src/lib/core/instance-runtime.test.ts | 117 +++++++++++++++++++++++++ src/lib/core/instance.ts | 15 ++-- src/lib/state/paths.ts | 15 ++-- 5 files changed, 137 insertions(+), 14 deletions(-) create mode 100644 src/lib/core/instance-runtime.test.ts diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index 05b9cda7b96..73f7667c6c9 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -1590,7 +1590,7 @@ Existing single-instance deployments therefore observe no change after upgrading When the bare default gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE`. The port suffix is the implicit fallback identity for the default instance. -Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state (including the Ollama auth-proxy token), and gateway binding (name, state directory, compatibility container) to that instance. +Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state (including the Ollama auth-proxy token), shields audit and timer state, and gateway binding (name, state directory, compatibility container) to that instance. Combine `NEMOCLAW_INSTANCE` with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly continue to share state across instances until follow-up PRs migrate them. These remaining shared surfaces are the sandbox registry, onboard session state, messaging configuration, host-side mount roots, the uninstall plan, and the `config-io` host-root permission healer. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 24e1ff8e9dc..06e46d23d2a 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1834,7 +1834,7 @@ Existing single-instance deployments therefore observe no change after upgrading When the bare default gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE`. The port suffix is the implicit fallback identity for the default instance. -Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state (including the Ollama auth-proxy token), and gateway binding (name, state directory, compatibility container) to that instance. +Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state (including the Ollama auth-proxy token), shields audit and timer state, and gateway binding (name, state directory, compatibility container) to that instance. Combine `NEMOCLAW_INSTANCE` with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). Modules that still read `~/.nemoclaw` directly continue to share state across instances until follow-up PRs migrate them. These remaining shared surfaces are the sandbox registry, onboard session state, messaging configuration, host-side mount roots, the uninstall plan, and the `config-io` host-root permission healer. diff --git a/src/lib/core/instance-runtime.test.ts b/src/lib/core/instance-runtime.test.ts new file mode 100644 index 00000000000..cc3bf505254 --- /dev/null +++ b/src/lib/core/instance-runtime.test.ts @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// These tests prove the runtime call-site contract: setting `NEMOCLAW_INSTANCE` +// before importing the modules that capture the active instance at module load +// must route their on-disk paths under `~/.nemoclaw-` for the +// migrated surfaces (credentials store, local inference adapter state, Ollama +// auth-proxy token reader, rebuild backups, shields state). The pure resolver +// tests in `instance.test.ts` / `paths.test.ts` / `gateway-binding.test.ts` +// cover the underlying helpers; this file pins the integration so a regression +// in a downstream import would surface here. +// +// One test per migrated surface — each test gets a fresh tmpdir HOME, a fresh +// module graph (`vi.resetModules()`), and a fresh `process.env.NEMOCLAW_INSTANCE`, +// then dynamically imports the affected module so the module-load-time +// instance capture sees the configured value. + +const ORIGINAL_ENV = { ...process.env }; + +async function withFreshHome(fn: (home: string) => Promise | T): Promise { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-instance-runtime-")); + try { + return await fn(home); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +} + +describe("runtime call-site coverage under NEMOCLAW_INSTANCE", () => { + beforeEach(() => { + vi.resetModules(); + process.env = { ...ORIGINAL_ENV }; + }); + + afterEach(() => { + process.env = { ...ORIGINAL_ENV }; + vi.resetModules(); + }); + + // The bare-default ("unset NEMOCLAW_INSTANCE") behaviour is pinned by the + // pure resolver tests in src/lib/state/paths.test.ts and + // src/lib/onboard/gateway-binding.test.ts. This file asserts only the + // non-default-instance integration path because Vitest's per-file module + // graph captures the first-seen instance constant and does not re-evaluate + // it on subsequent in-file imports of CommonJS dist modules. + + it("getCredsDir() lands the credentials store under .nemoclaw-", async () => { + await withFreshHome(async (home) => { + process.env.HOME = home; + process.env.NEMOCLAW_INSTANCE = "agent-a"; + const { getCredsDir, getCredsFile } = await import("../../../dist/lib/credentials/store"); + expect(getCredsDir()).toBe(path.join(home, ".nemoclaw-agent-a")); + expect(getCredsFile()).toBe(path.join(home, ".nemoclaw-agent-a", "credentials.json")); + }); + }); + + it("DEFAULT_LOCAL_ADAPTER_STATE_DIR lands under .nemoclaw-", async () => { + await withFreshHome(async (home) => { + process.env.HOME = home; + process.env.NEMOCLAW_INSTANCE = "agent-a"; + const { DEFAULT_LOCAL_ADAPTER_STATE_DIR } = await import( + "../../../dist/lib/inference/local-adapter-lifecycle" + ); + expect(DEFAULT_LOCAL_ADAPTER_STATE_DIR).toBe(path.join(home, ".nemoclaw-agent-a")); + }); + }); + + it("Ollama auth-proxy reader and writer agree on the instance-scoped home dir", async () => { + await withFreshHome(async (home) => { + process.env.HOME = home; + process.env.NEMOCLAW_INSTANCE = "agent-a"; + const { resolveNemoclawHomeDir } = await import("../../../dist/lib/state/paths"); + const { DEFAULT_LOCAL_ADAPTER_STATE_DIR } = await import( + "../../../dist/lib/inference/local-adapter-lifecycle" + ); + // The writer (inference/ollama/proxy.ts) composes ollama-proxy-token + // under DEFAULT_LOCAL_ADAPTER_STATE_DIR. The reader + // (defaultLoadOllamaProxyToken in inference/local.ts) composes it under + // resolveNemoclawHomeDir(). Both must compose the same parent dir under + // the active instance so the probe sees the token the writer persists. + expect(DEFAULT_LOCAL_ADAPTER_STATE_DIR).toBe(resolveNemoclawHomeDir()); + expect(DEFAULT_LOCAL_ADAPTER_STATE_DIR).toBe(path.join(home, ".nemoclaw-agent-a")); + }); + }); + + it("rebuild-backups directory lands under .nemoclaw-/rebuild-backups", async () => { + await withFreshHome(async (home) => { + process.env.HOME = home; + process.env.NEMOCLAW_INSTANCE = "agent-a"; + const { resolveNemoclawHomeDir } = await import("../../../dist/lib/state/paths"); + // state/sandbox.ts caches REBUILD_BACKUPS_DIR at module load via the + // same helper. Asserting via the helper composes the same path the + // module captures, without dragging in sandbox.ts's heavy side-effect + // imports just to read a constant. + const composed = path.join(resolveNemoclawHomeDir(home), "rebuild-backups"); + expect(composed).toBe(path.join(home, ".nemoclaw-agent-a", "rebuild-backups")); + }); + }); + + it("shields state directory lands under .nemoclaw-/state", async () => { + await withFreshHome(async (home) => { + process.env.HOME = home; + process.env.NEMOCLAW_INSTANCE = "agent-a"; + const { resolveNemoclawStateDir } = await import("../../../dist/lib/state/paths"); + // shields/{index,audit,timer}.ts all capture STATE_DIR / AUDIT_DIR from + // resolveNemoclawStateDir() at module load. Asserting via the helper is + // sufficient — the modules close over the same value. + expect(resolveNemoclawStateDir(home)).toBe(path.join(home, ".nemoclaw-agent-a", "state")); + }); + }); +}); diff --git a/src/lib/core/instance.ts b/src/lib/core/instance.ts index f9d43104c00..d5a428fa502 100644 --- a/src/lib/core/instance.ts +++ b/src/lib/core/instance.ts @@ -33,12 +33,15 @@ * Scope of segregation in this groundwork: NemoClaw home directory, gateway * binding (name, state dir, compat container), credentials store (including * the legacy plaintext credentials file path), rebuild backups and the - * snapshot tree underneath, local inference adapter state, and the Ollama - * auth-proxy token reader/writer. Out of scope here and tracked as follow-up: - * the sandbox registry, onboard session state, messaging configuration, - * host-side mount roots, the uninstall plan, and the `config-io` host-root - * permission healer. Callers that have not yet migrated to - * `resolveNemoclawHomeDir()` still share state across instances. + * snapshot tree underneath, local inference adapter state, the Ollama + * auth-proxy token reader/writer, and every consumer of + * `resolveNemoclawStateDir()` — shields audit, shields posture, and the + * shields timer all already route through the instance-aware state dir. + * Out of scope here and tracked as follow-up: the sandbox registry, onboard + * session state, messaging configuration, host-side mount roots, the + * uninstall plan, and the `config-io` host-root permission healer. Callers + * that have not yet migrated to `resolveNemoclawHomeDir()` still share state + * across instances. * * This module is the single source of truth for resolving the active instance * name; downstream callers thread the resolved value through their own paths diff --git a/src/lib/state/paths.ts b/src/lib/state/paths.ts index 2109fe24aed..8623c96be34 100644 --- a/src/lib/state/paths.ts +++ b/src/lib/state/paths.ts @@ -24,12 +24,15 @@ export const BASE_NEMOCLAW_HOME_DIR_NAME = ".nemoclaw"; * credentials store (`credentials/store.ts`), rebuild backups + blueprint * digest (`state/sandbox.ts`), the local-adapter state directory and Ollama * auth-proxy token (`inference/local-adapter-lifecycle.ts`, `inference/local.ts`), - * and the gateway-name binding (`onboard/gateway-binding.ts`). Surfaces that - * still hard-code `.nemoclaw` — the sandbox registry (`state/registry.ts`), - * onboard session state (`state/onboard-session.ts`), messaging configuration, - * uninstall plan, host-side mount roots, and the `config-io` host-root - * permission healer — continue to share state across instances until - * follow-up PRs migrate them. + * the gateway-name binding (`onboard/gateway-binding.ts`), and every consumer + * of `resolveNemoclawStateDir()` — shields audit (`shields/audit.ts`), + * shields posture (`shields/index.ts`), and the shields timer + * (`shields/timer.ts`) all already land under `.nemoclaw-/state`. + * Surfaces that still hard-code `.nemoclaw` — the sandbox registry + * (`state/registry.ts`), onboard session state (`state/onboard-session.ts`), + * messaging configuration, uninstall plan, host-side mount roots, and the + * `config-io` host-root permission healer — continue to share state across + * instances until follow-up PRs migrate them. */ export function resolveNemoclawHomeDirName(instance: string = NEMOCLAW_INSTANCE): string { return isDefaultInstance(instance) From 2efd8cbe2f388b09b61f97ab99fece6b91a44535 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 15:51:55 +0000 Subject: [PATCH 08/29] fix: import downstream exports in runtime tests, narrow scope claim, drop issue refs Signed-off-by: Tinson Lai --- docs/reference/commands-nemohermes.mdx | 4 ++-- docs/reference/commands.mdx | 4 ++-- src/lib/core/instance-runtime.test.ts | 27 ++++++++++++------------- src/lib/onboard/gateway-binding.test.ts | 2 +- src/lib/onboard/gateway-binding.ts | 8 ++++---- src/lib/state/sandbox.ts | 2 +- 6 files changed, 23 insertions(+), 24 deletions(-) diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index 73f7667c6c9..ec0e009d067 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -1114,7 +1114,7 @@ The installer calls `backup-all` automatically before onboarding to protect agai ### `nemohermes snapshot create` Create a timestamped snapshot of sandbox state. -Snapshots are stored in `~/.nemoclaw/rebuild-backups//` for the default instance, or `~/.nemoclaw-/rebuild-backups//` when `NEMOCLAW_INSTANCE` is set to a non-default value. +The command writes the snapshot to `~/.nemoclaw/rebuild-backups//` for the default instance, or `~/.nemoclaw-/rebuild-backups//` when `NEMOCLAW_INSTANCE` is set to a non-default value. ```bash nemohermes my-assistant snapshot create @@ -1573,7 +1573,7 @@ All ports must be non-privileged integers between 1024 and 65535. | `NEMOCLAW_OLLAMA_PORT` | 11434 | Ollama inference | | `NEMOCLAW_OLLAMA_PROXY_PORT` | 11435 | Ollama auth proxy | | `NEMOCLAW_DASHBOARD_BIND` | *unset* (loopback) | Dashboard or API forward bind address. Set to `0.0.0.0` to opt in to remote bind for SSH-deployed hosts. | -| `NEMOCLAW_INSTANCE` | _historical default_ | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | +| `NEMOCLAW_INSTANCE` | nemoclaw | NemoClaw instance identity for multi-instance hosts. Scopes the migrated host-side surfaces — state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise), credentials store, rebuild backups, local inference adapter state, shields audit and timer state, and the OpenShell gateway binding. Registry, onboard session, messaging, mount roots, uninstall plan, and `config-io` host-root healing still share `~/.nemoclaw` until follow-up PRs migrate them. | If a port value is not a valid integer or falls outside the allowed range, the CLI exits with an error. `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 06e46d23d2a..4ca5e4ba19e 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1340,7 +1340,7 @@ The installer calls `backup-all` automatically before onboarding to protect agai ### `$$nemoclaw snapshot create` Create a timestamped snapshot of sandbox state. -Snapshots are stored in `~/.nemoclaw/rebuild-backups//` for the default instance, or `~/.nemoclaw-/rebuild-backups//` when `NEMOCLAW_INSTANCE` is set to a non-default value. +The command writes the snapshot to `~/.nemoclaw/rebuild-backups//` for the default instance, or `~/.nemoclaw-/rebuild-backups//` when `NEMOCLAW_INSTANCE` is set to a non-default value. ```bash $$nemoclaw my-assistant snapshot create @@ -1817,7 +1817,7 @@ All ports must be non-privileged integers between 1024 and 65535. | `NEMOCLAW_OLLAMA_PORT` | 11434 | Ollama inference | | `NEMOCLAW_OLLAMA_PROXY_PORT` | 11435 | Ollama auth proxy | | `NEMOCLAW_DASHBOARD_BIND` | *unset* (loopback) | Dashboard or API forward bind address. Set to `0.0.0.0` to opt in to remote bind for SSH-deployed hosts. | -| `NEMOCLAW_INSTANCE` | _historical default_ | NemoClaw instance identity for multi-instance hosts. Scopes the state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise) and the OpenShell gateway name so two instances on the same host stay segregated. | +| `NEMOCLAW_INSTANCE` | nemoclaw | NemoClaw instance identity for multi-instance hosts. Scopes the migrated host-side surfaces — state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise), credentials store, rebuild backups, local inference adapter state, shields audit and timer state, and the OpenShell gateway binding. Registry, onboard session, messaging, mount roots, uninstall plan, and `config-io` host-root healing still share `~/.nemoclaw` until follow-up PRs migrate them. | If a port value is not a valid integer or falls outside the allowed range, the CLI exits with an error. `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. diff --git a/src/lib/core/instance-runtime.test.ts b/src/lib/core/instance-runtime.test.ts index cc3bf505254..4030686a58a 100644 --- a/src/lib/core/instance-runtime.test.ts +++ b/src/lib/core/instance-runtime.test.ts @@ -89,29 +89,28 @@ describe("runtime call-site coverage under NEMOCLAW_INSTANCE", () => { }); }); - it("rebuild-backups directory lands under .nemoclaw-/rebuild-backups", async () => { + it("state/sandbox.ts captures REBUILD_BACKUPS_DIR under .nemoclaw-/rebuild-backups", async () => { await withFreshHome(async (home) => { process.env.HOME = home; process.env.NEMOCLAW_INSTANCE = "agent-a"; - const { resolveNemoclawHomeDir } = await import("../../../dist/lib/state/paths"); - // state/sandbox.ts caches REBUILD_BACKUPS_DIR at module load via the - // same helper. Asserting via the helper composes the same path the - // module captures, without dragging in sandbox.ts's heavy side-effect - // imports just to read a constant. - const composed = path.join(resolveNemoclawHomeDir(home), "rebuild-backups"); - expect(composed).toBe(path.join(home, ".nemoclaw-agent-a", "rebuild-backups")); + const { REBUILD_BACKUPS_DIR } = await import("../../../dist/lib/state/sandbox"); + expect(REBUILD_BACKUPS_DIR).toBe(path.join(home, ".nemoclaw-agent-a", "rebuild-backups")); }); }); - it("shields state directory lands under .nemoclaw-/state", async () => { + it("shields/audit.ts captures AUDIT_DIR / AUDIT_FILE under .nemoclaw-/state", async () => { await withFreshHome(async (home) => { process.env.HOME = home; process.env.NEMOCLAW_INSTANCE = "agent-a"; - const { resolveNemoclawStateDir } = await import("../../../dist/lib/state/paths"); - // shields/{index,audit,timer}.ts all capture STATE_DIR / AUDIT_DIR from - // resolveNemoclawStateDir() at module load. Asserting via the helper is - // sufficient — the modules close over the same value. - expect(resolveNemoclawStateDir(home)).toBe(path.join(home, ".nemoclaw-agent-a", "state")); + const { AUDIT_DIR, AUDIT_FILE } = await import("../../../dist/lib/shields/audit"); + const expectedStateDir = path.join(home, ".nemoclaw-agent-a", "state"); + expect(AUDIT_DIR).toBe(expectedStateDir); + expect(AUDIT_FILE).toBe(path.join(expectedStateDir, "shields-audit.jsonl")); + // shields/index.ts and shields/timer.ts capture their own STATE_DIR + // constants from the same `resolveNemoclawStateDir()` call, so the + // audit module's captured value is the canonical observable: a + // regression in the resolver, the helper, or the import order would + // surface here too. }); }); }); diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index f02fdd38de6..42ffb7dab59 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -63,7 +63,7 @@ describe("gateway-binding resolver (#4422)", () => { }); }); -describe("gateway-binding resolver factors NEMOCLAW_INSTANCE (#3053)", () => { +describe("gateway-binding resolver factors NEMOCLAW_INSTANCE", () => { const DEFAULT_INSTANCE = DEFAULT_NEMOCLAW_INSTANCE; it("suffixes the gateway name with the instance for a non-default instance on the default port", () => { diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index e0220f6bc03..b11fe1b2edc 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -9,15 +9,15 @@ * a single compatibility container. A second onboard that requested a * different `NEMOCLAW_GATEWAY_PORT` therefore reused the same named gateway, * the same runtime-marker state dir, and the same compat container — so - * creating the second sandbox recreated/killed the first sandbox's gateway and - * overwrote its runtime marker (#4422). + * creating the second sandbox recreated/killed the first sandbox's gateway + * and overwrote its runtime marker. * * These pure resolvers derive a stable per-binding identity along two * independent axes: * * 1. **Gateway port** — the original `nemoclaw-` suffix introduced for - * `NEMOCLAW_GATEWAY_PORT` (#4422). The default port keeps the bare - * `nemoclaw` name verbatim for backward compatibility. + * `NEMOCLAW_GATEWAY_PORT`. The default port keeps the bare `nemoclaw` + * name verbatim for backward compatibility. * 2. **NemoClaw instance** — the `NEMOCLAW_INSTANCE` identity that scopes the * entire host-side install (state root, gateway name, lifecycle). The * default instance keeps the bare `nemoclaw` name verbatim; any other diff --git a/src/lib/state/sandbox.ts b/src/lib/state/sandbox.ts index d9ab5110ed7..715d72a1c5c 100644 --- a/src/lib/state/sandbox.ts +++ b/src/lib/state/sandbox.ts @@ -42,7 +42,7 @@ import * as registry from "./registry.js"; import { runTarListing } from "./tar-listing.js"; const HOME_DIR = path.resolve(process.env.HOME || os.homedir()); -const REBUILD_BACKUPS_DIR = path.join(resolveNemoclawHomeDir(HOME_DIR), "rebuild-backups"); +export const REBUILD_BACKUPS_DIR = path.join(resolveNemoclawHomeDir(HOME_DIR), "rebuild-backups"); const MANIFEST_VERSION = 1; From 815111fd8046a2b2a8eae1a1d030a5b86bf1eee7 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 17:30:08 +0000 Subject: [PATCH 09/29] refactor(gateway): centralise gateway-name literal, resolve per-sandbox gateway Signed-off-by: Tinson Lai --- docs/reference/commands-nemohermes.mdx | 21 +-- docs/reference/commands.mdx | 21 +-- src/commands/internal/uninstall/plan.ts | 7 +- src/commands/internal/uninstall/run-plan.ts | 7 +- src/lib/actions/sandbox/connect.ts | 4 +- src/lib/actions/sandbox/destroy.ts | 21 ++- src/lib/actions/sandbox/doctor.ts | 16 +- .../sandbox/gateway-state-drift.test.ts | 2 + src/lib/actions/sandbox/gateway-state.ts | 21 ++- src/lib/actions/sandbox/rebuild.ts | 11 +- src/lib/actions/sandbox/snapshot.test.ts | 1 + src/lib/actions/sandbox/snapshot.ts | 23 ++- src/lib/actions/uninstall/run-plan.ts | 3 +- src/lib/adapters/openshell/gateway-drift.ts | 4 +- src/lib/core/instance-runtime.test.ts | 116 ------------- src/lib/core/instance.test.ts | 117 ------------- src/lib/core/instance.ts | 116 ------------- src/lib/credentials/store.ts | 12 +- src/lib/domain/uninstall/paths.ts | 4 +- src/lib/gateway-runtime-action.ts | 40 +++-- src/lib/inference/live.ts | 4 +- src/lib/inference/local-adapter-lifecycle.ts | 7 +- src/lib/inference/local.ts | 15 +- src/lib/onboard.ts | 2 +- src/lib/onboard/gateway-binding.test.ts | 163 ++++-------------- src/lib/onboard/gateway-binding.ts | 125 ++++++++------ src/lib/resources-cmd.ts | 4 +- src/lib/state/gateway.ts | 19 +- src/lib/state/onboard-session.ts | 6 +- src/lib/state/paths.test.ts | 58 +------ src/lib/state/paths.ts | 45 +---- src/lib/state/sandbox.ts | 14 +- 32 files changed, 259 insertions(+), 770 deletions(-) delete mode 100644 src/lib/core/instance-runtime.test.ts delete mode 100644 src/lib/core/instance.test.ts delete mode 100644 src/lib/core/instance.ts diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index ec0e009d067..58c6ccb8d38 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -1102,7 +1102,7 @@ If the registry is unreachable (offline or firewalled hosts), NemoClaw falls bac ### `nemohermes backup-all` -Back up all registered running sandboxes to `~/.nemoclaw/rebuild-backups/` for the default instance, or `~/.nemoclaw-/rebuild-backups/` when `NEMOCLAW_INSTANCE` is set to a non-default value (see the Environment Variables section). +Back up all registered running sandboxes to `~/.nemoclaw/rebuild-backups/`. Sandboxes that are not running are skipped. ```bash @@ -1114,7 +1114,7 @@ The installer calls `backup-all` automatically before onboarding to protect agai ### `nemohermes snapshot create` Create a timestamped snapshot of sandbox state. -The command writes the snapshot to `~/.nemoclaw/rebuild-backups//` for the default instance, or `~/.nemoclaw-/rebuild-backups//` when `NEMOCLAW_INSTANCE` is set to a non-default value. +Snapshots are stored in `~/.nemoclaw/rebuild-backups//`. ```bash nemohermes my-assistant snapshot create @@ -1573,27 +1573,10 @@ All ports must be non-privileged integers between 1024 and 65535. | `NEMOCLAW_OLLAMA_PORT` | 11434 | Ollama inference | | `NEMOCLAW_OLLAMA_PROXY_PORT` | 11435 | Ollama auth proxy | | `NEMOCLAW_DASHBOARD_BIND` | *unset* (loopback) | Dashboard or API forward bind address. Set to `0.0.0.0` to opt in to remote bind for SSH-deployed hosts. | -| `NEMOCLAW_INSTANCE` | nemoclaw | NemoClaw instance identity for multi-instance hosts. Scopes the migrated host-side surfaces — state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise), credentials store, rebuild backups, local inference adapter state, shields audit and timer state, and the OpenShell gateway binding. Registry, onboard session, messaging, mount roots, uninstall plan, and `config-io` host-root healing still share `~/.nemoclaw` until follow-up PRs migrate them. | If a port value is not a valid integer or falls outside the allowed range, the CLI exits with an error. `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` values, NemoClaw derives a separate gateway name, state directory, and compatibility container name from the port so one gateway does not tear down another. - -`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). -Hyphen-separated segments may not be purely numeric so the instance name cannot collide with the gateway port suffix. -Without this rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name. - -The default instance name is the historical singleton identity NemoClaw has always used. -Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it explicitly to that default value all resolve to the same identity. -The state root then stays at `~/.nemoclaw` and the OpenShell gateway keeps its bare historical name (`nemoclaw-` for non-default ports, with no suffix on the default port). -Existing single-instance deployments therefore observe no change after upgrading. -When the bare default gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE`. -The port suffix is the implicit fallback identity for the default instance. - -Setting `NEMOCLAW_INSTANCE` to a non-default value before `nemohermes onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state (including the Ollama auth-proxy token), shields audit and timer state, and gateway binding (name, state directory, compatibility container) to that instance. -Combine `NEMOCLAW_INSTANCE` with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). -Modules that still read `~/.nemoclaw` directly continue to share state across instances until follow-up PRs migrate them. -These remaining shared surfaces are the sandbox registry, onboard session state, messaging configuration, host-side mount roots, the uninstall plan, and the `config-io` host-root permission healer. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 4ca5e4ba19e..22270cafd6d 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1328,7 +1328,7 @@ If the registry is unreachable (offline or firewalled hosts), NemoClaw falls bac ### `$$nemoclaw backup-all` -Back up all registered running sandboxes to `~/.nemoclaw/rebuild-backups/` for the default instance, or `~/.nemoclaw-/rebuild-backups/` when `NEMOCLAW_INSTANCE` is set to a non-default value (see the Environment Variables section). +Back up all registered running sandboxes to `~/.nemoclaw/rebuild-backups/`. Sandboxes that are not running are skipped. ```bash @@ -1340,7 +1340,7 @@ The installer calls `backup-all` automatically before onboarding to protect agai ### `$$nemoclaw snapshot create` Create a timestamped snapshot of sandbox state. -The command writes the snapshot to `~/.nemoclaw/rebuild-backups//` for the default instance, or `~/.nemoclaw-/rebuild-backups//` when `NEMOCLAW_INSTANCE` is set to a non-default value. +Snapshots are stored in `~/.nemoclaw/rebuild-backups//`. ```bash $$nemoclaw my-assistant snapshot create @@ -1817,27 +1817,10 @@ All ports must be non-privileged integers between 1024 and 65535. | `NEMOCLAW_OLLAMA_PORT` | 11434 | Ollama inference | | `NEMOCLAW_OLLAMA_PROXY_PORT` | 11435 | Ollama auth proxy | | `NEMOCLAW_DASHBOARD_BIND` | *unset* (loopback) | Dashboard or API forward bind address. Set to `0.0.0.0` to opt in to remote bind for SSH-deployed hosts. | -| `NEMOCLAW_INSTANCE` | nemoclaw | NemoClaw instance identity for multi-instance hosts. Scopes the migrated host-side surfaces — state root (`~/.nemoclaw` for the default instance, `~/.nemoclaw-` otherwise), credentials store, rebuild backups, local inference adapter state, shields audit and timer state, and the OpenShell gateway binding. Registry, onboard session, messaging, mount roots, uninstall plan, and `config-io` host-root healing still share `~/.nemoclaw` until follow-up PRs migrate them. | If a port value is not a valid integer or falls outside the allowed range, the CLI exits with an error. `NEMOCLAW_GATEWAY_PORT` also cannot overlap the configured dashboard, vLLM, Ollama, or Ollama proxy ports, and cannot use the dashboard auto-allocation range `18789` through `18799` or the default inference/proxy ports `8000`, `11434`, and `11435`. When you run multiple NemoClaw gateways with different `NEMOCLAW_GATEWAY_PORT` values, NemoClaw derives a separate gateway name, state directory, and compatibility container name from the port so one gateway does not tear down another. - -`NEMOCLAW_INSTANCE` must be 1–32 lower-case alphanumerics with internal `-` (for example `agent-a`, `tenant1`). -Hyphen-separated segments may not be purely numeric so the instance name cannot collide with the gateway port suffix. -Without this rule, `agent-a` plus `NEMOCLAW_GATEWAY_PORT=8081` and `agent-a-8081` plus the default port would produce the same composed name. - -The default instance name is the historical singleton identity NemoClaw has always used. -Leaving `NEMOCLAW_INSTANCE` unset, setting it to the empty string, or setting it explicitly to that default value all resolve to the same identity. -The state root then stays at `~/.nemoclaw` and the OpenShell gateway keeps its bare historical name (`nemoclaw-` for non-default ports, with no suffix on the default port). -Existing single-instance deployments therefore observe no change after upgrading. -When the bare default gateway is already in use, varying `NEMOCLAW_GATEWAY_PORT` alone produces a `nemoclaw-` gateway that segregates from the bare default without requiring `NEMOCLAW_INSTANCE`. -The port suffix is the implicit fallback identity for the default instance. - -Setting `NEMOCLAW_INSTANCE` to a non-default value before `$$nemoclaw onboard` routes the NemoClaw home directory, credentials store, rebuild backups (and the snapshot tree underneath), local inference adapter state (including the Ollama auth-proxy token), shields audit and timer state, and gateway binding (name, state directory, compatibility container) to that instance. -Combine `NEMOCLAW_INSTANCE` with `NEMOCLAW_GATEWAY_PORT` to compose the instance and port suffixes (`nemoclaw--`). -Modules that still read `~/.nemoclaw` directly continue to share state across instances until follow-up PRs migrate them. -These remaining shared surfaces are the sandbox registry, onboard session state, messaging configuration, host-side mount roots, the uninstall plan, and the `config-io` host-root permission healer. On non-WSL hosts, `NEMOCLAW_OLLAMA_PORT` and `NEMOCLAW_OLLAMA_PROXY_PORT` must be different. If you run Ollama on port 11435, set `NEMOCLAW_OLLAMA_PROXY_PORT` to another free port before onboarding. diff --git a/src/commands/internal/uninstall/plan.ts b/src/commands/internal/uninstall/plan.ts index ad94012087b..4303cbcac0b 100644 --- a/src/commands/internal/uninstall/plan.ts +++ b/src/commands/internal/uninstall/plan.ts @@ -5,6 +5,8 @@ import { Flags } from "@oclif/core"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../../lib/cli/branding"; import { jsonFlag } from "../../../lib/cli/common-flags"; import { NemoClawCommand } from "../../../lib/cli/nemoclaw-oclif-command"; +import { GATEWAY_PORT } from "../../../lib/core/ports"; +import { resolveGatewayName } from "../../../lib/onboard/gateway-binding"; import { buildHostUninstallPlan } from "../../../lib/actions/uninstall/plan"; @@ -24,7 +26,10 @@ export default class InternalUninstallPlanCommand extends NemoClawCommand { description: `Plan removal of ${CLI_DISPLAY_NAME}-pulled Ollama models`, }), "keep-openshell": Flags.boolean({ description: "Keep the openshell binary installed" }), - gateway: Flags.string({ description: "Gateway name", default: "nemoclaw" }), + gateway: Flags.string({ + description: "Gateway name", + default: resolveGatewayName(GATEWAY_PORT), + }), }; public async run(): Promise { diff --git a/src/commands/internal/uninstall/run-plan.ts b/src/commands/internal/uninstall/run-plan.ts index 26809e33e35..e1b8758dac3 100644 --- a/src/commands/internal/uninstall/run-plan.ts +++ b/src/commands/internal/uninstall/run-plan.ts @@ -6,6 +6,8 @@ import { NemoClawCommand } from "../../../lib/cli/nemoclaw-oclif-command"; import { runUninstallPlan } from "../../../lib/actions/uninstall/run-plan"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../../lib/cli/branding"; +import { GATEWAY_PORT } from "../../../lib/core/ports"; +import { resolveGatewayName } from "../../../lib/onboard/gateway-binding"; export default class InternalUninstallRunPlanCommand extends NemoClawCommand { static hidden = true; @@ -20,7 +22,10 @@ export default class InternalUninstallRunPlanCommand extends NemoClawCommand { "delete-models": Flags.boolean({ description: `Remove ${CLI_DISPLAY_NAME}-pulled Ollama models`, }), - gateway: Flags.string({ description: "Gateway name", default: "nemoclaw" }), + gateway: Flags.string({ + description: "Gateway name", + default: resolveGatewayName(GATEWAY_PORT), + }), }; public async run(): Promise { diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 874234b015a..f091097d713 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -26,6 +26,7 @@ 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 { isWsl } from "../../platform"; import { ROOT } from "../../runner"; import * as sandboxVersion from "../../sandbox/version"; @@ -54,7 +55,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; @@ -512,7 +512,7 @@ function repairSandboxInferenceRouteIfNeeded( reapplyVmInferenceRoute, repairLegacyDnsProxy: (name, isQuiet) => runSetupDnsProxy( - { gatewayName: NEMOCLAW_GATEWAY_NAME, sandboxName: name }, + { gatewayName: resolveSandboxGatewayName(sb), sandboxName: name }, { log: isQuiet ? () => undefined : console.log }, ), }, diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 89b591c2a9c..e5d4507cfb4 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -8,7 +8,7 @@ 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 { DASHBOARD_PORT, GATEWAY_PORT } from "../../core/ports"; import { prompt as askPrompt } from "../../credentials/store"; import { type DestroySandboxOptions, @@ -19,6 +19,10 @@ import { shouldCleanupGatewayAfterDestroy, shouldStopHostServicesAfterDestroy, } from "../../domain/sandbox/destroy"; +import { + resolveGatewayName, + resolveSandboxGatewayName, +} from "../../onboard/gateway-binding"; import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; import { @@ -76,10 +80,10 @@ type RemoveShieldsStateDeps = { warn?: (message: string) => void; }; -const NEMOCLAW_GATEWAY_NAME = "nemoclaw"; const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); function cleanupGatewayAfterLastSandbox(): void { + const gatewayName = resolveGatewayName(GATEWAY_PORT); const { runOpenshell } = require("../../adapters/openshell/runtime") as { runOpenshell: (args: string[], opts?: Record) => { status: number | null }; }; @@ -103,22 +107,22 @@ function cleanupGatewayAfterLastSandbox(): void { // 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], { + const removeResult = runOpenshell(["gateway", "remove", gatewayName], { ignoreError: true, stdio: ["ignore", "pipe", "pipe"], }); if (removeResult.status !== 0) { - runOpenshell(["gateway", "destroy", "-g", NEMOCLAW_GATEWAY_NAME], { + runOpenshell(["gateway", "destroy", "-g", gatewayName], { ignoreError: true, stdio: ["ignore", "pipe", "pipe"], }); } } else { - runOpenshell(["gateway", "destroy", "-g", NEMOCLAW_GATEWAY_NAME], { + runOpenshell(["gateway", "destroy", "-g", gatewayName], { ignoreError: true, }); } - dockerRemoveVolumesByPrefix(`openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`, { + dockerRemoveVolumesByPrefix(`openshell-cluster-${gatewayName}`, { ignoreError: true, }); } @@ -457,10 +461,11 @@ export async function destroySandbox( if (shouldCleanupGateway) { cleanupGatewayAfterLastSandbox(); } else { + const preservedGatewayName = resolveGatewayName(GATEWAY_PORT); const gatewayRemovalHint = process.platform === "linux" - ? `openshell gateway remove ${NEMOCLAW_GATEWAY_NAME}` - : `openshell gateway destroy -g ${NEMOCLAW_GATEWAY_NAME}`; + ? `openshell gateway remove ${preservedGatewayName}` + : `openshell gateway destroy -g ${preservedGatewayName}`; console.log( ` Shared NemoClaw gateway preserved. Re-run '${gatewayRemovalHint}' to remove it,`, ); diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index 13ee084e209..7c61bd4b74f 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -18,6 +18,10 @@ 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"; @@ -37,7 +41,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"; @@ -550,6 +553,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 @@ -603,15 +607,17 @@ 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, }), ); diff --git a/src/lib/actions/sandbox/gateway-state-drift.test.ts b/src/lib/actions/sandbox/gateway-state-drift.test.ts index 8830dd1fa40..4fefcff0915 100644 --- a/src/lib/actions/sandbox/gateway-state-drift.test.ts +++ b/src/lib/actions/sandbox/gateway-state-drift.test.ts @@ -49,6 +49,8 @@ describe("sandbox gateway state drift guard", () => { const gatewayRuntime = requireDist("../../../../dist/lib/gateway-runtime-action.js"); const registry = requireDist("../../../../dist/lib/state/registry.js"); + vi.spyOn(registry, "getSandbox").mockReturnValue(null); + captureOpenshellSpy = vi .spyOn(openshellRuntime, "captureOpenshell") .mockReturnValue({ status: 0, output: "Sandbox:\n Name: alpha\n Phase: Ready" }); diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 080ee32bdb6..1844b72c31e 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -6,11 +6,17 @@ import os from "node:os"; import path from "node:path"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../cli/branding"; +import { GATEWAY_PORT } from "../../core/ports"; import { getNamedGatewayLifecycleState, recoverNamedGatewayRuntime, } from "../../gateway-runtime-action"; +import { + resolveGatewayName, + resolveSandboxGatewayName, +} from "../../onboard/gateway-binding"; import { isTerminalSandboxPhase, parseSandboxPhase } from "../../state/gateway"; +import * as registry from "../../state/registry"; const { pruneKnownHostsEntries } = require("../../onboard") as { pruneKnownHostsEntries: (contents: string) => string; @@ -227,9 +233,11 @@ export function reconcileMissingAgainstNamedGateway( sandboxName: string, missingLookup: SandboxGatewayState, ): SandboxGatewayState { - const lifecycle = getNamedGatewayLifecycleState(); + const sb = registry.getSandbox(sandboxName); + const targetGatewayName = sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); + const lifecycle = getNamedGatewayLifecycleState(targetGatewayName); if (lifecycle.state === "connected_other") { - runOpenshell(["gateway", "select", "nemoclaw"], { + runOpenshell(["gateway", "select", targetGatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); @@ -317,12 +325,15 @@ export function printWrongGatewayActiveGuidance( // guidance points back to the workflow the user actually invoked. retryCommand = "connect", ): void { - const other = activeGateway && activeGateway !== "nemoclaw" ? activeGateway : "another gateway"; + const sb = registry.getSandbox(sandboxName); + const targetGatewayName = sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); + const other = + activeGateway && activeGateway !== targetGatewayName ? activeGateway : "another gateway"; writer( - ` Sandbox '${sandboxName}' is registered against the ${CLI_DISPLAY_NAME} gateway, but the currently active OpenShell gateway is '${other}'. Your sandbox has NOT been removed.`, + ` Sandbox '${sandboxName}' is registered against the ${CLI_DISPLAY_NAME} gateway '${targetGatewayName}', but the currently active OpenShell gateway is '${other}'. Your sandbox has NOT been removed.`, ); writer(" Switch gateways and retry:"); - writer(" openshell gateway select nemoclaw"); + writer(` openshell gateway select ${targetGatewayName}`); writer(` Then re-run: ${CLI_NAME} ${sandboxName} ${retryCommand}`); } diff --git a/src/lib/actions/sandbox/rebuild.ts b/src/lib/actions/sandbox/rebuild.ts index e53c1dc4261..da38b78eecf 100644 --- a/src/lib/actions/sandbox/rebuild.ts +++ b/src/lib/actions/sandbox/rebuild.ts @@ -2,7 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { CLI_NAME } from "../../cli/branding"; +import { GATEWAY_PORT } from "../../core/ports"; import { prompt as askPrompt } from "../../credentials/store"; +import { + resolveGatewayName, + resolveSandboxGatewayName, +} from "../../onboard/gateway-binding"; import { normalizeRebuildSandboxOptions, type RebuildSandboxOptions, @@ -586,9 +591,9 @@ export async function rebuildSandbox( // orphan its live workspace. Refuse the destructive path in that case and // point the operator at the sandbox's own gateway. (If that gateway were // active, the sandbox would have appeared in the list above.) - const recordedGateway = - typeof sb.gatewayName === "string" && sb.gatewayName ? sb.gatewayName : "nemoclaw"; - if (recordedGateway !== "nemoclaw") { + const recordedGateway = resolveSandboxGatewayName(sb); + const activeDefaultGateway = resolveGatewayName(GATEWAY_PORT); + if (recordedGateway !== activeDefaultGateway) { console.error( ` Sandbox '${sandboxName}' is registered on the '${recordedGateway}' OpenShell gateway, which is not the active gateway.`, ); diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index 2dd22b61e16..95c1e732db6 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -47,6 +47,7 @@ vi.mock("../../shields", () => ({ })); vi.mock("../../state/gateway", () => ({ + BASE_GATEWAY_NAME: "nemoclaw", isGatewayHealthy: isGatewayHealthyMock, })); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 47e2398de41..e2edd920852 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -12,6 +12,11 @@ import { import { CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt } from "../../credentials/store"; import { getSandboxDeleteOutcome } from "../../domain/sandbox/destroy"; +import { GATEWAY_PORT } from "../../core/ports"; +import { + resolveGatewayName, + resolveSandboxGatewayName, +} from "../../onboard/gateway-binding"; import * as policies from "../../policy"; import { ROOT, run, shellQuote, validateName } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; @@ -30,8 +35,6 @@ const B = useColor ? "\x1b[1m" : ""; const D = useColor ? "\x1b[2m" : ""; const R = useColor ? "\x1b[0m" : ""; -const NEMOCLAW_GATEWAY_NAME = "nemoclaw"; - export type SnapshotRequest = | { kind: "help" } | { kind: "create"; name?: string } @@ -116,7 +119,7 @@ function resolveSrcPodImage( return registeredImage ?? null; } - const gatewayContainer = `openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`; + const gatewayContainer = `openshell-cluster-${resolveSandboxGatewayName(srcEntry as { gatewayName?: string | null; gatewayPort?: number | null })}`; try { const output = dockerCapture( [ @@ -207,7 +210,7 @@ async function autoCreateSandboxFromSource( const dnsScript = path.join(ROOT, "scripts", "setup-dns-proxy.sh"); const srcDriver = (srcEntry as { openshellDriver?: string | null }).openshellDriver; if (srcDriver === "kubernetes" && fs.existsSync(dnsScript)) { - run(["bash", dnsScript, NEMOCLAW_GATEWAY_NAME, dstName], { ignoreError: true }); + run(["bash", dnsScript, resolveSandboxGatewayName(srcEntry as { gatewayName?: string | null; gatewayPort?: number | null }), dstName], { ignoreError: true }); } // Register dst in the NemoClaw registry, cloning most fields from src. @@ -294,9 +297,9 @@ function deleteSandboxForRestore(name: string): void { // Docker/VM-driver sandboxes do not expose the legacy cluster container, so // verify gateway health through OpenShell metadata instead. -function probeGatewayMetadataHealth(): boolean { +function probeGatewayMetadataHealth(gatewayName: string): boolean { const status = captureOpenshell(["status"], { ignoreError: true, timeout: 10000 }); - const namedGatewayInfo = captureOpenshell(["gateway", "info", "-g", NEMOCLAW_GATEWAY_NAME], { + const namedGatewayInfo = captureOpenshell(["gateway", "info", "-g", gatewayName], { ignoreError: true, timeout: 10000, }); @@ -308,6 +311,7 @@ function probeGatewayMetadataHealth(): boolean { status.output || "", namedGatewayInfo.output || "", activeGatewayInfo.output || "", + gatewayName, ); } @@ -317,10 +321,13 @@ function usesGatewayMetadataProbe(driver: string | null | undefined): boolean { function probeGatewayRunning(sandboxName?: string): boolean { const entry = sandboxName ? registry.getSandbox(sandboxName) : null; + const gatewayName = entry + ? resolveSandboxGatewayName(entry) + : resolveGatewayName(GATEWAY_PORT); if (usesGatewayMetadataProbe(entry?.openshellDriver)) { - return probeGatewayMetadataHealth(); + return probeGatewayMetadataHealth(gatewayName); } - const container = `openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`; + const container = `openshell-cluster-${gatewayName}`; const result = dockerInspect( ["--type", "container", "--format", "{{.State.Running}}", container], { ignoreError: true, suppressOutput: true }, diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index d52d95ab089..02116134d32 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -16,6 +16,7 @@ import { type UninstallPaths, } from "../../domain/uninstall/paths"; import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; +import { DEFAULT_GATEWAY_NAME } from "../../domain/uninstall/paths"; import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; import { classifyShimPath, type FileSystemDeps } from "./plan"; @@ -529,7 +530,7 @@ function removeOpenShellResources(options: UninstallRunOptions, runtime: Uninsta provider, ]); } - const gatewayLabel = options.gatewayName || "nemoclaw"; + const gatewayLabel = options.gatewayName || DEFAULT_GATEWAY_NAME; runOptional( runtime, `Destroyed gateway '${gatewayLabel}'`, diff --git a/src/lib/adapters/openshell/gateway-drift.ts b/src/lib/adapters/openshell/gateway-drift.ts index 024f610f46a..3c2b35b5fd8 100644 --- a/src/lib/adapters/openshell/gateway-drift.ts +++ b/src/lib/adapters/openshell/gateway-drift.ts @@ -16,14 +16,14 @@ import { resolveDockerDriverGatewayStateDir, } from "../../onboard/host-gateway-process"; import { isOpenShellProtobufSchemaMismatch } from "../../runtime-recovery"; -import { isGatewayHealthy } from "../../state/gateway"; +import { BASE_GATEWAY_NAME, isGatewayHealthy } from "../../state/gateway"; import { dockerContainerInspectFormat } from "../docker"; import { parseVersionFromText, stripAnsi } from "./client"; import { resolveOpenshell } from "./resolve"; import { captureOpenshell, getInstalledOpenshellVersionOrNull } from "./runtime"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "./timeouts"; -const DEFAULT_GATEWAY_NAME = "nemoclaw"; +const DEFAULT_GATEWAY_NAME = BASE_GATEWAY_NAME; export type GatewayClusterImageDrift = { containerName: string; diff --git a/src/lib/core/instance-runtime.test.ts b/src/lib/core/instance-runtime.test.ts deleted file mode 100644 index 4030686a58a..00000000000 --- a/src/lib/core/instance-runtime.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -// These tests prove the runtime call-site contract: setting `NEMOCLAW_INSTANCE` -// before importing the modules that capture the active instance at module load -// must route their on-disk paths under `~/.nemoclaw-` for the -// migrated surfaces (credentials store, local inference adapter state, Ollama -// auth-proxy token reader, rebuild backups, shields state). The pure resolver -// tests in `instance.test.ts` / `paths.test.ts` / `gateway-binding.test.ts` -// cover the underlying helpers; this file pins the integration so a regression -// in a downstream import would surface here. -// -// One test per migrated surface — each test gets a fresh tmpdir HOME, a fresh -// module graph (`vi.resetModules()`), and a fresh `process.env.NEMOCLAW_INSTANCE`, -// then dynamically imports the affected module so the module-load-time -// instance capture sees the configured value. - -const ORIGINAL_ENV = { ...process.env }; - -async function withFreshHome(fn: (home: string) => Promise | T): Promise { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-instance-runtime-")); - try { - return await fn(home); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } -} - -describe("runtime call-site coverage under NEMOCLAW_INSTANCE", () => { - beforeEach(() => { - vi.resetModules(); - process.env = { ...ORIGINAL_ENV }; - }); - - afterEach(() => { - process.env = { ...ORIGINAL_ENV }; - vi.resetModules(); - }); - - // The bare-default ("unset NEMOCLAW_INSTANCE") behaviour is pinned by the - // pure resolver tests in src/lib/state/paths.test.ts and - // src/lib/onboard/gateway-binding.test.ts. This file asserts only the - // non-default-instance integration path because Vitest's per-file module - // graph captures the first-seen instance constant and does not re-evaluate - // it on subsequent in-file imports of CommonJS dist modules. - - it("getCredsDir() lands the credentials store under .nemoclaw-", async () => { - await withFreshHome(async (home) => { - process.env.HOME = home; - process.env.NEMOCLAW_INSTANCE = "agent-a"; - const { getCredsDir, getCredsFile } = await import("../../../dist/lib/credentials/store"); - expect(getCredsDir()).toBe(path.join(home, ".nemoclaw-agent-a")); - expect(getCredsFile()).toBe(path.join(home, ".nemoclaw-agent-a", "credentials.json")); - }); - }); - - it("DEFAULT_LOCAL_ADAPTER_STATE_DIR lands under .nemoclaw-", async () => { - await withFreshHome(async (home) => { - process.env.HOME = home; - process.env.NEMOCLAW_INSTANCE = "agent-a"; - const { DEFAULT_LOCAL_ADAPTER_STATE_DIR } = await import( - "../../../dist/lib/inference/local-adapter-lifecycle" - ); - expect(DEFAULT_LOCAL_ADAPTER_STATE_DIR).toBe(path.join(home, ".nemoclaw-agent-a")); - }); - }); - - it("Ollama auth-proxy reader and writer agree on the instance-scoped home dir", async () => { - await withFreshHome(async (home) => { - process.env.HOME = home; - process.env.NEMOCLAW_INSTANCE = "agent-a"; - const { resolveNemoclawHomeDir } = await import("../../../dist/lib/state/paths"); - const { DEFAULT_LOCAL_ADAPTER_STATE_DIR } = await import( - "../../../dist/lib/inference/local-adapter-lifecycle" - ); - // The writer (inference/ollama/proxy.ts) composes ollama-proxy-token - // under DEFAULT_LOCAL_ADAPTER_STATE_DIR. The reader - // (defaultLoadOllamaProxyToken in inference/local.ts) composes it under - // resolveNemoclawHomeDir(). Both must compose the same parent dir under - // the active instance so the probe sees the token the writer persists. - expect(DEFAULT_LOCAL_ADAPTER_STATE_DIR).toBe(resolveNemoclawHomeDir()); - expect(DEFAULT_LOCAL_ADAPTER_STATE_DIR).toBe(path.join(home, ".nemoclaw-agent-a")); - }); - }); - - it("state/sandbox.ts captures REBUILD_BACKUPS_DIR under .nemoclaw-/rebuild-backups", async () => { - await withFreshHome(async (home) => { - process.env.HOME = home; - process.env.NEMOCLAW_INSTANCE = "agent-a"; - const { REBUILD_BACKUPS_DIR } = await import("../../../dist/lib/state/sandbox"); - expect(REBUILD_BACKUPS_DIR).toBe(path.join(home, ".nemoclaw-agent-a", "rebuild-backups")); - }); - }); - - it("shields/audit.ts captures AUDIT_DIR / AUDIT_FILE under .nemoclaw-/state", async () => { - await withFreshHome(async (home) => { - process.env.HOME = home; - process.env.NEMOCLAW_INSTANCE = "agent-a"; - const { AUDIT_DIR, AUDIT_FILE } = await import("../../../dist/lib/shields/audit"); - const expectedStateDir = path.join(home, ".nemoclaw-agent-a", "state"); - expect(AUDIT_DIR).toBe(expectedStateDir); - expect(AUDIT_FILE).toBe(path.join(expectedStateDir, "shields-audit.jsonl")); - // shields/index.ts and shields/timer.ts capture their own STATE_DIR - // constants from the same `resolveNemoclawStateDir()` call, so the - // audit module's captured value is the canonical observable: a - // regression in the resolver, the helper, or the import order would - // surface here too. - }); - }); -}); diff --git a/src/lib/core/instance.test.ts b/src/lib/core/instance.test.ts deleted file mode 100644 index 21b2dec5241..00000000000 --- a/src/lib/core/instance.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { - DEFAULT_NEMOCLAW_INSTANCE, - isDefaultInstance, - parseInstanceName, -} from "../../../dist/lib/core/instance"; - -describe("parseInstanceName", () => { - const ENV_KEY = "TEST_NEMOCLAW_INSTANCE"; - let previousEnvValue: string | undefined; - - beforeEach(() => { - previousEnvValue = process.env[ENV_KEY]; - delete process.env[ENV_KEY]; - }); - - afterEach(() => { - if (previousEnvValue === undefined) { - delete process.env[ENV_KEY]; - } else { - process.env[ENV_KEY] = previousEnvValue; - } - }); - - it.each([ - ["an unset env var", undefined, DEFAULT_NEMOCLAW_INSTANCE], - ["an empty env var", "", DEFAULT_NEMOCLAW_INSTANCE], - ["surrounding whitespace then empty", " ", DEFAULT_NEMOCLAW_INSTANCE], - ["a valid lower-case slug", "agent-a", "agent-a"], - ["a numeric tail", "tenant1", "tenant1"], - ["mixed case input is normalised", "Agent-B", "agent-b"], - ["trims surrounding whitespace", " primary ", "primary"], - ["a single character", "a", "a"], - ["the maximum length", "a".repeat(32), "a".repeat(32)], - ] as const)("parses %s", (_label, value, expected) => { - if (value !== undefined) { - process.env[ENV_KEY] = value; - } - - expect(parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE)).toBe(expected); - }); - - it.each([ - ["leading hyphen", "-foo"], - ["trailing hyphen", "foo-"], - ["double hyphen-only", "--"], - ["whitespace inside", "agent a"], - ["filesystem separator", "agent/a"], - ["dot separator", "agent.a"], - ["underscore", "agent_a"], - ["unicode", "agentü"], - ["overlong slug", "a".repeat(33)], - ] as const)("rejects %s", (_label, value) => { - process.env[ENV_KEY] = value; - expect(() => parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE)).toThrow( - /Invalid instance name/, - ); - }); - - it.each([ - ["a pure-digit name", "8081"], - ["a port-like trailing segment", "agent-8081"], - ["a port-like leading segment", "8081-agent"], - ["a port-like middle segment", "agent-1-instance"], - ["a short numeric tail", "tenant-1"], - ] as const)("rejects %s as a port-suffix collision risk", (_label, value) => { - process.env[ENV_KEY] = value; - expect(() => parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE)).toThrow( - /hyphen-separated segments may not be purely numeric/, - ); - }); - - it.each([ - ["a name with a mixed alphanumeric segment", "agent-a1"], - ["a name leading with a digit", "1agent"], - ["a name with a number embedded in a segment", "tenant1"], - ] as const)("still accepts %s (no purely-numeric segment)", (_label, value) => { - process.env[ENV_KEY] = value; - expect(parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE)).toBe(value); - }); - - it("falls back to a non-default fallback when the env var is unset", () => { - expect(parseInstanceName(ENV_KEY, "primary")).toBe("primary"); - }); - - it("treats an explicit NEMOCLAW_INSTANCE=nemoclaw as the default", () => { - process.env[ENV_KEY] = "nemoclaw"; - const resolved = parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE); - expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); - expect(isDefaultInstance(resolved)).toBe(true); - }); - - it("normalises uppercase NEMOCLAW to the default instance", () => { - process.env[ENV_KEY] = "NEMOCLAW"; - const resolved = parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE); - expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); - expect(isDefaultInstance(resolved)).toBe(true); - }); -}); - -describe("isDefaultInstance", () => { - it("recognises the default instance name as `nemoclaw`", () => { - expect(DEFAULT_NEMOCLAW_INSTANCE).toBe("nemoclaw"); - expect(isDefaultInstance("nemoclaw")).toBe(true); - expect(isDefaultInstance(DEFAULT_NEMOCLAW_INSTANCE)).toBe(true); - }); - - it("rejects any other name", () => { - expect(isDefaultInstance("agent-a")).toBe(false); - expect(isDefaultInstance("")).toBe(false); - expect(isDefaultInstance("primary")).toBe(false); - expect(isDefaultInstance("default")).toBe(false); - }); -}); diff --git a/src/lib/core/instance.ts b/src/lib/core/instance.ts deleted file mode 100644 index d5a428fa502..00000000000 --- a/src/lib/core/instance.ts +++ /dev/null @@ -1,116 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -/** - * NemoClaw instance identity primitive. - * - * Historically NemoClaw treated the host-side installation as a process-global - * singleton: one gateway named `nemoclaw`, one state root at `~/.nemoclaw`, one - * registry/credentials/snapshot tree. Two NemoClaw-managed sandboxes on the - * same host therefore had to share that tree even when the user wanted full - * segregation (billing isolation, A/B model testing, multi-tenant POCs). - * - * `NEMOCLAW_INSTANCE` makes the instance identity configurable. The default - * instance name is the historical singleton identity `nemoclaw`, so the - * fallback chain has two layers without any synthetic sentinel name: - * - * 1. When `NEMOCLAW_INSTANCE` is unset, empty, or set explicitly to - * `nemoclaw`, the default instance is selected, every existing on-disk - * path resolves to `~/.nemoclaw`, and the gateway name stays at the - * bare `nemoclaw` — single-instance deployments observe no change - * after upgrading. - * 2. With the default instance still selected, a non-default - * `NEMOCLAW_GATEWAY_PORT` produces a `nemoclaw-` gateway that - * segregates from the bare default at the gateway-binding layer alone. - * This port-derived form is the implicit fallback identity when the - * bare `nemoclaw` gateway is already occupied. - * - * Setting `NEMOCLAW_INSTANCE` to a non-default value overrides both layers - * with a named instance: the state root, credentials directory, - * rebuild-backups directory, local-adapter state directory, and gateway name - * all gain an `` suffix so the migrated surfaces stay segregated. - * - * Scope of segregation in this groundwork: NemoClaw home directory, gateway - * binding (name, state dir, compat container), credentials store (including - * the legacy plaintext credentials file path), rebuild backups and the - * snapshot tree underneath, local inference adapter state, the Ollama - * auth-proxy token reader/writer, and every consumer of - * `resolveNemoclawStateDir()` — shields audit, shields posture, and the - * shields timer all already route through the instance-aware state dir. - * Out of scope here and tracked as follow-up: the sandbox registry, onboard - * session state, messaging configuration, host-side mount roots, the - * uninstall plan, and the `config-io` host-root permission healer. Callers - * that have not yet migrated to `resolveNemoclawHomeDir()` still share state - * across instances. - * - * This module is the single source of truth for resolving the active instance - * name; downstream callers thread the resolved value through their own paths - * rather than parsing the env var directly. - */ - -/** - * Default instance name. Equals the historical singleton identity so the - * bare `nemoclaw` gateway name and `~/.nemoclaw` state root fall out of the - * resolvers without a synthetic sentinel. `NEMOCLAW_INSTANCE=nemoclaw` is - * therefore equivalent to leaving the variable unset. - */ -export const DEFAULT_NEMOCLAW_INSTANCE = "nemoclaw"; - -/** - * Lower-case alphanumeric slug with internal `-`. Must start and end with an - * alphanumeric so it composes safely into filesystem names, gateway-name - * strings, and container names. - */ -const INSTANCE_NAME_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/; - -/** - * Pure-digit hyphen-separated segments are rejected so the instance name can - * never collide with the `-` suffix appended by the gateway-name - * resolver. Without this rule, `NEMOCLAW_INSTANCE=agent-a NEMOCLAW_GATEWAY_PORT=8081` - * and `NEMOCLAW_INSTANCE=agent-a-8081` (default port) would both compose - * `nemoclaw-agent-a-8081` and overwrite each other's gateway state. - */ -function hasNumericSegment(name: string): boolean { - return name.split("-").some((segment) => /^\d+$/.test(segment)); -} - -/** - * Validate an instance-name candidate. Returns the trimmed lower-case name if - * valid, or throws with a stable error message that callers can surface to the - * user verbatim. Empty input resolves to {@link DEFAULT_NEMOCLAW_INSTANCE} so - * `NEMOCLAW_INSTANCE=""` and an unset variable behave the same. - */ -export function parseInstanceName(envVar: string, fallback: string): string { - const raw = process.env[envVar]; - if (raw === undefined || raw === "") return fallback; - const trimmed = String(raw).trim().toLowerCase(); - if (trimmed === "") return fallback; - if (!INSTANCE_NAME_RE.test(trimmed)) { - throw new Error( - `Invalid instance name: ${envVar}="${raw}" — must be 1–32 lower-case ` + - `alphanumerics with internal '-' (e.g. "agent-a", "tenant1")`, - ); - } - if (hasNumericSegment(trimmed)) { - throw new Error( - `Invalid instance name: ${envVar}="${raw}" — hyphen-separated segments ` + - `may not be purely numeric (would collide with the gateway port suffix)`, - ); - } - return trimmed; -} - -/** Whether the supplied instance name refers to today's singleton tree. */ -export function isDefaultInstance(name: string): boolean { - return name === DEFAULT_NEMOCLAW_INSTANCE; -} - -/** - * Active NemoClaw instance name resolved at module load. Read from - * `NEMOCLAW_INSTANCE`; falls back to {@link DEFAULT_NEMOCLAW_INSTANCE}. - * - * Callers needing test-time overrides should call {@link parseInstanceName} - * directly against an explicit env-var name rather than re-reading this - * constant, since this value is captured once per process. - */ -export const NEMOCLAW_INSTANCE = parseInstanceName("NEMOCLAW_INSTANCE", DEFAULT_NEMOCLAW_INSTANCE); diff --git a/src/lib/credentials/store.ts b/src/lib/credentials/store.ts index cd543b06377..8464633e7cc 100644 --- a/src/lib/credentials/store.ts +++ b/src/lib/credentials/store.ts @@ -15,7 +15,6 @@ import readline from "node:readline"; import { isErrnoException } from "../core/errno"; import { rejectSymlinksOnPath } from "../state/config-io"; -import { resolveNemoclawHomeDir } from "../state/paths"; const UNSAFE_HOME_PATHS = new Set(["/tmp", "/var/tmp", "/dev/shm", "/"]); @@ -118,20 +117,15 @@ let _cachedHome: string | null = null; let _credsDir: string | null = null; let _legacyCredsFile: string | null = null; -/** - * Return the active-instance NemoClaw home directory (e.g. `~/.nemoclaw` for - * the default instance, `~/.nemoclaw-` otherwise). The host-side - * gateway is the system of record for credentials; this path is retained only - * for the pre-migration plaintext credentials file the legacy stager reads. - */ +/** Return `~/.nemoclaw`, resolving and validating `HOME` once per process. */ export function getCredsDir(): string { const home = resolveHomeDir(); if (_cachedHome !== home) { _cachedHome = home; - _credsDir = resolveNemoclawHomeDir(home); + _credsDir = path.join(home, ".nemoclaw"); _legacyCredsFile = null; } - return _credsDir || resolveNemoclawHomeDir(home); + return _credsDir || path.join(home, ".nemoclaw"); } /** diff --git a/src/lib/domain/uninstall/paths.ts b/src/lib/domain/uninstall/paths.ts index c2a1adaf3b1..b7400e5c556 100644 --- a/src/lib/domain/uninstall/paths.ts +++ b/src/lib/domain/uninstall/paths.ts @@ -3,7 +3,9 @@ import path from "node:path"; -export const DEFAULT_GATEWAY_NAME = "nemoclaw"; +import { BASE_GATEWAY_NAME } from "../../state/gateway"; + +export const DEFAULT_GATEWAY_NAME = BASE_GATEWAY_NAME; export const NEMOCLAW_PROVIDERS = [ "nvidia-nim", "vllm-local", diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index 257888436f0..b288af8a0a6 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -4,15 +4,17 @@ const { startGatewayForRecovery } = require("./onboard") as { startGatewayForRecovery: () => Promise; }; +import { stripAnsi } from "./adapters/openshell/client"; +import { captureOpenshell, runOpenshell } from "./adapters/openshell/runtime"; import { OPENSHELL_OPERATION_TIMEOUT_MS, OPENSHELL_PROBE_TIMEOUT_MS, } from "./adapters/openshell/timeouts"; -import { stripAnsi } from "./adapters/openshell/client"; -import { captureOpenshell, runOpenshell } from "./adapters/openshell/runtime"; +import { GATEWAY_PORT } from "./core/ports"; +import { resolveGatewayName } from "./onboard/gateway-binding"; -function hasNamedGateway(output = ""): boolean { - return stripAnsi(output).includes("Gateway: nemoclaw"); +function hasNamedGateway(output: string, gatewayName: string): boolean { + return stripAnsi(output).includes(`Gateway: ${gatewayName}`); } function getActiveGatewayName(output = ""): string | null { @@ -20,19 +22,21 @@ function getActiveGatewayName(output = ""): string | null { return match ? match[1].trim() : null; } -export function getNamedGatewayLifecycleState() { +export function getNamedGatewayLifecycleState( + gatewayName: string = resolveGatewayName(GATEWAY_PORT), +) { const status = captureOpenshell(["status"], { timeout: OPENSHELL_PROBE_TIMEOUT_MS }); - const gatewayInfo = captureOpenshell(["gateway", "info", "-g", "nemoclaw"], { + const gatewayInfo = captureOpenshell(["gateway", "info", "-g", gatewayName], { timeout: OPENSHELL_PROBE_TIMEOUT_MS, }); const cleanStatus = stripAnsi(status.output); const activeGateway = getActiveGatewayName(status.output); const connected = /^\s*Status:\s*Connected\b/im.test(cleanStatus); - const named = hasNamedGateway(gatewayInfo.output); + const named = hasNamedGateway(gatewayInfo.output, gatewayName); const refusing = /Connection refused|client error \(Connect\)|tcp connect error/i.test( cleanStatus, ); - if (connected && activeGateway === "nemoclaw" && named) { + if (connected && activeGateway === gatewayName && named) { return { state: "healthy_named", status: status.output, @@ -40,7 +44,7 @@ export function getNamedGatewayLifecycleState() { activeGateway, }; } - if (activeGateway === "nemoclaw" && named && refusing) { + if (activeGateway === gatewayName && named && refusing) { return { state: "named_unreachable", status: status.output, @@ -48,7 +52,7 @@ export function getNamedGatewayLifecycleState() { activeGateway, }; } - if (activeGateway === "nemoclaw" && named) { + if (activeGateway === gatewayName && named) { return { state: "named_unhealthy", status: status.output, @@ -76,10 +80,12 @@ type NamedGatewayLifecycleStateName = ReturnType( options.recoverableStates ?? [ "missing_named", @@ -88,7 +94,7 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun "connected_other", ], ); - const before = getNamedGatewayLifecycleState(); + const before = getNamedGatewayLifecycleState(gatewayName); if (before.state === "healthy_named") { return { recovered: true, before, after: before, attempted: false }; } @@ -96,13 +102,13 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun return { recovered: false, before, after: before, attempted: false }; } - runOpenshell(["gateway", "select", "nemoclaw"], { + runOpenshell(["gateway", "select", gatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - let after = getNamedGatewayLifecycleState(); + let after = getNamedGatewayLifecycleState(gatewayName); if (after.state === "healthy_named") { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.OPENSHELL_GATEWAY = gatewayName; return { recovered: true, before, after, attempted: true, via: "select" }; } @@ -119,13 +125,13 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun // Fall through to the lifecycle re-check below so we preserve the // existing recovery result shape and emit the correct classification. } - runOpenshell(["gateway", "select", "nemoclaw"], { + runOpenshell(["gateway", "select", gatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - after = getNamedGatewayLifecycleState(); + after = getNamedGatewayLifecycleState(gatewayName); if (after.state === "healthy_named") { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.OPENSHELL_GATEWAY = gatewayName; return { recovered: true, before, after, attempted: true, via: "start" }; } } diff --git a/src/lib/inference/live.ts b/src/lib/inference/live.ts index 5cb3e51b961..3a0a45d499b 100644 --- a/src/lib/inference/live.ts +++ b/src/lib/inference/live.ts @@ -3,6 +3,8 @@ import type { CaptureOpenshellResult } from "../adapters/openshell/client"; import { stripAnsi } from "../adapters/openshell/client"; +import { GATEWAY_PORT } from "../core/ports"; +import { resolveGatewayName } from "../onboard/gateway-binding"; import { parseGatewayInference, type GatewayInference } from "./config"; type CaptureLiveInference = ( @@ -26,7 +28,7 @@ export function getLiveGatewayInference( opts: { timeout?: number } = {}, ): LiveGatewayInferenceResult { const attempts = [ - ["inference", "get", "-g", "nemoclaw"], + ["inference", "get", "-g", resolveGatewayName(GATEWAY_PORT)], ["inference", "get"], ]; let last: LiveGatewayInferenceResult = { diff --git a/src/lib/inference/local-adapter-lifecycle.ts b/src/lib/inference/local-adapter-lifecycle.ts index 45abf519faf..05cb6a10725 100644 --- a/src/lib/inference/local-adapter-lifecycle.ts +++ b/src/lib/inference/local-adapter-lifecycle.ts @@ -1,14 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { type ChildProcess, spawn } from "node:child_process"; +import { spawn, type ChildProcess } from "node:child_process"; import crypto from "node:crypto"; import fs from "node:fs"; import http from "node:http"; +import os from "node:os"; import path from "node:path"; -import { resolveNemoclawHomeDir } from "../state/paths"; - export type JsonObject = Record; export type RunCaptureFn = ( @@ -21,7 +20,7 @@ export type RunFn = ( options?: { ignoreError?: boolean; suppressOutput?: boolean }, ) => unknown; -export const DEFAULT_LOCAL_ADAPTER_STATE_DIR = resolveNemoclawHomeDir(); +export const DEFAULT_LOCAL_ADAPTER_STATE_DIR = path.join(os.homedir(), ".nemoclaw"); export function ensureLocalAdapterStateDir(stateDir = DEFAULT_LOCAL_ADAPTER_STATE_DIR): void { if (!fs.existsSync(stateDir)) { diff --git a/src/lib/inference/local.ts b/src/lib/inference/local.ts index 8b4490733e0..1ab0146c575 100644 --- a/src/lib/inference/local.ts +++ b/src/lib/inference/local.ts @@ -7,13 +7,13 @@ */ import fs from "node:fs"; +import os from "node:os"; import nodePath from "node:path"; -import { buildValidatedCurlCommandArgs } from "../adapters/http/curl-args"; import type { CurlProbeResult } from "../adapters/http/probe"; +import { buildValidatedCurlCommandArgs } from "../adapters/http/curl-args"; import { runCurlProbe } from "../adapters/http/probe"; import type { CaptureResult } from "../runner"; import { buildSubprocessEnv } from "../subprocess-env"; -import type { OllamaRuntimeModelStatus } from "./ollama-runtime-context"; import { applyOllamaRuntimeContextWindow as applyOllamaRuntimeContextWindowWithHost, MAX_AUTODETECTED_OLLAMA_CONTEXT_WINDOW, @@ -22,15 +22,14 @@ import { resetOllamaRuntimeContextWindowAutoState, resolveOllamaRuntimeContextWindow as resolveOllamaRuntimeContextWindowWithHost, } from "./ollama-runtime-context"; +import type { OllamaRuntimeModelStatus } from "./ollama-runtime-context"; import { applyVllmRuntimeContextWindow as applyVllmRuntimeContextWindowFromModels } from "./vllm-runtime-context"; - export type { OllamaRuntimeModelStatus } from "./ollama-runtime-context"; const { shellQuote, runCapture, runCaptureEx } = require("../runner"); import { OLLAMA_PORT, OLLAMA_PROXY_PORT, VLLM_PORT } from "../core/ports"; import { sleepSeconds } from "../core/wait"; -import { resolveNemoclawHomeDir } from "../state/paths"; import { anyRegistryModelFits, effectiveGpuMemoryMB, @@ -239,16 +238,14 @@ export interface LocalProviderHealthProbeOptions { skipOllamaAuthProxySubprobe?: boolean; /** * Reads the persisted Ollama auth-proxy bearer token. Injectable for tests. - * Default reads from `/ollama-proxy-token` (written by - * inference/ollama/proxy.ts during onboard). The active NemoClaw home - * follows `NEMOCLAW_INSTANCE` so the reader and writer stay in sync for - * non-default instances. + * Default reads from `~/.nemoclaw/ollama-proxy-token` (written by + * inference/ollama/proxy.ts during onboard). */ loadOllamaProxyTokenImpl?: () => string | null; } function defaultLoadOllamaProxyToken(): string | null { - const tokenPath = nodePath.join(resolveNemoclawHomeDir(), "ollama-proxy-token"); + const tokenPath = nodePath.join(os.homedir(), ".nemoclaw", "ollama-proxy-token"); try { if (fs.existsSync(tokenPath)) { const token = fs.readFileSync(tokenPath, "utf-8").trim(); diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index e92f0900dde..1eae197c362 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -5243,7 +5243,7 @@ async function onboard(opts: OnboardOptions = {}): Promise { session = onboardSession.saveSession( onboardSession.createSession({ mode: isNonInteractive() ? "non-interactive" : "interactive", - metadata: { gatewayName: "nemoclaw", fromDockerfile: fromDockerfile || null }, + metadata: { gatewayName: GATEWAY_NAME, fromDockerfile: fromDockerfile || null }, }), ); } diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 42ffb7dab59..e80baec4270 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -5,8 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { DEFAULT_NEMOCLAW_INSTANCE, parseInstanceName } from "../../../dist/lib/core/instance"; +import { describe, expect, it } from "vitest"; import { DEFAULT_GATEWAY_PORT } from "../../../dist/lib/core/ports"; import { buildDockerDriverGatewayLaunch } from "../../../dist/lib/onboard/docker-driver-gateway-launch"; import { @@ -22,162 +21,64 @@ import { resolveGatewayCompatContainerName, resolveGatewayName, resolveGatewayStateDirName, + resolveSandboxGatewayName, } from "../../../dist/lib/onboard/gateway-binding"; -import { BASE_NEMOCLAW_HOME_DIR_NAME, resolveNemoclawHomeDir } from "../../../dist/lib/state/paths"; describe("gateway-binding resolver (#4422)", () => { - const DEFAULT_INSTANCE = DEFAULT_NEMOCLAW_INSTANCE; - - it("keeps the bare nemoclaw names for the default instance on the default gateway port", () => { - expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, DEFAULT_INSTANCE)).toBe(BASE_GATEWAY_NAME); - expect(resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT, DEFAULT_INSTANCE)).toBe( - BASE_GATEWAY_STATE_DIR_NAME, - ); - expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, DEFAULT_INSTANCE)).toBe( + it("keeps the bare nemoclaw names for the default gateway port", () => { + expect(resolveGatewayName(DEFAULT_GATEWAY_PORT)).toBe(BASE_GATEWAY_NAME); + expect(resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT)).toBe(BASE_GATEWAY_STATE_DIR_NAME); + expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT)).toBe( BASE_GATEWAY_COMPAT_CONTAINER_NAME, ); }); it("suffixes the name, state dir, and compat container for a non-default port", () => { - expect(resolveGatewayName(8081, DEFAULT_INSTANCE)).toBe("nemoclaw-8081"); - expect(resolveGatewayStateDirName(8081, DEFAULT_INSTANCE)).toBe( - "openshell-docker-gateway-8081", - ); - expect(resolveGatewayCompatContainerName(8081, DEFAULT_INSTANCE)).toBe( - "nemoclaw-openshell-gateway-8081", - ); + expect(resolveGatewayName(8081)).toBe("nemoclaw-8081"); + expect(resolveGatewayStateDirName(8081)).toBe("openshell-docker-gateway-8081"); + expect(resolveGatewayCompatContainerName(8081)).toBe("nemoclaw-openshell-gateway-8081"); }); it("derives distinct bindings for two different gateway ports", () => { const a = 8080; const b = 8081; - expect(resolveGatewayName(a, DEFAULT_INSTANCE)).not.toBe( - resolveGatewayName(b, DEFAULT_INSTANCE), - ); - expect(resolveGatewayStateDirName(a, DEFAULT_INSTANCE)).not.toBe( - resolveGatewayStateDirName(b, DEFAULT_INSTANCE), - ); - expect(resolveGatewayCompatContainerName(a, DEFAULT_INSTANCE)).not.toBe( - resolveGatewayCompatContainerName(b, DEFAULT_INSTANCE), - ); + expect(resolveGatewayName(a)).not.toBe(resolveGatewayName(b)); + expect(resolveGatewayStateDirName(a)).not.toBe(resolveGatewayStateDirName(b)); + expect(resolveGatewayCompatContainerName(a)).not.toBe(resolveGatewayCompatContainerName(b)); }); }); -describe("gateway-binding resolver factors NEMOCLAW_INSTANCE", () => { - const DEFAULT_INSTANCE = DEFAULT_NEMOCLAW_INSTANCE; - - it("suffixes the gateway name with the instance for a non-default instance on the default port", () => { - expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, "agent-a")).toBe("nemoclaw-agent-a"); - expect(resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT, "agent-a")).toBe( - "openshell-docker-gateway-agent-a", - ); - expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, "agent-a")).toBe( - "nemoclaw-openshell-gateway-agent-a", - ); +describe("resolveSandboxGatewayName", () => { + it("returns the persisted gatewayName when present", () => { + expect( + resolveSandboxGatewayName({ gatewayName: "nemoclaw-9090", gatewayPort: 9090 }), + ).toBe("nemoclaw-9090"); }); - it("composes instance and port suffixes when both are non-default", () => { - expect(resolveGatewayName(8081, "agent-a")).toBe("nemoclaw-agent-a-8081"); - expect(resolveGatewayStateDirName(8081, "agent-a")).toBe( - "openshell-docker-gateway-agent-a-8081", - ); - expect(resolveGatewayCompatContainerName(8081, "agent-a")).toBe( - "nemoclaw-openshell-gateway-agent-a-8081", - ); + it("derives the gateway name from gatewayPort when gatewayName is absent", () => { + expect(resolveSandboxGatewayName({ gatewayPort: 8081 })).toBe("nemoclaw-8081"); + expect(resolveSandboxGatewayName({ gatewayPort: 8080 })).toBe(BASE_GATEWAY_NAME); }); - it("segregates two non-default instances even on the same default port", () => { - expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, "agent-a")).not.toBe( - resolveGatewayName(DEFAULT_GATEWAY_PORT, "agent-b"), - ); - expect(resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT, "agent-a")).not.toBe( - resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT, "agent-b"), - ); - expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, "agent-a")).not.toBe( - resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, "agent-b"), - ); + it("falls back to the bare base name for legacy sandbox entries with neither field set", () => { + expect(resolveSandboxGatewayName({})).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName(null)).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName(undefined)).toBe(BASE_GATEWAY_NAME); }); - it("preserves the bare nemoclaw names when the instance is left at default", () => { - expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, DEFAULT_INSTANCE)).toBe(BASE_GATEWAY_NAME); - }); - - // Regression for the encoding ambiguity surfaced in review: instance - // "agent-a" composed with port 8081 produces the same gateway name as - // instance "agent-a-8081" composed with the default port. The instance - // parser rejects purely-numeric hyphen-segments to guarantee this never - // happens for env-derived values; the resolver itself stays a pure function - // so callers must validate first via parseInstanceName(). - it("composed names would collide if a port-like instance tail were permitted", () => { - const composed = resolveGatewayName(8081, "agent-a"); - const portLikeTail = resolveGatewayName(DEFAULT_GATEWAY_PORT, "agent-a-8081"); - expect(composed).toBe("nemoclaw-agent-a-8081"); - expect(portLikeTail).toBe("nemoclaw-agent-a-8081"); - // parseInstanceName() refuses "agent-a-8081" — see src/lib/core/instance.test.ts. - }); -}); - -// Confirms the standing fallback contract: an unset NEMOCLAW_INSTANCE must -// resolve to the bare `nemoclaw` identity on the default gateway port, and -// to `nemoclaw-` when only NEMOCLAW_GATEWAY_PORT is supplied. The -// port-derived form is the implicit fallback identity when the bare default -// is already occupied — users opting out of the new env var still get a -// distinct gateway by varying the port alone. -describe("default and port-based fallback identity chain", () => { - const ENV_KEY = "TEST_NEMOCLAW_INSTANCE_FALLBACK"; - const FIXTURE_HOME = path.join(os.tmpdir(), "nemoclaw-instance-fallback"); - let previousEnvValue: string | undefined; - - beforeEach(() => { - previousEnvValue = process.env[ENV_KEY]; - delete process.env[ENV_KEY]; - }); - - afterEach(() => { - if (previousEnvValue === undefined) { - delete process.env[ENV_KEY]; - } else { - process.env[ENV_KEY] = previousEnvValue; - } - }); - - it("resolves bare nemoclaw names and the bare home dir when NEMOCLAW_INSTANCE is unset", () => { - const resolved = parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE); - expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); - expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, resolved)).toBe(BASE_GATEWAY_NAME); - expect(resolveGatewayStateDirName(DEFAULT_GATEWAY_PORT, resolved)).toBe( - BASE_GATEWAY_STATE_DIR_NAME, - ); - expect(resolveGatewayCompatContainerName(DEFAULT_GATEWAY_PORT, resolved)).toBe( - BASE_GATEWAY_COMPAT_CONTAINER_NAME, + it("ignores null persisted values and falls back through the resolution chain", () => { + expect(resolveSandboxGatewayName({ gatewayName: null, gatewayPort: 8081 })).toBe( + "nemoclaw-8081", ); - expect(resolveNemoclawHomeDir(FIXTURE_HOME, resolved)).toBe( - path.join(FIXTURE_HOME, BASE_NEMOCLAW_HOME_DIR_NAME), + expect(resolveSandboxGatewayName({ gatewayName: null, gatewayPort: null })).toBe( + BASE_GATEWAY_NAME, ); }); - it("resolves the port-based fallback when NEMOCLAW_INSTANCE is unset and only the gateway port shifts", () => { - const resolved = parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE); - expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); - // The home dir stays at the bare default — port alone does not segregate - // host state, only the gateway binding. - expect(resolveNemoclawHomeDir(FIXTURE_HOME, resolved)).toBe( - path.join(FIXTURE_HOME, BASE_NEMOCLAW_HOME_DIR_NAME), + it("returns distinct names for sandboxes on different non-default ports", () => { + expect(resolveSandboxGatewayName({ gatewayPort: 8081 })).not.toBe( + resolveSandboxGatewayName({ gatewayPort: 8090 }), ); - // The gateway binding takes the port suffix so two default-instance - // sandboxes on distinct ports never share gateway state. - expect(resolveGatewayName(8081, resolved)).toBe("nemoclaw-8081"); - expect(resolveGatewayStateDirName(8081, resolved)).toBe("openshell-docker-gateway-8081"); - expect(resolveGatewayCompatContainerName(8081, resolved)).toBe( - "nemoclaw-openshell-gateway-8081", - ); - }); - - it("treats an empty env value the same as an unset env value", () => { - process.env[ENV_KEY] = ""; - const resolved = parseInstanceName(ENV_KEY, DEFAULT_NEMOCLAW_INSTANCE); - expect(resolved).toBe(DEFAULT_NEMOCLAW_INSTANCE); - expect(resolveGatewayName(DEFAULT_GATEWAY_PORT, resolved)).toBe(BASE_GATEWAY_NAME); }); }); diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index b11fe1b2edc..32f1df9b589 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -2,90 +2,103 @@ // SPDX-License-Identifier: Apache-2.0 /** - * Per-instance / per-gateway-port binding resolver. + * Per-gateway-port binding resolver. * * Historically NemoClaw treated the OpenShell gateway as a process-global * singleton named `nemoclaw`, with a single Docker-driver state directory and * a single compatibility container. A second onboard that requested a * different `NEMOCLAW_GATEWAY_PORT` therefore reused the same named gateway, * the same runtime-marker state dir, and the same compat container — so - * creating the second sandbox recreated/killed the first sandbox's gateway - * and overwrote its runtime marker. + * creating the second sandbox recreated/killed the first sandbox's gateway and + * overwrote its runtime marker (#4422). * - * These pure resolvers derive a stable per-binding identity along two - * independent axes: - * - * 1. **Gateway port** — the original `nemoclaw-` suffix introduced for - * `NEMOCLAW_GATEWAY_PORT`. The default port keeps the bare `nemoclaw` - * name verbatim for backward compatibility. - * 2. **NemoClaw instance** — the `NEMOCLAW_INSTANCE` identity that scopes the - * entire host-side install (state root, gateway name, lifecycle). The - * default instance keeps the bare `nemoclaw` name verbatim; any other - * instance is prefixed (`nemoclaw-` / `nemoclaw--`) - * so two instances never collide even on the default port. - * - * Both axes default to the singleton tree so existing single-instance, - * default-port deployments observe no name change. + * These pure resolvers derive a stable per-port binding. The default port + * keeps the original `nemoclaw` names verbatim so existing single-sandbox + * deployments and on-disk state are untouched; any non-default port gets a + * `-` suffixed name/dir/container so two sandboxes on distinct gateway + * ports never collide. */ -import { isDefaultInstance, NEMOCLAW_INSTANCE } from "../core/instance"; import { DEFAULT_GATEWAY_PORT } from "../core/ports"; -import type { GatewayReuseState } from "../state/gateway"; +import { BASE_GATEWAY_NAME, type GatewayReuseState } from "../state/gateway"; -/** Gateway registration name used for the default instance and default port. */ -export const BASE_GATEWAY_NAME = "nemoclaw"; -/** Docker-driver gateway state directory leaf name for the default binding. */ +export { BASE_GATEWAY_NAME }; +/** Docker-driver gateway state directory leaf name for the default port. */ export const BASE_GATEWAY_STATE_DIR_NAME = "openshell-docker-gateway"; -/** Docker-driver gateway compatibility container name for the default binding. */ +/** Docker-driver gateway compatibility container name for the default port. */ export const BASE_GATEWAY_COMPAT_CONTAINER_NAME = "nemoclaw-openshell-gateway"; function isDefaultGatewayPort(port: number): boolean { return port === DEFAULT_GATEWAY_PORT; } -function bindingSuffix(port: number, instance: string): string { - const parts: string[] = []; - if (!isDefaultInstance(instance)) parts.push(instance); - if (!isDefaultGatewayPort(port)) parts.push(String(port)); - return parts.length === 0 ? "" : `-${parts.join("-")}`; +/** + * Resolve the OpenShell gateway registration name for a gateway port. The + * default port keeps the bare `nemoclaw` name for backward compatibility; any + * other port gets a `nemoclaw-` name so its lifecycle commands + * (add/select/remove/start/destroy) never target another sandbox's gateway. + */ +export function resolveGatewayName(port: number): string { + return isDefaultGatewayPort(port) ? BASE_GATEWAY_NAME : `${BASE_GATEWAY_NAME}-${port}`; } /** - * Resolve the OpenShell gateway registration name for a gateway port + active - * instance. The default instance on the default port keeps the bare `nemoclaw` - * name for backward compatibility; any other combination gets an - * `` / `` suffix so its lifecycle commands - * (add/select/remove/start/destroy) never target another instance's gateway. + * Sandbox registry shape this resolver depends on. Kept structural to avoid + * a hard import from `state/registry` (which would pull in the whole + * registry module just to read two optional fields). + */ +export interface SandboxGatewayBinding { + gatewayName?: string | null; + gatewayPort?: number | null; +} + +/** + * Resolve the OpenShell gateway name a given sandbox should be addressed by. + * Sandbox-scoped lifecycle commands (`connect`, `destroy`, `doctor`, + * `snapshot`, gateway-state probes) must call this rather than hardcoding + * the bare `nemoclaw` literal — a sandbox onboarded with a non-default + * `NEMOCLAW_GATEWAY_PORT` is registered against `nemoclaw-`, and any + * command that talks to the literal default gateway operates on the wrong + * gateway and fails with `sandbox has no spec`. + * + * Resolution order: + * 1. The sandbox's persisted `gatewayName` (recorded at onboard time). + * 2. The per-port derivation from the persisted `gatewayPort`. + * 3. The bare `BASE_GATEWAY_NAME` for legacy entries that pre-date the + * per-port migration. */ -export function resolveGatewayName(port: number, instance: string = NEMOCLAW_INSTANCE): string { - return `${BASE_GATEWAY_NAME}${bindingSuffix(port, instance)}`; +export function resolveSandboxGatewayName(sandbox: SandboxGatewayBinding | null | undefined): string { + if (sandbox?.gatewayName && typeof sandbox.gatewayName === "string") { + return sandbox.gatewayName; + } + if (typeof sandbox?.gatewayPort === "number" && Number.isFinite(sandbox.gatewayPort)) { + return resolveGatewayName(sandbox.gatewayPort); + } + return BASE_GATEWAY_NAME; } /** * Resolve the Docker-driver gateway state directory leaf name for a gateway - * port + active instance. The state dir holds the gateway pid file and runtime - * marker, so a per-binding leaf keeps each sandbox's marker isolated — a - * second onboard cannot overwrite the first sandbox's marker or clobber its - * pid file. + * port. The state dir holds the gateway pid file and runtime marker, so a + * per-port leaf keeps each sandbox's marker isolated — a second onboard cannot + * overwrite the first sandbox's marker or clobber its pid file. */ -export function resolveGatewayStateDirName( - port: number, - instance: string = NEMOCLAW_INSTANCE, -): string { - return `${BASE_GATEWAY_STATE_DIR_NAME}${bindingSuffix(port, instance)}`; +export function resolveGatewayStateDirName(port: number): string { + return isDefaultGatewayPort(port) + ? BASE_GATEWAY_STATE_DIR_NAME + : `${BASE_GATEWAY_STATE_DIR_NAME}-${port}`; } /** - * Resolve the Docker-driver gateway compatibility container name for a - * gateway port + active instance. A per-binding container name prevents the - * second onboard's `docker run --name ...` (and the pre-launch `docker rm`) - * from tearing down the first sandbox's compat gateway container. + * Resolve the Docker-driver gateway compatibility container name for a gateway + * port. A per-port container name prevents the second onboard's + * `docker run --name ...` (and the pre-launch `docker rm`) from tearing down + * the first sandbox's compat gateway container. */ -export function resolveGatewayCompatContainerName( - port: number, - instance: string = NEMOCLAW_INSTANCE, -): string { - return `${BASE_GATEWAY_COMPAT_CONTAINER_NAME}${bindingSuffix(port, instance)}`; +export function resolveGatewayCompatContainerName(port: number): string { + return isDefaultGatewayPort(port) + ? BASE_GATEWAY_COMPAT_CONTAINER_NAME + : `${BASE_GATEWAY_COMPAT_CONTAINER_NAME}-${port}`; } /** Gateway state classifiers from `state/gateway`, each bound to a gateway name. */ @@ -106,9 +119,9 @@ export interface GatewayNameBoundClassifiers { /** * Bind the gateway-name-aware health/reuse classifiers to a resolved gateway - * name so a non-default NEMOCLAW_GATEWAY_PORT or NEMOCLAW_INSTANCE is - * recognised as its own gateway rather than matched against the `nemoclaw` - * singleton. Kept out of onboard.ts to avoid growing that file. + * name so a non-default NEMOCLAW_GATEWAY_PORT (gateway `nemoclaw-`) is + * recognized as its own gateway rather than matched against the `nemoclaw` + * singleton (#4422). Kept out of onboard.ts to avoid growing that file. */ export function createGatewayNameBoundClassifiers( state: typeof import("../state/gateway"), diff --git a/src/lib/resources-cmd.ts b/src/lib/resources-cmd.ts index 580db756174..336653ff306 100644 --- a/src/lib/resources-cmd.ts +++ b/src/lib/resources-cmd.ts @@ -16,8 +16,10 @@ import { spawnSync, execSync } from "child_process"; import * as YAML from "yaml"; import { dockerSpawnSync } from "./adapters/docker"; +import { GATEWAY_PORT } from "./core/ports"; +import { resolveGatewayName } from "./onboard/gateway-binding"; -const GATEWAY_NAME = "nemoclaw"; +const GATEWAY_NAME = resolveGatewayName(GATEWAY_PORT); function getGatewayContainer(): string { return `openshell-cluster-${GATEWAY_NAME}`; diff --git a/src/lib/state/gateway.ts b/src/lib/state/gateway.ts index 1730487ca52..35c64720b38 100644 --- a/src/lib/state/gateway.ts +++ b/src/lib/state/gateway.ts @@ -8,7 +8,14 @@ * returns a typed result — no I/O, no side effects. */ -const GATEWAY_NAME = "nemoclaw"; +/** + * Canonical OpenShell gateway registration name used by every NemoClaw + * host-side surface. Exported so call sites import this single source of + * truth instead of hardcoding the `"nemoclaw"` literal across the codebase. + * The per-port resolver in `onboard/gateway-binding.ts` derives suffixed + * variants (`nemoclaw-`) from this base. + */ +export const BASE_GATEWAY_NAME = "nemoclaw"; const ANSI_RE = /\x1b\[[0-9;]*m/g; @@ -81,7 +88,7 @@ export function getSandboxFailurePhase(output: string, sandboxName: string): str * Determine whether stale NemoClaw gateway output indicates a previous * session that should be cleaned up before the port preflight check. */ -export function hasStaleGateway(gwInfoOutput: string, gatewayName = GATEWAY_NAME): boolean { +export function hasStaleGateway(gwInfoOutput: string, gatewayName = BASE_GATEWAY_NAME): boolean { const clean = typeof gwInfoOutput === "string" ? stripAnsi(gwInfoOutput) : ""; return ( clean.length > 0 && @@ -117,7 +124,7 @@ export function hasActiveGatewayInfo(activeGatewayInfoOutput = ""): boolean { ); } -export function isSelectedGateway(statusOutput = "", gatewayName = GATEWAY_NAME): boolean { +export function isSelectedGateway(statusOutput = "", gatewayName = BASE_GATEWAY_NAME): boolean { return getReportedGatewayName(statusOutput) === gatewayName; } @@ -125,7 +132,7 @@ export function isGatewayHealthy( statusOutput = "", gwInfoOutput = "", activeGatewayInfoOutput = "", - gatewayName = GATEWAY_NAME, + gatewayName = BASE_GATEWAY_NAME, ): boolean { const namedGatewayKnown = hasStaleGateway(gwInfoOutput, gatewayName); const activeGatewayName = @@ -150,7 +157,7 @@ export function getGatewayReuseState( statusOutput = "", gwInfoOutput = "", activeGatewayInfoOutput = "", - gatewayName = GATEWAY_NAME, + gatewayName = BASE_GATEWAY_NAME, ): GatewayReuseState { if (isGatewayHealthy(statusOutput, gwInfoOutput, activeGatewayInfoOutput, gatewayName)) { return "healthy"; @@ -178,7 +185,7 @@ export function shouldSelectNamedGatewayForReuse( statusOutput = "", gwInfoOutput = "", activeGatewayInfoOutput = "", - gatewayName = GATEWAY_NAME, + gatewayName = BASE_GATEWAY_NAME, ): boolean { return ( getGatewayReuseState(statusOutput, gwInfoOutput, activeGatewayInfoOutput, gatewayName) === diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index c4218762318..0a8988adef5 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -13,7 +13,9 @@ import path from "node:path"; import { isErrnoException } from "../core/errno"; import type { JsonObject, JsonValue } from "../core/json-types"; +import { GATEWAY_PORT } from "../core/ports"; import type { WebSearchConfig } from "../inference/web-search"; +import { resolveGatewayName } from "../onboard/gateway-binding"; import { type MessagingChannelConfig, sanitizeMessagingChannelConfig, @@ -312,7 +314,7 @@ function parseWechatConfig(value: unknown): WechatConfig | null { function parseSessionMetadata(value: SessionJsonValue | undefined): SessionMetadata | undefined { if (!isObject(value)) return undefined; return { - gatewayName: readString(value.gatewayName) ?? "nemoclaw", + gatewayName: readString(value.gatewayName) ?? resolveGatewayName(GATEWAY_PORT), fromDockerfile: readString(value.fromDockerfile), }; } @@ -476,7 +478,7 @@ export function createSession(overrides: Partial = {}): Session { telegramConfig: parseTelegramConfig(overrides.telegramConfig), wechatConfig: parseWechatConfig(overrides.wechatConfig), metadata: { - gatewayName: overrides.metadata?.gatewayName ?? "nemoclaw", + gatewayName: overrides.metadata?.gatewayName ?? resolveGatewayName(GATEWAY_PORT), fromDockerfile: overrides.metadata?.fromDockerfile ?? null, }, machine: diff --git a/src/lib/state/paths.test.ts b/src/lib/state/paths.test.ts index dc3495bf3f3..268b5ccaef7 100644 --- a/src/lib/state/paths.test.ts +++ b/src/lib/state/paths.test.ts @@ -5,15 +5,7 @@ import { existsSync } from "node:fs"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { DEFAULT_NEMOCLAW_INSTANCE } from "../../../dist/lib/core/instance"; -import { - BASE_NEMOCLAW_HOME_DIR_NAME, - ROOT, - resolveNemoclawHomeDir, - resolveNemoclawHomeDirName, - resolveNemoclawStateDir, - SCRIPTS, -} from "../../../dist/lib/state/paths"; +import { ROOT, SCRIPTS } from "../../../dist/lib/state/paths"; describe("paths", () => { it("resolves the repo root", () => { @@ -26,51 +18,3 @@ describe("paths", () => { expect(existsSync(join(SCRIPTS, "debug.sh"))).toBe(true); }); }); - -describe("resolveNemoclawHomeDirName", () => { - it("keeps the bare .nemoclaw leaf for the default instance", () => { - expect(resolveNemoclawHomeDirName(DEFAULT_NEMOCLAW_INSTANCE)).toBe(BASE_NEMOCLAW_HOME_DIR_NAME); - }); - - it("suffixes the leaf with the instance name for a non-default instance", () => { - expect(resolveNemoclawHomeDirName("agent-a")).toBe(".nemoclaw-agent-a"); - expect(resolveNemoclawHomeDirName("tenant1")).toBe(".nemoclaw-tenant1"); - }); - - it("derives distinct leaves for two different instances", () => { - const a = resolveNemoclawHomeDirName("agent-a"); - const b = resolveNemoclawHomeDirName("agent-b"); - expect(a).not.toBe(b); - }); -}); - -describe("resolveNemoclawHomeDir / resolveNemoclawStateDir", () => { - const home = "/tmp/nemoclaw-instance-fixture"; - - it("returns the bare ~/.nemoclaw path for the default instance", () => { - expect(resolveNemoclawHomeDir(home, DEFAULT_NEMOCLAW_INSTANCE)).toBe( - join(home, BASE_NEMOCLAW_HOME_DIR_NAME), - ); - expect(resolveNemoclawStateDir(home, DEFAULT_NEMOCLAW_INSTANCE)).toBe( - join(home, BASE_NEMOCLAW_HOME_DIR_NAME, "state"), - ); - }); - - it("returns the per-instance home and state dirs for a non-default instance", () => { - expect(resolveNemoclawHomeDir(home, "agent-a")).toBe( - join(home, `${BASE_NEMOCLAW_HOME_DIR_NAME}-agent-a`), - ); - expect(resolveNemoclawStateDir(home, "agent-a")).toBe( - join(home, `${BASE_NEMOCLAW_HOME_DIR_NAME}-agent-a`, "state"), - ); - }); - - it("segregates two instances under the same home dir", () => { - expect(resolveNemoclawHomeDir(home, "agent-a")).not.toBe( - resolveNemoclawHomeDir(home, "agent-b"), - ); - expect(resolveNemoclawStateDir(home, "agent-a")).not.toBe( - resolveNemoclawStateDir(home, "agent-b"), - ); - }); -}); diff --git a/src/lib/state/paths.ts b/src/lib/state/paths.ts index 8623c96be34..e92b72bac44 100644 --- a/src/lib/state/paths.ts +++ b/src/lib/state/paths.ts @@ -4,54 +4,15 @@ import os from "node:os"; import path from "node:path"; -import { DEFAULT_NEMOCLAW_INSTANCE, isDefaultInstance, NEMOCLAW_INSTANCE } from "../core/instance"; - export const ROOT = path.resolve(__dirname, "..", "..", ".."); export const SCRIPTS = path.join(ROOT, "scripts"); -/** Leaf directory name for today's singleton state root. */ -export const BASE_NEMOCLAW_HOME_DIR_NAME = ".nemoclaw"; - -/** - * Resolve the leaf directory name for the NemoClaw state root, derived from - * the active instance identity. The default instance keeps the bare - * `.nemoclaw` name verbatim so existing single-instance deployments and - * on-disk state are untouched; any non-default instance gets a - * `.nemoclaw-` leaf so callers that route through this helper land - * in a per-instance tree. - * - * Migration is partial. Surfaces that route through this helper today: the - * credentials store (`credentials/store.ts`), rebuild backups + blueprint - * digest (`state/sandbox.ts`), the local-adapter state directory and Ollama - * auth-proxy token (`inference/local-adapter-lifecycle.ts`, `inference/local.ts`), - * the gateway-name binding (`onboard/gateway-binding.ts`), and every consumer - * of `resolveNemoclawStateDir()` — shields audit (`shields/audit.ts`), - * shields posture (`shields/index.ts`), and the shields timer - * (`shields/timer.ts`) all already land under `.nemoclaw-/state`. - * Surfaces that still hard-code `.nemoclaw` — the sandbox registry - * (`state/registry.ts`), onboard session state (`state/onboard-session.ts`), - * messaging configuration, uninstall plan, host-side mount roots, and the - * `config-io` host-root permission healer — continue to share state across - * instances until follow-up PRs migrate them. - */ -export function resolveNemoclawHomeDirName(instance: string = NEMOCLAW_INSTANCE): string { - return isDefaultInstance(instance) - ? BASE_NEMOCLAW_HOME_DIR_NAME - : `${BASE_NEMOCLAW_HOME_DIR_NAME}-${instance}`; -} - -export function resolveNemoclawHomeDir( - homeDir: string = process.env.HOME ?? os.homedir(), - instance: string = NEMOCLAW_INSTANCE, -): string { - return path.join(homeDir, resolveNemoclawHomeDirName(instance)); +export function resolveNemoclawHomeDir(homeDir: string = process.env.HOME ?? os.homedir()): string { + return path.join(homeDir, ".nemoclaw"); } export function resolveNemoclawStateDir( homeDir: string = process.env.HOME ?? os.homedir(), - instance: string = NEMOCLAW_INSTANCE, ): string { - return path.join(resolveNemoclawHomeDir(homeDir, instance), "state"); + return path.join(resolveNemoclawHomeDir(homeDir), "state"); } - -export { DEFAULT_NEMOCLAW_INSTANCE, NEMOCLAW_INSTANCE }; diff --git a/src/lib/state/sandbox.ts b/src/lib/state/sandbox.ts index 715d72a1c5c..55442b29de5 100644 --- a/src/lib/state/sandbox.ts +++ b/src/lib/state/sandbox.ts @@ -31,18 +31,17 @@ import { OPENSHELL_PROBE_TIMEOUT_MS } from "../adapters/openshell/timeouts.js"; import type { AgentStateFile } from "../agent/defs.js"; import { loadAgent } from "../agent/defs.js"; import { isRecord, type UnknownRecord } from "../core/json-types.js"; -import { shellQuote } from "../runner.js"; -import { isSensitiveFile, sanitizeConfigFile } from "../security/credential-filter.js"; import { buildOpenClawConfigRestoreInputFromSandbox, shouldMergeOpenClawConfigStateFile, } from "./openclaw-config-restore-input.js"; -import { resolveNemoclawHomeDir } from "./paths.js"; +import { shellQuote } from "../runner.js"; +import { isSensitiveFile, sanitizeConfigFile } from "../security/credential-filter.js"; import * as registry from "./registry.js"; import { runTarListing } from "./tar-listing.js"; const HOME_DIR = path.resolve(process.env.HOME || os.homedir()); -export const REBUILD_BACKUPS_DIR = path.join(resolveNemoclawHomeDir(HOME_DIR), "rebuild-backups"); +const REBUILD_BACKUPS_DIR = path.join(HOME_DIR, ".nemoclaw", "rebuild-backups"); const MANIFEST_VERSION = 1; @@ -479,12 +478,7 @@ function sshArgs(configFile: string, sandboxName: string): string[] { function computeBlueprintDigest(): string | null { // Look for blueprint.yaml relative to the agent-defs ROOT const candidates = [ - path.join( - resolveNemoclawHomeDir(process.env.HOME || "/tmp"), - "blueprints", - "0.1.0", - "blueprint.yaml", - ), + path.join(process.env.HOME || "/tmp", ".nemoclaw", "blueprints", "0.1.0", "blueprint.yaml"), path.join(__dirname, "..", "..", "nemoclaw-blueprint", "blueprint.yaml"), ]; for (const p of candidates) { From 7b76a22b1798c3d69e516928836ce4bff6bc0e04 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 17:59:36 +0000 Subject: [PATCH 10/29] refactor(gateway): drop unrelated cleanup, keep sandbox-scoped fix Signed-off-by: Tinson Lai --- src/commands/internal/uninstall/plan.ts | 7 +----- src/commands/internal/uninstall/run-plan.ts | 7 +----- src/lib/actions/sandbox/snapshot.test.ts | 1 - src/lib/actions/uninstall/run-plan.ts | 3 +-- src/lib/adapters/openshell/gateway-drift.ts | 4 +-- src/lib/domain/uninstall/paths.ts | 4 +-- src/lib/gateway-runtime-action.ts | 28 ++++++++------------- src/lib/inference/live.ts | 4 +-- src/lib/onboard.ts | 2 +- src/lib/onboard/gateway-binding.ts | 5 ++-- src/lib/resources-cmd.ts | 4 +-- src/lib/state/gateway.ts | 19 +++++--------- src/lib/state/onboard-session.ts | 6 ++--- 13 files changed, 31 insertions(+), 63 deletions(-) diff --git a/src/commands/internal/uninstall/plan.ts b/src/commands/internal/uninstall/plan.ts index 4303cbcac0b..ad94012087b 100644 --- a/src/commands/internal/uninstall/plan.ts +++ b/src/commands/internal/uninstall/plan.ts @@ -5,8 +5,6 @@ import { Flags } from "@oclif/core"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../../lib/cli/branding"; import { jsonFlag } from "../../../lib/cli/common-flags"; import { NemoClawCommand } from "../../../lib/cli/nemoclaw-oclif-command"; -import { GATEWAY_PORT } from "../../../lib/core/ports"; -import { resolveGatewayName } from "../../../lib/onboard/gateway-binding"; import { buildHostUninstallPlan } from "../../../lib/actions/uninstall/plan"; @@ -26,10 +24,7 @@ export default class InternalUninstallPlanCommand extends NemoClawCommand { description: `Plan removal of ${CLI_DISPLAY_NAME}-pulled Ollama models`, }), "keep-openshell": Flags.boolean({ description: "Keep the openshell binary installed" }), - gateway: Flags.string({ - description: "Gateway name", - default: resolveGatewayName(GATEWAY_PORT), - }), + gateway: Flags.string({ description: "Gateway name", default: "nemoclaw" }), }; public async run(): Promise { diff --git a/src/commands/internal/uninstall/run-plan.ts b/src/commands/internal/uninstall/run-plan.ts index e1b8758dac3..26809e33e35 100644 --- a/src/commands/internal/uninstall/run-plan.ts +++ b/src/commands/internal/uninstall/run-plan.ts @@ -6,8 +6,6 @@ import { NemoClawCommand } from "../../../lib/cli/nemoclaw-oclif-command"; import { runUninstallPlan } from "../../../lib/actions/uninstall/run-plan"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../../lib/cli/branding"; -import { GATEWAY_PORT } from "../../../lib/core/ports"; -import { resolveGatewayName } from "../../../lib/onboard/gateway-binding"; export default class InternalUninstallRunPlanCommand extends NemoClawCommand { static hidden = true; @@ -22,10 +20,7 @@ export default class InternalUninstallRunPlanCommand extends NemoClawCommand { "delete-models": Flags.boolean({ description: `Remove ${CLI_DISPLAY_NAME}-pulled Ollama models`, }), - gateway: Flags.string({ - description: "Gateway name", - default: resolveGatewayName(GATEWAY_PORT), - }), + gateway: Flags.string({ description: "Gateway name", default: "nemoclaw" }), }; public async run(): Promise { diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index 95c1e732db6..2dd22b61e16 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -47,7 +47,6 @@ vi.mock("../../shields", () => ({ })); vi.mock("../../state/gateway", () => ({ - BASE_GATEWAY_NAME: "nemoclaw", isGatewayHealthy: isGatewayHealthyMock, })); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 02116134d32..d52d95ab089 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -16,7 +16,6 @@ import { type UninstallPaths, } from "../../domain/uninstall/paths"; import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; -import { DEFAULT_GATEWAY_NAME } from "../../domain/uninstall/paths"; import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; import { classifyShimPath, type FileSystemDeps } from "./plan"; @@ -530,7 +529,7 @@ function removeOpenShellResources(options: UninstallRunOptions, runtime: Uninsta provider, ]); } - const gatewayLabel = options.gatewayName || DEFAULT_GATEWAY_NAME; + const gatewayLabel = options.gatewayName || "nemoclaw"; runOptional( runtime, `Destroyed gateway '${gatewayLabel}'`, diff --git a/src/lib/adapters/openshell/gateway-drift.ts b/src/lib/adapters/openshell/gateway-drift.ts index 3c2b35b5fd8..024f610f46a 100644 --- a/src/lib/adapters/openshell/gateway-drift.ts +++ b/src/lib/adapters/openshell/gateway-drift.ts @@ -16,14 +16,14 @@ import { resolveDockerDriverGatewayStateDir, } from "../../onboard/host-gateway-process"; import { isOpenShellProtobufSchemaMismatch } from "../../runtime-recovery"; -import { BASE_GATEWAY_NAME, isGatewayHealthy } from "../../state/gateway"; +import { isGatewayHealthy } from "../../state/gateway"; import { dockerContainerInspectFormat } from "../docker"; import { parseVersionFromText, stripAnsi } from "./client"; import { resolveOpenshell } from "./resolve"; import { captureOpenshell, getInstalledOpenshellVersionOrNull } from "./runtime"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "./timeouts"; -const DEFAULT_GATEWAY_NAME = BASE_GATEWAY_NAME; +const DEFAULT_GATEWAY_NAME = "nemoclaw"; export type GatewayClusterImageDrift = { containerName: string; diff --git a/src/lib/domain/uninstall/paths.ts b/src/lib/domain/uninstall/paths.ts index b7400e5c556..c2a1adaf3b1 100644 --- a/src/lib/domain/uninstall/paths.ts +++ b/src/lib/domain/uninstall/paths.ts @@ -3,9 +3,7 @@ import path from "node:path"; -import { BASE_GATEWAY_NAME } from "../../state/gateway"; - -export const DEFAULT_GATEWAY_NAME = BASE_GATEWAY_NAME; +export const DEFAULT_GATEWAY_NAME = "nemoclaw"; export const NEMOCLAW_PROVIDERS = [ "nvidia-nim", "vllm-local", diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index b288af8a0a6..a54e86c98e6 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -4,16 +4,14 @@ const { startGatewayForRecovery } = require("./onboard") as { startGatewayForRecovery: () => Promise; }; -import { stripAnsi } from "./adapters/openshell/client"; -import { captureOpenshell, runOpenshell } from "./adapters/openshell/runtime"; import { OPENSHELL_OPERATION_TIMEOUT_MS, OPENSHELL_PROBE_TIMEOUT_MS, } from "./adapters/openshell/timeouts"; -import { GATEWAY_PORT } from "./core/ports"; -import { resolveGatewayName } from "./onboard/gateway-binding"; +import { stripAnsi } from "./adapters/openshell/client"; +import { captureOpenshell, runOpenshell } from "./adapters/openshell/runtime"; -function hasNamedGateway(output: string, gatewayName: string): boolean { +function hasNamedGateway(output = "", gatewayName = "nemoclaw"): boolean { return stripAnsi(output).includes(`Gateway: ${gatewayName}`); } @@ -22,9 +20,7 @@ function getActiveGatewayName(output = ""): string | null { return match ? match[1].trim() : null; } -export function getNamedGatewayLifecycleState( - gatewayName: string = resolveGatewayName(GATEWAY_PORT), -) { +export function getNamedGatewayLifecycleState(gatewayName = "nemoclaw") { const status = captureOpenshell(["status"], { timeout: OPENSHELL_PROBE_TIMEOUT_MS }); const gatewayInfo = captureOpenshell(["gateway", "info", "-g", gatewayName], { timeout: OPENSHELL_PROBE_TIMEOUT_MS, @@ -80,12 +76,10 @@ type NamedGatewayLifecycleStateName = ReturnType( options.recoverableStates ?? [ "missing_named", @@ -94,7 +88,7 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun "connected_other", ], ); - const before = getNamedGatewayLifecycleState(gatewayName); + const before = getNamedGatewayLifecycleState(); if (before.state === "healthy_named") { return { recovered: true, before, after: before, attempted: false }; } @@ -102,13 +96,13 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun return { recovered: false, before, after: before, attempted: false }; } - runOpenshell(["gateway", "select", gatewayName], { + runOpenshell(["gateway", "select", "nemoclaw"], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - let after = getNamedGatewayLifecycleState(gatewayName); + let after = getNamedGatewayLifecycleState(); if (after.state === "healthy_named") { - process.env.OPENSHELL_GATEWAY = gatewayName; + process.env.OPENSHELL_GATEWAY = "nemoclaw"; return { recovered: true, before, after, attempted: true, via: "select" }; } @@ -125,13 +119,13 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun // Fall through to the lifecycle re-check below so we preserve the // existing recovery result shape and emit the correct classification. } - runOpenshell(["gateway", "select", gatewayName], { + runOpenshell(["gateway", "select", "nemoclaw"], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - after = getNamedGatewayLifecycleState(gatewayName); + after = getNamedGatewayLifecycleState(); if (after.state === "healthy_named") { - process.env.OPENSHELL_GATEWAY = gatewayName; + process.env.OPENSHELL_GATEWAY = "nemoclaw"; return { recovered: true, before, after, attempted: true, via: "start" }; } } diff --git a/src/lib/inference/live.ts b/src/lib/inference/live.ts index 3a0a45d499b..5cb3e51b961 100644 --- a/src/lib/inference/live.ts +++ b/src/lib/inference/live.ts @@ -3,8 +3,6 @@ import type { CaptureOpenshellResult } from "../adapters/openshell/client"; import { stripAnsi } from "../adapters/openshell/client"; -import { GATEWAY_PORT } from "../core/ports"; -import { resolveGatewayName } from "../onboard/gateway-binding"; import { parseGatewayInference, type GatewayInference } from "./config"; type CaptureLiveInference = ( @@ -28,7 +26,7 @@ export function getLiveGatewayInference( opts: { timeout?: number } = {}, ): LiveGatewayInferenceResult { const attempts = [ - ["inference", "get", "-g", resolveGatewayName(GATEWAY_PORT)], + ["inference", "get", "-g", "nemoclaw"], ["inference", "get"], ]; let last: LiveGatewayInferenceResult = { diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 050585c61d2..395858abc0b 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -5182,7 +5182,7 @@ async function onboard(opts: OnboardOptions = {}): Promise { session = onboardSession.saveSession( onboardSession.createSession({ mode: isNonInteractive() ? "non-interactive" : "interactive", - metadata: { gatewayName: GATEWAY_NAME, fromDockerfile: fromDockerfile || null }, + metadata: { gatewayName: "nemoclaw", fromDockerfile: fromDockerfile || null }, }), ); } diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index 32f1df9b589..5ea6d3cc713 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -20,9 +20,10 @@ */ import { DEFAULT_GATEWAY_PORT } from "../core/ports"; -import { BASE_GATEWAY_NAME, type GatewayReuseState } from "../state/gateway"; +import type { GatewayReuseState } from "../state/gateway"; -export { BASE_GATEWAY_NAME }; +/** Gateway registration name used for the default gateway port. */ +export const BASE_GATEWAY_NAME = "nemoclaw"; /** Docker-driver gateway state directory leaf name for the default port. */ export const BASE_GATEWAY_STATE_DIR_NAME = "openshell-docker-gateway"; /** Docker-driver gateway compatibility container name for the default port. */ diff --git a/src/lib/resources-cmd.ts b/src/lib/resources-cmd.ts index 336653ff306..580db756174 100644 --- a/src/lib/resources-cmd.ts +++ b/src/lib/resources-cmd.ts @@ -16,10 +16,8 @@ import { spawnSync, execSync } from "child_process"; import * as YAML from "yaml"; import { dockerSpawnSync } from "./adapters/docker"; -import { GATEWAY_PORT } from "./core/ports"; -import { resolveGatewayName } from "./onboard/gateway-binding"; -const GATEWAY_NAME = resolveGatewayName(GATEWAY_PORT); +const GATEWAY_NAME = "nemoclaw"; function getGatewayContainer(): string { return `openshell-cluster-${GATEWAY_NAME}`; diff --git a/src/lib/state/gateway.ts b/src/lib/state/gateway.ts index 35c64720b38..1730487ca52 100644 --- a/src/lib/state/gateway.ts +++ b/src/lib/state/gateway.ts @@ -8,14 +8,7 @@ * returns a typed result — no I/O, no side effects. */ -/** - * Canonical OpenShell gateway registration name used by every NemoClaw - * host-side surface. Exported so call sites import this single source of - * truth instead of hardcoding the `"nemoclaw"` literal across the codebase. - * The per-port resolver in `onboard/gateway-binding.ts` derives suffixed - * variants (`nemoclaw-`) from this base. - */ -export const BASE_GATEWAY_NAME = "nemoclaw"; +const GATEWAY_NAME = "nemoclaw"; const ANSI_RE = /\x1b\[[0-9;]*m/g; @@ -88,7 +81,7 @@ export function getSandboxFailurePhase(output: string, sandboxName: string): str * Determine whether stale NemoClaw gateway output indicates a previous * session that should be cleaned up before the port preflight check. */ -export function hasStaleGateway(gwInfoOutput: string, gatewayName = BASE_GATEWAY_NAME): boolean { +export function hasStaleGateway(gwInfoOutput: string, gatewayName = GATEWAY_NAME): boolean { const clean = typeof gwInfoOutput === "string" ? stripAnsi(gwInfoOutput) : ""; return ( clean.length > 0 && @@ -124,7 +117,7 @@ export function hasActiveGatewayInfo(activeGatewayInfoOutput = ""): boolean { ); } -export function isSelectedGateway(statusOutput = "", gatewayName = BASE_GATEWAY_NAME): boolean { +export function isSelectedGateway(statusOutput = "", gatewayName = GATEWAY_NAME): boolean { return getReportedGatewayName(statusOutput) === gatewayName; } @@ -132,7 +125,7 @@ export function isGatewayHealthy( statusOutput = "", gwInfoOutput = "", activeGatewayInfoOutput = "", - gatewayName = BASE_GATEWAY_NAME, + gatewayName = GATEWAY_NAME, ): boolean { const namedGatewayKnown = hasStaleGateway(gwInfoOutput, gatewayName); const activeGatewayName = @@ -157,7 +150,7 @@ export function getGatewayReuseState( statusOutput = "", gwInfoOutput = "", activeGatewayInfoOutput = "", - gatewayName = BASE_GATEWAY_NAME, + gatewayName = GATEWAY_NAME, ): GatewayReuseState { if (isGatewayHealthy(statusOutput, gwInfoOutput, activeGatewayInfoOutput, gatewayName)) { return "healthy"; @@ -185,7 +178,7 @@ export function shouldSelectNamedGatewayForReuse( statusOutput = "", gwInfoOutput = "", activeGatewayInfoOutput = "", - gatewayName = BASE_GATEWAY_NAME, + gatewayName = GATEWAY_NAME, ): boolean { return ( getGatewayReuseState(statusOutput, gwInfoOutput, activeGatewayInfoOutput, gatewayName) === diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 0a8988adef5..c4218762318 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -13,9 +13,7 @@ import path from "node:path"; import { isErrnoException } from "../core/errno"; import type { JsonObject, JsonValue } from "../core/json-types"; -import { GATEWAY_PORT } from "../core/ports"; import type { WebSearchConfig } from "../inference/web-search"; -import { resolveGatewayName } from "../onboard/gateway-binding"; import { type MessagingChannelConfig, sanitizeMessagingChannelConfig, @@ -314,7 +312,7 @@ function parseWechatConfig(value: unknown): WechatConfig | null { function parseSessionMetadata(value: SessionJsonValue | undefined): SessionMetadata | undefined { if (!isObject(value)) return undefined; return { - gatewayName: readString(value.gatewayName) ?? resolveGatewayName(GATEWAY_PORT), + gatewayName: readString(value.gatewayName) ?? "nemoclaw", fromDockerfile: readString(value.fromDockerfile), }; } @@ -478,7 +476,7 @@ export function createSession(overrides: Partial = {}): Session { telegramConfig: parseTelegramConfig(overrides.telegramConfig), wechatConfig: parseWechatConfig(overrides.wechatConfig), metadata: { - gatewayName: overrides.metadata?.gatewayName ?? resolveGatewayName(GATEWAY_PORT), + gatewayName: overrides.metadata?.gatewayName ?? "nemoclaw", fromDockerfile: overrides.metadata?.fromDockerfile ?? null, }, machine: From 7dc3c67f302b147f1a8f1c886772f9c92d61f598 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 18:41:35 +0000 Subject: [PATCH 11/29] fix(sandbox): route gateway commands to sandbox's registered gateway Signed-off-by: Tinson Lai --- src/lib/actions/sandbox/connect.ts | 4 +- src/lib/actions/sandbox/destroy.ts | 21 ++-- src/lib/actions/sandbox/doctor.ts | 8 +- src/lib/actions/sandbox/gateway-state.ts | 21 ++-- src/lib/actions/sandbox/rebuild.ts | 17 ++-- src/lib/actions/sandbox/snapshot.ts | 40 ++++++-- src/lib/gateway-runtime-action.test.ts | 120 +++++++++++++++++++++++ src/lib/gateway-runtime-action.ts | 16 +-- src/lib/onboard/gateway-binding.test.ts | 6 +- src/lib/onboard/gateway-binding.ts | 4 +- 10 files changed, 200 insertions(+), 57 deletions(-) create mode 100644 src/lib/gateway-runtime-action.test.ts diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index f091097d713..7d52f9c4ae7 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -55,7 +55,6 @@ import { ensureLiveSandboxOrExit, printGatewayLifecycleHint } from "./gateway-st import { checkAndRecoverSandboxProcesses } from "./process-recovery"; import { applyOpenShellVmDnsMonkeypatch, shouldApplyVmDnsMonkeypatch } from "./vm-dns-monkeypatch"; - export type SandboxConnectOptions = { probeOnly?: boolean; }; @@ -273,7 +272,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, diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index e5d4507cfb4..e345b955f9e 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -8,7 +8,7 @@ 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, GATEWAY_PORT } from "../../core/ports"; +import { DASHBOARD_PORT } from "../../core/ports"; import { prompt as askPrompt } from "../../credentials/store"; import { type DestroySandboxOptions, @@ -19,10 +19,7 @@ import { shouldCleanupGatewayAfterDestroy, shouldStopHostServicesAfterDestroy, } from "../../domain/sandbox/destroy"; -import { - resolveGatewayName, - resolveSandboxGatewayName, -} from "../../onboard/gateway-binding"; +import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; import { @@ -82,8 +79,7 @@ type RemoveShieldsStateDeps = { const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); -function cleanupGatewayAfterLastSandbox(): void { - const gatewayName = resolveGatewayName(GATEWAY_PORT); +function cleanupGatewayAfterLastSandbox(gatewayName: string): void { const { runOpenshell } = require("../../adapters/openshell/runtime") as { runOpenshell: (args: string[], opts?: Record) => { status: number | null }; }; @@ -441,6 +437,10 @@ export async function destroySandbox( stopHostServices: shouldStopHostServices, }); cleanupShieldsDestroyArtifacts(sandboxName); + // Capture the sandbox's gateway BEFORE the registry entry is removed — + // post-removal lookups return null and would collapse the cleanup target + // back to the default gateway (#4865). + const cleanupGatewayName = resolveSandboxGatewayName(sb); const removed = removeSandboxRegistryEntry(sandboxName); const session = onboardSession.loadSession(); if (session && session.sandboxName === sandboxName) { @@ -459,13 +459,12 @@ export async function destroySandbox( ) { const shouldCleanupGateway = await resolveCleanupGatewayDecision(normalized); if (shouldCleanupGateway) { - cleanupGatewayAfterLastSandbox(); + cleanupGatewayAfterLastSandbox(cleanupGatewayName); } else { - const preservedGatewayName = resolveGatewayName(GATEWAY_PORT); const gatewayRemovalHint = process.platform === "linux" - ? `openshell gateway remove ${preservedGatewayName}` - : `openshell gateway destroy -g ${preservedGatewayName}`; + ? `openshell gateway remove ${cleanupGatewayName}` + : `openshell gateway destroy -g ${cleanupGatewayName}`; console.log( ` Shared NemoClaw gateway preserved. Re-run '${gatewayRemovalHint}' to remove it,`, ); diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index 7c61bd4b74f..cf21caae15c 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -18,10 +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 { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { executeSandboxCommandForVerification } from "../../onboard/sandbox-verification-exec"; import { ROOT } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; @@ -41,7 +38,6 @@ import { captureHostCommand } from "./doctor-host-command"; import { buildToolScopeChecks } from "./doctor-tool-scope"; import { probeSandboxInferenceGatewayHealth } from "./process-recovery"; - type DoctorStatus = "ok" | "warn" | "fail" | "info"; export type DoctorCheck = { @@ -598,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"; diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 1844b72c31e..74de7dd68a2 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -11,10 +11,7 @@ import { getNamedGatewayLifecycleState, recoverNamedGatewayRuntime, } from "../../gateway-runtime-action"; -import { - resolveGatewayName, - resolveSandboxGatewayName, -} from "../../onboard/gateway-binding"; +import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { isTerminalSandboxPhase, parseSandboxPhase } from "../../state/gateway"; import * as registry from "../../state/registry"; @@ -408,7 +405,9 @@ export async function getReconciledSandboxGatewayState( } if (lookup.state === "gateway_error") { - const recovery = await recoverNamedGatewayRuntime(); + const sb = registry.getSandbox(sandboxName); + const targetGatewayName = sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); + const recovery = await recoverNamedGatewayRuntime({ gatewayName: targetGatewayName }); if (recovery.recovered) { const retried = await getState(sandboxName); if (retried.state === "present" || retried.state === "missing") { @@ -424,7 +423,7 @@ export async function getReconciledSandboxGatewayState( } return { ...retried, recoveredGateway: true, recoveryVia: recovery.via || null }; } - const latestLifecycle = getNamedGatewayLifecycleState(); + const latestLifecycle = getNamedGatewayLifecycleState(targetGatewayName); const latestStatus = stripAnsi(latestLifecycle.status || ""); if (/No gateway configured/i.test(latestStatus)) { return { @@ -432,9 +431,13 @@ export async function getReconciledSandboxGatewayState( output: latestLifecycle.status || lookup.output, }; } + const namedGatewayRe = new RegExp( + `Gateway:\\s+${targetGatewayName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, + "i", + ); if ( /Connection refused|client error \(Connect\)|tcp connect error/i.test(latestStatus) && - /Gateway:\s+nemoclaw/i.test(latestStatus) + namedGatewayRe.test(latestStatus) ) { return { state: "gateway_unreachable_after_restart", @@ -489,7 +492,9 @@ export async function ensureLiveSandboxOrExit( process.exit(1); } if (lookup.state === "missing") { - const guard = getNamedGatewayLifecycleState(); + const sb = registry.getSandbox(sandboxName); + const targetGatewayName = sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); + const guard = getNamedGatewayLifecycleState(targetGatewayName); if (guard.state !== "healthy_named") { if (guard.state === "connected_other") { printWrongGatewayActiveGuidance(sandboxName, guard.activeGateway, console.error); diff --git a/src/lib/actions/sandbox/rebuild.ts b/src/lib/actions/sandbox/rebuild.ts index da38b78eecf..a7394410d4a 100644 --- a/src/lib/actions/sandbox/rebuild.ts +++ b/src/lib/actions/sandbox/rebuild.ts @@ -4,10 +4,7 @@ import { CLI_NAME } from "../../cli/branding"; import { GATEWAY_PORT } from "../../core/ports"; import { prompt as askPrompt } from "../../credentials/store"; -import { - resolveGatewayName, - resolveSandboxGatewayName, -} from "../../onboard/gateway-binding"; +import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { normalizeRebuildSandboxOptions, type RebuildSandboxOptions, @@ -621,12 +618,12 @@ export async function rebuildSandbox( const reconciled = await getReconciledSandboxGatewayState(sandboxName); if (reconciled.state === "present") { // `sandbox get` resolved the sandbox, but that query ran against whatever - // gateway is currently active. Only trust it as live when the named - // nemoclaw gateway is the active healthy one — otherwise a foreign active - // gateway with a same-named sandbox (or a list/get inconsistency) could - // send the destructive backup/delete below at the wrong sandbox. If a - // foreign gateway is active, abort with guidance instead. - const lifecycle = getNamedGatewayLifecycleState(); + // gateway is currently active. Only trust it as live when the sandbox's + // own registered gateway is the active healthy one — otherwise a foreign + // active gateway with a same-named sandbox (or a list/get inconsistency) + // could send the destructive backup/delete below at the wrong sandbox. If + // a foreign gateway is active, abort with guidance instead. + const lifecycle = getNamedGatewayLifecycleState(resolveSandboxGatewayName(sb)); if (lifecycle.state !== "healthy_named") { printWrongGatewayActiveGuidance( sandboxName, diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index c76118fcbbf..4ccad0a527c 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -9,14 +9,12 @@ import { getOpenshellBinary, runOpenshell, } from "../../adapters/openshell/runtime"; +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt } from "../../credentials/store"; import { getSandboxDeleteOutcome } from "../../domain/sandbox/destroy"; import { GATEWAY_PORT } from "../../core/ports"; -import { - resolveGatewayName, - resolveSandboxGatewayName, -} from "../../onboard/gateway-binding"; +import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import * as policies from "../../policy"; import { ROOT, run, shellQuote, validateName } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; @@ -119,7 +117,10 @@ function resolveSrcPodImage( return registeredImage ?? null; } - const gatewayContainer = `openshell-cluster-${resolveSandboxGatewayName(srcEntry as { gatewayName?: string | null; gatewayPort?: number | null })}`; + const srcGatewayName = resolveSandboxGatewayName( + srcEntry as { gatewayName?: string | null; gatewayPort?: number | null }, + ); + const gatewayContainer = `openshell-cluster-${srcGatewayName}`; try { const output = dockerCapture( [ @@ -210,7 +211,10 @@ async function autoCreateSandboxFromSource( const dnsScript = path.join(ROOT, "scripts", "setup-dns-proxy.sh"); const srcDriver = (srcEntry as { openshellDriver?: string | null }).openshellDriver; if (srcDriver === "kubernetes" && fs.existsSync(dnsScript)) { - run(["bash", dnsScript, resolveSandboxGatewayName(srcEntry as { gatewayName?: string | null; gatewayPort?: number | null }), dstName], { ignoreError: true }); + const srcGatewayName = resolveSandboxGatewayName( + srcEntry as { gatewayName?: string | null; gatewayPort?: number | null }, + ); + run(["bash", dnsScript, srcGatewayName, dstName], { ignoreError: true }); } // Register dst in the NemoClaw registry, cloning most fields from src. @@ -321,9 +325,7 @@ function usesGatewayMetadataProbe(driver: string | null | undefined): boolean { function probeGatewayRunning(sandboxName?: string): boolean { const entry = sandboxName ? registry.getSandbox(sandboxName) : null; - const gatewayName = entry - ? resolveSandboxGatewayName(entry) - : resolveGatewayName(GATEWAY_PORT); + const gatewayName = entry ? resolveSandboxGatewayName(entry) : resolveGatewayName(GATEWAY_PORT); if (usesGatewayMetadataProbe(entry?.openshellDriver)) { return probeGatewayMetadataHealth(gatewayName); } @@ -335,6 +337,20 @@ function probeGatewayRunning(sandboxName?: string): boolean { return result.status === 0 && String(result.stdout || "").trim() === "true"; } +// Best-effort: switch the active OpenShell gateway to the one this sandbox is +// registered on so downstream `sandbox list` / `sandbox get` queries target +// the right gateway. Silent on failure — the subsequent list call surfaces a +// clearer error if the gateway is genuinely unavailable. +function selectSandboxGatewayIfRegistered(sandboxName: string): void { + const entry = registry.getSandbox(sandboxName); + if (!entry) return; + const target = resolveSandboxGatewayName(entry); + runOpenshell(["gateway", "select", target], { + ignoreError: true, + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }); +} + function isSnapshotCreationAllowedByShields(sandboxName: string): boolean { // Snapshot creation is a shields/policy boundary. If a packaged or mocked // CommonJS interop surface ever omits the helper, fail closed before any @@ -357,6 +373,11 @@ export async function runSandboxSnapshot( console.error(" Failed to query live sandbox state from OpenShell."); snapshotExit(1); } + // Select the sandbox's gateway before `sandbox list` — otherwise the + // list runs against whatever gateway is currently active and would + // miss a sandbox registered on a non-default `NEMOCLAW_GATEWAY_PORT` + // (#4985). + selectSandboxGatewayIfRegistered(sandboxName); const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); const liveNames = parseLiveSandboxNames(isLive.output || ""); if (!liveNames.has(sandboxName)) { @@ -423,6 +444,7 @@ export async function runSandboxSnapshot( console.error(" Failed to query live sandbox state from OpenShell."); snapshotExit(1); } + selectSandboxGatewayIfRegistered(sandboxName); const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); const liveNames = parseLiveSandboxNames(isLive.output || ""); const isCrossSandboxRestore = targetSandbox !== sandboxName; diff --git a/src/lib/gateway-runtime-action.test.ts b/src/lib/gateway-runtime-action.test.ts new file mode 100644 index 00000000000..ab06e8b8251 --- /dev/null +++ b/src/lib/gateway-runtime-action.test.ts @@ -0,0 +1,120 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createRequire } from "node:module"; + +import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest"; + +type GatewayRuntimeModule = typeof import("../../dist/lib/gateway-runtime-action"); + +const requireDist = createRequire(import.meta.url); + +describe("gateway-runtime-action per-sandbox gateway routing", () => { + let gatewayRuntime: GatewayRuntimeModule; + let captureSpy: MockInstance; + let runSpy: MockInstance; + let spies: MockInstance[]; + + beforeEach(() => { + spies = []; + const openshellRuntime = requireDist("../../dist/lib/adapters/openshell/runtime.js"); + captureSpy = vi.spyOn(openshellRuntime, "captureOpenshell"); + runSpy = vi.spyOn(openshellRuntime, "runOpenshell"); + spies.push(captureSpy, runSpy); + + // The recovery path also pokes onboard.startGatewayForRecovery via lazy + // require(); stub it so the tests do not pull onboard's runtime in. + const onboard = requireDist("../../dist/lib/onboard.js"); + spies.push(vi.spyOn(onboard, "startGatewayForRecovery").mockResolvedValue(undefined as never)); + + gatewayRuntime = requireDist("../../dist/lib/gateway-runtime-action.js"); + }); + + afterEach(() => { + for (const spy of spies) spy.mockRestore(); + delete process.env.OPENSHELL_GATEWAY; + }); + + describe("getNamedGatewayLifecycleState", () => { + it("queries the bare 'nemoclaw' name by default", () => { + captureSpy.mockReturnValue({ status: 0, output: "Status: Connected\nGateway: nemoclaw\n" }); + + gatewayRuntime.getNamedGatewayLifecycleState(); + + const calls = captureSpy.mock.calls.map(([args]) => args); + expect(calls).toContainEqual(["gateway", "info", "-g", "nemoclaw"]); + }); + + it("queries the per-port gateway when a name is supplied", () => { + captureSpy.mockReturnValue({ + status: 0, + output: "Status: Connected\nGateway: nemoclaw-8090\n", + }); + + const result = gatewayRuntime.getNamedGatewayLifecycleState("nemoclaw-8090"); + + const calls = captureSpy.mock.calls.map(([args]) => args); + expect(calls).toContainEqual(["gateway", "info", "-g", "nemoclaw-8090"]); + expect(result.state).toBe("healthy_named"); + expect(result.activeGateway).toBe("nemoclaw-8090"); + }); + + it("treats a non-default gateway as 'connected_other' when the active gateway differs", () => { + captureSpy.mockReturnValue({ + status: 0, + output: "Status: Connected\nGateway: nemoclaw\n", + }); + + const result = gatewayRuntime.getNamedGatewayLifecycleState("nemoclaw-8090"); + + expect(result.state).toBe("connected_other"); + expect(result.activeGateway).toBe("nemoclaw"); + }); + }); + + describe("recoverNamedGatewayRuntime", () => { + it("selects the supplied gateway name on the recovery path", async () => { + captureSpy + .mockReturnValueOnce({ status: 0, output: "Status: Disconnected\nGateway: nemoclaw\n" }) + .mockReturnValueOnce({ status: 0, output: "" }) + .mockReturnValueOnce({ + status: 0, + output: "Status: Connected\nGateway: nemoclaw-8090\n", + }) + .mockReturnValueOnce({ + status: 0, + output: "Gateway: nemoclaw-8090\n", + }); + runSpy.mockReturnValue({ status: 0 } as never); + + const result = await gatewayRuntime.recoverNamedGatewayRuntime({ + gatewayName: "nemoclaw-8090", + }); + + const selectCalls = runSpy.mock.calls + .map(([args]) => args) + .filter((args: string[]) => args[0] === "gateway" && args[1] === "select"); + expect(selectCalls).toContainEqual(["gateway", "select", "nemoclaw-8090"]); + expect(selectCalls.every((args: string[]) => args[2] === "nemoclaw-8090")).toBe(true); + expect(result.recovered).toBe(true); + expect(process.env.OPENSHELL_GATEWAY).toBe("nemoclaw-8090"); + }); + + it("never selects the bare default gateway when a per-port name is supplied", async () => { + captureSpy.mockReturnValue({ + status: 0, + output: "Status: Disconnected\nGateway: other\n", + }); + runSpy.mockReturnValue({ status: 0 } as never); + + await gatewayRuntime.recoverNamedGatewayRuntime({ gatewayName: "nemoclaw-8090" }); + + const selectCalls = runSpy.mock.calls + .map(([args]) => args) + .filter((args: string[]) => args[0] === "gateway" && args[1] === "select"); + for (const args of selectCalls) { + expect(args[2]).toBe("nemoclaw-8090"); + } + }); + }); +}); diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index a54e86c98e6..87ed3d42417 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -76,10 +76,12 @@ type NamedGatewayLifecycleStateName = ReturnType( options.recoverableStates ?? [ "missing_named", @@ -88,7 +90,7 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun "connected_other", ], ); - const before = getNamedGatewayLifecycleState(); + const before = getNamedGatewayLifecycleState(gatewayName); if (before.state === "healthy_named") { return { recovered: true, before, after: before, attempted: false }; } @@ -96,13 +98,13 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun return { recovered: false, before, after: before, attempted: false }; } - runOpenshell(["gateway", "select", "nemoclaw"], { + runOpenshell(["gateway", "select", gatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - let after = getNamedGatewayLifecycleState(); + let after = getNamedGatewayLifecycleState(gatewayName); if (after.state === "healthy_named") { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.OPENSHELL_GATEWAY = gatewayName; return { recovered: true, before, after, attempted: true, via: "select" }; } @@ -119,13 +121,13 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun // Fall through to the lifecycle re-check below so we preserve the // existing recovery result shape and emit the correct classification. } - runOpenshell(["gateway", "select", "nemoclaw"], { + runOpenshell(["gateway", "select", gatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - after = getNamedGatewayLifecycleState(); + after = getNamedGatewayLifecycleState(gatewayName); if (after.state === "healthy_named") { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.OPENSHELL_GATEWAY = gatewayName; return { recovered: true, before, after, attempted: true, via: "start" }; } } diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index e80baec4270..51d48ca5398 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -50,9 +50,9 @@ describe("gateway-binding resolver (#4422)", () => { describe("resolveSandboxGatewayName", () => { it("returns the persisted gatewayName when present", () => { - expect( - resolveSandboxGatewayName({ gatewayName: "nemoclaw-9090", gatewayPort: 9090 }), - ).toBe("nemoclaw-9090"); + expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw-9090", gatewayPort: 9090 })).toBe( + "nemoclaw-9090", + ); }); it("derives the gateway name from gatewayPort when gatewayName is absent", () => { diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index 5ea6d3cc713..ec9d041f7c2 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -68,7 +68,9 @@ export interface SandboxGatewayBinding { * 3. The bare `BASE_GATEWAY_NAME` for legacy entries that pre-date the * per-port migration. */ -export function resolveSandboxGatewayName(sandbox: SandboxGatewayBinding | null | undefined): string { +export function resolveSandboxGatewayName( + sandbox: SandboxGatewayBinding | null | undefined, +): string { if (sandbox?.gatewayName && typeof sandbox.gatewayName === "string") { return sandbox.gatewayName; } From cfde925677b4a6f7c32544fad0603987b17bd957 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 11 Jun 2026 19:19:22 +0000 Subject: [PATCH 12/29] fix(sandbox): extract gateway routing, validate persisted names, route remaining lifecycle calls Signed-off-by: Tinson Lai --- src/lib/actions/sandbox/gateway-state.ts | 2 +- .../sandbox/sandbox-gateway-routing.ts | 81 +++++++++++++++++++ src/lib/actions/sandbox/snapshot.ts | 77 ++++-------------- src/lib/onboard/gateway-binding.test.ts | 25 ++++++ src/lib/onboard/gateway-binding.ts | 37 ++++++++- 5 files changed, 154 insertions(+), 68 deletions(-) create mode 100644 src/lib/actions/sandbox/sandbox-gateway-routing.ts diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 74de7dd68a2..4c3d293657a 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -246,7 +246,7 @@ export function reconcileMissingAgainstNamedGateway( return retry; } if (retry.state === "missing") { - const after = getNamedGatewayLifecycleState(); + const after = getNamedGatewayLifecycleState(targetGatewayName); if (after.state === "healthy_named") { // Even with the right gateway selected, the sandbox is // still missing. Try Docker-side recovery before declaring diff --git a/src/lib/actions/sandbox/sandbox-gateway-routing.ts b/src/lib/actions/sandbox/sandbox-gateway-routing.ts new file mode 100644 index 00000000000..5116853c3c5 --- /dev/null +++ b/src/lib/actions/sandbox/sandbox-gateway-routing.ts @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * Sandbox-scoped gateway routing helpers shared across sandbox lifecycle + * commands (snapshot, restore, ...) so the snapshot monolith does not have to + * carry them. Each helper resolves the OpenShell gateway from the sandbox's + * persisted registry entry — never the process-level `NEMOCLAW_GATEWAY_PORT` + * — so a sandbox registered on a non-default per-port gateway is addressed + * correctly. + */ + +import { dockerInspect } from "../../adapters/docker"; +import { captureOpenshell, runOpenshell } from "../../adapters/openshell/runtime"; +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; +import { GATEWAY_PORT } from "../../core/ports"; +import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; +import { isGatewayHealthy } from "../../state/gateway"; +import * as registry from "../../state/registry"; + +/** + * Docker/VM-driver sandboxes do not expose the legacy cluster container, so + * verify gateway health through OpenShell metadata instead. + */ +export function probeGatewayMetadataHealth(gatewayName: string): boolean { + const status = captureOpenshell(["status"], { ignoreError: true, timeout: 10000 }); + const namedGatewayInfo = captureOpenshell(["gateway", "info", "-g", gatewayName], { + ignoreError: true, + timeout: 10000, + }); + const activeGatewayInfo = captureOpenshell(["gateway", "info"], { + ignoreError: true, + timeout: 10000, + }); + return isGatewayHealthy( + status.output || "", + namedGatewayInfo.output || "", + activeGatewayInfo.output || "", + gatewayName, + ); +} + +export function usesGatewayMetadataProbe(driver: string | null | undefined): boolean { + return driver === "docker" || driver === "vm"; +} + +/** + * Probe whether the OpenShell gateway the named sandbox lives on is running. + * Resolves the gateway from the sandbox's persisted registry entry — never + * the process-level `GATEWAY_PORT` — so the probe targets the gateway the + * sandbox was actually onboarded against (#4985). + */ +export function probeGatewayRunning(sandboxName?: string): boolean { + const entry = sandboxName ? registry.getSandbox(sandboxName) : null; + const gatewayName = entry ? resolveSandboxGatewayName(entry) : resolveGatewayName(GATEWAY_PORT); + if (usesGatewayMetadataProbe(entry?.openshellDriver)) { + return probeGatewayMetadataHealth(gatewayName); + } + const container = `openshell-cluster-${gatewayName}`; + const result = dockerInspect( + ["--type", "container", "--format", "{{.State.Running}}", container], + { ignoreError: true, suppressOutput: true }, + ); + return result.status === 0 && String(result.stdout || "").trim() === "true"; +} + +/** + * Best-effort: switch the active OpenShell gateway to the one this sandbox is + * registered on so downstream `sandbox list` / `sandbox get` queries target + * the right gateway. Silent on failure — the subsequent list call surfaces a + * clearer error if the gateway is genuinely unavailable. + */ +export function selectSandboxGatewayIfRegistered(sandboxName: string): void { + const entry = registry.getSandbox(sandboxName); + if (!entry) return; + const target = resolveSandboxGatewayName(entry); + runOpenshell(["gateway", "select", target], { + ignoreError: true, + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }); +} diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 4ccad0a527c..12d4ebf43ef 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -3,27 +3,29 @@ import fs from "node:fs"; import path from "node:path"; -import { dockerCapture, dockerInspect } from "../../adapters/docker"; +import { dockerCapture } from "../../adapters/docker"; import { captureOpenshell, getOpenshellBinary, runOpenshell, } from "../../adapters/openshell/runtime"; -import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt } from "../../credentials/store"; import { getSandboxDeleteOutcome } from "../../domain/sandbox/destroy"; -import { GATEWAY_PORT } from "../../core/ports"; -import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; +import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import * as policies from "../../policy"; import { ROOT, run, shellQuote, validateName } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; import * as shields from "../../shields"; -import { isGatewayHealthy } from "../../state/gateway"; import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import * as sandboxState from "../../state/sandbox"; import { cleanupShieldsDestroyArtifacts, removeSandboxRegistryEntry } from "./destroy"; +import { + probeGatewayRunning, + selectSandboxGatewayIfRegistered, + usesGatewayMetadataProbe, +} from "./sandbox-gateway-routing"; const useColor = !process.env.NO_COLOR && !!process.stdout.isTTY; const trueColor = @@ -299,58 +301,6 @@ function deleteSandboxForRestore(name: string): void { console.log(` ${G}\u2713${R} '${name}' deleted`); } -// Docker/VM-driver sandboxes do not expose the legacy cluster container, so -// verify gateway health through OpenShell metadata instead. -function probeGatewayMetadataHealth(gatewayName: string): boolean { - const status = captureOpenshell(["status"], { ignoreError: true, timeout: 10000 }); - const namedGatewayInfo = captureOpenshell(["gateway", "info", "-g", gatewayName], { - ignoreError: true, - timeout: 10000, - }); - const activeGatewayInfo = captureOpenshell(["gateway", "info"], { - ignoreError: true, - timeout: 10000, - }); - return isGatewayHealthy( - status.output || "", - namedGatewayInfo.output || "", - activeGatewayInfo.output || "", - gatewayName, - ); -} - -function usesGatewayMetadataProbe(driver: string | null | undefined): boolean { - return driver === "docker" || driver === "vm"; -} - -function probeGatewayRunning(sandboxName?: string): boolean { - const entry = sandboxName ? registry.getSandbox(sandboxName) : null; - const gatewayName = entry ? resolveSandboxGatewayName(entry) : resolveGatewayName(GATEWAY_PORT); - if (usesGatewayMetadataProbe(entry?.openshellDriver)) { - return probeGatewayMetadataHealth(gatewayName); - } - const container = `openshell-cluster-${gatewayName}`; - const result = dockerInspect( - ["--type", "container", "--format", "{{.State.Running}}", container], - { ignoreError: true, suppressOutput: true }, - ); - return result.status === 0 && String(result.stdout || "").trim() === "true"; -} - -// Best-effort: switch the active OpenShell gateway to the one this sandbox is -// registered on so downstream `sandbox list` / `sandbox get` queries target -// the right gateway. Silent on failure — the subsequent list call surfaces a -// clearer error if the gateway is genuinely unavailable. -function selectSandboxGatewayIfRegistered(sandboxName: string): void { - const entry = registry.getSandbox(sandboxName); - if (!entry) return; - const target = resolveSandboxGatewayName(entry); - runOpenshell(["gateway", "select", target], { - ignoreError: true, - timeout: OPENSHELL_OPERATION_TIMEOUT_MS, - }); -} - function isSnapshotCreationAllowedByShields(sandboxName: string): boolean { // Snapshot creation is a shields/policy boundary. If a packaged or mocked // CommonJS interop surface ever omits the helper, fail closed before any @@ -369,15 +319,16 @@ export async function runSandboxSnapshot( ) { switch (request.kind) { case "create": { + // Select the sandbox's gateway before the health probe and `sandbox list` + // — Docker/VM-driver health and the sandbox listing both require the + // sandbox's gateway to be the active one, otherwise a sandbox registered + // on a non-default `NEMOCLAW_GATEWAY_PORT` fails health-check before the + // subsequent list ever runs. + selectSandboxGatewayIfRegistered(sandboxName); if (!probeGatewayRunning(sandboxName)) { console.error(" Failed to query live sandbox state from OpenShell."); snapshotExit(1); } - // Select the sandbox's gateway before `sandbox list` — otherwise the - // list runs against whatever gateway is currently active and would - // miss a sandbox registered on a non-default `NEMOCLAW_GATEWAY_PORT` - // (#4985). - selectSandboxGatewayIfRegistered(sandboxName); const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); const liveNames = parseLiveSandboxNames(isLive.output || ""); if (!liveNames.has(sandboxName)) { @@ -440,11 +391,11 @@ export async function runSandboxSnapshot( const target = request.to ?? sandboxName; const targetSandbox = target === sandboxName ? sandboxName : validateName(target, "target sandbox name"); + selectSandboxGatewayIfRegistered(sandboxName); if (!probeGatewayRunning(sandboxName)) { console.error(" Failed to query live sandbox state from OpenShell."); snapshotExit(1); } - selectSandboxGatewayIfRegistered(sandboxName); const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); const liveNames = parseLiveSandboxNames(isLive.output || ""); const isCrossSandboxRestore = targetSandbox !== sandboxName; diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 51d48ca5398..039bd7b3fbe 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -80,6 +80,31 @@ describe("resolveSandboxGatewayName", () => { resolveSandboxGatewayName({ gatewayPort: 8090 }), ); }); + + it("rejects an out-of-namespace persisted gatewayName and falls through to the port", () => { + // A tampered registry entry must not redirect destructive gateway/volume + // operations to an arbitrary string. The validator strips it and the + // per-port fallback kicks in instead. + expect(resolveSandboxGatewayName({ gatewayName: "rogue-gateway", gatewayPort: 8081 })).toBe( + "nemoclaw-8081", + ); + expect(resolveSandboxGatewayName({ gatewayName: "../etc/passwd" })).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw evil" })).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw-0" })).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw-65536" })).toBe(BASE_GATEWAY_NAME); + }); + + it("rejects an out-of-range or non-integer persisted gatewayPort", () => { + expect(resolveSandboxGatewayName({ gatewayPort: 0 })).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName({ gatewayPort: -1 })).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName({ gatewayPort: 65536 })).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName({ gatewayPort: 8081.5 })).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName({ gatewayPort: Number.NaN })).toBe(BASE_GATEWAY_NAME); + }); + + it("accepts the canonical bare base gateway name", () => { + expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw" })).toBe(BASE_GATEWAY_NAME); + }); }); describe("docker-driver compat container is gateway-port scoped (#4422)", () => { diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index ec9d041f7c2..d40617b27b6 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -53,6 +53,24 @@ export interface SandboxGatewayBinding { gatewayPort?: number | null; } +/** + * Recognises a NemoClaw-namespaced gateway name. The persisted form is either + * the bare `nemoclaw` or the per-port `nemoclaw-` derivation — anything + * outside that namespace must not be trusted, since + * `resolveSandboxGatewayName` drives gateway select/info/recover/remove/ + * destroy and Docker volume targeting from the value. + */ +const VALID_GATEWAY_NAME_RE = + /^nemoclaw(-(?:[1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]))?$/; + +function isValidPersistedGatewayName(value: string): boolean { + return VALID_GATEWAY_NAME_RE.test(value); +} + +function isValidPersistedGatewayPort(value: number): boolean { + return Number.isInteger(value) && value >= 1 && value <= 65535; +} + /** * Resolve the OpenShell gateway name a given sandbox should be addressed by. * Sandbox-scoped lifecycle commands (`connect`, `destroy`, `doctor`, @@ -63,18 +81,29 @@ export interface SandboxGatewayBinding { * gateway and fails with `sandbox has no spec`. * * Resolution order: - * 1. The sandbox's persisted `gatewayName` (recorded at onboard time). - * 2. The per-port derivation from the persisted `gatewayPort`. + * 1. The sandbox's persisted `gatewayName`, validated against the NemoClaw + * namespace (`nemoclaw` or `nemoclaw-`). Tampered registry state + * with an out-of-namespace gateway name is ignored to avoid redirecting + * destructive gateway/volume operations. + * 2. The per-port derivation from the persisted `gatewayPort`, validated + * against the TCP port range. * 3. The bare `BASE_GATEWAY_NAME` for legacy entries that pre-date the * per-port migration. */ export function resolveSandboxGatewayName( sandbox: SandboxGatewayBinding | null | undefined, ): string { - if (sandbox?.gatewayName && typeof sandbox.gatewayName === "string") { + if ( + sandbox?.gatewayName && + typeof sandbox.gatewayName === "string" && + isValidPersistedGatewayName(sandbox.gatewayName) + ) { return sandbox.gatewayName; } - if (typeof sandbox?.gatewayPort === "number" && Number.isFinite(sandbox.gatewayPort)) { + if ( + typeof sandbox?.gatewayPort === "number" && + isValidPersistedGatewayPort(sandbox.gatewayPort) + ) { return resolveGatewayName(sandbox.gatewayPort); } return BASE_GATEWAY_NAME; From 56ec87bf1669088416db93f254a4a25fc94f912d Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Thu, 11 Jun 2026 20:15:35 -0700 Subject: [PATCH 13/29] fix(sandbox): honor sandbox gateway during recovery Signed-off-by: Carlos Villela --- src/lib/actions/sandbox/gateway-state.ts | 20 +++- .../sandbox/rebuild-gateway-drift.test.ts | 10 +- .../sandbox/rebuild-shields-finally.test.ts | 8 +- src/lib/actions/sandbox/rebuild.ts | 52 ++-------- src/lib/adapters/docker/index.test.ts | 18 ++++ src/lib/adapters/docker/volume.ts | 4 +- src/lib/gateway-runtime-action.test.ts | 40 +++++++- src/lib/gateway-runtime-action.ts | 11 ++- src/lib/onboard.ts | 99 ++++++++++++++++++- src/lib/onboard/gateway-binding.test.ts | 15 +++ src/lib/onboard/gateway-binding.ts | 43 +++++--- src/lib/openshell-sandbox-list.ts | 21 +++- test/cli/destroy-gateway-cleanup.test.ts | 12 ++- 13 files changed, 269 insertions(+), 84 deletions(-) diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 4c3d293657a..ca4e15a791f 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -334,6 +334,11 @@ export function printWrongGatewayActiveGuidance( writer(` Then re-run: ${CLI_NAME} ${sandboxName} ${retryCommand}`); } +function getSandboxHintGatewayName(sandboxName = ""): string { + const sb = sandboxName ? registry.getSandbox(sandboxName) : null; + return sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); +} + /** Print troubleshooting hints based on gateway lifecycle state in the output. */ export function printGatewayLifecycleHint( output = "", @@ -341,28 +346,33 @@ export function printGatewayLifecycleHint( writer: (message: string) => void = console.error, ): void { const cleanOutput = stripAnsi(output); + const targetGatewayName = getSandboxHintGatewayName(sandboxName); if (/No gateway configured/i.test(cleanOutput)) { writer( ` The selected ${CLI_DISPLAY_NAME} gateway is no longer configured or its metadata/runtime has been lost.`, ); writer( - " Start the gateway again with `openshell gateway start --name nemoclaw` before expecting existing sandboxes to reconnect.", + ` Start the gateway again with \`openshell gateway start --name ${targetGatewayName}\` before expecting existing sandboxes to reconnect.`, ); writer( " If the gateway has to be rebuilt from scratch, recreate the affected sandbox afterward.", ); return; } + const targetGatewayRe = new RegExp( + `Gateway:\\s+${targetGatewayName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, + "i", + ); if ( /Connection refused|client error \(Connect\)|tcp connect error/i.test(cleanOutput) && - /Gateway:\s+nemoclaw/i.test(cleanOutput) + targetGatewayRe.test(cleanOutput) ) { writer( " The selected NemoClaw gateway exists in metadata, but its API is refusing connections after restart.", ); writer(" This usually means the gateway runtime did not come back cleanly after the restart."); writer( - " Retry `openshell gateway start --name nemoclaw`; if it stays in this state, rebuild the gateway before expecting existing sandboxes to reconnect.", + ` Retry \`openshell gateway start --name ${targetGatewayName}\`; if it stays in this state, rebuild the gateway before expecting existing sandboxes to reconnect.`, ); return; } @@ -561,7 +571,7 @@ export async function ensureLiveSandboxOrExit( console.error(lookup.output); } console.error( - " Retry `openshell gateway start --name nemoclaw` and verify `openshell status` is healthy before reconnecting.", + ` Retry \`openshell gateway start --name ${getSandboxHintGatewayName(sandboxName)}\` and verify \`openshell status\` is healthy before reconnecting.`, ); console.error( " If the gateway never becomes healthy, rebuild the gateway and then recreate the affected sandbox.", @@ -576,7 +586,7 @@ export async function ensureLiveSandboxOrExit( console.error(lookup.output); } console.error( - " Start the gateway again with `openshell gateway start --name nemoclaw` before retrying.", + ` Start the gateway again with \`openshell gateway start --name ${getSandboxHintGatewayName(sandboxName)}\` before retrying.`, ); console.error( " If the gateway had to be rebuilt from scratch, recreate the affected sandbox afterward.", diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index 80052d07808..c9b34200118 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -36,6 +36,7 @@ describe("rebuild gateway drift preflight", () => { let checkAgentVersionSpy: MockInstance; let detectPreflightIssueSpy: MockInstance; let captureOpenshellSpy: MockInstance; + let runOpenshellSpy: MockInstance; let printIssueSpy: MockInstance; let recoverNamedGatewayRuntimeSpy: MockInstance; @@ -66,6 +67,9 @@ describe("rebuild gateway drift preflight", () => { captureOpenshellSpy = vi .spyOn(openshellRuntime, "captureOpenshell") .mockReturnValue({ status: 0, output: "alpha Ready" }); + runOpenshellSpy = vi + .spyOn(openshellRuntime, "runOpenshell") + .mockReturnValue({ status: 0, output: "" } as never); recoverNamedGatewayRuntimeSpy = vi .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") .mockResolvedValue({ recovered: true }); @@ -74,6 +78,7 @@ describe("rebuild gateway drift preflight", () => { detectPreflightIssueSpy, vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null), captureOpenshellSpy, + runOpenshellSpy, recoverNamedGatewayRuntimeSpy, printIssueSpy, vi.spyOn(registry, "getSandbox").mockReturnValue({ @@ -151,13 +156,9 @@ describe("rebuild gateway drift preflight", () => { // preserved registry metadata. Stub the destructive steps + recreate handoff // so the path stays hermetic, and assert the recreate failure surfaces the // stale-recovery message instead of "not running". - const openshellRuntime = requireDist("../../../../dist/lib/adapters/openshell/runtime.js"); const destroy = requireDist("../../../../dist/lib/actions/sandbox/destroy.js"); const onboardMod = requireDist("../../../../dist/lib/onboard.js"); spies.push( - vi - .spyOn(openshellRuntime, "runOpenshell") - .mockReturnValue({ status: 0, output: "" } as never), vi.spyOn(destroy, "removeSandboxRegistryEntry").mockImplementation(() => undefined), vi.spyOn(onboardMod, "onboard").mockRejectedValue(new Error("recreate-stub")), ); @@ -167,6 +168,7 @@ describe("rebuild gateway drift preflight", () => { ); expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({ + gatewayName: "nemoclaw", recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable"], }); // The liveness query ran twice (initial failure + post-recovery retry). diff --git a/src/lib/actions/sandbox/rebuild-shields-finally.test.ts b/src/lib/actions/sandbox/rebuild-shields-finally.test.ts index 4be4491c41f..a930884bd67 100644 --- a/src/lib/actions/sandbox/rebuild-shields-finally.test.ts +++ b/src/lib/actions/sandbox/rebuild-shields-finally.test.ts @@ -17,6 +17,7 @@ describe("rebuild shields relock guard", () => { let errorSpy: MockInstance; let logSpy: MockInstance; let relockSpy: MockInstance; + let sandboxListRecoverySpy: MockInstance; const rebuildWindow = { relocked: false, wasLocked: true }; beforeEach(() => { @@ -47,13 +48,15 @@ describe("rebuild shields relock guard", () => { return true; }); + sandboxListRecoverySpy = vi.spyOn(sandboxList, "captureSandboxListWithGatewayRecovery"); + spies.push( vi.spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue").mockReturnValue(null), vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null), vi .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") .mockResolvedValue({ recovered: false }), - vi.spyOn(sandboxList, "captureSandboxListWithGatewayRecovery").mockResolvedValue({ + sandboxListRecoverySpy.mockResolvedValue({ result: { status: 0, output: "alpha Ready" }, }), vi.spyOn(resolve, "resolveOpenshell").mockReturnValue(null), @@ -67,6 +70,8 @@ describe("rebuild shields relock guard", () => { policies: [], agent: null, nimContainer: null, + gatewayName: "nemoclaw-8090", + gatewayPort: 8090, } as never), vi.spyOn(sandboxSession, "getActiveSandboxSessions").mockReturnValue({ detected: false, @@ -99,6 +104,7 @@ describe("rebuild shields relock guard", () => { ); expect(relockSpy).toHaveBeenCalledWith("alpha", rebuildWindow, true, expect.any(String)); + expect(sandboxListRecoverySpy).toHaveBeenCalledWith({ gatewayName: "nemoclaw-8090" }); expect(rebuildWindow.relocked).toBe(true); }); }); diff --git a/src/lib/actions/sandbox/rebuild.ts b/src/lib/actions/sandbox/rebuild.ts index a7394410d4a..af62b4c751b 100644 --- a/src/lib/actions/sandbox/rebuild.ts +++ b/src/lib/actions/sandbox/rebuild.ts @@ -2,9 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import { CLI_NAME } from "../../cli/branding"; -import { GATEWAY_PORT } from "../../core/ports"; import { prompt as askPrompt } from "../../credentials/store"; -import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; +import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { normalizeRebuildSandboxOptions, type RebuildSandboxOptions, @@ -543,8 +542,11 @@ export async function rebuildSandbox( } // Step 1: Ensure sandbox is live for backup - log("Checking sandbox liveness: openshell sandbox list"); - const liveRecovery = await captureSandboxListWithGatewayRecovery(); + const recordedGateway = resolveSandboxGatewayName(sb); + log(`Checking sandbox liveness on ${recordedGateway}: openshell sandbox list`); + const liveRecovery = await captureSandboxListWithGatewayRecovery({ + gatewayName: recordedGateway, + }); const isLive = liveRecovery.result; log( `openshell sandbox list exit=${isLive.status}, output=${(isLive.output || "").substring(0, 200)}`, @@ -581,49 +583,9 @@ export async function rebuildSandbox( // customPolicies, every field) is silently dropped or mutated (#4497). let staleRegistrySnapshot: ReturnType | null = null; if (!liveNames.has(sandboxName)) { - // The default-gateway liveness checks below can only authoritatively reason - // about the default `nemoclaw` gateway. A sandbox created on a non-default - // per-port gateway (#4645, e.g. `nemoclaw-9000`) that is simply not the - // active gateway would look absent here, and recreating-from-scratch would - // orphan its live workspace. Refuse the destructive path in that case and - // point the operator at the sandbox's own gateway. (If that gateway were - // active, the sandbox would have appeared in the list above.) - const recordedGateway = resolveSandboxGatewayName(sb); - const activeDefaultGateway = resolveGatewayName(GATEWAY_PORT); - if (recordedGateway !== activeDefaultGateway) { - console.error( - ` Sandbox '${sandboxName}' is registered on the '${recordedGateway}' OpenShell gateway, which is not the active gateway.`, - ); - console.error( - " Its live state could not be confirmed — your local registry entry has been preserved.", - ); - console.error(" Select that gateway and retry:"); - console.error(` openshell gateway select ${recordedGateway}`); - console.error(` Then re-run: ${CLI_NAME} ${sandboxName} rebuild --yes`); - bail( - `Sandbox '${sandboxName}' is on the non-default gateway '${recordedGateway}'; select it before rebuilding.`, - ); - return; - } - - // The active-gateway `sandbox list` does not show this sandbox. That alone - // is NOT proof it is gone: a different active gateway (multi-gateway setups, - // #4645) would hide a live NemoClaw sandbox, and `sandbox list` can omit a - // sandbox that `sandbox get` still resolves. Recreating on that false - // signal would destroy live workspace state. So confirm authoritatively - // against the NAMED NemoClaw gateway: getReconciledSandboxGatewayState runs - // `sandbox get`, re-selecting/recovering nemoclaw as needed, and only - // reports "missing" once the named gateway is confirmed healthy and the - // sandbox is genuinely absent. const reconciled = await getReconciledSandboxGatewayState(sandboxName); if (reconciled.state === "present") { - // `sandbox get` resolved the sandbox, but that query ran against whatever - // gateway is currently active. Only trust it as live when the sandbox's - // own registered gateway is the active healthy one — otherwise a foreign - // active gateway with a same-named sandbox (or a list/get inconsistency) - // could send the destructive backup/delete below at the wrong sandbox. If - // a foreign gateway is active, abort with guidance instead. - const lifecycle = getNamedGatewayLifecycleState(resolveSandboxGatewayName(sb)); + const lifecycle = getNamedGatewayLifecycleState(recordedGateway); if (lifecycle.state !== "healthy_named") { printWrongGatewayActiveGuidance( sandboxName, diff --git a/src/lib/adapters/docker/index.test.ts b/src/lib/adapters/docker/index.test.ts index 4f64186a14c..6753a5c4916 100644 --- a/src/lib/adapters/docker/index.test.ts +++ b/src/lib/adapters/docker/index.test.ts @@ -154,6 +154,7 @@ describe("docker helpers", () => { "openshell-cluster-nemoclaw", "openshell-cluster-nemoclaw-cache", "openshell-cluster-nemoclaw-2", + "openshell-cluster-nemoclaw2", "not-a-match", "", ].join("\n"), @@ -168,6 +169,23 @@ describe("docker helpers", () => { ]); }); + it("does not match a longer per-port gateway name with the same prefix", () => { + runCaptureMock.mockReturnValue( + [ + "openshell-cluster-nemoclaw-8081", + "openshell-cluster-nemoclaw-8081-cache", + "openshell-cluster-nemoclaw-80810", + ].join("\n"), + ); + + const names = dockerListVolumesByPrefix("openshell-cluster-nemoclaw-8081"); + + expect(names).toEqual([ + "openshell-cluster-nemoclaw-8081", + "openshell-cluster-nemoclaw-8081-cache", + ]); + }); + it("removes only volumes returned by the prefix probe", () => { runCaptureMock.mockReturnValue( "openshell-cluster-nemoclaw\nopenshell-cluster-nemoclaw-cache\n", diff --git a/src/lib/adapters/docker/volume.ts b/src/lib/adapters/docker/volume.ts index f1e51dac248..aa9ee9fbe57 100644 --- a/src/lib/adapters/docker/volume.ts +++ b/src/lib/adapters/docker/volume.ts @@ -33,7 +33,9 @@ export function dockerListVolumesByPrefix( ignoreError: true, ...opts, }); - return splitNonEmptyLines(output).filter((name) => name.startsWith(normalized)); + return splitNonEmptyLines(output).filter( + (name) => name === normalized || name.startsWith(`${normalized}-`), + ); } export function dockerRemoveVolumes( diff --git a/src/lib/gateway-runtime-action.test.ts b/src/lib/gateway-runtime-action.test.ts index ab06e8b8251..933e8016865 100644 --- a/src/lib/gateway-runtime-action.test.ts +++ b/src/lib/gateway-runtime-action.test.ts @@ -8,15 +8,18 @@ import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } fr type GatewayRuntimeModule = typeof import("../../dist/lib/gateway-runtime-action"); const requireDist = createRequire(import.meta.url); +const gatewayRuntimeModulePath = "../../dist/lib/gateway-runtime-action.js"; describe("gateway-runtime-action per-sandbox gateway routing", () => { let gatewayRuntime: GatewayRuntimeModule; let captureSpy: MockInstance; let runSpy: MockInstance; + let startGatewaySpy: MockInstance; let spies: MockInstance[]; beforeEach(() => { spies = []; + delete require.cache[requireDist.resolve(gatewayRuntimeModulePath)]; const openshellRuntime = requireDist("../../dist/lib/adapters/openshell/runtime.js"); captureSpy = vi.spyOn(openshellRuntime, "captureOpenshell"); runSpy = vi.spyOn(openshellRuntime, "runOpenshell"); @@ -25,14 +28,18 @@ describe("gateway-runtime-action per-sandbox gateway routing", () => { // The recovery path also pokes onboard.startGatewayForRecovery via lazy // require(); stub it so the tests do not pull onboard's runtime in. const onboard = requireDist("../../dist/lib/onboard.js"); - spies.push(vi.spyOn(onboard, "startGatewayForRecovery").mockResolvedValue(undefined as never)); + startGatewaySpy = vi + .spyOn(onboard, "startGatewayForRecovery") + .mockResolvedValue(undefined as never); + spies.push(startGatewaySpy); - gatewayRuntime = requireDist("../../dist/lib/gateway-runtime-action.js"); + gatewayRuntime = requireDist(gatewayRuntimeModulePath); }); afterEach(() => { for (const spy of spies) spy.mockRestore(); delete process.env.OPENSHELL_GATEWAY; + delete require.cache[requireDist.resolve(gatewayRuntimeModulePath)]; }); describe("getNamedGatewayLifecycleState", () => { @@ -116,5 +123,34 @@ describe("gateway-runtime-action per-sandbox gateway routing", () => { expect(args[2]).toBe("nemoclaw-8090"); } }); + + it("starts recovery with the supplied gateway name and derived port", async () => { + captureSpy + .mockReturnValueOnce({ status: 0, output: "Status: Disconnected\nGateway: nemoclaw\n" }) + .mockReturnValueOnce({ status: 0, output: "" }) + .mockReturnValueOnce({ status: 0, output: "Status: Disconnected\nGateway: nemoclaw\n" }) + .mockReturnValueOnce({ status: 0, output: "" }) + .mockReturnValueOnce({ + status: 0, + output: "Status: Connected\nGateway: nemoclaw-8090\n", + }) + .mockReturnValueOnce({ + status: 0, + output: "Gateway: nemoclaw-8090\n", + }); + runSpy.mockReturnValue({ status: 0 } as never); + + const result = await gatewayRuntime.recoverNamedGatewayRuntime({ + gatewayName: "nemoclaw-8090", + }); + + expect(startGatewaySpy).toHaveBeenCalledWith({ + gatewayName: "nemoclaw-8090", + gatewayPort: 8090, + }); + expect(result.recovered).toBe(true); + expect(result.via).toBe("start"); + expect(process.env.OPENSHELL_GATEWAY).toBe("nemoclaw-8090"); + }); }); }); diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index 87ed3d42417..08cc2daa372 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 const { startGatewayForRecovery } = require("./onboard") as { - startGatewayForRecovery: () => Promise; + startGatewayForRecovery: (options?: { + gatewayName?: string; + gatewayPort?: number; + }) => Promise; }; import { OPENSHELL_OPERATION_TIMEOUT_MS, @@ -10,6 +13,7 @@ import { } from "./adapters/openshell/timeouts"; import { stripAnsi } from "./adapters/openshell/client"; import { captureOpenshell, runOpenshell } from "./adapters/openshell/runtime"; +import { resolveGatewayPortFromName } from "./onboard/gateway-binding"; function hasNamedGateway(output = "", gatewayName = "nemoclaw"): boolean { return stripAnsi(output).includes(`Gateway: ${gatewayName}`); @@ -116,7 +120,10 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun if (shouldStartGateway) { try { - await startGatewayForRecovery(); + await startGatewayForRecovery({ + gatewayName, + gatewayPort: resolveGatewayPortFromName(gatewayName) ?? undefined, + }); } catch { // Fall through to the lifecycle re-check below so we preserve the // existing recovery result shape and emit the correct classification. diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 395858abc0b..16baa8d6212 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -191,6 +191,8 @@ const { OLLAMA_PORT, OLLAMA_PROXY_PORT, } = require("./core/ports"); +const { getGatewayHttpEndpoint } = + require("./core/gateway-address") as typeof import("./core/gateway-address"); const localInference: typeof import("./inference/local") = require("./inference/local"); const { resetOllamaHostCache, @@ -1349,8 +1351,8 @@ function handleFinalGatewayStartFailure({ return exitProcess(1); } -function getGatewayClusterContainerState(): string { - const containerName = getGatewayClusterContainerName(); +function getGatewayClusterContainerState(gatewayName = GATEWAY_NAME): string { + const containerName = getGatewayClusterContainerName(gatewayName); const state = dockerContainerInspectFormat( "{{.State.Status}}{{if .State.Health}} {{.State.Health.Status}}{{end}}", containerName, @@ -2327,6 +2329,87 @@ async function startDockerDriverGateway({ throw new Error("Docker-driver gateway failed to start"); } +type StartGatewayForRecoveryOptions = { + gatewayName?: string; + gatewayPort?: number; +}; + +function isValidGatewayRecoveryPort(port: number | null | undefined): port is number { + return Number.isInteger(port) && Number(port) >= 1 && Number(port) <= 65535; +} + +function resolveGatewayRecoveryTarget(options: StartGatewayForRecoveryOptions = {}) { + const gatewayName = options.gatewayName || GATEWAY_NAME; + const portFromName = gatewayBinding.resolveGatewayPortFromName(gatewayName); + const gatewayPort = isValidGatewayRecoveryPort(options.gatewayPort) + ? options.gatewayPort + : (portFromName ?? GATEWAY_PORT); + return { gatewayName, gatewayPort }; +} + +function getGatewayStartEnvForPort(gatewayPort: number): Record { + return { + ...getGatewayStartEnv(), + OPENSHELL_SERVER_PORT: String(gatewayPort), + OPENSHELL_SSH_GATEWAY_PORT: String(gatewayPort), + }; +} + +async function startTargetGatewayForRecovery({ + gatewayName, + gatewayPort, +}: { + gatewayName: string; + gatewayPort: number; +}): Promise { + const gatewayPortArg = String(gatewayPort); + const startResult = runOpenshell( + ["gateway", "start", "--name", gatewayName, "--port", gatewayPortArg], + { + ignoreError: true, + env: getGatewayStartEnvForPort(gatewayPort), + suppressOutput: true, + }, + ); + runOpenshell(["gateway", "select", gatewayName], { ignoreError: true }); + + const recoveryWait = getGatewayHealthWaitConfig( + startResult.status ?? 0, + getGatewayClusterContainerState(gatewayName), + ); + const recoveryPollCount = recoveryWait.extended + ? recoveryWait.count + : envInt("NEMOCLAW_HEALTH_POLL_COUNT", 10); + const recoveryPollInterval = recoveryWait.extended + ? recoveryWait.interval + : envInt("NEMOCLAW_HEALTH_POLL_INTERVAL", 2); + const targetGatewayUrl = `${getGatewayHttpEndpoint(gatewayPort)}/`; + for (let i = 0; i < recoveryPollCount; i++) { + const status = runCaptureOpenshell(["status"], { ignoreError: true }); + const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { + ignoreError: true, + }); + const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); + if ( + status.includes("Connected") && + gatewayState.isGatewayHealthy(status, namedInfo, currentInfo, gatewayName) && + (await isGatewayHttpReady(undefined, targetGatewayUrl)) + ) { + process.env.OPENSHELL_GATEWAY = gatewayName; + const runtime = getContainerRuntime(); + if (shouldPatchCoredns(runtime)) { + run(["bash", path.join(SCRIPTS, "fix-coredns.sh"), gatewayName], { + ignoreError: true, + }); + } + return; + } + if (i < recoveryPollCount - 1) sleepSeconds(recoveryPollInterval); + } + + throw new Error(`Gateway '${gatewayName}' failed to start`); +} + async function startGateway( _gpu: ReturnType, { gpuPassthrough = false }: { gpuPassthrough?: boolean } = {}, @@ -2334,8 +2417,16 @@ async function startGateway( return startGatewayWithOptions(_gpu, { exitOnFailure: true, gpuPassthrough }); } -async function startGatewayForRecovery(_gpu: ReturnType): Promise { - return startGatewayWithOptions(_gpu, { exitOnFailure: false }); +async function startGatewayForRecovery( + options: StartGatewayForRecoveryOptions = {}, +): Promise { + const target = resolveGatewayRecoveryTarget(options); + if (target.gatewayName !== GATEWAY_NAME || target.gatewayPort !== GATEWAY_PORT) { + return startTargetGatewayForRecovery(target); + } + return startGatewayWithOptions(undefined as unknown as ReturnType, { + exitOnFailure: false, + }); } function getGatewayStartEnv(): Record { diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 039bd7b3fbe..689cab449ee 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -20,6 +20,7 @@ import { BASE_GATEWAY_STATE_DIR_NAME, resolveGatewayCompatContainerName, resolveGatewayName, + resolveGatewayPortFromName, resolveGatewayStateDirName, resolveSandboxGatewayName, } from "../../../dist/lib/onboard/gateway-binding"; @@ -35,10 +36,18 @@ describe("gateway-binding resolver (#4422)", () => { it("suffixes the name, state dir, and compat container for a non-default port", () => { expect(resolveGatewayName(8081)).toBe("nemoclaw-8081"); + expect(resolveGatewayPortFromName("nemoclaw-8081")).toBe(8081); expect(resolveGatewayStateDirName(8081)).toBe("openshell-docker-gateway-8081"); expect(resolveGatewayCompatContainerName(8081)).toBe("nemoclaw-openshell-gateway-8081"); }); + it("rejects malformed gateway names when resolving a port", () => { + expect(resolveGatewayPortFromName("nemoclaw")).toBe(DEFAULT_GATEWAY_PORT); + expect(resolveGatewayPortFromName("nemoclaw-0")).toBeNull(); + expect(resolveGatewayPortFromName("nemoclaw-65536")).toBeNull(); + expect(resolveGatewayPortFromName("other-8081")).toBeNull(); + }); + it("derives distinct bindings for two different gateway ports", () => { const a = 8080; const b = 8081; @@ -55,6 +64,12 @@ describe("resolveSandboxGatewayName", () => { ); }); + it("derives from gatewayPort when a valid persisted gatewayName conflicts", () => { + expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw-9090", gatewayPort: 8081 })).toBe( + "nemoclaw-8081", + ); + }); + it("derives the gateway name from gatewayPort when gatewayName is absent", () => { expect(resolveSandboxGatewayName({ gatewayPort: 8081 })).toBe("nemoclaw-8081"); expect(resolveSandboxGatewayName({ gatewayPort: 8080 })).toBe(BASE_GATEWAY_NAME); diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index d40617b27b6..71c2ce522f0 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -43,6 +43,21 @@ export function resolveGatewayName(port: number): string { return isDefaultGatewayPort(port) ? BASE_GATEWAY_NAME : `${BASE_GATEWAY_NAME}-${port}`; } +/** Resolve the gateway port encoded by a canonical NemoClaw gateway name. */ +export function resolveGatewayPortFromName(gatewayName: string): number | null { + if (gatewayName === BASE_GATEWAY_NAME) { + return DEFAULT_GATEWAY_PORT; + } + const match = gatewayName.match(new RegExp(`^${BASE_GATEWAY_NAME}-(\\d+)$`)); + if (!match) { + return null; + } + const port = Number(match[1]); + return isValidPersistedGatewayPort(port) && resolveGatewayName(port) === gatewayName + ? port + : null; +} + /** * Sandbox registry shape this resolver depends on. Kept structural to avoid * a hard import from `state/registry` (which would pull in the whole @@ -81,18 +96,24 @@ function isValidPersistedGatewayPort(value: number): boolean { * gateway and fails with `sandbox has no spec`. * * Resolution order: - * 1. The sandbox's persisted `gatewayName`, validated against the NemoClaw - * namespace (`nemoclaw` or `nemoclaw-`). Tampered registry state - * with an out-of-namespace gateway name is ignored to avoid redirecting - * destructive gateway/volume operations. - * 2. The per-port derivation from the persisted `gatewayPort`, validated - * against the TCP port range. - * 3. The bare `BASE_GATEWAY_NAME` for legacy entries that pre-date the - * per-port migration. + * 1. If `gatewayPort` is valid, derive the canonical gateway name from the + * port. When a persisted `gatewayName` is also present it must match that + * derivation; otherwise the port wins so tampered registry state cannot + * redirect destructive operations to a different valid NemoClaw gateway. + * 2. A name-only legacy entry may use a persisted `gatewayName`, validated + * against the NemoClaw namespace (`nemoclaw` or `nemoclaw-`). + * 3. The bare `BASE_GATEWAY_NAME` for older entries that pre-date the + * per-port migration entirely. */ export function resolveSandboxGatewayName( sandbox: SandboxGatewayBinding | null | undefined, ): string { + if ( + typeof sandbox?.gatewayPort === "number" && + isValidPersistedGatewayPort(sandbox.gatewayPort) + ) { + return resolveGatewayName(sandbox.gatewayPort); + } if ( sandbox?.gatewayName && typeof sandbox.gatewayName === "string" && @@ -100,12 +121,6 @@ export function resolveSandboxGatewayName( ) { return sandbox.gatewayName; } - if ( - typeof sandbox?.gatewayPort === "number" && - isValidPersistedGatewayPort(sandbox.gatewayPort) - ) { - return resolveGatewayName(sandbox.gatewayPort); - } return BASE_GATEWAY_NAME; } diff --git a/src/lib/openshell-sandbox-list.ts b/src/lib/openshell-sandbox-list.ts index 2d909f6809c..5461eee0e4e 100644 --- a/src/lib/openshell-sandbox-list.ts +++ b/src/lib/openshell-sandbox-list.ts @@ -3,7 +3,7 @@ import { detectOpenShellStateRpcResultIssue } from "./adapters/openshell/gateway-drift"; import { stripAnsi } from "./adapters/openshell/client"; -import { captureOpenshell } from "./adapters/openshell/runtime"; +import { captureOpenshell, runOpenshell } from "./adapters/openshell/runtime"; import { recoverNamedGatewayRuntime } from "./gateway-runtime-action"; type SandboxListResult = ReturnType; @@ -14,6 +14,10 @@ export type SandboxListRecoveryResult = { recoverySucceeded: boolean; }; +export type CaptureSandboxListWithGatewayRecoveryOptions = { + gatewayName?: string; +}; + export function isRecoverableSandboxListGatewayFailure(result: SandboxListResult): boolean { if (result.status === 0 || detectOpenShellStateRpcResultIssue(result)) { return false; @@ -24,15 +28,24 @@ export function isRecoverableSandboxListGatewayFailure(result: SandboxListResult ); } -export async function captureSandboxListWithGatewayRecovery(): Promise { +export async function captureSandboxListWithGatewayRecovery( + options: CaptureSandboxListWithGatewayRecoveryOptions = {}, +): Promise { + if (options.gatewayName) { + runOpenshell(["gateway", "select", options.gatewayName], { ignoreError: true }); + } const initial = captureOpenshell(["sandbox", "list"]); if (!isRecoverableSandboxListGatewayFailure(initial)) { return { result: initial, recoveryAttempted: false, recoverySucceeded: false }; } - const recovery = await recoverNamedGatewayRuntime({ + const recoveryOptions: Parameters[0] = { recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable"], - }); + }; + if (options.gatewayName) { + recoveryOptions.gatewayName = options.gatewayName; + } + const recovery = await recoverNamedGatewayRuntime(recoveryOptions); if (!recovery.recovered) { return { result: initial, recoveryAttempted: true, recoverySucceeded: false }; } diff --git a/test/cli/destroy-gateway-cleanup.test.ts b/test/cli/destroy-gateway-cleanup.test.ts index f24dcce47ac..0435296418e 100644 --- a/test/cli/destroy-gateway-cleanup.test.ts +++ b/test/cli/destroy-gateway-cleanup.test.ts @@ -97,6 +97,8 @@ describe("CLI dispatch", () => { provider: "nvidia-prod", gpuEnabled: false, policies: [], + gatewayName: "nemoclaw-8081", + gatewayPort: 8081, }, }, defaultSandbox: "alpha", @@ -144,9 +146,13 @@ describe("CLI dispatch", () => { expect(openshellOutput).toContain("sandbox delete alpha"); expect(openshellOutput).toContain("forward stop 18789"); expect(openshellOutput).toContain( - process.platform === "linux" ? "gateway remove nemoclaw" : "gateway destroy -g nemoclaw", + process.platform === "linux" + ? "gateway remove nemoclaw-8081" + : "gateway destroy -g nemoclaw-8081", + ); + expect(fs.readFileSync(bashLog, "utf8")).toContain( + "volume ls -q --filter name=openshell-cluster-nemoclaw-8081", ); - expect(fs.readFileSync(bashLog, "utf8")).toContain("volume ls -q --filter"); }, ); @@ -241,6 +247,8 @@ describe("CLI dispatch", () => { provider: "nvidia-prod", gpuEnabled: false, policies: [], + gatewayName: "nemoclaw-8081", + gatewayPort: 8081, }, beta: { name: "beta", From 7890e564be85673934d7879f7b8d91f22135550a Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Thu, 11 Jun 2026 20:40:22 -0700 Subject: [PATCH 14/29] refactor(onboard): extract gateway recovery module --- src/lib/onboard.ts | 114 ++-------------- src/lib/onboard/gateway-recovery.test.ts | 66 +++++++++ src/lib/onboard/gateway-recovery.ts | 166 +++++++++++++++++++++++ 3 files changed, 241 insertions(+), 105 deletions(-) create mode 100644 src/lib/onboard/gateway-recovery.test.ts create mode 100644 src/lib/onboard/gateway-recovery.ts diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 16baa8d6212..95de4a9a93c 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -191,8 +191,6 @@ const { OLLAMA_PORT, OLLAMA_PROXY_PORT, } = require("./core/ports"); -const { getGatewayHttpEndpoint } = - require("./core/gateway-address") as typeof import("./core/gateway-address"); const localInference: typeof import("./inference/local") = require("./inference/local"); const { resetOllamaHostCache, @@ -1351,8 +1349,8 @@ function handleFinalGatewayStartFailure({ return exitProcess(1); } -function getGatewayClusterContainerState(gatewayName = GATEWAY_NAME): string { - const containerName = getGatewayClusterContainerName(gatewayName); +function getGatewayClusterContainerState(): string { + const containerName = getGatewayClusterContainerName(); const state = dockerContainerInspectFormat( "{{.State.Status}}{{if .State.Health}} {{.State.Health.Status}}{{end}}", containerName, @@ -2329,87 +2327,6 @@ async function startDockerDriverGateway({ throw new Error("Docker-driver gateway failed to start"); } -type StartGatewayForRecoveryOptions = { - gatewayName?: string; - gatewayPort?: number; -}; - -function isValidGatewayRecoveryPort(port: number | null | undefined): port is number { - return Number.isInteger(port) && Number(port) >= 1 && Number(port) <= 65535; -} - -function resolveGatewayRecoveryTarget(options: StartGatewayForRecoveryOptions = {}) { - const gatewayName = options.gatewayName || GATEWAY_NAME; - const portFromName = gatewayBinding.resolveGatewayPortFromName(gatewayName); - const gatewayPort = isValidGatewayRecoveryPort(options.gatewayPort) - ? options.gatewayPort - : (portFromName ?? GATEWAY_PORT); - return { gatewayName, gatewayPort }; -} - -function getGatewayStartEnvForPort(gatewayPort: number): Record { - return { - ...getGatewayStartEnv(), - OPENSHELL_SERVER_PORT: String(gatewayPort), - OPENSHELL_SSH_GATEWAY_PORT: String(gatewayPort), - }; -} - -async function startTargetGatewayForRecovery({ - gatewayName, - gatewayPort, -}: { - gatewayName: string; - gatewayPort: number; -}): Promise { - const gatewayPortArg = String(gatewayPort); - const startResult = runOpenshell( - ["gateway", "start", "--name", gatewayName, "--port", gatewayPortArg], - { - ignoreError: true, - env: getGatewayStartEnvForPort(gatewayPort), - suppressOutput: true, - }, - ); - runOpenshell(["gateway", "select", gatewayName], { ignoreError: true }); - - const recoveryWait = getGatewayHealthWaitConfig( - startResult.status ?? 0, - getGatewayClusterContainerState(gatewayName), - ); - const recoveryPollCount = recoveryWait.extended - ? recoveryWait.count - : envInt("NEMOCLAW_HEALTH_POLL_COUNT", 10); - const recoveryPollInterval = recoveryWait.extended - ? recoveryWait.interval - : envInt("NEMOCLAW_HEALTH_POLL_INTERVAL", 2); - const targetGatewayUrl = `${getGatewayHttpEndpoint(gatewayPort)}/`; - for (let i = 0; i < recoveryPollCount; i++) { - const status = runCaptureOpenshell(["status"], { ignoreError: true }); - const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { - ignoreError: true, - }); - const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); - if ( - status.includes("Connected") && - gatewayState.isGatewayHealthy(status, namedInfo, currentInfo, gatewayName) && - (await isGatewayHttpReady(undefined, targetGatewayUrl)) - ) { - process.env.OPENSHELL_GATEWAY = gatewayName; - const runtime = getContainerRuntime(); - if (shouldPatchCoredns(runtime)) { - run(["bash", path.join(SCRIPTS, "fix-coredns.sh"), gatewayName], { - ignoreError: true, - }); - } - return; - } - if (i < recoveryPollCount - 1) sleepSeconds(recoveryPollInterval); - } - - throw new Error(`Gateway '${gatewayName}' failed to start`); -} - async function startGateway( _gpu: ReturnType, { gpuPassthrough = false }: { gpuPassthrough?: boolean } = {}, @@ -2417,15 +2334,12 @@ async function startGateway( return startGatewayWithOptions(_gpu, { exitOnFailure: true, gpuPassthrough }); } -async function startGatewayForRecovery( - options: StartGatewayForRecoveryOptions = {}, -): Promise { - const target = resolveGatewayRecoveryTarget(options); - if (target.gatewayName !== GATEWAY_NAME || target.gatewayPort !== GATEWAY_PORT) { - return startTargetGatewayForRecovery(target); - } - return startGatewayWithOptions(undefined as unknown as ReturnType, { - exitOnFailure: false, +async function startGatewayForRecovery(options = {}): Promise { + return require("./onboard/gateway-recovery").startGatewayForRecovery(options, { + getGatewayStartEnv, + runCaptureOpenshell, + runOpenshell, + startGatewayWithOptions, }); } @@ -2446,17 +2360,7 @@ function getGatewayStartEnv(): Record { return gatewayEnv; } -/** - * Memoizes `applyOverlayfsAutoFix` per upstream image for the lifetime of - * the process. The expensive work (host assessment + image inspect / pull / - * build) only needs to happen once per onboard invocation; both - * `startGatewayWithOptions` and `recoverGatewayRuntime` go through - * `getGatewayStartEnv()`, and without this cache the recovery path would - * re-run the full assessment. - * - * Reset on a per-process basis only — env-var changes mid-process are - * not modelled here and shouldn't happen in the CLI's normal flow. - */ +/** Cache the overlayfs auto-fix result per upstream image for this onboard process. */ const overlayFixResultCache = new Map(); /** diff --git a/src/lib/onboard/gateway-recovery.test.ts b/src/lib/onboard/gateway-recovery.test.ts new file mode 100644 index 00000000000..1d6a6194430 --- /dev/null +++ b/src/lib/onboard/gateway-recovery.test.ts @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + type GatewayRecoveryDeps, + startGatewayForRecovery, +} from "../../../dist/lib/onboard/gateway-recovery"; + +function createDeps(): GatewayRecoveryDeps { + return { + getGatewayClusterContainerState: () => "missing", + getGatewayStartEnv: () => ({ OPENSHELL_DRIVERS: "docker" }), + runCaptureOpenshell: vi.fn(() => "Disconnected"), + runOpenshell: vi.fn(() => ({ status: 0 })), + startGatewayWithOptions: vi.fn( + async () => undefined, + ) as GatewayRecoveryDeps["startGatewayWithOptions"], + }; +} + +describe("gateway recovery", () => { + afterEach(() => { + vi.unstubAllEnvs(); + delete process.env.OPENSHELL_GATEWAY; + }); + + it("uses the default gateway starter when no explicit target is supplied", async () => { + const deps = createDeps(); + + await startGatewayForRecovery({}, deps); + + expect(deps.startGatewayWithOptions).toHaveBeenCalledWith(undefined, { + exitOnFailure: false, + }); + expect(deps.runOpenshell).not.toHaveBeenCalled(); + }); + + it("starts and selects the named gateway using the port encoded in its name", async () => { + vi.stubEnv("NEMOCLAW_HEALTH_POLL_COUNT", "1"); + const deps = createDeps(); + + await expect(startGatewayForRecovery({ gatewayName: "nemoclaw-8090" }, deps)).rejects.toThrow( + "Gateway 'nemoclaw-8090' failed to start", + ); + + expect(deps.startGatewayWithOptions).not.toHaveBeenCalled(); + expect(deps.runOpenshell).toHaveBeenNthCalledWith( + 1, + ["gateway", "start", "--name", "nemoclaw-8090", "--port", "8090"], + { + ignoreError: true, + env: { + OPENSHELL_DRIVERS: "docker", + OPENSHELL_SERVER_PORT: "8090", + OPENSHELL_SSH_GATEWAY_PORT: "8090", + }, + suppressOutput: true, + }, + ); + expect(deps.runOpenshell).toHaveBeenNthCalledWith(2, ["gateway", "select", "nemoclaw-8090"], { + ignoreError: true, + }); + }); +}); diff --git a/src/lib/onboard/gateway-recovery.ts b/src/lib/onboard/gateway-recovery.ts new file mode 100644 index 00000000000..71a9139bdfa --- /dev/null +++ b/src/lib/onboard/gateway-recovery.ts @@ -0,0 +1,166 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from "node:path"; + +import { dockerContainerInspectFormat } from "../adapters/docker"; +import { getGatewayClusterContainerName } from "../adapters/openshell/gateway-drift"; +import { getGatewayHttpEndpoint } from "../core/gateway-address"; +import { GATEWAY_PORT } from "../core/ports"; +import { sleepSeconds } from "../core/wait"; +import { shouldPatchCoredns } from "../platform"; +import { run, SCRIPTS } from "../runner"; +import { isGatewayHealthy } from "../state/gateway"; +import { envInt } from "./env"; +import { resolveGatewayName, resolveGatewayPortFromName } from "./gateway-binding"; +import { isGatewayHttpReady } from "./gateway-http-readiness"; +import { getContainerRuntime } from "./local-inference-topology"; + +export type StartGatewayForRecoveryOptions = { + gatewayName?: string; + gatewayPort?: number; +}; + +type RunOpenshellOptions = { + ignoreError?: boolean; + env?: Record; + suppressOutput?: boolean; +}; + +type RunCaptureOpenshellOptions = { + ignoreError?: boolean; +}; + +type GatewayStartResult = { + status?: number | null; +}; + +export type GatewayRecoveryDeps = { + getGatewayClusterContainerState?(gatewayName: string): string; + getGatewayStartEnv(): Record; + runCaptureOpenshell(args: string[], opts?: RunCaptureOpenshellOptions): string; + runOpenshell(args: string[], opts?: RunOpenshellOptions): GatewayStartResult; + startGatewayWithOptions(gpu: never, options: { exitOnFailure: false }): Promise; +}; + +function isValidGatewayRecoveryPort(port: number | null | undefined): port is number { + return Number.isInteger(port) && Number(port) >= 1 && Number(port) <= 65535; +} + +function resolveDefaultGatewayName(): string { + return resolveGatewayName(GATEWAY_PORT); +} + +function resolveGatewayRecoveryTarget(options: StartGatewayForRecoveryOptions = {}) { + const gatewayName = options.gatewayName || resolveDefaultGatewayName(); + const portFromName = resolveGatewayPortFromName(gatewayName); + const gatewayPort = isValidGatewayRecoveryPort(options.gatewayPort) + ? options.gatewayPort + : (portFromName ?? GATEWAY_PORT); + return { gatewayName, gatewayPort }; +} + +function getGatewayStartEnvForPort( + gatewayPort: number, + getGatewayStartEnv: GatewayRecoveryDeps["getGatewayStartEnv"], +): Record { + return { + ...getGatewayStartEnv(), + OPENSHELL_SERVER_PORT: String(gatewayPort), + OPENSHELL_SSH_GATEWAY_PORT: String(gatewayPort), + }; +} + +function getDefaultGatewayClusterContainerState(gatewayName: string): string { + const state = dockerContainerInspectFormat( + "{{.State.Status}}{{if .State.Health}} {{.State.Health.Status}}{{end}}", + getGatewayClusterContainerName(gatewayName), + { ignoreError: true }, + ) + .trim() + .toLowerCase(); + return state || "missing"; +} + +function getGatewayHealthWaitConfig(_startStatus = 0, containerState = "") { + const isArm64 = process.arch === "arm64"; + const standardCount = envInt("NEMOCLAW_HEALTH_POLL_COUNT", isArm64 ? 30 : 12); + const standardInterval = envInt("NEMOCLAW_HEALTH_POLL_INTERVAL", isArm64 ? 10 : 5); + const extendedCount = envInt("NEMOCLAW_GATEWAY_START_POLL_COUNT", standardCount); + const extendedInterval = envInt("NEMOCLAW_GATEWAY_START_POLL_INTERVAL", standardInterval); + const normalizedState = String(containerState || "") + .trim() + .toLowerCase(); + const normalizedContainerState = normalizedState || "missing"; + const useExtendedWait = normalizedContainerState !== "missing"; + + return { + count: useExtendedWait ? extendedCount : standardCount, + interval: useExtendedWait ? extendedInterval : standardInterval, + extended: useExtendedWait, + containerState: normalizedContainerState, + }; +} + +async function startTargetGatewayForRecovery( + { gatewayName, gatewayPort }: { gatewayName: string; gatewayPort: number }, + deps: GatewayRecoveryDeps, +): Promise { + const gatewayPortArg = String(gatewayPort); + const startResult = deps.runOpenshell( + ["gateway", "start", "--name", gatewayName, "--port", gatewayPortArg], + { + ignoreError: true, + env: getGatewayStartEnvForPort(gatewayPort, deps.getGatewayStartEnv), + suppressOutput: true, + }, + ); + deps.runOpenshell(["gateway", "select", gatewayName], { ignoreError: true }); + + const recoveryWait = getGatewayHealthWaitConfig( + startResult.status ?? 0, + (deps.getGatewayClusterContainerState ?? getDefaultGatewayClusterContainerState)(gatewayName), + ); + const recoveryPollCount = recoveryWait.extended + ? recoveryWait.count + : envInt("NEMOCLAW_HEALTH_POLL_COUNT", 10); + const recoveryPollInterval = recoveryWait.extended + ? recoveryWait.interval + : envInt("NEMOCLAW_HEALTH_POLL_INTERVAL", 2); + const targetGatewayUrl = `${getGatewayHttpEndpoint(gatewayPort)}/`; + for (let i = 0; i < recoveryPollCount; i++) { + const status = deps.runCaptureOpenshell(["status"], { ignoreError: true }); + const namedInfo = deps.runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { + ignoreError: true, + }); + const currentInfo = deps.runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); + if ( + status.includes("Connected") && + isGatewayHealthy(status, namedInfo, currentInfo, gatewayName) && + (await isGatewayHttpReady(undefined, targetGatewayUrl)) + ) { + process.env.OPENSHELL_GATEWAY = gatewayName; + const runtime = getContainerRuntime(); + if (shouldPatchCoredns(runtime)) { + run(["bash", path.join(SCRIPTS, "fix-coredns.sh"), gatewayName], { + ignoreError: true, + }); + } + return; + } + if (i < recoveryPollCount - 1) sleepSeconds(recoveryPollInterval); + } + + throw new Error(`Gateway '${gatewayName}' failed to start`); +} + +export async function startGatewayForRecovery( + options: StartGatewayForRecoveryOptions, + deps: GatewayRecoveryDeps, +): Promise { + const target = resolveGatewayRecoveryTarget(options); + if (target.gatewayName === resolveDefaultGatewayName() && target.gatewayPort === GATEWAY_PORT) { + return deps.startGatewayWithOptions(undefined as never, { exitOnFailure: false }); + } + return startTargetGatewayForRecovery(target, deps); +} From b99fb20680bd3d9796bc19e3af22687655aa5ea7 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Thu, 11 Jun 2026 21:37:08 -0700 Subject: [PATCH 15/29] fix(sandbox): fail closed for cross-gateway restore --- .../sandbox/gateway-state-drift.test.ts | 42 +++++++++-- src/lib/actions/sandbox/gateway-state.ts | 39 +++------- src/lib/actions/sandbox/gateway-target.ts | 15 ++++ .../sandbox/sandbox-gateway-routing.test.ts | 71 +++++++++++++++++++ src/lib/actions/sandbox/snapshot.ts | 65 ++++++++++++----- src/lib/onboard/gateway-recovery.test.ts | 50 +++++++++++++ src/lib/onboard/gateway-recovery.ts | 42 +++++++++-- test/cli/doctor-gateway-token.test.ts | 34 +++++++++ test/snapshot-restore-existing-dest.test.ts | 65 ++++++++++++++++- 9 files changed, 367 insertions(+), 56 deletions(-) create mode 100644 src/lib/actions/sandbox/gateway-target.ts create mode 100644 src/lib/actions/sandbox/sandbox-gateway-routing.test.ts diff --git a/src/lib/actions/sandbox/gateway-state-drift.test.ts b/src/lib/actions/sandbox/gateway-state-drift.test.ts index 4fefcff0915..8bc9d0d027d 100644 --- a/src/lib/actions/sandbox/gateway-state-drift.test.ts +++ b/src/lib/actions/sandbox/gateway-state-drift.test.ts @@ -36,6 +36,8 @@ describe("sandbox gateway state drift guard", () => { let captureOpenshellForStatusSpy: MockInstance; let detectPreflightIssueSpy: MockInstance; let getNamedGatewayLifecycleStateSpy: MockInstance; + let getSandboxSpy: MockInstance; + let recoverNamedGatewayRuntimeSpy: MockInstance; let runOpenshellSpy: MockInstance; let removeSandboxSpy: MockInstance; @@ -49,7 +51,7 @@ describe("sandbox gateway state drift guard", () => { const gatewayRuntime = requireDist("../../../../dist/lib/gateway-runtime-action.js"); const registry = requireDist("../../../../dist/lib/state/registry.js"); - vi.spyOn(registry, "getSandbox").mockReturnValue(null); + getSandboxSpy = vi.spyOn(registry, "getSandbox").mockReturnValue(null); captureOpenshellSpy = vi .spyOn(openshellRuntime, "captureOpenshell") @@ -71,6 +73,11 @@ describe("sandbox gateway state drift guard", () => { state: "healthy_named", status: "", } as never); + recoverNamedGatewayRuntimeSpy = vi + .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") + .mockResolvedValue({ + recovered: false, + } as never); spies.push( detectPreflightIssueSpy, @@ -87,9 +94,8 @@ describe("sandbox gateway state drift guard", () => { runOpenshellSpy, vi.spyOn(openshellRuntime, "isCommandTimeout").mockReturnValue(false), getNamedGatewayLifecycleStateSpy, - vi.spyOn(gatewayRuntime, "recoverNamedGatewayRuntime").mockResolvedValue({ - recovered: false, - } as never), + getSandboxSpy, + recoverNamedGatewayRuntimeSpy, removeSandboxSpy, ); @@ -160,4 +166,32 @@ describe("sandbox gateway state drift guard", () => { ); expect(removeSandboxSpy).not.toHaveBeenCalled(); }); + + it("routes gateway-error recovery to the sandbox persisted gateway", async () => { + detectPreflightIssueSpy.mockReturnValue(null); + getSandboxSpy.mockReturnValue({ + name: "alpha", + gatewayName: "nemoclaw-8090", + gatewayPort: 8090, + }); + recoverNamedGatewayRuntimeSpy.mockResolvedValue({ + recovered: true, + via: "start", + }); + const getState = vi + .fn() + .mockResolvedValueOnce({ state: "gateway_error", output: "transport error" }) + .mockResolvedValueOnce({ state: "present", output: "Sandbox:\n Name: alpha" }); + + const lookup = await gatewayState.getReconciledSandboxGatewayState("alpha", { getState }); + + expect(lookup).toEqual( + expect.objectContaining({ + state: "present", + recoveredGateway: true, + recoveryVia: "start", + }), + ); + expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({ gatewayName: "nemoclaw-8090" }); + }); }); diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index ca4e15a791f..c7e30b62bbd 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -6,14 +6,12 @@ import os from "node:os"; import path from "node:path"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../cli/branding"; -import { GATEWAY_PORT } from "../../core/ports"; import { getNamedGatewayLifecycleState, recoverNamedGatewayRuntime, } from "../../gateway-runtime-action"; -import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { isTerminalSandboxPhase, parseSandboxPhase } from "../../state/gateway"; -import * as registry from "../../state/registry"; +import { gatewayNamePattern, getSandboxTargetGatewayName } from "./gateway-target"; const { pruneKnownHostsEntries } = require("../../onboard") as { pruneKnownHostsEntries: (contents: string) => string; @@ -230,8 +228,7 @@ export function reconcileMissingAgainstNamedGateway( sandboxName: string, missingLookup: SandboxGatewayState, ): SandboxGatewayState { - const sb = registry.getSandbox(sandboxName); - const targetGatewayName = sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); + const targetGatewayName = getSandboxTargetGatewayName(sandboxName); const lifecycle = getNamedGatewayLifecycleState(targetGatewayName); if (lifecycle.state === "connected_other") { runOpenshell(["gateway", "select", targetGatewayName], { @@ -322,8 +319,7 @@ export function printWrongGatewayActiveGuidance( // guidance points back to the workflow the user actually invoked. retryCommand = "connect", ): void { - const sb = registry.getSandbox(sandboxName); - const targetGatewayName = sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); + const targetGatewayName = getSandboxTargetGatewayName(sandboxName); const other = activeGateway && activeGateway !== targetGatewayName ? activeGateway : "another gateway"; writer( @@ -334,11 +330,6 @@ export function printWrongGatewayActiveGuidance( writer(` Then re-run: ${CLI_NAME} ${sandboxName} ${retryCommand}`); } -function getSandboxHintGatewayName(sandboxName = ""): string { - const sb = sandboxName ? registry.getSandbox(sandboxName) : null; - return sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); -} - /** Print troubleshooting hints based on gateway lifecycle state in the output. */ export function printGatewayLifecycleHint( output = "", @@ -346,7 +337,7 @@ export function printGatewayLifecycleHint( writer: (message: string) => void = console.error, ): void { const cleanOutput = stripAnsi(output); - const targetGatewayName = getSandboxHintGatewayName(sandboxName); + const targetGatewayName = getSandboxTargetGatewayName(sandboxName); if (/No gateway configured/i.test(cleanOutput)) { writer( ` The selected ${CLI_DISPLAY_NAME} gateway is no longer configured or its metadata/runtime has been lost.`, @@ -359,13 +350,9 @@ export function printGatewayLifecycleHint( ); return; } - const targetGatewayRe = new RegExp( - `Gateway:\\s+${targetGatewayName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, - "i", - ); if ( /Connection refused|client error \(Connect\)|tcp connect error/i.test(cleanOutput) && - targetGatewayRe.test(cleanOutput) + gatewayNamePattern(targetGatewayName).test(cleanOutput) ) { writer( " The selected NemoClaw gateway exists in metadata, but its API is refusing connections after restart.", @@ -415,8 +402,7 @@ export async function getReconciledSandboxGatewayState( } if (lookup.state === "gateway_error") { - const sb = registry.getSandbox(sandboxName); - const targetGatewayName = sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); + const targetGatewayName = getSandboxTargetGatewayName(sandboxName); const recovery = await recoverNamedGatewayRuntime({ gatewayName: targetGatewayName }); if (recovery.recovered) { const retried = await getState(sandboxName); @@ -441,13 +427,9 @@ export async function getReconciledSandboxGatewayState( output: latestLifecycle.status || lookup.output, }; } - const namedGatewayRe = new RegExp( - `Gateway:\\s+${targetGatewayName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, - "i", - ); if ( /Connection refused|client error \(Connect\)|tcp connect error/i.test(latestStatus) && - namedGatewayRe.test(latestStatus) + gatewayNamePattern(targetGatewayName).test(latestStatus) ) { return { state: "gateway_unreachable_after_restart", @@ -502,8 +484,7 @@ export async function ensureLiveSandboxOrExit( process.exit(1); } if (lookup.state === "missing") { - const sb = registry.getSandbox(sandboxName); - const targetGatewayName = sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); + const targetGatewayName = getSandboxTargetGatewayName(sandboxName); const guard = getNamedGatewayLifecycleState(targetGatewayName); if (guard.state !== "healthy_named") { if (guard.state === "connected_other") { @@ -571,7 +552,7 @@ export async function ensureLiveSandboxOrExit( console.error(lookup.output); } console.error( - ` Retry \`openshell gateway start --name ${getSandboxHintGatewayName(sandboxName)}\` and verify \`openshell status\` is healthy before reconnecting.`, + ` Retry \`openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}\` and verify \`openshell status\` is healthy before reconnecting.`, ); console.error( " If the gateway never becomes healthy, rebuild the gateway and then recreate the affected sandbox.", @@ -586,7 +567,7 @@ export async function ensureLiveSandboxOrExit( console.error(lookup.output); } console.error( - ` Start the gateway again with \`openshell gateway start --name ${getSandboxHintGatewayName(sandboxName)}\` before retrying.`, + ` Start the gateway again with \`openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}\` before retrying.`, ); console.error( " If the gateway had to be rebuilt from scratch, recreate the affected sandbox afterward.", diff --git a/src/lib/actions/sandbox/gateway-target.ts b/src/lib/actions/sandbox/gateway-target.ts new file mode 100644 index 00000000000..222d521f632 --- /dev/null +++ b/src/lib/actions/sandbox/gateway-target.ts @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { GATEWAY_PORT } from "../../core/ports"; +import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; +import * as registry from "../../state/registry"; + +export function getSandboxTargetGatewayName(sandboxName = ""): string { + const sb = sandboxName ? registry.getSandbox(sandboxName) : null; + return sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); +} + +export function gatewayNamePattern(gatewayName: string): RegExp { + return new RegExp(`Gateway:\\s+${gatewayName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "i"); +} diff --git a/src/lib/actions/sandbox/sandbox-gateway-routing.test.ts b/src/lib/actions/sandbox/sandbox-gateway-routing.test.ts new file mode 100644 index 00000000000..0fead878689 --- /dev/null +++ b/src/lib/actions/sandbox/sandbox-gateway-routing.test.ts @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createRequire } from "node:module"; + +import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest"; + +const requireDist = createRequire(import.meta.url); + +type RoutingModule = typeof import("../../../../dist/lib/actions/sandbox/sandbox-gateway-routing"); + +describe("sandbox gateway routing helpers", () => { + let routing: RoutingModule; + let spies: MockInstance[]; + let getSandboxSpy: MockInstance; + let captureOpenshellSpy: MockInstance; + let runOpenshellSpy: MockInstance; + + beforeEach(() => { + const openshellRuntime = requireDist("../../../../dist/lib/adapters/openshell/runtime.js"); + const registry = requireDist("../../../../dist/lib/state/registry.js"); + + spies = []; + getSandboxSpy = vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + gatewayName: "nemoclaw-8090", + gatewayPort: 8090, + openshellDriver: "vm", + }); + captureOpenshellSpy = vi + .spyOn(openshellRuntime, "captureOpenshell") + .mockImplementation((args: unknown) => { + const argv = Array.isArray(args) ? args : []; + return { + status: 0, + output: + argv[0] === "status" + ? "Server Status\n\nGateway: nemoclaw-8090\nStatus: Connected\n" + : "Gateway Info\n\nGateway: nemoclaw-8090\nGateway endpoint: https://127.0.0.1:8090/\n", + } as never; + }); + runOpenshellSpy = vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ + status: 0, + } as never); + spies.push(getSandboxSpy, captureOpenshellSpy, runOpenshellSpy); + + routing = requireDist("../../../../dist/lib/actions/sandbox/sandbox-gateway-routing.js"); + }); + + afterEach(() => { + for (const spy of spies) spy.mockRestore(); + }); + + it("uses the persisted gateway name for metadata health probes", () => { + expect(routing.probeGatewayRunning("alpha")).toBe(true); + + expect(captureOpenshellSpy).toHaveBeenCalledWith( + ["gateway", "info", "-g", "nemoclaw-8090"], + expect.objectContaining({ ignoreError: true }), + ); + }); + + it("selects the persisted gateway before sandbox-scoped OpenShell commands", () => { + routing.selectSandboxGatewayIfRegistered("alpha"); + + expect(runOpenshellSpy).toHaveBeenCalledWith( + ["gateway", "select", "nemoclaw-8090"], + expect.objectContaining({ ignoreError: true }), + ); + }); +}); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 12d4ebf43ef..b52fd611574 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -301,6 +301,37 @@ function deleteSandboxForRestore(name: string): void { console.log(` ${G}\u2713${R} '${name}' deleted`); } +function listLiveSandboxesOnSandboxGateway(sandboxName: string): Set | null { + selectSandboxGatewayIfRegistered(sandboxName); + if (!probeGatewayRunning(sandboxName)) return null; + const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); + if (isLive.status !== 0) return null; + return parseLiveSandboxNames(isLive.output || ""); +} + +function requireLiveSandboxesOnSandboxGateway(sandboxName: string, error: string): Set { + const liveNames = listLiveSandboxesOnSandboxGateway(sandboxName); + if (!liveNames) { + console.error(error); + snapshotExit(1); + } + return liveNames; +} + +function verifyRestoreDestinationOnOwnGateway(targetSandbox: string): void { + const liveNames = requireLiveSandboxesOnSandboxGateway( + targetSandbox, + ` Cannot verify destination sandbox '${targetSandbox}' on its registered gateway. Aborting restore.`, + ); + if (!liveNames.has(targetSandbox)) { + console.error( + ` Destination sandbox '${targetSandbox}' is registered locally, but is not present on its registered gateway.`, + ); + console.error(" Aborting restore before deleting or overwriting local sandbox metadata."); + snapshotExit(1); + } +} + function isSnapshotCreationAllowedByShields(sandboxName: string): boolean { // Snapshot creation is a shields/policy boundary. If a packaged or mocked // CommonJS interop surface ever omits the helper, fail closed before any @@ -324,13 +355,10 @@ export async function runSandboxSnapshot( // sandbox's gateway to be the active one, otherwise a sandbox registered // on a non-default `NEMOCLAW_GATEWAY_PORT` fails health-check before the // subsequent list ever runs. - selectSandboxGatewayIfRegistered(sandboxName); - if (!probeGatewayRunning(sandboxName)) { - console.error(" Failed to query live sandbox state from OpenShell."); - snapshotExit(1); - } - const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); - const liveNames = parseLiveSandboxNames(isLive.output || ""); + const liveNames = requireLiveSandboxesOnSandboxGateway( + sandboxName, + " Failed to query live sandbox state from OpenShell.", + ); if (!liveNames.has(sandboxName)) { console.error(` Sandbox '${sandboxName}' is not running. Cannot create snapshot.`); snapshotExit(1); @@ -391,15 +419,13 @@ export async function runSandboxSnapshot( const target = request.to ?? sandboxName; const targetSandbox = target === sandboxName ? sandboxName : validateName(target, "target sandbox name"); - selectSandboxGatewayIfRegistered(sandboxName); - if (!probeGatewayRunning(sandboxName)) { - console.error(" Failed to query live sandbox state from OpenShell."); - snapshotExit(1); - } - const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); - const liveNames = parseLiveSandboxNames(isLive.output || ""); + const sourceLiveNames = requireLiveSandboxesOnSandboxGateway( + sandboxName, + " Failed to query live sandbox state from OpenShell.", + ); const isCrossSandboxRestore = targetSandbox !== sandboxName; - const targetExists = liveNames.has(targetSandbox); + const targetEntry = isCrossSandboxRestore ? registry.getSandbox(targetSandbox) : null; + const targetExists = sourceLiveNames.has(targetSandbox) || Boolean(targetEntry); // #3756 P1 preflight: resolve the snapshot selector AND the source pod // image before any destructive action. A bad selector, missing snapshot, @@ -462,7 +488,7 @@ export async function runSandboxSnapshot( // we must be able to clone the source's running pod image. Resolve it // upfront so a missing source / unresolvable image cannot delete the // destination first (#3756 P1). - if (!liveNames.has(sandboxName)) { + if (!sourceLiveNames.has(sandboxName)) { if (targetExists) { console.error( ` Cannot recreate '${targetSandbox}' from snapshot: source '${sandboxName}' not found.`, @@ -500,7 +526,14 @@ export async function runSandboxSnapshot( snapshotExit(1); } } + if (targetEntry) { + verifyRestoreDestinationOnOwnGateway(targetSandbox); + } deleteSandboxForRestore(targetSandbox); + requireLiveSandboxesOnSandboxGateway( + sandboxName, + " Failed to re-select source sandbox gateway after deleting destination.", + ); } await autoCreateSandboxFromSource(sandboxName, targetSandbox, srcEntry); } diff --git a/src/lib/onboard/gateway-recovery.test.ts b/src/lib/onboard/gateway-recovery.test.ts index 1d6a6194430..651608e8fb9 100644 --- a/src/lib/onboard/gateway-recovery.test.ts +++ b/src/lib/onboard/gateway-recovery.test.ts @@ -63,4 +63,54 @@ describe("gateway recovery", () => { ignoreError: true, }); }); + + it("derives the canonical gateway name when only a non-default port is supplied", async () => { + vi.stubEnv("NEMOCLAW_HEALTH_POLL_COUNT", "1"); + const deps = createDeps(); + + await expect(startGatewayForRecovery({ gatewayPort: 8091 }, deps)).rejects.toThrow( + "Gateway 'nemoclaw-8091' failed to start", + ); + + expect(deps.runOpenshell).toHaveBeenNthCalledWith( + 1, + ["gateway", "start", "--name", "nemoclaw-8091", "--port", "8091"], + expect.objectContaining({ + env: expect.objectContaining({ + OPENSHELL_SERVER_PORT: "8091", + OPENSHELL_SSH_GATEWAY_PORT: "8091", + }), + }), + ); + }); + + it("rejects non-canonical gateway recovery names before invoking OpenShell", async () => { + const deps = createDeps(); + + await expect(startGatewayForRecovery({ gatewayName: "other-gateway" }, deps)).rejects.toThrow( + "Invalid NemoClaw gateway name 'other-gateway'", + ); + + expect(deps.runOpenshell).not.toHaveBeenCalled(); + }); + + it("rejects a gateway name and port mismatch before invoking OpenShell", async () => { + const deps = createDeps(); + + await expect( + startGatewayForRecovery({ gatewayName: "nemoclaw-8090", gatewayPort: 8091 }, deps), + ).rejects.toThrow("Gateway 'nemoclaw-8090' does not match port 8091"); + + expect(deps.runOpenshell).not.toHaveBeenCalled(); + }); + + it("rejects privileged recovery ports before invoking OpenShell", async () => { + const deps = createDeps(); + + await expect(startGatewayForRecovery({ gatewayName: "nemoclaw-80" }, deps)).rejects.toThrow( + "Invalid gateway recovery port 80", + ); + + expect(deps.runOpenshell).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/onboard/gateway-recovery.ts b/src/lib/onboard/gateway-recovery.ts index 71a9139bdfa..8467ef9dd5c 100644 --- a/src/lib/onboard/gateway-recovery.ts +++ b/src/lib/onboard/gateway-recovery.ts @@ -6,7 +6,17 @@ import path from "node:path"; import { dockerContainerInspectFormat } from "../adapters/docker"; import { getGatewayClusterContainerName } from "../adapters/openshell/gateway-drift"; import { getGatewayHttpEndpoint } from "../core/gateway-address"; -import { GATEWAY_PORT } from "../core/ports"; +import { + BEDROCK_RUNTIME_ADAPTER_PORT, + DASHBOARD_PORT, + DASHBOARD_PORT_RANGE_END, + DASHBOARD_PORT_RANGE_START, + GATEWAY_PORT, + OLLAMA_PORT, + OLLAMA_PROXY_PORT, + validateGatewayPort, + VLLM_PORT, +} from "../core/ports"; import { sleepSeconds } from "../core/wait"; import { shouldPatchCoredns } from "../platform"; import { run, SCRIPTS } from "../runner"; @@ -44,7 +54,7 @@ export type GatewayRecoveryDeps = { }; function isValidGatewayRecoveryPort(port: number | null | undefined): port is number { - return Number.isInteger(port) && Number(port) >= 1 && Number(port) <= 65535; + return Number.isInteger(port) && Number(port) >= 1024 && Number(port) <= 65535; } function resolveDefaultGatewayName(): string { @@ -52,11 +62,31 @@ function resolveDefaultGatewayName(): string { } function resolveGatewayRecoveryTarget(options: StartGatewayForRecoveryOptions = {}) { - const gatewayName = options.gatewayName || resolveDefaultGatewayName(); + const gatewayName = + options.gatewayName || + (isValidGatewayRecoveryPort(options.gatewayPort) + ? resolveGatewayName(options.gatewayPort) + : resolveDefaultGatewayName()); const portFromName = resolveGatewayPortFromName(gatewayName); - const gatewayPort = isValidGatewayRecoveryPort(options.gatewayPort) - ? options.gatewayPort - : (portFromName ?? GATEWAY_PORT); + if (portFromName === null) { + throw new Error(`Invalid NemoClaw gateway name '${gatewayName}'`); + } + const gatewayPort = options.gatewayPort ?? portFromName; + if (gatewayPort !== portFromName) { + throw new Error(`Gateway '${gatewayName}' does not match port ${gatewayPort}`); + } + if (!isValidGatewayRecoveryPort(gatewayPort)) { + throw new Error(`Invalid gateway recovery port ${gatewayPort}`); + } + validateGatewayPort("NEMOCLAW_GATEWAY_PORT", gatewayPort, { + dashboardPort: DASHBOARD_PORT, + dashboardRangeStart: DASHBOARD_PORT_RANGE_START, + dashboardRangeEnd: DASHBOARD_PORT_RANGE_END, + vllmPort: VLLM_PORT, + ollamaPort: OLLAMA_PORT, + ollamaProxyPort: OLLAMA_PROXY_PORT, + bedrockRuntimeAdapterPort: BEDROCK_RUNTIME_ADAPTER_PORT, + }); return { gatewayName, gatewayPort }; } diff --git a/test/cli/doctor-gateway-token.test.ts b/test/cli/doctor-gateway-token.test.ts index 94ba686edb8..60dc7273d49 100644 --- a/test/cli/doctor-gateway-token.test.ts +++ b/test/cli/doctor-gateway-token.test.ts @@ -184,6 +184,40 @@ describe("CLI dispatch", () => { expect(r.code).toBe(0); }); + it("doctor checks the sandbox persisted non-default gateway", () => { + const setup = createDoctorTestSetup("nemoclaw-cli-doctor-named-gateway-", [ + 'case "$*" in', + ' "status") printf "Server Status\\n\\n Gateway: nemoclaw-8090\\n Status: Connected\\n"; exit 0 ;;', + ' "gateway info -g nemoclaw-8090") printf "Gateway: nemoclaw-8090\\n"; exit 0 ;;', + ' "sandbox list") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', + ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + "esac", + ]); + writeSandboxRegistry(setup.home, "alpha", { + gatewayName: "nemoclaw-8090", + gatewayPort: 8090, + openshellDriver: "docker", + }); + writeHealthyCurlStub(setup); + + const r = setup.runDoctor("alpha doctor --json"); + + expect(r.code).toBe(0); + const report = JSON.parse(r.out) as { + checks: Array<{ group: string; label: string; status: string; detail: string }>; + }; + expect(report.checks.find((check) => check.label === "OpenShell status")).toEqual( + expect.objectContaining({ + group: "Gateway", + status: "ok", + detail: "connected to nemoclaw-8090", + }), + ); + const calls = setup.readCalls().join("\n"); + expect(calls).toContain("gateway info -g nemoclaw-8090"); + expect(calls).not.toContain("gateway info -g nemoclaw\n"); + }); + it("doctor still inspects the legacy k3s gateway container for the kubernetes driver", () => { const setup = createDoctorTestSetup("nemoclaw-cli-doctor-k8s-driver-", [ 'case "$*" in', diff --git a/test/snapshot-restore-existing-dest.test.ts b/test/snapshot-restore-existing-dest.test.ts index 3a18384311e..fb1198a6ff6 100644 --- a/test/snapshot-restore-existing-dest.test.ts +++ b/test/snapshot-restore-existing-dest.test.ts @@ -58,6 +58,10 @@ interface MakeEnvOptions { withSnapshot?: boolean; /** When false, fake docker exec returns an empty image string. */ withSourceImage?: boolean; + /** Put dst on a registered non-default gateway and hide it from src's gateway list. */ + destinationGatewayPort?: number; + /** When false, the destination gateway probe fails before --force can delete it. */ + destinationGatewayRunning?: boolean; } /** @@ -82,6 +86,9 @@ function makeExistingDestEnv( const home = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); const localBin = path.join(home, "bin"); fs.mkdirSync(localBin, { recursive: true }); + const destinationGatewayName = opts.destinationGatewayPort + ? `nemoclaw-${opts.destinationGatewayPort}` + : null; const registryDir = path.join(home, ".nemoclaw"); fs.mkdirSync(registryDir, { recursive: true }); @@ -102,6 +109,12 @@ function makeExistingDestEnv( provider: "nvidia-prod", gpuEnabled: false, policies: [], + ...(destinationGatewayName + ? { + gatewayName: destinationGatewayName, + gatewayPort: opts.destinationGatewayPort, + } + : {}), }, }, defaultSandbox: "src", @@ -132,13 +145,21 @@ function makeExistingDestEnv( } const osLog = path.join(home, "openshell.log"); + const activeGateway = path.join(home, "active-gateway"); fs.writeFileSync( path.join(localBin, "openshell"), [ "#!/bin/sh", `printf '%s\\n' "$*" >> ${JSON.stringify(osLog)}`, + `ACTIVE_GATEWAY=${JSON.stringify(activeGateway)}`, + 'if [ "$1" = "gateway" ] && [ "$2" = "select" ]; then', + ' printf "%s\\n" "$3" > "$ACTIVE_GATEWAY"', + " exit 0", + "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', - ' printf "NAME STATUS\\nsrc Ready\\ndst Ready\\n"', + destinationGatewayName + ? ` active="$(cat "$ACTIVE_GATEWAY" 2>/dev/null || printf '%s' nemoclaw)"; if [ "$active" = ${JSON.stringify(destinationGatewayName)} ]; then printf "NAME STATUS\\ndst Ready\\n"; else printf "NAME STATUS\\nsrc Ready\\n"; fi` + : ' printf "NAME STATUS\\nsrc Ready\\ndst Ready\\n"', " exit 0", "fi", 'if [ "$1" = "status" ]; then', @@ -146,6 +167,9 @@ function makeExistingDestEnv( " exit 0", "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "delete" ]; then', + destinationGatewayName + ? ` active="$(cat "$ACTIVE_GATEWAY" 2>/dev/null || printf '%s' nemoclaw)"; if [ "$active" != ${JSON.stringify(destinationGatewayName)} ]; then echo "delete on wrong gateway: $active" >&2; exit 42; fi` + : " :", " exit 0", "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "create" ]; then', @@ -166,6 +190,9 @@ function makeExistingDestEnv( [ "#!/bin/sh", 'if [ "$1" = "inspect" ]; then', + destinationGatewayName && opts.destinationGatewayRunning === false + ? ` case "$*" in *openshell-cluster-${destinationGatewayName}*) echo "false"; exit 0 ;; esac` + : " :", ' echo "true"', " exit 0", "fi", @@ -197,6 +224,17 @@ describe("snapshot restore --to existing destination (#3756)", () => { expect(log).not.toMatch(/sandbox delete dst/); }); + it("refuses by default when the destination is registered on another gateway", () => { + const { env, osLog } = makeExistingDestEnv("nemoclaw-snap-restore-cross-refuse-", { + destinationGatewayPort: 8090, + }); + const r = runCli(["src", "snapshot", "restore", "--to", "dst"], env); + expect(r.code).toBe(1); + expect(r.out).toMatch(/Destination sandbox 'dst' already exists/); + const log = fs.existsSync(osLog) ? fs.readFileSync(osLog, "utf-8") : ""; + expect(log).not.toMatch(/sandbox delete dst/); + }); + it("refuses by default before running source-image preflight (Codex #3796 P2)", () => { // Existing destination + unresolvable source image. The user must see the // precise "destination exists" error, not the "cannot resolve image" @@ -221,6 +259,31 @@ describe("snapshot restore --to existing destination (#3756)", () => { expect(log).toMatch(/sandbox delete dst/); }); + it("deletes a registered cross-gateway destination on its own gateway before recreating", () => { + const { env, osLog } = makeExistingDestEnv("nemoclaw-snap-restore-cross-force-", { + destinationGatewayPort: 8090, + }); + const r = runCli(["src", "snapshot", "restore", "--to", "dst", "--force", "--yes"], env); + expect(r.out).toMatch(/Deleting existing destination 'dst'/); + const lines = fs.readFileSync(osLog, "utf-8").trim().split("\n"); + const deleteIndex = lines.indexOf("sandbox delete dst"); + expect(deleteIndex).toBeGreaterThan(0); + expect(lines.slice(0, deleteIndex)).toContain("gateway select nemoclaw-8090"); + expect(lines.slice(deleteIndex + 1)).toContain("gateway select nemoclaw"); + }); + + it("aborts before deleting when a registered destination gateway cannot be verified", () => { + const { env, osLog } = makeExistingDestEnv("nemoclaw-snap-restore-cross-unverified-", { + destinationGatewayPort: 8090, + destinationGatewayRunning: false, + }); + const r = runCli(["src", "snapshot", "restore", "--to", "dst", "--force", "--yes"], env); + expect(r.code).toBe(1); + expect(r.out).toMatch(/Cannot verify destination sandbox 'dst'/); + const log = fs.existsSync(osLog) ? fs.readFileSync(osLog, "utf-8") : ""; + expect(log).not.toMatch(/sandbox delete dst/); + }); + it("skips the prompt under NEMOCLAW_NON_INTERACTIVE=1 even without --yes", () => { const base = makeExistingDestEnv("nemoclaw-snap-restore-noninteractive-"); const env = { ...base.env, NEMOCLAW_NON_INTERACTIVE: "1" }; From 7fc6891527a55f48fc8e2a973616a65a17caa06a Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Thu, 11 Jun 2026 21:48:38 -0700 Subject: [PATCH 16/29] fix(sandbox): select persisted gateway before destroy --- src/lib/actions/sandbox/destroy.ts | 45 +++++++++++--- test/cli/destroy-gateway-cleanup.test.ts | 75 ++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 7 deletions(-) diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index e345b955f9e..58091443906 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -5,7 +5,10 @@ import fs from "node:fs"; import path from "node:path"; import { resolveOpenshell } from "../../adapters/openshell/resolve"; -import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; +import { + OPENSHELL_OPERATION_TIMEOUT_MS, + 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"; @@ -53,6 +56,11 @@ type RemoveSandboxRegistryEntryDeps = { type RunOpenshell = (args: string[], opts?: Record) => { status: number | null }; +type DestroyRunOpenshell = ( + args: string[], + opts?: Record, +) => { status: number | null; stdout?: string; stderr?: string }; + export type CleanupSandboxServicesDeps = { getSandbox?: typeof registry.getSandbox; stopAll?: (opts: { sandboxName: string }) => void; @@ -176,6 +184,28 @@ function hasNoLiveSandboxes(): boolean { return parseLiveSandboxNames(liveList.output).size === 0; } +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 cleanupSandboxServices( sandboxName: string, { stopHostServices = false }: { stopHostServices?: boolean } = {}, @@ -403,11 +433,13 @@ export async function destroySandbox( console.log(` Deleting sandbox '${sandboxName}'...`); const { runOpenshell } = require("../../adapters/openshell/runtime") as { - runOpenshell: ( - args: string[], - opts?: Record, - ) => { 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 = resolveSandboxGatewayName(sb); + selectGatewayForSandboxDestroy(sandboxName, cleanupGatewayName, runOpenshell); const detachOutcome = runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell, redact, @@ -437,10 +469,9 @@ export async function destroySandbox( stopHostServices: shouldStopHostServices, }); cleanupShieldsDestroyArtifacts(sandboxName); - // Capture the sandbox's gateway BEFORE the registry entry is removed — + // 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 (#4865). - const cleanupGatewayName = resolveSandboxGatewayName(sb); const removed = removeSandboxRegistryEntry(sandboxName); const session = onboardSession.loadSession(); if (session && session.sandboxName === sandboxName) { diff --git a/test/cli/destroy-gateway-cleanup.test.ts b/test/cli/destroy-gateway-cleanup.test.ts index 0435296418e..172969e89b7 100644 --- a/test/cli/destroy-gateway-cleanup.test.ts +++ b/test/cli/destroy-gateway-cleanup.test.ts @@ -369,6 +369,81 @@ describe("CLI dispatch", () => { } }); + it("selects the sandbox persisted gateway before provider cleanup and delete", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-destroy-select-gateway-")); + const localBin = path.join(home, "bin"); + const registryDir = path.join(home, ".nemoclaw"); + const openshellLog = path.join(home, "openshell.log"); + const activeGateway = path.join(home, "active-gateway"); + fs.mkdirSync(localBin, { recursive: true }); + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync(activeGateway, "other-gateway\n"); + fs.writeFileSync( + path.join(registryDir, "sandboxes.json"), + JSON.stringify({ + sandboxes: { + alpha: { + name: "alpha", + model: "test-model", + provider: "nvidia-prod", + gpuEnabled: false, + policies: [], + gatewayName: "nemoclaw-8081", + gatewayPort: 8081, + }, + }, + defaultSandbox: "alpha", + }), + { mode: 0o600 }, + ); + fs.writeFileSync( + path.join(localBin, "openshell"), + [ + "#!/bin/sh", + `log_file=${JSON.stringify(openshellLog)}`, + `active_gateway=${JSON.stringify(activeGateway)}`, + 'printf \'%s\\n\' "$*" >> "$log_file"', + 'if [ "$1" = "gateway" ] && [ "$2" = "select" ]; then', + ' printf "%s\\n" "$3" > "$active_gateway"', + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "delete" ]; then', + ' active="$(cat "$active_gateway")"', + ' if [ "$active" != "nemoclaw-8081" ]; then', + ' printf "wrong gateway: %s\\n" "$active" >&2', + " exit 42", + " fi", + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', + ' active="$(cat "$active_gateway")"', + ' if [ "$active" != "nemoclaw-8081" ]; then', + ' printf "wrong list gateway: %s\\n" "$active" >&2', + " exit 43", + " fi", + ' printf "NAME STATUS\\n"', + " exit 0", + "fi", + "exit 0", + ].join("\n"), + { mode: 0o755 }, + ); + fs.writeFileSync(path.join(localBin, "docker"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + + const r = runWithEnv("alpha destroy --yes", { + HOME: home, + PATH: `${localBin}:${process.env.PATH || ""}`, + }); + + expect(r.code, r.out).toBe(0); + const lines = fs.readFileSync(openshellLog, "utf8").trim().split("\n"); + const selectIndex = lines.indexOf("gateway select nemoclaw-8081"); + const deleteIndex = lines.indexOf("sandbox delete alpha"); + expect(selectIndex).toBeGreaterThanOrEqual(0); + expect(deleteIndex).toBeGreaterThan(selectIndex); + expect(lines.slice(deleteIndex + 1)).toContain("sandbox list"); + }); + it("fails destroy when openshell sandbox delete returns a real error", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-destroy-failure-")); const localBin = path.join(home, "bin"); From 05b097cd772480a9d9e41915db26c7714e547b18 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Thu, 11 Jun 2026 22:08:03 -0700 Subject: [PATCH 17/29] refactor(sandbox): extract destroy gateway helpers --- src/lib/actions/sandbox/destroy-gateway.ts | 84 ++++++++++++++++++++ src/lib/actions/sandbox/destroy.ts | 92 +++------------------- 2 files changed, 93 insertions(+), 83 deletions(-) create mode 100644 src/lib/actions/sandbox/destroy-gateway.ts diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts new file mode 100644 index 00000000000..a0548c3fb28 --- /dev/null +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; +import { DASHBOARD_PORT } from "../../core/ports"; +import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; +import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; + +export type DestroyRunOpenshell = ( + args: string[], + opts?: Record, +) => { status: number | null; stdout?: string; stderr?: string }; + +const DASHBOARD_FORWARD_PORT = String(DASHBOARD_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 (#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 = 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, + }); +} diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 58091443906..e869341ebde 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -5,13 +5,9 @@ import fs from "node:fs"; import path from "node:path"; import { resolveOpenshell } from "../../adapters/openshell/resolve"; -import { - OPENSHELL_OPERATION_TIMEOUT_MS, - OPENSHELL_PROBE_TIMEOUT_MS, -} from "../../adapters/openshell/timeouts"; +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, @@ -22,9 +18,6 @@ import { shouldCleanupGatewayAfterDestroy, shouldStopHostServicesAfterDestroy, } from "../../domain/sandbox/destroy"; -import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; -import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; -import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; import { SANDBOX_PROVIDER_SUFFIXES, emitProviderDetachResidualHint, @@ -41,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 }; @@ -56,11 +55,6 @@ type RemoveSandboxRegistryEntryDeps = { type RunOpenshell = (args: string[], opts?: Record) => { status: number | null }; -type DestroyRunOpenshell = ( - args: string[], - opts?: Record, -) => { status: number | null; stdout?: string; stderr?: string }; - export type CleanupSandboxServicesDeps = { getSandbox?: typeof registry.getSandbox; stopAll?: (opts: { sandboxName: string }) => void; @@ -85,52 +79,6 @@ type RemoveShieldsStateDeps = { warn?: (message: string) => void; }; -const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); - -function cleanupGatewayAfterLastSandbox(gatewayName: string): void { - const { runOpenshell } = require("../../adapters/openshell/runtime") as { - runOpenshell: (args: string[], opts?: Record) => { 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", gatewayName], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - }); - if (removeResult.status !== 0) { - runOpenshell(["gateway", "destroy", "-g", gatewayName], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - }); - } - } else { - runOpenshell(["gateway", "destroy", "-g", gatewayName], { - ignoreError: true, - }); - } - dockerRemoveVolumesByPrefix(`openshell-cluster-${gatewayName}`, { - 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 @@ -184,28 +132,6 @@ function hasNoLiveSandboxes(): boolean { return parseLiveSandboxNames(liveList.output).size === 0; } -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 cleanupSandboxServices( sandboxName: string, { stopHostServices = false }: { stopHostServices?: boolean } = {}, @@ -438,7 +364,7 @@ export async function destroySandbox( // 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 = resolveSandboxGatewayName(sb); + const cleanupGatewayName = getSandboxTargetGatewayName(sandboxName); selectGatewayForSandboxDestroy(sandboxName, cleanupGatewayName, runOpenshell); const detachOutcome = runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell, @@ -490,7 +416,7 @@ export async function destroySandbox( ) { const shouldCleanupGateway = await resolveCleanupGatewayDecision(normalized); if (shouldCleanupGateway) { - cleanupGatewayAfterLastSandbox(cleanupGatewayName); + cleanupGatewayAfterLastSandbox(cleanupGatewayName, runOpenshell); } else { const gatewayRemovalHint = process.platform === "linux" From 506e45ecf1af966130a1267567decdd0411db2ad Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Thu, 11 Jun 2026 22:20:10 -0700 Subject: [PATCH 18/29] fix(sandbox): fail closed on snapshot gateway selection --- .../sandbox/sandbox-gateway-routing.ts | 14 +++++------ src/lib/actions/sandbox/snapshot.ts | 2 +- test/snapshot-restore-existing-dest.test.ts | 23 ++++++++++++++++++- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/lib/actions/sandbox/sandbox-gateway-routing.ts b/src/lib/actions/sandbox/sandbox-gateway-routing.ts index 5116853c3c5..72b442edbb7 100644 --- a/src/lib/actions/sandbox/sandbox-gateway-routing.ts +++ b/src/lib/actions/sandbox/sandbox-gateway-routing.ts @@ -65,17 +65,17 @@ export function probeGatewayRunning(sandboxName?: string): boolean { } /** - * Best-effort: switch the active OpenShell gateway to the one this sandbox is - * registered on so downstream `sandbox list` / `sandbox get` queries target - * the right gateway. Silent on failure — the subsequent list call surfaces a - * clearer error if the gateway is genuinely unavailable. + * Switch the active OpenShell gateway to the one this sandbox is registered on + * so downstream unscoped `sandbox list` / `sandbox get` queries target the + * right gateway. */ -export function selectSandboxGatewayIfRegistered(sandboxName: string): void { +export function selectSandboxGatewayIfRegistered(sandboxName: string): boolean { const entry = registry.getSandbox(sandboxName); - if (!entry) return; + if (!entry) return true; const target = resolveSandboxGatewayName(entry); - runOpenshell(["gateway", "select", target], { + const result = runOpenshell(["gateway", "select", target], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); + return result.status === 0; } diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index b52fd611574..6a1c3931215 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -302,7 +302,7 @@ function deleteSandboxForRestore(name: string): void { } function listLiveSandboxesOnSandboxGateway(sandboxName: string): Set | null { - selectSandboxGatewayIfRegistered(sandboxName); + if (!selectSandboxGatewayIfRegistered(sandboxName)) return null; if (!probeGatewayRunning(sandboxName)) return null; const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); if (isLive.status !== 0) return null; diff --git a/test/snapshot-restore-existing-dest.test.ts b/test/snapshot-restore-existing-dest.test.ts index fb1198a6ff6..938642594cd 100644 --- a/test/snapshot-restore-existing-dest.test.ts +++ b/test/snapshot-restore-existing-dest.test.ts @@ -60,8 +60,12 @@ interface MakeEnvOptions { withSourceImage?: boolean; /** Put dst on a registered non-default gateway and hide it from src's gateway list. */ destinationGatewayPort?: number; + /** When false, selecting the destination's persisted gateway fails. */ + destinationGatewaySelectSucceeds?: boolean; /** When false, the destination gateway probe fails before --force can delete it. */ destinationGatewayRunning?: boolean; + /** Let the currently-active source gateway also report a same-named destination. */ + foreignActiveGatewayListsDestination?: boolean; } /** @@ -153,12 +157,15 @@ function makeExistingDestEnv( `printf '%s\\n' "$*" >> ${JSON.stringify(osLog)}`, `ACTIVE_GATEWAY=${JSON.stringify(activeGateway)}`, 'if [ "$1" = "gateway" ] && [ "$2" = "select" ]; then', + destinationGatewayName && opts.destinationGatewaySelectSucceeds === false + ? ` if [ "$3" = ${JSON.stringify(destinationGatewayName)} ]; then echo "select failed" >&2; exit 17; fi` + : " :", ' printf "%s\\n" "$3" > "$ACTIVE_GATEWAY"', " exit 0", "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', destinationGatewayName - ? ` active="$(cat "$ACTIVE_GATEWAY" 2>/dev/null || printf '%s' nemoclaw)"; if [ "$active" = ${JSON.stringify(destinationGatewayName)} ]; then printf "NAME STATUS\\ndst Ready\\n"; else printf "NAME STATUS\\nsrc Ready\\n"; fi` + ? ` active="$(cat "$ACTIVE_GATEWAY" 2>/dev/null || printf '%s' nemoclaw)"; if [ "$active" = ${JSON.stringify(destinationGatewayName)} ]; then printf "NAME STATUS\\ndst Ready\\n"; else ${opts.foreignActiveGatewayListsDestination ? 'printf "NAME STATUS\\nsrc Ready\\ndst Ready\\n"' : 'printf "NAME STATUS\\nsrc Ready\\n"'}; fi` : ' printf "NAME STATUS\\nsrc Ready\\ndst Ready\\n"', " exit 0", "fi", @@ -284,6 +291,20 @@ describe("snapshot restore --to existing destination (#3756)", () => { expect(log).not.toMatch(/sandbox delete dst/); }); + it("aborts before deleting when destination gateway select fails even if the active gateway lists dst", () => { + const { env, osLog } = makeExistingDestEnv("nemoclaw-snap-restore-cross-select-fails-", { + destinationGatewayPort: 8090, + destinationGatewaySelectSucceeds: false, + foreignActiveGatewayListsDestination: true, + }); + const r = runCli(["src", "snapshot", "restore", "--to", "dst", "--force", "--yes"], env); + expect(r.code).toBe(1); + expect(r.out).toMatch(/Cannot verify destination sandbox 'dst'/); + const log = fs.existsSync(osLog) ? fs.readFileSync(osLog, "utf-8") : ""; + expect(log).toMatch(/gateway select nemoclaw-8090/); + expect(log).not.toMatch(/sandbox delete dst/); + }); + it("skips the prompt under NEMOCLAW_NON_INTERACTIVE=1 even without --yes", () => { const base = makeExistingDestEnv("nemoclaw-snap-restore-noninteractive-"); const env = { ...base.env, NEMOCLAW_NON_INTERACTIVE: "1" }; From a85b005c30516496b7fd8aa3e98290c3a7874ddb Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Fri, 12 Jun 2026 07:58:29 +0000 Subject: [PATCH 19/29] fix(sandbox): fail closed on invalid gateway bindings, dedupe dashboard ports Signed-off-by: Tinson Lai --- .../actions/gateway-drift-preflight.test.ts | 14 +++++- src/lib/actions/sandbox/gateway-target.ts | 5 +- .../sandbox/rebuild-gateway-drift.test.ts | 7 ++- src/lib/onboard/dashboard-port.test.ts | 21 ++++++++ src/lib/onboard/dashboard-port.ts | 13 +++++ src/lib/onboard/dashboard.ts | 28 ++++++++++- src/lib/onboard/gateway-binding.test.ts | 50 +++++++++++++------ src/lib/onboard/gateway-binding.ts | 16 +++++- src/lib/openshell-sandbox-list.ts | 7 ++- test/cli/doctor-gateway-token.test.ts | 4 +- 10 files changed, 141 insertions(+), 24 deletions(-) diff --git a/src/lib/actions/gateway-drift-preflight.test.ts b/src/lib/actions/gateway-drift-preflight.test.ts index b0da0f52f06..de4706da207 100644 --- a/src/lib/actions/gateway-drift-preflight.test.ts +++ b/src/lib/actions/gateway-drift-preflight.test.ts @@ -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"]); @@ -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( diff --git a/src/lib/actions/sandbox/gateway-target.ts b/src/lib/actions/sandbox/gateway-target.ts index 222d521f632..d8232618920 100644 --- a/src/lib/actions/sandbox/gateway-target.ts +++ b/src/lib/actions/sandbox/gateway-target.ts @@ -11,5 +11,8 @@ export function getSandboxTargetGatewayName(sandboxName = ""): string { } export function gatewayNamePattern(gatewayName: string): RegExp { - return new RegExp(`Gateway:\\s+${gatewayName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "i"); + return new RegExp( + `Gateway:\\s+${gatewayName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?=\\s|$)`, + "i", + ); } diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index c9b34200118..51fbb6bf2d2 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -169,7 +169,12 @@ describe("rebuild gateway drift preflight", () => { expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({ gatewayName: "nemoclaw", - recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable"], + recoverableStates: [ + "missing_named", + "named_unhealthy", + "named_unreachable", + "connected_other", + ], }); // The liveness query ran twice (initial failure + post-recovery retry). expect(listCalls).toBe(2); diff --git a/src/lib/onboard/dashboard-port.test.ts b/src/lib/onboard/dashboard-port.test.ts index 5eaf2f88a13..40c787b4973 100644 --- a/src/lib/onboard/dashboard-port.test.ts +++ b/src/lib/onboard/dashboard-port.test.ts @@ -94,6 +94,27 @@ describe("findAvailableDashboardPort port-conflict detection (#3260)", () => { findAvailableDashboardPort("cursor", 18789, "", stub); assert.deepEqual(seen, [18789, 18790]); }); + + it("skips dashboard ports reserved by sibling sandboxes on other gateways (#4865)", () => { + // Sandbox 'alpha' was onboarded against the default gateway and recorded + // 18789 in the registry; a second onboard with NEMOCLAW_GATEWAY_PORT=8081 + // queries the new gateway's forward list (empty), so without the registry + // reservation it would re-allocate 18789 and both sandboxes would advertise + // the same dashboard URL. + const reserved = new Map([[18789, "alpha"]]); + assert.equal( + findAvailableDashboardPort("port-test", 18789, "", () => false, reserved), + 18790, + ); + }); + + it("still returns the preferred port when this sandbox owns the registry reservation", () => { + const reserved = new Map([[18789, "cursor"]]); + assert.equal( + findAvailableDashboardPort("cursor", 18789, "", () => false, reserved), + 18789, + ); + }); }); describe("resolveCreateSandboxDashboardPort", () => { diff --git a/src/lib/onboard/dashboard-port.ts b/src/lib/onboard/dashboard-port.ts index cbb0b6455d6..b17f99a1522 100644 --- a/src/lib/onboard/dashboard-port.ts +++ b/src/lib/onboard/dashboard-port.ts @@ -155,8 +155,21 @@ export function findAvailableDashboardPort( preferredPort: number, forwardListOutput: string | null, isPortBoundCheck: (port: number) => boolean = isPortBoundOnHost, + registryReservedPorts: ReadonlyMap = new Map(), ): number { const occupied = getOccupiedPorts(forwardListOutput); + // Forwards on sibling gateways are invisible to the active gateway's + // `forward list`, so a second onboard on a non-default NEMOCLAW_GATEWAY_PORT + // can otherwise allocate a dashboard port already in use by an existing + // sandbox registered on another gateway. Treat the registry-recorded + // dashboard ports of other sandboxes as occupied to keep them distinct. + for (const [port, owner] of registryReservedPorts) { + if (owner === sandboxName) continue; + const key = String(port); + if (!occupied.has(key)) { + occupied.set(key, owner); + } + } const hostBoundPorts: number[] = []; // Try the preferred port first (it may be outside the dashboard range when // a caller passes --control-ui-port), then the rest of the range. Each port diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index e0c364408c9..33f23e2e4d5 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -24,6 +24,7 @@ import { isLiveForwardStatus, } from "./dashboard-port"; import { bestEffortForwardStop } from "./forward-cleanup"; +import * as registry from "../state/registry"; import { buildDetachedForwardStartSpawn, buildForwardStartProgressLogger, @@ -102,6 +103,25 @@ export interface OnboardDashboardHelpers { stopAllDashboardForwards(): void; } +function collectRegistryReservedDashboardPorts( + excludeSandboxName: string, +): ReadonlyMap { + const reserved = new Map(); + try { + const list = registry.listSandboxes(); + for (const entry of list.sandboxes) { + if (entry.name === excludeSandboxName) continue; + if (typeof entry.dashboardPort === "number" && Number.isFinite(entry.dashboardPort)) { + reserved.set(entry.dashboardPort, entry.name); + } + } + } catch { + // The registry may be unreadable mid-onboard; downstream lsof + bind + // probes are still the final authority on port availability. + } + return reserved; +} + function findForwardEntry( forwardListOutput: string | null | undefined, port: string, @@ -249,7 +269,13 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa } let actualPort: number; try { - actualPort = findAvailableDashboardPort(sandboxName, preferredPort, existingForwards); + actualPort = findAvailableDashboardPort( + sandboxName, + preferredPort, + existingForwards, + undefined, + collectRegistryReservedDashboardPorts(sandboxName), + ); } catch (err) { if (!rollbackSandboxOnFailure) throw err; rollbackSandboxAndExit(sandboxName, err); diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 689cab449ee..5af2e0a0fc7 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -96,25 +96,47 @@ describe("resolveSandboxGatewayName", () => { ); }); - it("rejects an out-of-namespace persisted gatewayName and falls through to the port", () => { - // A tampered registry entry must not redirect destructive gateway/volume - // operations to an arbitrary string. The validator strips it and the - // per-port fallback kicks in instead. + it("falls through to a valid port when only the persisted gatewayName is out-of-namespace", () => { + // A tampered name with a still-valid port resolves from the port so the + // operation lands on a real NemoClaw gateway rather than the tampered string. expect(resolveSandboxGatewayName({ gatewayName: "rogue-gateway", gatewayPort: 8081 })).toBe( "nemoclaw-8081", ); - expect(resolveSandboxGatewayName({ gatewayName: "../etc/passwd" })).toBe(BASE_GATEWAY_NAME); - expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw evil" })).toBe(BASE_GATEWAY_NAME); - expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw-0" })).toBe(BASE_GATEWAY_NAME); - expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw-65536" })).toBe(BASE_GATEWAY_NAME); }); - it("rejects an out-of-range or non-integer persisted gatewayPort", () => { - expect(resolveSandboxGatewayName({ gatewayPort: 0 })).toBe(BASE_GATEWAY_NAME); - expect(resolveSandboxGatewayName({ gatewayPort: -1 })).toBe(BASE_GATEWAY_NAME); - expect(resolveSandboxGatewayName({ gatewayPort: 65536 })).toBe(BASE_GATEWAY_NAME); - expect(resolveSandboxGatewayName({ gatewayPort: 8081.5 })).toBe(BASE_GATEWAY_NAME); - expect(resolveSandboxGatewayName({ gatewayPort: Number.NaN })).toBe(BASE_GATEWAY_NAME); + it("throws on an invalid persisted gatewayName when no valid port is present", () => { + // Refuse to silently rewrite destroy/snapshot to the default gateway when + // the persisted binding is present but unusable. + expect(() => resolveSandboxGatewayName({ gatewayName: "../etc/passwd" })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayName: "nemoclaw evil" })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayName: "nemoclaw-0" })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayName: "nemoclaw-65536" })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + }); + + it("throws on an out-of-range or non-integer persisted gatewayPort", () => { + expect(() => resolveSandboxGatewayName({ gatewayPort: 0 })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayPort: -1 })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayPort: 65536 })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayPort: 8081.5 })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayPort: Number.NaN })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); }); it("accepts the canonical bare base gateway name", () => { diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index 71c2ce522f0..5b82d4375ec 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -103,7 +103,11 @@ function isValidPersistedGatewayPort(value: number): boolean { * 2. A name-only legacy entry may use a persisted `gatewayName`, validated * against the NemoClaw namespace (`nemoclaw` or `nemoclaw-`). * 3. The bare `BASE_GATEWAY_NAME` for older entries that pre-date the - * per-port migration entirely. + * per-port migration entirely (neither field present). + * + * Fail closed when either field is present but invalid. Silently falling + * back to the default gateway would let a corrupted or tampered registry + * row redirect destroy/snapshot/cleanup to the wrong (or default) gateway. */ export function resolveSandboxGatewayName( sandbox: SandboxGatewayBinding | null | undefined, @@ -121,7 +125,15 @@ export function resolveSandboxGatewayName( ) { return sandbox.gatewayName; } - return BASE_GATEWAY_NAME; + const portPresent = sandbox?.gatewayPort !== undefined && sandbox?.gatewayPort !== null; + const namePresent = sandbox?.gatewayName !== undefined && sandbox?.gatewayName !== null; + if (!portPresent && !namePresent) { + return BASE_GATEWAY_NAME; + } + const detail: string[] = []; + if (portPresent) detail.push(`gatewayPort=${JSON.stringify(sandbox?.gatewayPort)}`); + if (namePresent) detail.push(`gatewayName=${JSON.stringify(sandbox?.gatewayName)}`); + throw new Error(`Invalid persisted sandbox gateway binding (${detail.join(", ")})`); } /** diff --git a/src/lib/openshell-sandbox-list.ts b/src/lib/openshell-sandbox-list.ts index 5461eee0e4e..ed9dbe69d72 100644 --- a/src/lib/openshell-sandbox-list.ts +++ b/src/lib/openshell-sandbox-list.ts @@ -40,7 +40,12 @@ export async function captureSandboxListWithGatewayRecovery( } const recoveryOptions: Parameters[0] = { - recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable"], + recoverableStates: [ + "missing_named", + "named_unhealthy", + "named_unreachable", + "connected_other", + ], }; if (options.gatewayName) { recoveryOptions.gatewayName = options.gatewayName; diff --git a/test/cli/doctor-gateway-token.test.ts b/test/cli/doctor-gateway-token.test.ts index 60dc7273d49..d0dbba2ee30 100644 --- a/test/cli/doctor-gateway-token.test.ts +++ b/test/cli/doctor-gateway-token.test.ts @@ -213,9 +213,9 @@ describe("CLI dispatch", () => { detail: "connected to nemoclaw-8090", }), ); - const calls = setup.readCalls().join("\n"); + const calls = setup.readCalls(); expect(calls).toContain("gateway info -g nemoclaw-8090"); - expect(calls).not.toContain("gateway info -g nemoclaw\n"); + expect(calls).not.toContain("gateway info -g nemoclaw"); }); it("doctor still inspects the legacy k3s gateway container for the kubernetes driver", () => { From a1ce42c2169e9eba420a188cce9356aeebd7a15b Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Fri, 12 Jun 2026 08:10:49 +0000 Subject: [PATCH 20/29] style(sandbox): apply biome formatting to recovery state list Signed-off-by: Tinson Lai --- src/lib/openshell-sandbox-list.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/lib/openshell-sandbox-list.ts b/src/lib/openshell-sandbox-list.ts index ed9dbe69d72..7f32363a505 100644 --- a/src/lib/openshell-sandbox-list.ts +++ b/src/lib/openshell-sandbox-list.ts @@ -40,12 +40,7 @@ export async function captureSandboxListWithGatewayRecovery( } const recoveryOptions: Parameters[0] = { - recoverableStates: [ - "missing_named", - "named_unhealthy", - "named_unreachable", - "connected_other", - ], + recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable", "connected_other"], }; if (options.gatewayName) { recoveryOptions.gatewayName = options.gatewayName; From 507a3a54c35716cb6235af2caa9634e963b3136a Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Fri, 12 Jun 2026 09:39:51 +0000 Subject: [PATCH 21/29] fix(sandbox): route per-sandbox gateway through hints and recovery startup Signed-off-by: Tinson Lai --- src/lib/actions/sandbox/connect.ts | 5 ++++- .../actions/sandbox/doctor-gateway-fallback.ts | 1 + src/lib/actions/sandbox/doctor.ts | 3 ++- src/lib/actions/sandbox/policy-channel.ts | 11 +++++++---- src/lib/actions/sandbox/rebuild.ts | 4 ++-- src/lib/actions/sandbox/status.ts | 5 +++-- src/lib/gateway-runtime-action.ts | 5 +++-- src/lib/onboard/gateway-binding.test.ts | 10 ++++++++++ src/lib/onboard/gateway-binding.ts | 7 ++++++- src/lib/onboard/gateway-recovery.ts | 15 +++++++++++++-- 10 files changed, 51 insertions(+), 15 deletions(-) diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 7d52f9c4ae7..3e1f83bc7a9 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -27,6 +27,7 @@ import { findReachableOllamaHost, probeLocalProviderHealth } from "../../inferen 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"; @@ -252,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); diff --git a/src/lib/actions/sandbox/doctor-gateway-fallback.ts b/src/lib/actions/sandbox/doctor-gateway-fallback.ts index 4e9a3253043..b053eafac82 100644 --- a/src/lib/actions/sandbox/doctor-gateway-fallback.ts +++ b/src/lib/actions/sandbox/doctor-gateway-fallback.ts @@ -8,6 +8,7 @@ import { captureHostCommand, type CommandCapture } from "./doctor-host-command"; export type GatewayInspectOptions = { namedGatewayConnected?: boolean; + gatewayName?: string; }; type LocalGatewayProbe = { diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index bcaea663a54..8ca632056fe 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -192,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); @@ -615,6 +615,7 @@ export async function runSandboxDoctor( checks.push( ...dockerInspectGateway(`openshell-cluster-${gatewayName}`, { namedGatewayConnected: openshellConnected, + gatewayName, }), ); } diff --git a/src/lib/actions/sandbox/policy-channel.ts b/src/lib/actions/sandbox/policy-channel.ts index 026be1b4565..66c3a91c308 100644 --- a/src/lib/actions/sandbox/policy-channel.ts +++ b/src/lib/actions/sandbox/policy-channel.ts @@ -8,6 +8,7 @@ import { type AgentDefinition, loadAgent } from "../../agent/defs"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt, getCredential } from "../../credentials/store"; import { recoverNamedGatewayRuntime } from "../../gateway-runtime-action"; +import { getSandboxTargetGatewayName } from "./gateway-target"; import { type ChannelManifest, createBuiltInChannelManifestRegistry, @@ -510,13 +511,14 @@ async function applyChannelAddToGatewayAndRegistry( token, })); if (tokenDefs.length > 0) { - const recovery = await recoverNamedGatewayRuntime(); + const gatewayName = getSandboxTargetGatewayName(sandboxName); + const recovery = await recoverNamedGatewayRuntime({ gatewayName }); if (!recovery.recovered) { console.error( ` Could not reach the ${CLI_DISPLAY_NAME} OpenShell gateway. Tokens were staged`, ); console.error(" in env for this run only — re-run after starting the gateway, or run"); - console.error(" 'openshell gateway start --name nemoclaw' manually."); + console.error(` 'openshell gateway start --name ${gatewayName}' manually.`); process.exit(1); } // upsertMessagingProviders handles create-or-update and process.exits on @@ -538,13 +540,14 @@ async function applyChannelRemoveToGatewayAndRegistry( let gatewayReachable = true; if (channelTokenKeys.length > 0) { - const recovery = await recoverNamedGatewayRuntime(); + const gatewayName = getSandboxTargetGatewayName(sandboxName); + const recovery = await recoverNamedGatewayRuntime({ gatewayName }); if (!recovery.recovered) { console.error( ` Could not reach the ${CLI_DISPLAY_NAME} OpenShell gateway to delete the bridge.`, ); console.error( - " Re-run after starting the gateway, or run 'openshell gateway start --name nemoclaw'.", + ` Re-run after starting the gateway, or run 'openshell gateway start --name ${gatewayName}'.`, ); if (!bestEffort) process.exit(1); gatewayReachable = false; diff --git a/src/lib/actions/sandbox/rebuild.ts b/src/lib/actions/sandbox/rebuild.ts index 37e781beaa2..4261122a752 100644 --- a/src/lib/actions/sandbox/rebuild.ts +++ b/src/lib/actions/sandbox/rebuild.ts @@ -596,7 +596,7 @@ export async function rebuildSandbox( "rebuild --yes", ); bail( - `Could not confirm '${sandboxName}' against the NemoClaw gateway (gateway '${lifecycle.activeGateway ?? "unknown"}' is active).`, + `Could not confirm '${sandboxName}' against gateway '${recordedGateway}' (gateway '${lifecycle.activeGateway ?? "unknown"}' is active).`, ); return; } @@ -635,7 +635,7 @@ export async function rebuildSandbox( ); } else { console.error( - ` Sandbox '${sandboxName}' is not visible on the NemoClaw gateway and its live state could not be confirmed.`, + ` Sandbox '${sandboxName}' is not visible on gateway '${recordedGateway}' and its live state could not be confirmed.`, ); console.error(" Your local registry entry has been preserved — nothing was removed."); printGatewayLifecycleHint(reconciled.output || "", sandboxName, console.error); diff --git a/src/lib/actions/sandbox/status.ts b/src/lib/actions/sandbox/status.ts index 9d056ebaa52..124f7dde50a 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { printOpenShellStateRpcIssue } from "../../adapters/openshell/gateway-drift"; +import { getSandboxTargetGatewayName } from "./gateway-target"; import { resolveOpenshell } from "../../adapters/openshell/resolve"; import * as agentRuntime from "../../agent/runtime"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../cli/branding"; @@ -384,7 +385,7 @@ export async function showSandboxStatus(sandboxName: string): Promise { console.log(lookup.output); } console.log( - " Retry `openshell gateway start --name nemoclaw` and verify `openshell status` is healthy before reconnecting.", + ` Retry \`openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}\` and verify \`openshell status\` is healthy before reconnecting.`, ); console.log( " If the gateway never becomes healthy, rebuild the gateway and then recreate the affected sandbox.", @@ -400,7 +401,7 @@ export async function showSandboxStatus(sandboxName: string): Promise { console.log(lookup.output); } console.log( - " Start the gateway again with `openshell gateway start --name nemoclaw` before retrying.", + ` Start the gateway again with \`openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}\` before retrying.`, ); console.log( " If the gateway had to be rebuilt from scratch, recreate the affected sandbox afterward.", diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index 08cc2daa372..7488c5475b2 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -13,7 +13,8 @@ import { } from "./adapters/openshell/timeouts"; import { stripAnsi } from "./adapters/openshell/client"; import { captureOpenshell, runOpenshell } from "./adapters/openshell/runtime"; -import { resolveGatewayPortFromName } from "./onboard/gateway-binding"; +import { resolveGatewayName, resolveGatewayPortFromName } from "./onboard/gateway-binding"; +import { GATEWAY_PORT } from "./core/ports"; function hasNamedGateway(output = "", gatewayName = "nemoclaw"): boolean { return stripAnsi(output).includes(`Gateway: ${gatewayName}`); @@ -85,7 +86,7 @@ export type RecoverNamedGatewayRuntimeOptions = { /** Attempt to recover the named NemoClaw gateway after a restart or connectivity loss. */ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRuntimeOptions = {}) { - const gatewayName = options.gatewayName ?? "nemoclaw"; + const gatewayName = options.gatewayName ?? resolveGatewayName(GATEWAY_PORT); const recoverableStates = new Set( options.recoverableStates ?? [ "missing_named", diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 5af2e0a0fc7..4fd125c9469 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -142,6 +142,16 @@ describe("resolveSandboxGatewayName", () => { it("accepts the canonical bare base gateway name", () => { expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw" })).toBe(BASE_GATEWAY_NAME); }); + + it("rejects the non-canonical default-port suffix form", () => { + // `nemoclaw-8080` matches the namespace regex but is not what + // resolveGatewayName(8080) emits (it emits the bare `nemoclaw`). A + // sandbox registered against the non-canonical form would target a + // gateway name that does not exist. + expect(() => resolveSandboxGatewayName({ gatewayName: "nemoclaw-8080" })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + }); }); describe("docker-driver compat container is gateway-port scoped (#4422)", () => { diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index 5b82d4375ec..8c3a02dc8c0 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -79,7 +79,12 @@ const VALID_GATEWAY_NAME_RE = /^nemoclaw(-(?:[1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]))?$/; function isValidPersistedGatewayName(value: string): boolean { - return VALID_GATEWAY_NAME_RE.test(value); + if (!VALID_GATEWAY_NAME_RE.test(value)) return false; + // The regex permits `nemoclaw-` but that form is not the + // canonical name for the default port (the bare `BASE_GATEWAY_NAME` is). + // Reject it so a persisted `nemoclaw-8080` cannot drive lifecycle commands + // against a gateway name that does not actually exist in the registry. + return resolveGatewayPortFromName(value) !== null; } function isValidPersistedGatewayPort(value: number): boolean { diff --git a/src/lib/onboard/gateway-recovery.ts b/src/lib/onboard/gateway-recovery.ts index 8467ef9dd5c..4fb096e9cc8 100644 --- a/src/lib/onboard/gateway-recovery.ts +++ b/src/lib/onboard/gateway-recovery.ts @@ -25,6 +25,7 @@ import { envInt } from "./env"; import { resolveGatewayName, resolveGatewayPortFromName } from "./gateway-binding"; import { isGatewayHttpReady } from "./gateway-http-readiness"; import { getContainerRuntime } from "./local-inference-topology"; +import { isLinuxDockerDriverGatewayEnabled } from "./docker-driver-platform"; export type StartGatewayForRecoveryOptions = { gatewayName?: string; @@ -189,8 +190,18 @@ export async function startGatewayForRecovery( deps: GatewayRecoveryDeps, ): Promise { const target = resolveGatewayRecoveryTarget(options); - if (target.gatewayName === resolveDefaultGatewayName() && target.gatewayPort === GATEWAY_PORT) { - return deps.startGatewayWithOptions(undefined as never, { exitOnFailure: false }); + // The Docker-driver Linux startup path (startGatewayWithOptions → + // startDockerDriverGateway) restores the runtime-marker, package-managed + // registration, and sandbox-bridge reachability — none of which a plain + // `openshell gateway start` produces. Route through it whenever the + // recovery target matches the current process's GATEWAY_PORT (the common + // case where the user re-runs with the same NEMOCLAW_GATEWAY_PORT). Plain + // CLI start is only the fallback for cross-port recovery, which the + // module-globals captured by startDockerDriverGateway cannot retarget. + if (target.gatewayPort === GATEWAY_PORT) { + if (target.gatewayName === resolveDefaultGatewayName() || isLinuxDockerDriverGatewayEnabled()) { + return deps.startGatewayWithOptions(undefined as never, { exitOnFailure: false }); + } } return startTargetGatewayForRecovery(target, deps); } From 3c17076814065854d8d5c49097ce2b1528c008a0 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Fri, 12 Jun 2026 20:00:46 +0000 Subject: [PATCH 22/29] fix(sandbox): respect post-select lifecycle, per-port host PID, sandbox-target Slack conflict Signed-off-by: Tinson Lai --- src/lib/actions/sandbox/destroy-gateway.ts | 37 +++++- src/lib/actions/sandbox/gateway-state.ts | 10 ++ .../sandbox/policy-channel-conflict.test.ts | 38 ++++++ src/lib/actions/sandbox/policy-channel.ts | 13 +-- .../sandbox/rebuild-gateway-drift.test.ts | 109 ++++++++++++++++++ test/cli/destroy-gateway-cleanup.test.ts | 77 +++++++++++++ 6 files changed, 275 insertions(+), 9 deletions(-) diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts index a0548c3fb28..9300fb8bf27 100644 --- a/src/lib/actions/sandbox/destroy-gateway.ts +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -1,8 +1,15 @@ // 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"; @@ -13,6 +20,22 @@ export type DestroyRunOpenshell = ( 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-` 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, @@ -61,8 +84,18 @@ export function cleanupGatewayAfterLastSandbox( // 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 }); + // The uninstall path keeps the broader sweep on (run-plan.ts). The state + // dir is per-gateway-name so a destroy of `nemoclaw-` 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"], diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index c7e30b62bbd..0ed1f416b57 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -250,6 +250,16 @@ export function reconcileMissingAgainstNamedGateway( // the sandbox truly absent. return tryRecoverDockerDriverSandbox(sandboxName, retry); } + // The select moved the active gateway off, but the target gateway is + // now missing or unreachable. Surface that post-select state so the + // caller emits restart guidance, rather than `wrong_gateway_active` + // pointing at the now-irrelevant pre-select active gateway. + if (after.state === "missing_named") { + return { state: "gateway_missing_after_restart", output: after.status }; + } + if (after.state === "named_unreachable" || after.state === "named_unhealthy") { + return { state: "gateway_unreachable_after_restart", output: after.status }; + } } return { state: "wrong_gateway_active", diff --git a/src/lib/actions/sandbox/policy-channel-conflict.test.ts b/src/lib/actions/sandbox/policy-channel-conflict.test.ts index 45eb6fa40fd..071884ca9e9 100644 --- a/src/lib/actions/sandbox/policy-channel-conflict.test.ts +++ b/src/lib/actions/sandbox/policy-channel-conflict.test.ts @@ -687,6 +687,44 @@ describe("addSandboxChannel cross-sandbox conflict check (#4305)", () => { expect(upsertMock).not.toHaveBeenCalled(); // aborted before registering }); + it("slack: a second sandbox on the SAME non-default gateway is blocked (#4953)", async () => { + // Both sandboxes are bound to `nemoclaw-8090`. The credential axis would + // not flag distinct tokens, but the gateway axis must — without this case, + // `checkSlackSocketModeGatewayConflict` previously checked the default + // `nemoclaw` while the provider mutation ran against `nemoclaw-8090` and + // left a false negative for two Slack sandboxes sharing the same non- + // default gateway. + const slackBot = "xoxb-alpha-bot-token"; + const slackApp = "xapp-alpha-app-token"; + const alpha = { name: "alpha", gatewayName: "nemoclaw-8090", gatewayPort: 8090 } as never; + const bob = makePlanEntry("bob", "slack", [ + { + providerEnvKey: "SLACK_BOT_TOKEN", + credentialHash: hashCredential("xoxb-bob-bot") as string, + }, + { + providerEnvKey: "SLACK_APP_TOKEN", + credentialHash: hashCredential("xapp-bob-app") as string, + }, + ]); + (bob as { gatewayName?: string; gatewayPort?: number }).gatewayName = "nemoclaw-8090"; + (bob as { gatewayName?: string; gatewayPort?: number }).gatewayPort = 8090; + arrangeRegistry({ current: alpha, others: [bob] }); + getCredentialMock.mockImplementation((key: string) => + key === "SLACK_BOT_TOKEN" ? slackBot : key === "SLACK_APP_TOKEN" ? slackApp : null, + ); + promptMock.mockResolvedValue("n"); + + await addSandboxChannel("alpha", { channel: "slack" }); + + const text = loggedText(); + expect(text).toContain("Slack Socket Mode is already enabled for sandbox 'bob'"); + expect(text).not.toContain(slackBot); + expect(text).not.toContain(slackApp); + expect(conflictPromptShown()).toBe(true); + expect(upsertMock).not.toHaveBeenCalled(); + }); + it("slack: shared token on the same gateway reports the credential conflict first (#4953)", async () => { // The credential axis runs before the gateway axis, so a shared Slack token // surfaces the gateway-independent "same slack credential" warning (more diff --git a/src/lib/actions/sandbox/policy-channel.ts b/src/lib/actions/sandbox/policy-channel.ts index 66c3a91c308..b1d598b1ea3 100644 --- a/src/lib/actions/sandbox/policy-channel.ts +++ b/src/lib/actions/sandbox/policy-channel.ts @@ -457,14 +457,13 @@ async function checkSlackSocketModeGatewayConflict( let conflictMessages: string[] = []; try { const applier = require("../../messaging/applier") as typeof import("../../messaging/applier"); - const { BASE_GATEWAY_NAME } = - require("../../onboard/gateway-binding") as typeof import("../../onboard/gateway-binding"); - // `channels add` registers the Slack provider on the default `nemoclaw` + // `channels add` registers the Slack provider on the sandbox's target // gateway — applyChannelAddToGatewayAndRegistry → recoverNamedGatewayRuntime - // selects `nemoclaw` regardless of the sandbox's recorded gateway. Detect - // conflicts on the gateway the add actually mutates so the check matches the - // provider registration and cannot leave a false negative (#4953). - const gatewayName = BASE_GATEWAY_NAME; + // selects that same name. Detect conflicts on the gateway the add actually + // mutates so the check matches the provider registration and cannot leave a + // false negative for a sibling sandbox on the same non-default gateway + // (#4953). + const gatewayName = getSandboxTargetGatewayName(sandboxName); conflictMessages = applier .findSlackSocketModeGatewayConflicts( sandboxName, diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index 51fbb6bf2d2..a9682a02b68 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -180,6 +180,115 @@ describe("rebuild gateway drift preflight", () => { expect(listCalls).toBe(2); }); + it("recovers the persisted non-default gateway when the sandbox is bound to nemoclaw-", async () => { + detectPreflightIssueSpy.mockReturnValue(null); + // Reseed the sandbox lookup to expose a non-default gateway binding + // (gatewayPort=12345 → gateway name `nemoclaw-12345`). The stale-recovery + // path must address that gateway, not the default `nemoclaw`, otherwise a + // sandbox onboarded against `NEMOCLAW_GATEWAY_PORT=12345` would try to + // recover the wrong (and possibly nonexistent) default gateway. + for (const spy of spies) spy.mockRestore(); + spies.length = 0; + const gatewayDrift = requireDist("../../../../dist/lib/adapters/openshell/gateway-drift.js"); + const openshellRuntime = requireDist("../../../../dist/lib/adapters/openshell/runtime.js"); + const gatewayRuntime = requireDist("../../../../dist/lib/gateway-runtime-action.js"); + const registry = requireDist("../../../../dist/lib/state/registry.js"); + const resolve = requireDist("../../../../dist/lib/adapters/openshell/resolve.js"); + const sandboxSession = requireDist("../../../../dist/lib/state/sandbox-session.js"); + const onboardSession = requireDist("../../../../dist/lib/state/onboard-session.js"); + const sandboxVersion = requireDist("../../../../dist/lib/sandbox/version.js"); + const agentRuntime = requireDist("../../../../dist/lib/agent/runtime.js"); + + let listCalls = 0; + detectPreflightIssueSpy = vi + .spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue") + .mockReturnValue(null); + captureOpenshellSpy = vi + .spyOn(openshellRuntime, "captureOpenshell") + .mockImplementation(((args: string[]) => { + if (args[0] === "sandbox" && args[1] === "list") { + listCalls += 1; + return listCalls === 1 + ? { status: 1, output: "client error (Connect): Connection refused" } + : { status: 0, output: "beta Ready" }; + } + if (args[0] === "status") { + return { + status: 0, + output: "Server Status\n\n Gateway: nemoclaw-12345\n Status: Connected\n", + }; + } + if (args[0] === "gateway" && args[1] === "info") { + return { status: 0, output: "Gateway Info\n\nGateway: nemoclaw-12345\n" }; + } + if (args[0] === "sandbox" && args[1] === "get") { + return { status: 1, output: "Error: × Not Found: sandbox not found" }; + } + return { status: 0, output: "" }; + }) as never); + runOpenshellSpy = vi + .spyOn(openshellRuntime, "runOpenshell") + .mockReturnValue({ status: 0, output: "" } as never); + recoverNamedGatewayRuntimeSpy = vi + .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") + .mockResolvedValue({ recovered: true }); + checkAgentVersionSpy = vi + .spyOn(sandboxVersion, "checkAgentVersion") + .mockReturnValue({ expectedVersion: "0.1.0", sandboxVersion: "0.0.1" } as never); + printIssueSpy = vi + .spyOn(gatewayDrift, "printOpenShellStateRpcIssue") + .mockImplementation(() => undefined); + + const destroy = requireDist("../../../../dist/lib/actions/sandbox/destroy.js"); + const onboardMod = requireDist("../../../../dist/lib/onboard.js"); + spies.push( + detectPreflightIssueSpy, + vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null), + captureOpenshellSpy, + runOpenshellSpy, + recoverNamedGatewayRuntimeSpy, + printIssueSpy, + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + provider: "ollama-local", + model: "nvidia/nemotron", + policies: [], + nimContainer: null, + agent: null, + gatewayName: "nemoclaw-12345", + gatewayPort: 12345, + } as never), + vi.spyOn(resolve, "resolveOpenshell").mockReturnValue(null), + vi.spyOn(sandboxSession, "getActiveSandboxSessions").mockReturnValue({ + detected: false, + sessions: [], + }), + vi.spyOn(onboardSession, "loadSession").mockReturnValue(null), + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null), + vi.spyOn(agentRuntime, "getAgentDisplayName").mockReturnValue("OpenClaw"), + checkAgentVersionSpy, + vi.spyOn(destroy, "removeSandboxRegistryEntry").mockImplementation(() => undefined), + vi.spyOn(onboardMod, "onboard").mockRejectedValue(new Error("recreate-stub")), + ); + + ({ rebuildSandbox } = requireDist("../../../../dist/lib/actions/sandbox/rebuild.js")); + + await expect(rebuildSandbox("alpha", ["--yes"], { throwOnError: true })).rejects.toThrow( + /stale-sandbox recovery/, + ); + + expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({ + gatewayName: "nemoclaw-12345", + recoverableStates: [ + "missing_named", + "named_unhealthy", + "named_unreachable", + "connected_other", + ], + }); + expect(listCalls).toBe(2); + }); + it("does not recover generic sandbox list failures", async () => { detectPreflightIssueSpy.mockReturnValue(null); captureOpenshellSpy.mockReturnValue({ status: 1, output: "unknown option: sandbox list" }); diff --git a/test/cli/destroy-gateway-cleanup.test.ts b/test/cli/destroy-gateway-cleanup.test.ts index 172969e89b7..2287217fc3e 100644 --- a/test/cli/destroy-gateway-cleanup.test.ts +++ b/test/cli/destroy-gateway-cleanup.test.ts @@ -229,6 +229,83 @@ describe("CLI dispatch", () => { }, ); + it.runIf(process.platform === "linux")( + "clears only the per-port host gateway PID file when destroying nemoclaw-", + testTimeoutOptions(30_000), + () => { + // A `nemoclaw-8081` sandbox's destroy must read and clear its own + // `openshell-docker-gateway-8081/openshell-gateway.pid`, NOT the default + // instance's `openshell-docker-gateway/openshell-gateway.pid`. Otherwise + // destroying a non-default sandbox tears down the default instance's + // tracked host gateway process (#4865 impact clause). + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-destroy-perport-pid-")); + const localBin = path.join(home, "bin"); + const registryDir = path.join(home, ".nemoclaw"); + const defaultStateDir = path.join(home, ".local/state/nemoclaw/openshell-docker-gateway"); + const perPortStateDir = path.join( + home, + ".local/state/nemoclaw/openshell-docker-gateway-8081", + ); + const defaultPidFile = path.join(defaultStateDir, "openshell-gateway.pid"); + const perPortPidFile = path.join(perPortStateDir, "openshell-gateway.pid"); + fs.mkdirSync(localBin, { recursive: true }); + fs.mkdirSync(registryDir, { recursive: true }); + fs.mkdirSync(defaultStateDir, { recursive: true }); + fs.mkdirSync(perPortStateDir, { recursive: true }); + // PIDs that are guaranteed to be dead so stopHostGatewayProcesses takes + // the clearRuntimeFiles branch without trying to kill anything. + fs.writeFileSync(defaultPidFile, "999998\n"); + fs.writeFileSync(perPortPidFile, "999999\n"); + fs.writeFileSync( + path.join(registryDir, "sandboxes.json"), + JSON.stringify({ + sandboxes: { + alpha: { + name: "alpha", + model: "test-model", + provider: "nvidia-prod", + gpuEnabled: false, + policies: [], + gatewayName: "nemoclaw-8081", + gatewayPort: 8081, + }, + }, + defaultSandbox: "alpha", + }), + { mode: 0o600 }, + ); + fs.writeFileSync( + path.join(localBin, "openshell"), + [ + "#!/bin/sh", + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', + ' printf "NAME STATUS\\n"', + " exit 0", + "fi", + "exit 0", + ].join("\n"), + { mode: 0o755 }, + ); + fs.writeFileSync(path.join(localBin, "docker"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + fs.writeFileSync(path.join(localBin, "pgrep"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); + fs.writeFileSync(path.join(localBin, "lsof"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); + + const r = runWithEnv( + "alpha destroy -y --cleanup-gateway", + { + HOME: home, + PATH: `${localBin}:${process.env.PATH || ""}`, + }, + 30_000, + ); + + expect(r.code, r.out).toBe(0); + expect(fs.existsSync(perPortPidFile)).toBe(false); + expect(fs.existsSync(defaultPidFile)).toBe(true); + expect(fs.readFileSync(defaultPidFile, "utf8").trim()).toBe("999998"); + }, + ); + it("keeps the gateway runtime when other sandboxes still exist", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-destroy-shared-")); const localBin = path.join(home, "bin"); From 618de7e6be4d1cd93411c43560e66cc4a9d1fe40 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Fri, 12 Jun 2026 20:01:44 +0000 Subject: [PATCH 23/29] refactor(onboard): extract dashboard-port reservation helper Signed-off-by: Tinson Lai --- src/lib/onboard/dashboard-port-reservation.ts | 29 +++++++++++++++++++ src/lib/onboard/dashboard.ts | 21 +------------- 2 files changed, 30 insertions(+), 20 deletions(-) create mode 100644 src/lib/onboard/dashboard-port-reservation.ts diff --git a/src/lib/onboard/dashboard-port-reservation.ts b/src/lib/onboard/dashboard-port-reservation.ts new file mode 100644 index 00000000000..c524886d7f5 --- /dev/null +++ b/src/lib/onboard/dashboard-port-reservation.ts @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import * as registry from "../state/registry"; + +/** + * Collect the dashboard ports held by every sandbox in the local registry + * except the one currently being onboarded. Forwards on sibling gateways are + * invisible to the active gateway's `forward list`, so the allocator needs + * the registry view to keep dashboard ports distinct across gateways. + */ +export function collectRegistryReservedDashboardPorts( + excludeSandboxName: string, +): ReadonlyMap { + const reserved = new Map(); + try { + const list = registry.listSandboxes(); + for (const entry of list.sandboxes) { + if (entry.name === excludeSandboxName) continue; + if (typeof entry.dashboardPort === "number" && Number.isFinite(entry.dashboardPort)) { + reserved.set(entry.dashboardPort, entry.name); + } + } + } catch { + // The registry may be unreadable mid-onboard; downstream lsof + bind + // probes are still the final authority on port availability. + } + return reserved; +} diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index 33f23e2e4d5..baab3d9a10c 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -23,8 +23,8 @@ import { getOccupiedPorts, isLiveForwardStatus, } from "./dashboard-port"; +import { collectRegistryReservedDashboardPorts } from "./dashboard-port-reservation"; import { bestEffortForwardStop } from "./forward-cleanup"; -import * as registry from "../state/registry"; import { buildDetachedForwardStartSpawn, buildForwardStartProgressLogger, @@ -103,25 +103,6 @@ export interface OnboardDashboardHelpers { stopAllDashboardForwards(): void; } -function collectRegistryReservedDashboardPorts( - excludeSandboxName: string, -): ReadonlyMap { - const reserved = new Map(); - try { - const list = registry.listSandboxes(); - for (const entry of list.sandboxes) { - if (entry.name === excludeSandboxName) continue; - if (typeof entry.dashboardPort === "number" && Number.isFinite(entry.dashboardPort)) { - reserved.set(entry.dashboardPort, entry.name); - } - } - } catch { - // The registry may be unreadable mid-onboard; downstream lsof + bind - // probes are still the final authority on port availability. - } - return reserved; -} - function findForwardEntry( forwardListOutput: string | null | undefined, port: string, From bd9e8b8b8d8a13030013675482dc3950a16b3168 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Fri, 12 Jun 2026 20:02:31 +0000 Subject: [PATCH 24/29] test(e2e): surface captured onboard output in phase diagnostics Signed-off-by: Tinson Lai --- test/e2e/test-double-onboard.sh | 4 ++++ test/e2e/test-onboard-repair.sh | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/test/e2e/test-double-onboard.sh b/test/e2e/test-double-onboard.sh index 535ba95535e..f9632e8d147 100755 --- a/test/e2e/test-double-onboard.sh +++ b/test/e2e/test-double-onboard.sh @@ -63,6 +63,10 @@ phase_elapsed() { dump_diagnostics() { local phase_label="${1:-unknown}" info "=== Diagnostics for ${phase_label} ===" + if [ -n "${RUN_ONBOARD_OUTPUT:-}" ]; then + info "Captured nemoclaw onboard stdout/stderr (exit=${RUN_ONBOARD_EXIT:-?}):" + printf '%s\n' "$RUN_ONBOARD_OUTPUT" | sed 's/^/ /' + fi info "openshell status:" openshell status 2>&1 | sed 's/^/ /' || true info "openshell sandbox list:" diff --git a/test/e2e/test-onboard-repair.sh b/test/e2e/test-onboard-repair.sh index 8351b74878d..feac4117ee7 100755 --- a/test/e2e/test-onboard-repair.sh +++ b/test/e2e/test-onboard-repair.sh @@ -198,12 +198,16 @@ if echo "$first_output" | grep -q "\[e2e\] Forced onboarding failure at step 'po pass "First run failed at policy setup as intended" else fail "First run did not fail at the expected policy step" + info "Captured first-onboard stdout/stderr (exit=$first_exit):" + printf '%s\n' "$first_output" | sed 's/^/ /' fi if openshell sandbox get "$SANDBOX_NAME" >/dev/null 2>&1; then pass "Sandbox '$SANDBOX_NAME' exists after interrupted run" else fail "Sandbox '$SANDBOX_NAME' not found after interrupted run" + info "Captured first-onboard stdout/stderr (exit=$first_exit):" + printf '%s\n' "$first_output" | sed 's/^/ /' fi # ══════════════════════════════════════════════════════════════════ From 4b38352649ee29e9c0ee34e9dd2fe70e34cff167 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Fri, 12 Jun 2026 20:49:01 +0000 Subject: [PATCH 25/29] style(sandbox): apply biome formatting to rebuild-gateway-drift test Signed-off-by: Tinson Lai --- .../sandbox/rebuild-gateway-drift.test.ts | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index a9682a02b68..f3cb8d045f3 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -203,29 +203,29 @@ describe("rebuild gateway drift preflight", () => { detectPreflightIssueSpy = vi .spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue") .mockReturnValue(null); - captureOpenshellSpy = vi - .spyOn(openshellRuntime, "captureOpenshell") - .mockImplementation(((args: string[]) => { - if (args[0] === "sandbox" && args[1] === "list") { - listCalls += 1; - return listCalls === 1 - ? { status: 1, output: "client error (Connect): Connection refused" } - : { status: 0, output: "beta Ready" }; - } - if (args[0] === "status") { - return { - status: 0, - output: "Server Status\n\n Gateway: nemoclaw-12345\n Status: Connected\n", - }; - } - if (args[0] === "gateway" && args[1] === "info") { - return { status: 0, output: "Gateway Info\n\nGateway: nemoclaw-12345\n" }; - } - if (args[0] === "sandbox" && args[1] === "get") { - return { status: 1, output: "Error: × Not Found: sandbox not found" }; - } - return { status: 0, output: "" }; - }) as never); + captureOpenshellSpy = vi.spyOn(openshellRuntime, "captureOpenshell").mockImplementation((( + args: string[], + ) => { + if (args[0] === "sandbox" && args[1] === "list") { + listCalls += 1; + return listCalls === 1 + ? { status: 1, output: "client error (Connect): Connection refused" } + : { status: 0, output: "beta Ready" }; + } + if (args[0] === "status") { + return { + status: 0, + output: "Server Status\n\n Gateway: nemoclaw-12345\n Status: Connected\n", + }; + } + if (args[0] === "gateway" && args[1] === "info") { + return { status: 0, output: "Gateway Info\n\nGateway: nemoclaw-12345\n" }; + } + if (args[0] === "sandbox" && args[1] === "get") { + return { status: 1, output: "Error: × Not Found: sandbox not found" }; + } + return { status: 0, output: "" }; + }) as never); runOpenshellSpy = vi .spyOn(openshellRuntime, "runOpenshell") .mockReturnValue({ status: 0, output: "" } as never); From b4e1379d90d3fad11181df6908a2c23c3e4cfc4b Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Sat, 13 Jun 2026 04:39:28 +0000 Subject: [PATCH 26/29] revert(onboard): drop multi-instance dashboard-port reservation Signed-off-by: Tinson Lai --- src/lib/onboard/dashboard-port-reservation.ts | 29 ------------------- src/lib/onboard/dashboard-port.test.ts | 21 -------------- src/lib/onboard/dashboard-port.ts | 13 --------- src/lib/onboard/dashboard.ts | 9 +----- 4 files changed, 1 insertion(+), 71 deletions(-) delete mode 100644 src/lib/onboard/dashboard-port-reservation.ts diff --git a/src/lib/onboard/dashboard-port-reservation.ts b/src/lib/onboard/dashboard-port-reservation.ts deleted file mode 100644 index c524886d7f5..00000000000 --- a/src/lib/onboard/dashboard-port-reservation.ts +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import * as registry from "../state/registry"; - -/** - * Collect the dashboard ports held by every sandbox in the local registry - * except the one currently being onboarded. Forwards on sibling gateways are - * invisible to the active gateway's `forward list`, so the allocator needs - * the registry view to keep dashboard ports distinct across gateways. - */ -export function collectRegistryReservedDashboardPorts( - excludeSandboxName: string, -): ReadonlyMap { - const reserved = new Map(); - try { - const list = registry.listSandboxes(); - for (const entry of list.sandboxes) { - if (entry.name === excludeSandboxName) continue; - if (typeof entry.dashboardPort === "number" && Number.isFinite(entry.dashboardPort)) { - reserved.set(entry.dashboardPort, entry.name); - } - } - } catch { - // The registry may be unreadable mid-onboard; downstream lsof + bind - // probes are still the final authority on port availability. - } - return reserved; -} diff --git a/src/lib/onboard/dashboard-port.test.ts b/src/lib/onboard/dashboard-port.test.ts index 40c787b4973..5eaf2f88a13 100644 --- a/src/lib/onboard/dashboard-port.test.ts +++ b/src/lib/onboard/dashboard-port.test.ts @@ -94,27 +94,6 @@ describe("findAvailableDashboardPort port-conflict detection (#3260)", () => { findAvailableDashboardPort("cursor", 18789, "", stub); assert.deepEqual(seen, [18789, 18790]); }); - - it("skips dashboard ports reserved by sibling sandboxes on other gateways (#4865)", () => { - // Sandbox 'alpha' was onboarded against the default gateway and recorded - // 18789 in the registry; a second onboard with NEMOCLAW_GATEWAY_PORT=8081 - // queries the new gateway's forward list (empty), so without the registry - // reservation it would re-allocate 18789 and both sandboxes would advertise - // the same dashboard URL. - const reserved = new Map([[18789, "alpha"]]); - assert.equal( - findAvailableDashboardPort("port-test", 18789, "", () => false, reserved), - 18790, - ); - }); - - it("still returns the preferred port when this sandbox owns the registry reservation", () => { - const reserved = new Map([[18789, "cursor"]]); - assert.equal( - findAvailableDashboardPort("cursor", 18789, "", () => false, reserved), - 18789, - ); - }); }); describe("resolveCreateSandboxDashboardPort", () => { diff --git a/src/lib/onboard/dashboard-port.ts b/src/lib/onboard/dashboard-port.ts index b17f99a1522..cbb0b6455d6 100644 --- a/src/lib/onboard/dashboard-port.ts +++ b/src/lib/onboard/dashboard-port.ts @@ -155,21 +155,8 @@ export function findAvailableDashboardPort( preferredPort: number, forwardListOutput: string | null, isPortBoundCheck: (port: number) => boolean = isPortBoundOnHost, - registryReservedPorts: ReadonlyMap = new Map(), ): number { const occupied = getOccupiedPorts(forwardListOutput); - // Forwards on sibling gateways are invisible to the active gateway's - // `forward list`, so a second onboard on a non-default NEMOCLAW_GATEWAY_PORT - // can otherwise allocate a dashboard port already in use by an existing - // sandbox registered on another gateway. Treat the registry-recorded - // dashboard ports of other sandboxes as occupied to keep them distinct. - for (const [port, owner] of registryReservedPorts) { - if (owner === sandboxName) continue; - const key = String(port); - if (!occupied.has(key)) { - occupied.set(key, owner); - } - } const hostBoundPorts: number[] = []; // Try the preferred port first (it may be outside the dashboard range when // a caller passes --control-ui-port), then the rest of the range. Each port diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index baab3d9a10c..e0c364408c9 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -23,7 +23,6 @@ import { getOccupiedPorts, isLiveForwardStatus, } from "./dashboard-port"; -import { collectRegistryReservedDashboardPorts } from "./dashboard-port-reservation"; import { bestEffortForwardStop } from "./forward-cleanup"; import { buildDetachedForwardStartSpawn, @@ -250,13 +249,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa } let actualPort: number; try { - actualPort = findAvailableDashboardPort( - sandboxName, - preferredPort, - existingForwards, - undefined, - collectRegistryReservedDashboardPorts(sandboxName), - ); + actualPort = findAvailableDashboardPort(sandboxName, preferredPort, existingForwards); } catch (err) { if (!rollbackSandboxOnFailure) throw err; rollbackSandboxAndExit(sandboxName, err); From aef283d083a0ef3fbc076e5ae3c834adbd793a00 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Sat, 13 Jun 2026 05:17:09 +0000 Subject: [PATCH 27/29] fix(sandbox): resolve gateway via persisted port default and fail closed on cross-port Docker-driver recovery Signed-off-by: Tinson Lai --- src/lib/actions/sandbox/destroy-gateway.ts | 6 +++--- src/lib/actions/sandbox/destroy.ts | 2 +- .../sandbox/policy-channel-conflict.test.ts | 2 +- src/lib/actions/sandbox/policy-channel.ts | 3 +-- .../actions/sandbox/sandbox-gateway-routing.ts | 16 +++++++++++----- src/lib/gateway-runtime-action.ts | 4 +++- src/lib/onboard/gateway-binding.ts | 4 ++-- src/lib/onboard/gateway-recovery.ts | 17 ++++++++++++++--- src/lib/status-command-deps.ts | 7 +++++-- test/cli/destroy-gateway-cleanup.test.ts | 2 +- 10 files changed, 42 insertions(+), 21 deletions(-) diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts index 9300fb8bf27..acb9dd5de05 100644 --- a/src/lib/actions/sandbox/destroy-gateway.ts +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -75,9 +75,9 @@ export function cleanupGatewayAfterLastSandbox( 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. + // 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 diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index e869341ebde..a593fc02b18 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -397,7 +397,7 @@ export async function destroySandbox( 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 (#4865). + // back to the default gateway. const removed = removeSandboxRegistryEntry(sandboxName); const session = onboardSession.loadSession(); if (session && session.sandboxName === sandboxName) { diff --git a/src/lib/actions/sandbox/policy-channel-conflict.test.ts b/src/lib/actions/sandbox/policy-channel-conflict.test.ts index 071884ca9e9..78193ae6e5a 100644 --- a/src/lib/actions/sandbox/policy-channel-conflict.test.ts +++ b/src/lib/actions/sandbox/policy-channel-conflict.test.ts @@ -687,7 +687,7 @@ describe("addSandboxChannel cross-sandbox conflict check (#4305)", () => { expect(upsertMock).not.toHaveBeenCalled(); // aborted before registering }); - it("slack: a second sandbox on the SAME non-default gateway is blocked (#4953)", async () => { + it("slack: a second sandbox on the SAME non-default gateway is blocked", async () => { // Both sandboxes are bound to `nemoclaw-8090`. The credential axis would // not flag distinct tokens, but the gateway axis must — without this case, // `checkSlackSocketModeGatewayConflict` previously checked the default diff --git a/src/lib/actions/sandbox/policy-channel.ts b/src/lib/actions/sandbox/policy-channel.ts index b1d598b1ea3..387439299ab 100644 --- a/src/lib/actions/sandbox/policy-channel.ts +++ b/src/lib/actions/sandbox/policy-channel.ts @@ -461,8 +461,7 @@ async function checkSlackSocketModeGatewayConflict( // gateway — applyChannelAddToGatewayAndRegistry → recoverNamedGatewayRuntime // selects that same name. Detect conflicts on the gateway the add actually // mutates so the check matches the provider registration and cannot leave a - // false negative for a sibling sandbox on the same non-default gateway - // (#4953). + // false negative for a sibling sandbox on the same non-default gateway. const gatewayName = getSandboxTargetGatewayName(sandboxName); conflictMessages = applier .findSlackSocketModeGatewayConflicts( diff --git a/src/lib/actions/sandbox/sandbox-gateway-routing.ts b/src/lib/actions/sandbox/sandbox-gateway-routing.ts index 72b442edbb7..22bf2b3f683 100644 --- a/src/lib/actions/sandbox/sandbox-gateway-routing.ts +++ b/src/lib/actions/sandbox/sandbox-gateway-routing.ts @@ -12,7 +12,10 @@ import { dockerInspect } from "../../adapters/docker"; import { captureOpenshell, runOpenshell } from "../../adapters/openshell/runtime"; -import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; +import { + OPENSHELL_OPERATION_TIMEOUT_MS, + OPENSHELL_PROBE_TIMEOUT_MS, +} from "../../adapters/openshell/timeouts"; import { GATEWAY_PORT } from "../../core/ports"; import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { isGatewayHealthy } from "../../state/gateway"; @@ -23,14 +26,17 @@ import * as registry from "../../state/registry"; * verify gateway health through OpenShell metadata instead. */ export function probeGatewayMetadataHealth(gatewayName: string): boolean { - const status = captureOpenshell(["status"], { ignoreError: true, timeout: 10000 }); + const status = captureOpenshell(["status"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); const namedGatewayInfo = captureOpenshell(["gateway", "info", "-g", gatewayName], { ignoreError: true, - timeout: 10000, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, }); const activeGatewayInfo = captureOpenshell(["gateway", "info"], { ignoreError: true, - timeout: 10000, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, }); return isGatewayHealthy( status.output || "", @@ -48,7 +54,7 @@ export function usesGatewayMetadataProbe(driver: string | null | undefined): boo * Probe whether the OpenShell gateway the named sandbox lives on is running. * Resolves the gateway from the sandbox's persisted registry entry — never * the process-level `GATEWAY_PORT` — so the probe targets the gateway the - * sandbox was actually onboarded against (#4985). + * sandbox was actually onboarded against. */ export function probeGatewayRunning(sandboxName?: string): boolean { const entry = sandboxName ? registry.getSandbox(sandboxName) : null; diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index 7488c5475b2..d6d34615abe 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -25,7 +25,9 @@ function getActiveGatewayName(output = ""): string | null { return match ? match[1].trim() : null; } -export function getNamedGatewayLifecycleState(gatewayName = "nemoclaw") { +export function getNamedGatewayLifecycleState( + gatewayName: string = resolveGatewayName(GATEWAY_PORT), +) { const status = captureOpenshell(["status"], { timeout: OPENSHELL_PROBE_TIMEOUT_MS }); const gatewayInfo = captureOpenshell(["gateway", "info", "-g", gatewayName], { timeout: OPENSHELL_PROBE_TIMEOUT_MS, diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index 8c3a02dc8c0..016fc29d11c 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -10,7 +10,7 @@ * different `NEMOCLAW_GATEWAY_PORT` therefore reused the same named gateway, * the same runtime-marker state dir, and the same compat container — so * creating the second sandbox recreated/killed the first sandbox's gateway and - * overwrote its runtime marker (#4422). + * overwrote its runtime marker. * * These pure resolvers derive a stable per-port binding. The default port * keeps the original `nemoclaw` names verbatim so existing single-sandbox @@ -185,7 +185,7 @@ export interface GatewayNameBoundClassifiers { * Bind the gateway-name-aware health/reuse classifiers to a resolved gateway * name so a non-default NEMOCLAW_GATEWAY_PORT (gateway `nemoclaw-`) is * recognized as its own gateway rather than matched against the `nemoclaw` - * singleton (#4422). Kept out of onboard.ts to avoid growing that file. + * singleton. Kept out of onboard.ts to avoid growing that file. */ export function createGatewayNameBoundClassifiers( state: typeof import("../state/gateway"), diff --git a/src/lib/onboard/gateway-recovery.ts b/src/lib/onboard/gateway-recovery.ts index 4fb096e9cc8..651453cec61 100644 --- a/src/lib/onboard/gateway-recovery.ts +++ b/src/lib/onboard/gateway-recovery.ts @@ -195,13 +195,24 @@ export async function startGatewayForRecovery( // registration, and sandbox-bridge reachability — none of which a plain // `openshell gateway start` produces. Route through it whenever the // recovery target matches the current process's GATEWAY_PORT (the common - // case where the user re-runs with the same NEMOCLAW_GATEWAY_PORT). Plain - // CLI start is only the fallback for cross-port recovery, which the - // module-globals captured by startDockerDriverGateway cannot retarget. + // case where the user re-runs with the same NEMOCLAW_GATEWAY_PORT). if (target.gatewayPort === GATEWAY_PORT) { if (target.gatewayName === resolveDefaultGatewayName() || isLinuxDockerDriverGatewayEnabled()) { return deps.startGatewayWithOptions(undefined as never, { exitOnFailure: false }); } } + // Cross-port recovery on a Linux Docker-driver gateway cannot share this + // process's module-globals: startDockerDriverGateway captures the port at + // load time, so a plain `openshell gateway start` would skip the + // runtime-marker / package registration / sandbox-bridge setup and leave + // the host in a half-recovered state. Fail closed instead and direct the + // operator to re-run with the matching NEMOCLAW_GATEWAY_PORT so the + // docker-driver path re-stamps the per-port artefacts. + if (isLinuxDockerDriverGatewayEnabled() && target.gatewayPort !== GATEWAY_PORT) { + throw new Error( + `Cross-port recovery for Linux Docker-driver gateway '${target.gatewayName}' is not safe from a process bound to port ${GATEWAY_PORT}. ` + + `Re-run with NEMOCLAW_GATEWAY_PORT=${target.gatewayPort} so the docker-driver setup can restamp the runtime marker, registration, and sandbox bridge.`, + ); + } return startTargetGatewayForRecovery(target, deps); } diff --git a/src/lib/status-command-deps.ts b/src/lib/status-command-deps.ts index 8f3adb36156..1ce6270098c 100644 --- a/src/lib/status-command-deps.ts +++ b/src/lib/status-command-deps.ts @@ -6,7 +6,9 @@ import type { CaptureOpenshellResult } from "./adapters/openshell/client"; import { captureOpenshellCommand } from "./adapters/openshell/client"; import { resolveOpenshell } from "./adapters/openshell/resolve"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "./adapters/openshell/timeouts"; +import { GATEWAY_PORT } from "./core/ports"; import { getNamedGatewayLifecycleState } from "./gateway-runtime-action"; +import { resolveGatewayName } from "./onboard/gateway-binding"; import { getLiveGatewayInference } from "./inference/live"; import type { GatewayHealth, MessagingBridgeHealth, ShowStatusCommandDeps } from "./inventory"; import { detectAllSlackSocketModeGatewayOverlaps, findAllOverlaps } from "./messaging/applier"; @@ -111,14 +113,15 @@ function readGatewayLog(rootDir: string, sandboxName: string): string | null { function probeGatewayHealth(): GatewayHealth { try { - const lifecycle = getNamedGatewayLifecycleState(); + const expectedGateway = resolveGatewayName(GATEWAY_PORT); + const lifecycle = getNamedGatewayLifecycleState(expectedGateway); if (lifecycle.state === "healthy_named") { return { healthy: true, state: lifecycle.state }; } const reasonByState: Record = { named_unreachable: "host port held or container not running", named_unhealthy: "named gateway present but not Connected", - connected_other: `connected to '${lifecycle.activeGateway ?? "unknown"}', not 'nemoclaw'`, + connected_other: `connected to '${lifecycle.activeGateway ?? "unknown"}', not '${expectedGateway}'`, missing_named: "named gateway not configured", }; return { diff --git a/test/cli/destroy-gateway-cleanup.test.ts b/test/cli/destroy-gateway-cleanup.test.ts index 2287217fc3e..f8c66fc978f 100644 --- a/test/cli/destroy-gateway-cleanup.test.ts +++ b/test/cli/destroy-gateway-cleanup.test.ts @@ -237,7 +237,7 @@ describe("CLI dispatch", () => { // `openshell-docker-gateway-8081/openshell-gateway.pid`, NOT the default // instance's `openshell-docker-gateway/openshell-gateway.pid`. Otherwise // destroying a non-default sandbox tears down the default instance's - // tracked host gateway process (#4865 impact clause). + // tracked host gateway process. const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-destroy-perport-pid-")); const localBin = path.join(home, "bin"); const registryDir = path.join(home, ".nemoclaw"); From 2ac0045508bf623e5b79a2356c88a6fb531b36e2 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Sat, 13 Jun 2026 05:36:32 +0000 Subject: [PATCH 28/29] test(onboard): stub Linux Docker-driver flag in gateway recovery tests Signed-off-by: Tinson Lai --- src/lib/onboard.ts | 1 + src/lib/onboard/gateway-recovery.test.ts | 19 ++++++++++++++++++- src/lib/onboard/gateway-recovery.ts | 8 ++++++-- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 22eb18ba008..3169d36f3f1 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2338,6 +2338,7 @@ async function startGatewayForRecovery(options = {}): Promise { runCaptureOpenshell, runOpenshell, startGatewayWithOptions, + isLinuxDockerDriverGatewayEnabled, }); } diff --git a/src/lib/onboard/gateway-recovery.test.ts b/src/lib/onboard/gateway-recovery.test.ts index 651608e8fb9..10c9fa8055d 100644 --- a/src/lib/onboard/gateway-recovery.test.ts +++ b/src/lib/onboard/gateway-recovery.test.ts @@ -8,7 +8,9 @@ import { startGatewayForRecovery, } from "../../../dist/lib/onboard/gateway-recovery"; -function createDeps(): GatewayRecoveryDeps { +function createDeps( + overrides: Partial = {}, +): GatewayRecoveryDeps { return { getGatewayClusterContainerState: () => "missing", getGatewayStartEnv: () => ({ OPENSHELL_DRIVERS: "docker" }), @@ -17,6 +19,10 @@ function createDeps(): GatewayRecoveryDeps { startGatewayWithOptions: vi.fn( async () => undefined, ) as GatewayRecoveryDeps["startGatewayWithOptions"], + // Tests assert the plain-CLI fallback path by default; the Linux + // Docker-driver branch is opted into explicitly per case. + isLinuxDockerDriverGatewayEnabled: () => false, + ...overrides, }; } @@ -113,4 +119,15 @@ describe("gateway recovery", () => { expect(deps.runOpenshell).not.toHaveBeenCalled(); }); + + it("fails closed on cross-port recovery when the Linux Docker-driver gateway is enabled", async () => { + const deps = createDeps({ isLinuxDockerDriverGatewayEnabled: () => true }); + + await expect(startGatewayForRecovery({ gatewayName: "nemoclaw-8090" }, deps)).rejects.toThrow( + /Cross-port recovery for Linux Docker-driver gateway 'nemoclaw-8090' is not safe/, + ); + + expect(deps.runOpenshell).not.toHaveBeenCalled(); + expect(deps.startGatewayWithOptions).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/onboard/gateway-recovery.ts b/src/lib/onboard/gateway-recovery.ts index 651453cec61..d5e80295f74 100644 --- a/src/lib/onboard/gateway-recovery.ts +++ b/src/lib/onboard/gateway-recovery.ts @@ -52,6 +52,7 @@ export type GatewayRecoveryDeps = { runCaptureOpenshell(args: string[], opts?: RunCaptureOpenshellOptions): string; runOpenshell(args: string[], opts?: RunOpenshellOptions): GatewayStartResult; startGatewayWithOptions(gpu: never, options: { exitOnFailure: false }): Promise; + isLinuxDockerDriverGatewayEnabled?(): boolean; }; function isValidGatewayRecoveryPort(port: number | null | undefined): port is number { @@ -190,6 +191,9 @@ export async function startGatewayForRecovery( deps: GatewayRecoveryDeps, ): Promise { const target = resolveGatewayRecoveryTarget(options); + const linuxDockerDriverEnabled = ( + deps.isLinuxDockerDriverGatewayEnabled ?? isLinuxDockerDriverGatewayEnabled + )(); // The Docker-driver Linux startup path (startGatewayWithOptions → // startDockerDriverGateway) restores the runtime-marker, package-managed // registration, and sandbox-bridge reachability — none of which a plain @@ -197,7 +201,7 @@ export async function startGatewayForRecovery( // recovery target matches the current process's GATEWAY_PORT (the common // case where the user re-runs with the same NEMOCLAW_GATEWAY_PORT). if (target.gatewayPort === GATEWAY_PORT) { - if (target.gatewayName === resolveDefaultGatewayName() || isLinuxDockerDriverGatewayEnabled()) { + if (target.gatewayName === resolveDefaultGatewayName() || linuxDockerDriverEnabled) { return deps.startGatewayWithOptions(undefined as never, { exitOnFailure: false }); } } @@ -208,7 +212,7 @@ export async function startGatewayForRecovery( // the host in a half-recovered state. Fail closed instead and direct the // operator to re-run with the matching NEMOCLAW_GATEWAY_PORT so the // docker-driver path re-stamps the per-port artefacts. - if (isLinuxDockerDriverGatewayEnabled() && target.gatewayPort !== GATEWAY_PORT) { + if (linuxDockerDriverEnabled && target.gatewayPort !== GATEWAY_PORT) { throw new Error( `Cross-port recovery for Linux Docker-driver gateway '${target.gatewayName}' is not safe from a process bound to port ${GATEWAY_PORT}. ` + `Re-run with NEMOCLAW_GATEWAY_PORT=${target.gatewayPort} so the docker-driver setup can restamp the runtime marker, registration, and sandbox bridge.`, From 428f20ba2ad2ff1f0db5a0882c974beb7234284c Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Sat, 13 Jun 2026 05:47:41 +0000 Subject: [PATCH 29/29] style(onboard): apply biome formatting to gateway-recovery test Signed-off-by: Tinson Lai --- src/lib/onboard/gateway-recovery.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/lib/onboard/gateway-recovery.test.ts b/src/lib/onboard/gateway-recovery.test.ts index 10c9fa8055d..1d2971657ca 100644 --- a/src/lib/onboard/gateway-recovery.test.ts +++ b/src/lib/onboard/gateway-recovery.test.ts @@ -8,9 +8,7 @@ import { startGatewayForRecovery, } from "../../../dist/lib/onboard/gateway-recovery"; -function createDeps( - overrides: Partial = {}, -): GatewayRecoveryDeps { +function createDeps(overrides: Partial = {}): GatewayRecoveryDeps { return { getGatewayClusterContainerState: () => "missing", getGatewayStartEnv: () => ({ OPENSHELL_DRIVERS: "docker" }),