From 3f4fc776d37d131f3097a61778046280b46f2c6b Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 22 Sep 2026 12:48:19 -0700 Subject: [PATCH 01/35] fix(runtime): keep proxy credentials out of OpenClaw state Signed-off-by: Prekshi Vyas --- scripts/nemoclaw-start.sh | 86 ++++++++++++- .../runtime/auth-profile-boundary.test.ts | 117 ++++++++++++++++++ 2 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 test/agents/openclaw/runtime/auth-profile-boundary.test.ts diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 30e04575f5f..0d84b4afb11 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2410,8 +2410,91 @@ prepare_gateway_token_for_current_command() { fi } -# Write an auth profile JSON for the NVIDIA API key so the gateway can authenticate. +# Reconcile the legacy OpenClaw auth profile used by direct inference routes. +# Managed OpenShell routes authenticate at the inference.local proxy, so the +# sandbox must not retain even an environment-variable reference to the host +# credential. Direct custom-image routes still need the profile for OpenClaw. write_auth_profile() { + local provider_key="${NEMOCLAW_INFERENCE_PROVIDER_ID:-${NEMOCLAW_PROVIDER_KEY:-inference}}" + + case "${NEMOCLAW_INFERENCE_BASE_URL:-}" in + https://inference.local | https://inference.local/*) + # Remove only the exact entries this function historically generated. + # Preserve user-managed direct-provider profiles if they share the file. + python3 - <<'PYAUTH' +import json +import os +import stat +import tempfile + +path = os.path.expanduser('~/.openclaw/agents/main/agent/auth-profiles.json') +try: + path_stat = os.lstat(path) +except FileNotFoundError: + raise SystemExit(0) + +if stat.S_ISLNK(path_stat.st_mode): + raise SystemExit('[SECURITY] Refusing auth-profile cleanup through a symlink') + +try: + flags = os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) + descriptor = os.open(path, flags) + with os.fdopen(descriptor, encoding='utf-8') as profile_file: + profiles = json.load(profile_file) +except (OSError, UnicodeError, json.JSONDecodeError): + # Unknown or user-managed state is not ours to replace or delete. + raise SystemExit(0) + +if not isinstance(profiles, dict): + raise SystemExit(0) + +def is_legacy_managed_profile(profile_id, profile): + if not isinstance(profile, dict): + return False + provider = profile.get('provider') + expected_id = f'{provider}:manual' + return profile_id == expected_id and profile == { + 'type': 'api_key', + 'provider': provider, + 'keyRef': {'source': 'env', 'id': 'NVIDIA_INFERENCE_API_KEY'}, + 'profileId': expected_id, + } + +retained = { + profile_id: profile + for profile_id, profile in profiles.items() + if not is_legacy_managed_profile(profile_id, profile) + } +if retained == profiles: + raise SystemExit(0) +if not retained: + os.unlink(path) + raise SystemExit(0) + +directory = os.path.dirname(path) +descriptor, temporary_path = tempfile.mkstemp(prefix='.auth-profiles.', dir=directory) +try: + os.fchmod(descriptor, 0o600) + with os.fdopen(descriptor, 'w', encoding='utf-8') as profile_file: + json.dump(retained, profile_file) + profile_file.flush() + os.fsync(profile_file.fileno()) + os.replace(temporary_path, path) +except BaseException: + try: + os.close(descriptor) + except OSError: + pass + try: + os.unlink(temporary_path) + except FileNotFoundError: + pass + raise +PYAUTH + return + ;; + esac + if [ -z "${NVIDIA_INFERENCE_API_KEY:-}" ] && [ -n "${NVIDIA_API_KEY:-}" ]; then export NVIDIA_INFERENCE_API_KEY="$NVIDIA_API_KEY" fi @@ -2427,7 +2510,6 @@ write_auth_profile() { # through v0.0.89 so pre-existing custom images keep routing. Remove this # fallback in v0.0.90. # See: https://github.com/NVIDIA/NemoClaw/issues/1332 - local provider_key="${NEMOCLAW_INFERENCE_PROVIDER_ID:-${NEMOCLAW_PROVIDER_KEY:-inference}}" python3 - "$provider_key" <<'PYAUTH' import json import os diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts new file mode 100644 index 00000000000..47d9e1842d8 --- /dev/null +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +const START_SCRIPT = path.join( + import.meta.dirname, + "..", + "../../..", + "scripts", + "nemoclaw-start.sh", +); +const WRAPPER = [ + "set -euo pipefail", + `eval "$(sed -n '/^write_auth_profile() {$/,/^}$/p' "$1")"`, + "write_auth_profile", +].join("\n"); + +type AuthFixture = { + home: string; + authPath: string; + status: number; + stderr: string; +}; + +function runWriteAuthProfile( + env: Record, + prepare: (authPath: string) => void = () => undefined, +): AuthFixture { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-boundary-test-")); + const authPath = path.join(home, ".openclaw", "agents", "main", "agent", "auth-profiles.json"); + prepare(authPath); + const result = spawnSync("bash", ["-s", "--", START_SCRIPT], { + input: WRAPPER, + env: { PATH: process.env.PATH, HOME: home, ...env }, + encoding: "utf-8", + }); + return { + home, + authPath, + status: result.status ?? -1, + stderr: result.stderr ?? "", + }; +} + +function seedAuthProfile(profile: Record): (authPath: string) => void { + return (authPath) => { + fs.mkdirSync(path.dirname(authPath), { recursive: true }); + fs.writeFileSync(authPath, JSON.stringify(profile)); + }; +} + +const legacyManagedProfile = { + type: "api_key", + provider: "inference", + keyRef: { source: "env", id: "NVIDIA_INFERENCE_API_KEY" }, + profileId: "inference:manual", +}; + +describe("managed inference auth-profile boundary", () => { + it("does not create an auth profile for the inference.local route", () => { + const fixture = runWriteAuthProfile({ + NVIDIA_INFERENCE_API_KEY: "secret", + NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1", + NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", + }); + try { + expect(fixture.status, fixture.stderr).toBe(0); + expect(fs.existsSync(fixture.authPath)).toBe(false); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); + + it("removes a stale NemoClaw-generated profile from a proxy-routed sandbox", () => { + const fixture = runWriteAuthProfile( + { NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1" }, + seedAuthProfile({ "inference:manual": legacyManagedProfile }), + ); + try { + expect(fixture.status, fixture.stderr).toBe(0); + expect(fs.existsSync(fixture.authPath)).toBe(false); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); + + it("preserves user-managed profiles while removing the stale managed entry", () => { + const customProfile = { + type: "api_key", + provider: "custom", + keyRef: { source: "file", id: "/sandbox/custom-key" }, + profileId: "custom:manual", + }; + const fixture = runWriteAuthProfile( + { NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1" }, + seedAuthProfile({ + "inference:manual": legacyManagedProfile, + "custom:manual": customProfile, + }), + ); + try { + expect(fixture.status, fixture.stderr).toBe(0); + expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ + "custom:manual": customProfile, + }); + expect(fs.statSync(fixture.authPath).mode & 0o777).toBe(0o600); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); +}); From 5c0542dced8cfffefce43e2ef73541698725da9e Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 22 Sep 2026 13:08:49 -0700 Subject: [PATCH 02/35] fix(runtime): harden auth profile cleanup path Signed-off-by: Prekshi Vyas --- scripts/nemoclaw-start.sh | 157 ++++++++++++------ .../runtime/auth-profile-boundary.test.ts | 28 ++++ 2 files changed, 132 insertions(+), 53 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 0d84b4afb11..761a37a90bf 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2424,72 +2424,123 @@ write_auth_profile() { python3 - <<'PYAUTH' import json import os +import secrets import stat -import tempfile +import sys -path = os.path.expanduser('~/.openclaw/agents/main/agent/auth-profiles.json') -try: - path_stat = os.lstat(path) -except FileNotFoundError: - raise SystemExit(0) +profile_name = 'auth-profiles.json' +openclaw_path = os.path.expanduser('~/.openclaw') +directory_flags = os.O_RDONLY | os.O_DIRECTORY | getattr(os, 'O_NOFOLLOW', 0) + +def security_failure(detail): + print(f'[SECURITY] Refusing auth-profile cleanup: {detail}', file=sys.stderr) + raise SystemExit(1) + +def open_profile_directory(): + try: + directory_fd = os.open(openclaw_path, directory_flags) + except FileNotFoundError: + raise SystemExit(0) + except OSError: + security_failure('the .openclaw root is not a trusted directory') -if stat.S_ISLNK(path_stat.st_mode): - raise SystemExit('[SECURITY] Refusing auth-profile cleanup through a symlink') + for component in ('agents', 'main', 'agent'): + try: + child_fd = os.open(component, directory_flags, dir_fd=directory_fd) + except FileNotFoundError: + os.close(directory_fd) + raise SystemExit(0) + except OSError: + os.close(directory_fd) + security_failure(f'{component} is not a trusted directory') + os.close(directory_fd) + directory_fd = child_fd + return directory_fd +directory_fd = open_profile_directory() try: - flags = os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) - descriptor = os.open(path, flags) - with os.fdopen(descriptor, encoding='utf-8') as profile_file: - profiles = json.load(profile_file) -except (OSError, UnicodeError, json.JSONDecodeError): - # Unknown or user-managed state is not ours to replace or delete. - raise SystemExit(0) + try: + profile_fd = os.open( + profile_name, + os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0), + dir_fd=directory_fd, + ) + except FileNotFoundError: + raise SystemExit(0) + except OSError: + security_failure('auth-profiles.json is not a trusted regular file') -if not isinstance(profiles, dict): - raise SystemExit(0) + if not stat.S_ISREG(os.fstat(profile_fd).st_mode): + os.close(profile_fd) + security_failure('auth-profiles.json is not a regular file') -def is_legacy_managed_profile(profile_id, profile): - if not isinstance(profile, dict): - return False - provider = profile.get('provider') - expected_id = f'{provider}:manual' - return profile_id == expected_id and profile == { - 'type': 'api_key', - 'provider': provider, - 'keyRef': {'source': 'env', 'id': 'NVIDIA_INFERENCE_API_KEY'}, - 'profileId': expected_id, - } + try: + with os.fdopen(profile_fd, encoding='utf-8') as profile_file: + profiles = json.load(profile_file) + except (OSError, UnicodeError, json.JSONDecodeError): + # Unknown or user-managed state is not ours to replace or delete. + raise SystemExit(0) + + if not isinstance(profiles, dict): + raise SystemExit(0) -retained = { - profile_id: profile - for profile_id, profile in profiles.items() - if not is_legacy_managed_profile(profile_id, profile) + def is_legacy_managed_profile(profile_id, profile): + if not isinstance(profile, dict): + return False + provider = profile.get('provider') + expected_id = f'{provider}:manual' + return profile_id == expected_id and profile == { + 'type': 'api_key', + 'provider': provider, + 'keyRef': {'source': 'env', 'id': 'NVIDIA_INFERENCE_API_KEY'}, + 'profileId': expected_id, + } + + retained = { + profile_id: profile + for profile_id, profile in profiles.items() + if not is_legacy_managed_profile(profile_id, profile) } -if retained == profiles: - raise SystemExit(0) -if not retained: - os.unlink(path) - raise SystemExit(0) + if retained == profiles: + raise SystemExit(0) + if not retained: + os.unlink(profile_name, dir_fd=directory_fd) + raise SystemExit(0) -directory = os.path.dirname(path) -descriptor, temporary_path = tempfile.mkstemp(prefix='.auth-profiles.', dir=directory) -try: - os.fchmod(descriptor, 0o600) - with os.fdopen(descriptor, 'w', encoding='utf-8') as profile_file: - json.dump(retained, profile_file) - profile_file.flush() - os.fsync(profile_file.fileno()) - os.replace(temporary_path, path) -except BaseException: + temporary_name = f'.auth-profiles.{secrets.token_hex(16)}' try: - os.close(descriptor) + temporary_fd = os.open( + temporary_name, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), + mode=0o600, + dir_fd=directory_fd, + ) except OSError: - pass + security_failure('could not create a private replacement file') + try: - os.unlink(temporary_path) - except FileNotFoundError: - pass - raise + with os.fdopen(temporary_fd, 'w', encoding='utf-8') as profile_file: + json.dump(retained, profile_file) + profile_file.flush() + os.fsync(profile_file.fileno()) + os.replace( + temporary_name, + profile_name, + src_dir_fd=directory_fd, + dst_dir_fd=directory_fd, + ) + except BaseException: + try: + os.close(temporary_fd) + except OSError: + pass + try: + os.unlink(temporary_name, dir_fd=directory_fd) + except FileNotFoundError: + pass + raise +finally: + os.close(directory_fd) PYAUTH return ;; diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index 47d9e1842d8..7fc7f3e3801 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -114,4 +114,32 @@ describe("managed inference auth-profile boundary", () => { fs.rmSync(fixture.home, { recursive: true, force: true }); } }); + + it("rejects a symlinked auth-profile parent without changing its target", () => { + const externalContents = JSON.stringify({ "inference:manual": legacyManagedProfile }); + let externalProfile = ""; + const fixture = runWriteAuthProfile( + { NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1" }, + (authPath) => { + const openclawDir = path.resolve(authPath, "../../../../"); + const externalAgents = path.join(fixtureRoot(authPath), "external-agents"); + externalProfile = path.join(externalAgents, "main", "agent", "auth-profiles.json"); + fs.mkdirSync(path.dirname(externalProfile), { recursive: true }); + fs.writeFileSync(externalProfile, externalContents); + fs.mkdirSync(openclawDir, { recursive: true }); + fs.symlinkSync(externalAgents, path.join(openclawDir, "agents")); + }, + ); + try { + expect(fixture.status).not.toBe(0); + expect(fixture.stderr).toContain("[SECURITY] Refusing auth-profile cleanup"); + expect(fs.readFileSync(externalProfile, "utf-8")).toBe(externalContents); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); }); + +function fixtureRoot(authPath: string): string { + return path.resolve(authPath, "../../../../../"); +} From b8bd2b69ea3fa11d7c57ecfdac928894f114c290 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 22 Sep 2026 14:48:53 -0700 Subject: [PATCH 03/35] fix(runtime): complete credential boundary validation --- ci/test-file-size-budget.json | 2 +- docs/security/process-controls.mdx | 6 +- scripts/nemoclaw-start.sh | 31 ++-- src/lib/agent/base-image.test.ts | 3 +- .../agent/deep-agents-code-base-image.test.ts | 32 ++-- src/lib/agent/deep-agents-code-base-image.ts | 32 ++-- .../runtime/auth-profile-boundary.test.ts | 138 +++++++++++++++++- .../openclaw/runtime/nemoclaw-start.test.ts | 123 +--------------- 8 files changed, 197 insertions(+), 170 deletions(-) diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index 51ee41a8c1f..73cc94d402b 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -7,7 +7,7 @@ "src/lib/onboard/preflight.test.ts": 1875, "test/generation/generate-openclaw-config.test.ts": 1844, "test/installer-integration/install-preflight.test.ts": 2995, - "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 4309, + "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 4188, "test/onboarding/onboard-messaging.test.ts": 1960, "test/onboarding/onboard-selection.test.ts": 4126 } diff --git a/docs/security/process-controls.mdx b/docs/security/process-controls.mdx index fac86b93dd2..4c38a754d16 100644 --- a/docs/security/process-controls.mdx +++ b/docs/security/process-controls.mdx @@ -290,12 +290,12 @@ A registry-side tag change cannot silently select another managed sandbox image. ## Auth Profile Permissions -The entrypoint and migration flows enforce `chmod 600` on all `auth-profiles.json` files under `~/.openclaw`. -This prevents other users on the host from reading stored credentials. +For managed `inference.local` routes, the entrypoint removes the exact legacy NemoClaw-generated profile and clears its credential environment aliases before launching sandbox processes. Direct custom-image routes and user-managed profiles remain in `auth-profiles.json`; the entrypoint and migration flows enforce `chmod 600` on those files under `~/.openclaw`. +This prevents other users on the host from reading stored credentials that remain. | Aspect | Detail | |---|---| -| Default | `600` permissions applied recursively at startup and after migration restores. | +| Default | Managed routes retain no legacy host-credential reference. Remaining auth profiles receive `600` permissions recursively at startup and after migration restores. | | What you can change | This is not a user-facing knob. The entrypoint enforces it. | | Risk if relaxed | Looser permissions let other users or processes on the host read provider API keys and tokens stored in auth profiles. | | Recommendation | No action needed. If you see a `permission denied` error when reading auth profiles, verify that you are running as the same user who created them. | diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 761a37a90bf..73105ba1cfa 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2421,13 +2421,15 @@ write_auth_profile() { https://inference.local | https://inference.local/*) # Remove only the exact entries this function historically generated. # Preserve user-managed direct-provider profiles if they share the file. - python3 - <<'PYAUTH' + python3 - "$provider_key" <<'PYAUTH' import json import os import secrets import stat import sys +provider_key = sys.argv[1] +managed_profile_id = f'{provider_key}:manual' profile_name = 'auth-profiles.json' openclaw_path = os.path.expanduser('~/.openclaw') directory_flags = os.O_RDONLY | os.O_DIRECTORY | getattr(os, 'O_NOFOLLOW', 0) @@ -2485,15 +2487,13 @@ try: raise SystemExit(0) def is_legacy_managed_profile(profile_id, profile): - if not isinstance(profile, dict): + if profile_id != managed_profile_id or not isinstance(profile, dict): return False - provider = profile.get('provider') - expected_id = f'{provider}:manual' - return profile_id == expected_id and profile == { + return profile == { 'type': 'api_key', - 'provider': provider, + 'provider': provider_key, 'keyRef': {'source': 'env', 'id': 'NVIDIA_INFERENCE_API_KEY'}, - 'profileId': expected_id, + 'profileId': managed_profile_id, } retained = { @@ -2582,6 +2582,17 @@ os.chmod(path, 0o600) PYAUTH } +# Managed OpenShell routes authenticate at the host-owned proxy. Remove both +# accepted input aliases from the parent entrypoint environment after profile +# reconciliation succeeds, before any sandbox-user process can inherit them. +clear_managed_inference_credentials() { + case "${NEMOCLAW_INFERENCE_BASE_URL:-}" in + https://inference.local | https://inference.local/*) + unset NVIDIA_INFERENCE_API_KEY NVIDIA_API_KEY + ;; + esac +} + harden_auth_profiles() { if [ -d "${HOME}/.openclaw" ]; then # Enforce 600 for all auth profiles across all agents @@ -5539,6 +5550,9 @@ if [ "$(id -u)" -ne 0 ]; then # Apply manifest-declared runtime env aliases before any child inherits the # env. This covers both one-shot commands and the gateway launch. apply_messaging_runtime_env_aliases + write_auth_profile + clear_managed_inference_credentials + harden_auth_profiles if [ ${#NEMOCLAW_CMD[@]} -gt 0 ]; then install_messaging_runtime_preloads @@ -5577,8 +5591,6 @@ if [ "$(id -u)" -ne 0 ]; then fix_openclaw_ownership normalize_mutable_config_perms seed_default_workspace_templates /sandbox/.openclaw/workspace "" /sandbox/.openclaw/openclaw.json - write_auth_profile - harden_auth_profiles prepare_auto_pair_log @@ -5655,6 +5667,7 @@ verify_messaging_runtime_secret_scans # auth-profiles.json files under ~/.openclaw. See # setup_auth_profile_as_sandbox for the HOME-handling rationale. setup_auth_profile_as_sandbox +clear_managed_inference_credentials # If a command was passed (e.g., "openclaw agent ..."), run it as sandbox user if [ ${#NEMOCLAW_CMD[@]} -gt 0 ]; then diff --git a/src/lib/agent/base-image.test.ts b/src/lib/agent/base-image.test.ts index bf2ae649fbc..6fe3d6f338a 100644 --- a/src/lib/agent/base-image.test.ts +++ b/src/lib/agent/base-image.test.ts @@ -494,10 +494,11 @@ describe("agent base image provisioning", () => { inputPaths: [ "/test/root/agents/langchain-deepagents-code/manifest.yaml", "/test/root/agents/langchain-deepagents-code/requirements.lock", + "/test/root/agents/langchain-deepagents-code/validate-runtime-contract.py", ], validateImage: expect.any(Function), validationDescription: - "deepagents-code==0.1.55, dos2unix, and the immutable security package inventory", + "deepagents-code==0.1.55 runtime contract, dos2unix, and the immutable security package inventory", }), ); }); diff --git a/src/lib/agent/deep-agents-code-base-image.test.ts b/src/lib/agent/deep-agents-code-base-image.test.ts index c74568f04aa..3a8d384f764 100644 --- a/src/lib/agent/deep-agents-code-base-image.test.ts +++ b/src/lib/agent/deep-agents-code-base-image.test.ts @@ -23,8 +23,10 @@ describe("Deep Agents Code base image compatibility", () => { mocks.dockerCapture.mockReset(); }); - it("accepts only the exact installed distribution version (#6456)", () => { - mocks.dockerCapture.mockReturnValueOnce("0.1.55\n").mockReturnValueOnce("0.1.12\n"); + it("accepts only a complete installed runtime contract (#6456)", () => { + mocks.dockerCapture + .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok\n") + .mockReturnValueOnce("0.1.55\n"); expect(deepAgentsCodeBaseImageMatchesVersion("dcode-base:current", "0.1.55")).toBe(true); expect(deepAgentsCodeBaseImageMatchesVersion("dcode-base:stale", "0.1.55")).toBe(false); @@ -40,7 +42,7 @@ describe("Deep Agents Code base image compatibility", () => { "/test/root/agents/langchain-deepagents-code/Dockerfile.base", ); mocks.dockerCapture - .mockReturnValueOnce("9.8.7") + .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok") .mockReturnValueOnce("nemoclaw-dcode-dos2unix-ok") .mockReturnValueOnce("nemoclaw-security-inventory-ok"); @@ -48,9 +50,10 @@ describe("Deep Agents Code base image compatibility", () => { inputPaths: [ "/test/root/agents/langchain-deepagents-code/manifest.yaml", "/test/root/agents/langchain-deepagents-code/requirements.lock", + "/test/root/agents/langchain-deepagents-code/validate-runtime-contract.py", ], validationDescription: - "deepagents-code==9.8.7, dos2unix, and the immutable security package inventory", + "deepagents-code==9.8.7 runtime contract, dos2unix, and the immutable security package inventory", }); expect(options?.validateImage?.("dcode-base:manifest-version")).toBe(true); }); @@ -64,7 +67,9 @@ describe("Deep Agents Code base image compatibility", () => { }), "/test/root/agents/langchain-deepagents-code/Dockerfile.base", ); - mocks.dockerCapture.mockReturnValueOnce("0.1.34").mockReturnValueOnce(""); + mocks.dockerCapture + .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok") + .mockReturnValueOnce(""); expect(options?.validateImage?.("dcode-base:missing-dos2unix")).toBe(false); expect(mocks.dockerCapture).toHaveBeenCalledTimes(2); @@ -101,7 +106,7 @@ describe("Deep Agents Code base image compatibility", () => { "/test/root/agents/langchain-deepagents-code/Dockerfile.base", ); mocks.dockerCapture - .mockReturnValueOnce("0.1.55") + .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok") .mockReturnValueOnce("nemoclaw-dcode-dos2unix-ok") .mockReturnValueOnce(""); @@ -128,8 +133,8 @@ describe("Deep Agents Code base image compatibility", () => { ); }); - it("runs the version probe in a locked-down container (#6456)", () => { - mocks.dockerCapture.mockReturnValue("0.1.55"); + it("runs the runtime contract probe in a locked-down container (#6456)", () => { + mocks.dockerCapture.mockReturnValue("nemoclaw-dcode-runtime-contract-ok"); deepAgentsCodeBaseImageMatchesVersion("dcode-base:current", "0.1.55"); @@ -148,23 +153,24 @@ describe("Deep Agents Code base image compatibility", () => { "/opt/venv/bin/python3", "dcode-base:current", "-I", - "-c", - 'import importlib.metadata; print(importlib.metadata.version("deepagents-code"))', + "/usr/local/lib/nemoclaw/validate-dcode-runtime-contract.py", ], { ignoreError: true, timeout: 20_000 }, ); }); - it("warns and fails closed when the probe returns no version (#6456)", () => { + it("warns and fails closed when the probe returns no contract output (#6456)", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); mocks.dockerCapture.mockReturnValue(""); expect(deepAgentsCodeBaseImageMatchesVersion("dcode-base:unreadable", "0.1.55")).toBe(false); expect(warn).toHaveBeenCalledWith( - expect.stringContaining("dcode-base:unreadable returned no Deep Agents Code version output"), + expect.stringContaining( + "dcode-base:unreadable returned no Deep Agents Code runtime contract output", + ), ); expect(warn).toHaveBeenCalledWith( - expect.stringContaining("the container or metadata probe may have failed"), + expect.stringContaining("the container or contract validator may have failed"), ); expect(warn).toHaveBeenCalledWith(expect.stringContaining("deepagents-code==0.1.55")); warn.mockRestore(); diff --git a/src/lib/agent/deep-agents-code-base-image.ts b/src/lib/agent/deep-agents-code-base-image.ts index dbb84c1b1a9..7cc2fe6189f 100644 --- a/src/lib/agent/deep-agents-code-base-image.ts +++ b/src/lib/agent/deep-agents-code-base-image.ts @@ -9,6 +9,9 @@ import { sandboxBaseImageHasSecurityInventory } from "../sandbox-base-image/secu import type { AgentDefinition } from "./defs"; const DEEPAGENTS_CODE_DISTRIBUTION = "deepagents-code"; +const DEEPAGENTS_CODE_RUNTIME_CONTRACT_PATH = + "/usr/local/lib/nemoclaw/validate-dcode-runtime-contract.py"; +const DEEPAGENTS_CODE_RUNTIME_CONTRACT_OK = "nemoclaw-dcode-runtime-contract-ok"; const DEEPAGENTS_CODE_DOS2UNIX_PROBE_OK = "nemoclaw-dcode-dos2unix-ok"; const DEEPAGENTS_CODE_BASE_IMAGE_PROBE_GUARDS = [ "--network", @@ -26,10 +29,10 @@ type DeepAgentsCodeResolutionOptions = Pick< >; /** - * Reject a published or cached Deep Agents Code base whose installed package - * does not match the active manifest. The final image patchers intentionally - * require this exact source pairing, so accepting a merely runnable older base - * only defers the failure until the expensive final-image build (#6456). + * Reject a published or cached Deep Agents Code base whose installed runtime + * does not satisfy the active contract. The final image intentionally reruns + * this validator, so probing it here prevents a stale base from failing only + * after the expensive final-image build (#6456). */ export function deepAgentsCodeBaseImageMatchesVersion( imageRef: string, @@ -44,21 +47,20 @@ export function deepAgentsCodeBaseImageMatchesVersion( "/opt/venv/bin/python3", imageRef, "-I", - "-c", - `import importlib.metadata; print(importlib.metadata.version("${DEEPAGENTS_CODE_DISTRIBUTION}"))`, + DEEPAGENTS_CODE_RUNTIME_CONTRACT_PATH, ], { ignoreError: true, timeout: 20_000 }, ); - const installedVersion = output.trim(); - if (!installedVersion) { + const contractOutput = output.trim(); + if (!contractOutput) { console.warn( - ` Warning: ${imageRef} returned no Deep Agents Code version output; ` + - "the container or metadata probe may have failed. " + + ` Warning: ${imageRef} returned no Deep Agents Code runtime contract output; ` + + "the container or contract validator may have failed. " + `Rejecting the base image (expected ${DEEPAGENTS_CODE_DISTRIBUTION}==${expectedVersion}).`, ); return false; } - return installedVersion === expectedVersion; + return contractOutput === DEEPAGENTS_CODE_RUNTIME_CONTRACT_OK; } /** @@ -106,13 +108,17 @@ export function createDeepAgentsCodeBaseImageResolutionOptions( return { // Retain the resolver's pre-existing global inputs alongside these agent // inputs. Per-agent cache-policy isolation is a separate cross-agent change. - inputPaths: [path.join(agentRoot, "manifest.yaml"), path.join(agentRoot, "requirements.lock")], + inputPaths: [ + path.join(agentRoot, "manifest.yaml"), + path.join(agentRoot, "requirements.lock"), + path.join(agentRoot, "validate-runtime-contract.py"), + ], validateImage: (imageRef) => deepAgentsCodeBaseImageMatchesVersion(imageRef, expectedVersion) && deepAgentsCodeBaseImageHasDos2Unix(imageRef) && sandboxBaseImageHasSecurityInventory(imageRef), validationDescription: - `${DEEPAGENTS_CODE_DISTRIBUTION}==${expectedVersion}, dos2unix, and ` + + `${DEEPAGENTS_CODE_DISTRIBUTION}==${expectedVersion} runtime contract, dos2unix, and ` + "the immutable security package inventory", }; } diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index 7fc7f3e3801..fff1472065d 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -18,13 +18,17 @@ const START_SCRIPT = path.join( const WRAPPER = [ "set -euo pipefail", `eval "$(sed -n '/^write_auth_profile() {$/,/^}$/p' "$1")"`, + `eval "$(sed -n '/^clear_managed_inference_credentials() {$/,/^}$/p' "$1")"`, "write_auth_profile", + "clear_managed_inference_credentials", + 'bash -c \'printf "NVIDIA_INFERENCE_API_KEY=%s\\\\nNVIDIA_API_KEY=%s\\\\n" "${NVIDIA_INFERENCE_API_KEY-unset}" "${NVIDIA_API_KEY-unset}"\'', ].join("\n"); type AuthFixture = { home: string; authPath: string; status: number; + stdout: string; stderr: string; }; @@ -32,7 +36,7 @@ function runWriteAuthProfile( env: Record, prepare: (authPath: string) => void = () => undefined, ): AuthFixture { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-boundary-test-")); + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-test-")); const authPath = path.join(home, ".openclaw", "agents", "main", "agent", "auth-profiles.json"); prepare(authPath); const result = spawnSync("bash", ["-s", "--", START_SCRIPT], { @@ -44,6 +48,7 @@ function runWriteAuthProfile( home, authPath, status: result.status ?? -1, + stdout: result.stdout ?? "", stderr: result.stderr ?? "", }; } @@ -62,7 +67,90 @@ const legacyManagedProfile = { profileId: "inference:manual", }; -describe("managed inference auth-profile boundary", () => { +describe("write_auth_profile (#1332)", () => { + it("writes profile under the route identifier from NEMOCLAW_INFERENCE_PROVIDER_ID", () => { + const fixture = runWriteAuthProfile({ + NVIDIA_INFERENCE_API_KEY: "secret", + NEMOCLAW_INFERENCE_PROVIDER_ID: "openai", + }); + try { + expect(fixture.status, fixture.stderr).toBe(0); + expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ + "openai:manual": { + type: "api_key", + provider: "openai", + keyRef: { source: "env", id: "NVIDIA_INFERENCE_API_KEY" }, + profileId: "openai:manual", + }, + }); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); + + it("falls back to 'inference' when neither route identifier is set", () => { + const fixture = runWriteAuthProfile({ NVIDIA_INFERENCE_API_KEY: "secret" }); + try { + expect(fixture.status, fixture.stderr).toBe(0); + const profile = JSON.parse(fs.readFileSync(fixture.authPath, "utf-8")); + expect(profile).toHaveProperty("inference:manual"); + expect(profile["inference:manual"].provider).toBe("inference"); + expect(profile).not.toHaveProperty("nvidia:manual"); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); + + it("does not use 'nvidia' as the default provider key", () => { + const fixture = runWriteAuthProfile({ NVIDIA_INFERENCE_API_KEY: "secret" }); + try { + expect(fixture.status).toBe(0); + const profile = JSON.parse(fs.readFileSync(fixture.authPath, "utf-8")); + expect(Object.keys(profile).every((key) => !/^nvidia:/.test(key))).toBe(true); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); + + it("treats provider_key as a literal (no shell command substitution)", () => { + const fixture = runWriteAuthProfile({ + NVIDIA_INFERENCE_API_KEY: "secret", + NEMOCLAW_INFERENCE_PROVIDER_ID: "$(echo pwned)", + }); + try { + expect(fixture.status, fixture.stderr).toBe(0); + const profile = JSON.parse(fs.readFileSync(fixture.authPath, "utf-8")); + expect(profile).toHaveProperty("$(echo pwned):manual"); + expect(profile["$(echo pwned):manual"].provider).toBe("$(echo pwned)"); + expect(profile).not.toHaveProperty("pwned:manual"); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); + + it("is a no-op when NVIDIA_INFERENCE_API_KEY is unset", () => { + const fixture = runWriteAuthProfile({}); + try { + expect(fixture.status).toBe(0); + expect(fs.existsSync(fixture.authPath)).toBe(false); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); + + it("writes the auth profile with 0600 permissions", () => { + const fixture = runWriteAuthProfile({ + NVIDIA_INFERENCE_API_KEY: "secret", + NEMOCLAW_INFERENCE_PROVIDER_ID: "openai", + }); + try { + expect(fixture.status).toBe(0); + expect(fs.statSync(fixture.authPath).mode & 0o777).toBe(0o600); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); + it("does not create an auth profile for the inference.local route", () => { const fixture = runWriteAuthProfile({ NVIDIA_INFERENCE_API_KEY: "secret", @@ -94,7 +182,7 @@ describe("managed inference auth-profile boundary", () => { const customProfile = { type: "api_key", provider: "custom", - keyRef: { source: "file", id: "/sandbox/custom-key" }, + keyRef: { source: "env", id: "NVIDIA_INFERENCE_API_KEY" }, profileId: "custom:manual", }; const fixture = runWriteAuthProfile( @@ -115,6 +203,41 @@ describe("managed inference auth-profile boundary", () => { } }); + it("preserves a near-match user-managed profile for the managed provider", () => { + const userManagedProfile = { ...legacyManagedProfile, label: "user-managed" }; + const original = JSON.stringify({ "inference:manual": userManagedProfile }); + const fixture = runWriteAuthProfile( + { NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1" }, + (authPath) => { + fs.mkdirSync(path.dirname(authPath), { recursive: true }); + fs.writeFileSync(authPath, original); + }, + ); + try { + expect(fixture.status, fixture.stderr).toBe(0); + expect(fs.readFileSync(fixture.authPath, "utf-8")).toBe(original); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); + + it("clears both managed credential aliases before a child process starts", () => { + const fixture = runWriteAuthProfile({ + NVIDIA_INFERENCE_API_KEY: "primary-secret", + NVIDIA_API_KEY: "legacy-secret", + NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1", + }); + try { + expect(fixture.status, fixture.stderr).toBe(0); + expect(fixture.stdout).toContain("NVIDIA_INFERENCE_API_KEY=unset"); + expect(fixture.stdout).toContain("NVIDIA_API_KEY=unset"); + expect(fixture.stdout).not.toContain("primary-secret"); + expect(fixture.stdout).not.toContain("legacy-secret"); + } finally { + fs.rmSync(fixture.home, { recursive: true, force: true }); + } + }); + it("rejects a symlinked auth-profile parent without changing its target", () => { const externalContents = JSON.stringify({ "inference:manual": legacyManagedProfile }); let externalProfile = ""; @@ -122,7 +245,10 @@ describe("managed inference auth-profile boundary", () => { { NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1" }, (authPath) => { const openclawDir = path.resolve(authPath, "../../../../"); - const externalAgents = path.join(fixtureRoot(authPath), "external-agents"); + const externalAgents = path.join( + path.resolve(authPath, "../../../../../"), + "external-agents", + ); externalProfile = path.join(externalAgents, "main", "agent", "auth-profiles.json"); fs.mkdirSync(path.dirname(externalProfile), { recursive: true }); fs.writeFileSync(externalProfile, externalContents); @@ -139,7 +265,3 @@ describe("managed inference auth-profile boundary", () => { } }); }); - -function fixtureRoot(authPath: string): string { - return path.resolve(authPath, "../../../../../"); -} diff --git a/test/agents/openclaw/runtime/nemoclaw-start.test.ts b/test/agents/openclaw/runtime/nemoclaw-start.test.ts index 423163a1844..ed6a0f0bfdc 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start.test.ts @@ -3005,6 +3005,7 @@ describe("Telegram diagnostics (#2766)", () => { "seed_default_workspace_templates() { :; }", "seed_default_workspace_templates_as_sandbox() { seed_default_workspace_templates; }", "write_auth_profile() { :; }", + "clear_managed_inference_credentials() { :; }", "harden_auth_profiles() { :; }", "run_step_down_as_sandbox() { :; }", "setup_auth_profile_as_sandbox() { :; }", @@ -3296,128 +3297,6 @@ process.stderr.write('FailoverError: token=123456:LATER\\n'); }); }); -describe("write_auth_profile (#1332)", () => { - // Invokes write_auth_profile from the production start script in an isolated - // HOME, then asserts on the resulting auth-profiles.json — observable - // behavior, not source-text shape. - const wrapper = [ - "set -euo pipefail", - `eval "$(sed -n '/^write_auth_profile() {$/,/^}$/p' "$1")"`, - "write_auth_profile", - ].join("\n"); - - function runWriteAuthProfile(env: Record): { - home: string; - authPath: string; - status: number; - stderr: string; - } { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-test-")); - const result = spawnSync("bash", ["-s", "--", START_SCRIPT], { - input: wrapper, - env: { PATH: process.env.PATH, HOME: home, ...env }, - encoding: "utf-8", - }); - return { - home, - authPath: path.join(home, ".openclaw", "agents", "main", "agent", "auth-profiles.json"), - status: result.status ?? -1, - stderr: result.stderr ?? "", - }; - } - - it("writes profile under the route identifier from NEMOCLAW_INFERENCE_PROVIDER_ID", () => { - const { home, authPath, status, stderr } = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - NEMOCLAW_INFERENCE_PROVIDER_ID: "openai", - }); - try { - expect(status, stderr).toBe(0); - const profile = JSON.parse(fs.readFileSync(authPath, "utf-8")); - expect(profile).toEqual({ - "openai:manual": { - type: "api_key", - provider: "openai", - keyRef: { source: "env", id: "NVIDIA_INFERENCE_API_KEY" }, - profileId: "openai:manual", - }, - }); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("falls back to 'inference' when neither route identifier is set", () => { - const { home, authPath, status, stderr } = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - }); - try { - expect(status, stderr).toBe(0); - const profile = JSON.parse(fs.readFileSync(authPath, "utf-8")); - expect(profile).toHaveProperty("inference:manual"); - expect(profile["inference:manual"].provider).toBe("inference"); - expect(profile).not.toHaveProperty("nvidia:manual"); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("does not use 'nvidia' as the default provider key", () => { - const { home, authPath, status } = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - }); - try { - expect(status).toBe(0); - const profile = JSON.parse(fs.readFileSync(authPath, "utf-8")); - expect(Object.keys(profile).every((key) => !/^nvidia:/.test(key))).toBe(true); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("treats provider_key as a literal (no shell command substitution)", () => { - // If the provider_key were interpolated into the heredoc instead of - // passed as argv, $(...) inside the value would execute and replace it. - const { home, authPath, status, stderr } = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - NEMOCLAW_INFERENCE_PROVIDER_ID: "$(echo pwned)", - }); - try { - expect(status, stderr).toBe(0); - const profile = JSON.parse(fs.readFileSync(authPath, "utf-8")); - expect(profile).toHaveProperty("$(echo pwned):manual"); - expect(profile["$(echo pwned):manual"].provider).toBe("$(echo pwned)"); - expect(profile).not.toHaveProperty("pwned:manual"); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("is a no-op when NVIDIA_INFERENCE_API_KEY is unset", () => { - const { home, authPath, status } = runWriteAuthProfile({}); - try { - expect(status).toBe(0); - expect(fs.existsSync(authPath)).toBe(false); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - - it("writes the auth profile with 0600 permissions", () => { - const { home, authPath, status } = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - NEMOCLAW_INFERENCE_PROVIDER_ID: "openai", - }); - try { - expect(status).toBe(0); - const mode = fs.statSync(authPath).mode & 0o777; - expect(mode).toBe(0o600); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); -}); - // Recover truncated config from native last-good state or the protected baseline (#3118). describe("openclaw.json baseline + recovery (#3118)", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); From d79c1cf1eb350f59ce3e7caa47090e7a83e4a3ab Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 22 Sep 2026 15:34:16 -0700 Subject: [PATCH 04/35] fix(runtime): bind resolver and startup contracts --- docs/security/process-controls.mdx | 2 +- .../agent/deep-agents-code-base-image.test.ts | 19 ++++-- src/lib/agent/deep-agents-code-base-image.ts | 11 +++- .../runtime/auth-profile-boundary.test.ts | 62 +++++++++++++++++++ 4 files changed, 85 insertions(+), 9 deletions(-) diff --git a/docs/security/process-controls.mdx b/docs/security/process-controls.mdx index 4c38a754d16..079d8c33b88 100644 --- a/docs/security/process-controls.mdx +++ b/docs/security/process-controls.mdx @@ -290,7 +290,7 @@ A registry-side tag change cannot silently select another managed sandbox image. ## Auth Profile Permissions -For managed `inference.local` routes, the entrypoint removes the exact legacy NemoClaw-generated profile and clears its credential environment aliases before launching sandbox processes. Direct custom-image routes and user-managed profiles remain in `auth-profiles.json`; the entrypoint and migration flows enforce `chmod 600` on those files under `~/.openclaw`. +For managed `inference.local` routes, the entrypoint removes the exact legacy NemoClaw-generated profile, preserves non-matching user-managed profiles, and clears credential environment aliases before launching sandbox processes. Direct custom-image routes create or replace `auth-profiles.json` with the generated direct-route profile. The entrypoint and migration flows enforce `chmod 600` on auth-profile files under `~/.openclaw`. This prevents other users on the host from reading stored credentials that remain. | Aspect | Detail | diff --git a/src/lib/agent/deep-agents-code-base-image.test.ts b/src/lib/agent/deep-agents-code-base-image.test.ts index 3a8d384f764..692b46df297 100644 --- a/src/lib/agent/deep-agents-code-base-image.test.ts +++ b/src/lib/agent/deep-agents-code-base-image.test.ts @@ -25,13 +25,19 @@ describe("Deep Agents Code base image compatibility", () => { it("accepts only a complete installed runtime contract (#6456)", () => { mocks.dockerCapture - .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok\n") + .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok\n0.1.55\n") .mockReturnValueOnce("0.1.55\n"); expect(deepAgentsCodeBaseImageMatchesVersion("dcode-base:current", "0.1.55")).toBe(true); expect(deepAgentsCodeBaseImageMatchesVersion("dcode-base:stale", "0.1.55")).toBe(false); }); + it("rejects a valid runtime contract for a different manifest version (#6456)", () => { + mocks.dockerCapture.mockReturnValue("nemoclaw-dcode-runtime-contract-ok\n0.1.55\n"); + + expect(deepAgentsCodeBaseImageMatchesVersion("dcode-base:mismatched", "0.1.56")).toBe(false); + }); + it("binds the manifest version and source files into resolution options (#6456)", () => { const options = createDeepAgentsCodeBaseImageResolutionOptions( makeAgent({ @@ -42,7 +48,7 @@ describe("Deep Agents Code base image compatibility", () => { "/test/root/agents/langchain-deepagents-code/Dockerfile.base", ); mocks.dockerCapture - .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok") + .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok\n9.8.7") .mockReturnValueOnce("nemoclaw-dcode-dos2unix-ok") .mockReturnValueOnce("nemoclaw-security-inventory-ok"); @@ -68,7 +74,7 @@ describe("Deep Agents Code base image compatibility", () => { "/test/root/agents/langchain-deepagents-code/Dockerfile.base", ); mocks.dockerCapture - .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok") + .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok\n0.1.34") .mockReturnValueOnce(""); expect(options?.validateImage?.("dcode-base:missing-dos2unix")).toBe(false); @@ -106,7 +112,7 @@ describe("Deep Agents Code base image compatibility", () => { "/test/root/agents/langchain-deepagents-code/Dockerfile.base", ); mocks.dockerCapture - .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok") + .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok\n0.1.55") .mockReturnValueOnce("nemoclaw-dcode-dos2unix-ok") .mockReturnValueOnce(""); @@ -134,7 +140,7 @@ describe("Deep Agents Code base image compatibility", () => { }); it("runs the runtime contract probe in a locked-down container (#6456)", () => { - mocks.dockerCapture.mockReturnValue("nemoclaw-dcode-runtime-contract-ok"); + mocks.dockerCapture.mockReturnValue("nemoclaw-dcode-runtime-contract-ok\n0.1.55"); deepAgentsCodeBaseImageMatchesVersion("dcode-base:current", "0.1.55"); @@ -153,7 +159,8 @@ describe("Deep Agents Code base image compatibility", () => { "/opt/venv/bin/python3", "dcode-base:current", "-I", - "/usr/local/lib/nemoclaw/validate-dcode-runtime-contract.py", + "-c", + 'import importlib.metadata; import runpy; runpy.run_path("/usr/local/lib/nemoclaw/validate-dcode-runtime-contract.py", run_name="__main__"); print(importlib.metadata.version("deepagents-code"))', ], { ignoreError: true, timeout: 20_000 }, ); diff --git a/src/lib/agent/deep-agents-code-base-image.ts b/src/lib/agent/deep-agents-code-base-image.ts index 7cc2fe6189f..60d39d98ca4 100644 --- a/src/lib/agent/deep-agents-code-base-image.ts +++ b/src/lib/agent/deep-agents-code-base-image.ts @@ -12,6 +12,12 @@ const DEEPAGENTS_CODE_DISTRIBUTION = "deepagents-code"; const DEEPAGENTS_CODE_RUNTIME_CONTRACT_PATH = "/usr/local/lib/nemoclaw/validate-dcode-runtime-contract.py"; const DEEPAGENTS_CODE_RUNTIME_CONTRACT_OK = "nemoclaw-dcode-runtime-contract-ok"; +const DEEPAGENTS_CODE_RUNTIME_CONTRACT_PROBE = [ + "import importlib.metadata", + "import runpy", + `runpy.run_path("${DEEPAGENTS_CODE_RUNTIME_CONTRACT_PATH}", run_name="__main__")`, + `print(importlib.metadata.version("${DEEPAGENTS_CODE_DISTRIBUTION}"))`, +].join("; "); const DEEPAGENTS_CODE_DOS2UNIX_PROBE_OK = "nemoclaw-dcode-dos2unix-ok"; const DEEPAGENTS_CODE_BASE_IMAGE_PROBE_GUARDS = [ "--network", @@ -47,7 +53,8 @@ export function deepAgentsCodeBaseImageMatchesVersion( "/opt/venv/bin/python3", imageRef, "-I", - DEEPAGENTS_CODE_RUNTIME_CONTRACT_PATH, + "-c", + DEEPAGENTS_CODE_RUNTIME_CONTRACT_PROBE, ], { ignoreError: true, timeout: 20_000 }, ); @@ -60,7 +67,7 @@ export function deepAgentsCodeBaseImageMatchesVersion( ); return false; } - return contractOutput === DEEPAGENTS_CODE_RUNTIME_CONTRACT_OK; + return contractOutput === `${DEEPAGENTS_CODE_RUNTIME_CONTRACT_OK}\n${expectedVersion}`; } /** diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index fff1472065d..5cef74307c9 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -15,6 +15,7 @@ const START_SCRIPT = path.join( "scripts", "nemoclaw-start.sh", ); +const START_SOURCE = fs.readFileSync(START_SCRIPT, "utf-8"); const WRAPPER = [ "set -euo pipefail", `eval "$(sed -n '/^write_auth_profile() {$/,/^}$/p' "$1")"`, @@ -60,6 +61,54 @@ function seedAuthProfile(profile: Record): (authPath: string) = }; } +function startupCredentialBoundaryBlock(kind: "non-root" | "root"): string { + const regionStart = START_SOURCE.indexOf( + kind === "non-root" + ? "# ── Non-root fallback" + : "# ── Root path (full privilege separation via setpriv)", + ); + const startMarker = + kind === "non-root" + ? " apply_messaging_runtime_env_aliases\n" + : "setup_auth_profile_as_sandbox\n"; + const endMarker = + kind === "non-root" ? "\n configure_messaging_channels" : "\nprepare_auto_pair_log"; + const start = START_SOURCE.indexOf(startMarker, regionStart); + const end = START_SOURCE.indexOf(endMarker, start); + expect( + regionStart !== -1 && start !== -1 && end !== -1 && end > start, + `Expected ${kind} credential-boundary block in scripts/nemoclaw-start.sh`, + ).toBe(true); + return START_SOURCE.slice(start, end); +} + +function runStartupCredentialBoundary(kind: "non-root" | "root") { + const wrapper = [ + "set -euo pipefail", + `eval "$(sed -n '/^clear_managed_inference_credentials() {$/,/^}$/p' "$1")"`, + "NEMOCLAW_CMD=(probe)", + "STEP_DOWN_PREFIX_SANDBOX=(env)", + "apply_messaging_runtime_env_aliases() { :; }", + "write_auth_profile() { :; }", + "harden_auth_profiles() { :; }", + "setup_auth_profile_as_sandbox() { :; }", + "install_messaging_runtime_preloads() { :; }", + "verify_messaging_runtime_secret_scans() { :; }", + 'run_oneshot_command() { bash -c \'printf "NVIDIA_INFERENCE_API_KEY=%s\\\\nNVIDIA_API_KEY=%s\\\\n" "${NVIDIA_INFERENCE_API_KEY-unset}" "${NVIDIA_API_KEY-unset}"\'; }', + startupCredentialBoundaryBlock(kind), + ].join("\n"); + return spawnSync("bash", ["-s", "--", START_SCRIPT], { + input: wrapper, + env: { + PATH: process.env.PATH, + NVIDIA_INFERENCE_API_KEY: "primary-secret", + NVIDIA_API_KEY: "legacy-secret", + NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1", + }, + encoding: "utf-8", + }); +} + const legacyManagedProfile = { type: "api_key", provider: "inference", @@ -238,6 +287,19 @@ describe("write_auth_profile (#1332)", () => { } }); + it.each(["non-root", "root"] as const)( + "clears both managed credential aliases in the %s startup ordering before one-shot execution", + (kind) => { + const result = runStartupCredentialBoundary(kind); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain("NVIDIA_INFERENCE_API_KEY=unset"); + expect(result.stdout).toContain("NVIDIA_API_KEY=unset"); + expect(result.stdout).not.toContain("primary-secret"); + expect(result.stdout).not.toContain("legacy-secret"); + }, + ); + it("rejects a symlinked auth-profile parent without changing its target", () => { const externalContents = JSON.stringify({ "inference:manual": legacyManagedProfile }); let externalProfile = ""; From 6903dec5c07128739f7141d99544db2ebda2e21e Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 22 Sep 2026 18:33:49 -0700 Subject: [PATCH 05/35] test(e2e): retry empty provider responses --- test/e2e/live/launch-agent-turn.ts | 13 +++++++ ...h-agent-turn-provider-availability.test.ts | 39 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 1f6f67d12ed..c855839b4a7 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -1472,6 +1472,17 @@ fail_provider_unavailable() { fail_launch_session "launch did not record the required structured session turns" } +# OpenClaw can persist a structurally complete assistant record before the +# provider supplies any content. Treat only that exact, bounded diagnostic as +# a provider-response transient. The fresh-session retry below is safe because +# cleanup removes the baseline and PTY monitor before emitting the marker. +is_retryable_empty_message_evidence() { + awk ' + NR == 1 && /^\{"reason":"message_content_empty","sessionId":"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"\}$/ { matched = 1 } + END { exit !(NR == 1 && matched == 1) } + ' "$evidence_error" +} + session_evidence() { local mode="$1" local expected_turns="" @@ -1517,6 +1528,7 @@ wait_for_turn_count() { fi if [[ "$evidence_status" != 1 ]]; then case "$evidence_status" in + 2) is_retryable_empty_message_evidence && fail_provider_unavailable ;; 3) fail_provider_unavailable ;; esac fail_launch_session \ @@ -1671,6 +1683,7 @@ if session_evidence qualify 2 >/dev/null 2>"$evidence_error"; then else evidence_status=$? case "$evidence_status" in + 2) is_retryable_empty_message_evidence && fail_provider_unavailable ;; 3) fail_provider_unavailable ;; esac fail_launch_session "launch final structured session evidence did not qualify (status $evidence_status)" diff --git a/test/e2e/support/launch-agent-turn-provider-availability.test.ts b/test/e2e/support/launch-agent-turn-provider-availability.test.ts index f7c73cc1fea..33176ff2036 100644 --- a/test/e2e/support/launch-agent-turn-provider-availability.test.ts +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -64,6 +64,45 @@ it.each(["500", "503"] as const)( }, ); +it("retries an exact empty assistant provider response in a fresh launch session", async () => { + const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.useFakeTimers(); + const calls: Array<{ artifactName?: string; env?: NodeJS.ProcessEnv }> = []; + const host = { + command: async ( + _command: string, + _args: string[], + options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, + ) => { + calls.push({ artifactName: options?.artifactName, env: options?.env }); + return calls.length === 1 + ? { + exitCode: 1, + signal: null, + stderr: `launch did not record the required structured session turns\n{"reason":"message_content_empty","sessionId":"ed80ef8e-a026-424f-8ca4-669f6060e046"}\n\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, + stdout: "", + } + : { exitCode: 0, signal: null, stderr: "", stdout: "" }; + }, + openshellCommandPath: "/usr/bin/openshell", + }; + + try { + const launch = runOpenClawLaunchSession(launchOptions(host)); + await vi.advanceTimersByTimeAsync(1_000); + const result = await launch; + expect(result.exitCode).toBe(0); + expect(calls.map((call) => call.artifactName)).toEqual([ + "provider-turn", + "provider-turn-provider-retry-02", + ]); + expect(new Set(calls.map((call) => call.env?.NEMOCLAW_LAUNCH_RUN_ID)).size).toBe(2); + } finally { + vi.useRealTimers(); + platform.mockRestore(); + } +}); + it("classifies exhausted transient launch attempts as provider unavailable (#10978)", async () => { const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); vi.useFakeTimers(); From 4eca3dcb71bbcfd2a5f4407fd049b245d416a683 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 22 Sep 2026 19:55:06 -0700 Subject: [PATCH 06/35] test(e2e): classify wrapped empty responses --- test/e2e/live/launch-agent-turn.ts | 12 +++++++----- test/e2e/support/launch-agent-turn.test.ts | 10 ++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index c855839b4a7..47cabe0814d 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -1526,11 +1526,13 @@ wait_for_turn_count() { else evidence_status=$? fi + # OpenShell normalizes a nonzero sandbox child status to 1. Classify the + # exact bounded diagnostic for both the direct and transport-level status. + case "$evidence_status" in + 1|2) is_retryable_empty_message_evidence && fail_provider_unavailable ;; + 3) fail_provider_unavailable ;; + esac if [[ "$evidence_status" != 1 ]]; then - case "$evidence_status" in - 2) is_retryable_empty_message_evidence && fail_provider_unavailable ;; - 3) fail_provider_unavailable ;; - esac fail_launch_session \ "structured session evidence was invalid or unavailable (status $evidence_status)" fi @@ -1683,7 +1685,7 @@ if session_evidence qualify 2 >/dev/null 2>"$evidence_error"; then else evidence_status=$? case "$evidence_status" in - 2) is_retryable_empty_message_evidence && fail_provider_unavailable ;; + 1|2) is_retryable_empty_message_evidence && fail_provider_unavailable ;; 3) fail_provider_unavailable ;; esac fail_launch_session "launch final structured session evidence did not qualify (status $evidence_status)" diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index 5fdc597bb48..009a3aeaa9d 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -446,6 +446,16 @@ if [[ ( "$NEMOCLAW_FIXTURE_MODE" == "delayed-recording" || "$NEMOCLAW_FIXTURE_MO [[ "$NEMOCLAW_FIXTURE_MODE" != "provider-exit-after-recording" ]] || sleep 0.2 exit "$status" fi +if [[ "$NEMOCLAW_FIXTURE_MODE" == "provider-empty-message" && "$4" == "qualify" ]]; then + set +e + "$@" + status=$? + set -e + [[ "$status" == "0" ]] && exit 0 + # Match OpenShell's sandbox-exec boundary, which reports any nonzero child + # status as a generic 1 while preserving the child's stderr diagnostic. + exit 1 +fi exec "$@" `, ); From 6a5ca6b1a2bb63ed2e2bc318a23ac12adaed7a32 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 22 Sep 2026 20:29:27 -0700 Subject: [PATCH 07/35] test(e2e): preserve wrapped provider diagnostics --- test/e2e/live/launch-agent-turn.ts | 14 +++++++------- test/e2e/support/launch-agent-turn.test.ts | 8 +++++++- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 47cabe0814d..f0fc6da0dd9 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -1472,13 +1472,13 @@ fail_provider_unavailable() { fail_launch_session "launch did not record the required structured session turns" } -# OpenClaw can persist a structurally complete assistant record before the -# provider supplies any content. Treat only that exact, bounded diagnostic as -# a provider-response transient. The fresh-session retry below is safe because +# OpenClaw can persist either a structurally complete provider error or an +# assistant record without content. Treat only those exact, bounded diagnostics +# as provider-response transients. The fresh-session retry below is safe because # cleanup removes the baseline and PTY monitor before emitting the marker. -is_retryable_empty_message_evidence() { +is_retryable_provider_evidence() { awk ' - NR == 1 && /^\{"reason":"message_content_empty","sessionId":"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"\}$/ { matched = 1 } + NR == 1 && /^\{"reason":"(message_content_empty|provider_unavailable)","sessionId":"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"\}$/ { matched = 1 } END { exit !(NR == 1 && matched == 1) } ' "$evidence_error" } @@ -1529,7 +1529,7 @@ wait_for_turn_count() { # OpenShell normalizes a nonzero sandbox child status to 1. Classify the # exact bounded diagnostic for both the direct and transport-level status. case "$evidence_status" in - 1|2) is_retryable_empty_message_evidence && fail_provider_unavailable ;; + 1|2) is_retryable_provider_evidence && fail_provider_unavailable ;; 3) fail_provider_unavailable ;; esac if [[ "$evidence_status" != 1 ]]; then @@ -1685,7 +1685,7 @@ if session_evidence qualify 2 >/dev/null 2>"$evidence_error"; then else evidence_status=$? case "$evidence_status" in - 1|2) is_retryable_empty_message_evidence && fail_provider_unavailable ;; + 1|2) is_retryable_provider_evidence && fail_provider_unavailable ;; 3) fail_provider_unavailable ;; esac fail_launch_session "launch final structured session evidence did not qualify (status $evidence_status)" diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index 009a3aeaa9d..dc943314faf 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -492,7 +492,12 @@ exec "$@" NEMOCLAW_FIXTURE_PTY_MONITOR_ROOT: ptyMonitorRoot, NEMOCLAW_FIXTURE_PTY_PATH_UNREADABLE_MARKER: ptyPathUnreadableMarker, NEMOCLAW_FIXTURE_PTY_SOCKET_RECEIPT: ptySocketReceiptPath, - NEMOCLAW_FIXTURE_SESSION_FILE: join(sessionRoot, "session-a.jsonl"), + NEMOCLAW_FIXTURE_SESSION_FILE: join( + sessionRoot, + mode === "provider-empty-message" + ? "ed80ef8e-a026-424f-8ca4-669f6060e046.jsonl" + : "session-a.jsonl", + ), NEMOCLAW_FIXTURE_TERMINAL_COPY: terminalCopy, NEMOCLAW_FIXTURE_RUN_ID: runId, NEMOCLAW_FIXTURE_TUI_PIDS: tuiPidsPath, @@ -1072,6 +1077,7 @@ it.runIf(process.platform === "linux").concurrent( expect(result.status).toBe(1); expect(result.stderr).toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); }, + testTimeout(30_000), ); it.runIf(process.platform === "linux").each([ From 167fa5def39d4a03888b2fa0bde327499b648e8a Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 22 Sep 2026 22:00:03 -0700 Subject: [PATCH 08/35] test(e2e): retry transient sandbox inference --- test/e2e/live/full-e2e-inference-probe.ts | 29 +++++++++- .../support/full-e2e-inference-probe.test.ts | 54 ++++++++++++++++++- 2 files changed, 79 insertions(+), 4 deletions(-) diff --git a/test/e2e/live/full-e2e-inference-probe.ts b/test/e2e/live/full-e2e-inference-probe.ts index e73cf9e38b7..22ace98dcd0 100644 --- a/test/e2e/live/full-e2e-inference-probe.ts +++ b/test/e2e/live/full-e2e-inference-probe.ts @@ -9,6 +9,7 @@ const ARITHMETIC_PROMPT = "What is 6 multiplied by 7? Reply with only the intege export const FULL_E2E_INFERENCE_REPLY_BUDGETS = [512, 1024] as const; export const FULL_E2E_INFERENCE_CAPTURE_LIMIT_BYTES = 256 * 1024; export const FULL_E2E_INFERENCE_EVIDENCE_LIMIT_BYTES = 32 * 1024; +export const FULL_E2E_INFERENCE_TRANSIENT_RETRY_DELAY_MS = 5_000; const EVIDENCE_TEXT_LIMIT_BYTES = 4 * 1024; const EVIDENCE_PARSE_ERROR_LIMIT_BYTES = 2 * 1024; @@ -67,6 +68,10 @@ export interface FullE2eInferenceAttemptInput { requestBody: string; } +export interface FullE2eInferenceProbeOptions { + sleep?: (delayMs: number) => Promise; +} + function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } @@ -171,11 +176,16 @@ export function parseFullE2eInferenceResponse(body: string): FullE2eInferenceRes export async function runFullE2eInferenceProbe( model: string, execute: (input: FullE2eInferenceAttemptInput) => Promise, + options: FullE2eInferenceProbeOptions = {}, ): Promise> { const attempts: FullE2eInferenceAttempt[] = []; + const sleep = + options.sleep ?? ((delayMs: number) => new Promise((resolve) => setTimeout(resolve, delayMs))); + let transientRetryUsed = false; - for (const [index, maxTokens] of FULL_E2E_INFERENCE_REPLY_BUDGETS.entries()) { - const attempt = index + 1; + for (let budgetIndex = 0; budgetIndex < FULL_E2E_INFERENCE_REPLY_BUDGETS.length;) { + const maxTokens = FULL_E2E_INFERENCE_REPLY_BUDGETS[budgetIndex]!; + const attempt = attempts.length + 1; const result = await execute({ artifactName: `phase-4-sandbox-inference-local-attempt-${String(attempt).padStart(2, "0")}`, attempt, @@ -184,6 +194,11 @@ export async function runFullE2eInferenceProbe( probe: FullE2eInferenceProbeResult, ): Record { diff --git a/test/e2e/support/full-e2e-inference-probe.test.ts b/test/e2e/support/full-e2e-inference-probe.test.ts index f1c5f03d653..274d86d0e33 100644 --- a/test/e2e/support/full-e2e-inference-probe.test.ts +++ b/test/e2e/support/full-e2e-inference-probe.test.ts @@ -227,11 +227,61 @@ describe("full E2E sandbox inference probe", () => { expect(calls).toBe(1); }); - it("does not retry command, HTTP, or transport failures", async () => { + it("retries one transient HTTP command failure with the same reply budget", async () => { + const requests: FullE2eInferenceAttemptInput[] = []; + const delays: number[] = []; + const probe = await runFullE2eInferenceProbe( + "nvidia/nvidia/nemotron-3-ultra", + async (input) => { + requests.push(input); + return input.attempt === 1 + ? commandResult("", 22, "curl: (22) The requested URL returned error: 503") + : commandResult(completion("42")); + }, + { sleep: async (delayMs) => void delays.push(delayMs) }, + ); + + expect(probe.outcome).toBe("passed"); + expect(requests.map(({ attempt, maxTokens }) => ({ attempt, maxTokens }))).toEqual([ + { attempt: 1, maxTokens: 512 }, + { attempt: 2, maxTokens: 512 }, + ]); + expect(requests.map(({ artifactName }) => artifactName)).toEqual([ + "phase-4-sandbox-inference-local-attempt-01", + "phase-4-sandbox-inference-local-attempt-02", + ]); + expect(delays).toEqual([5_000]); + }); + + it.each([429, 502, 503, 504])( + "retries HTTP %i once, then preserves the command failure", + async (status) => { + let calls = 0; + const probe = await runFullE2eInferenceProbe( + "nvidia/nvidia/nemotron-3-ultra", + async () => { + calls += 1; + return commandResult("", 22, `curl: (22) The requested URL returned error: ${status}`); + }, + { sleep: async () => undefined }, + ); + + expect(probe.outcome).toBe("command-failure"); + expect(probe.attempts).toHaveLength(2); + expect(calls).toBe(2); + }, + ); + + it.each([ + [22, "curl: (22) The requested URL returned error: 401"], + [22, "curl: (22) The requested URL returned error: 403"], + [7, "curl: (7) Failed to connect"], + [28, "curl: (28) Operation timed out"], + ])("does not retry non-transient command failure exit=%i", async (exitCode, stderr) => { let calls = 0; const probe = await runFullE2eInferenceProbe("nvidia/nvidia/nemotron-3-ultra", async () => { calls += 1; - return commandResult("", 22, "curl: (22) HTTP 403"); + return commandResult("", exitCode, stderr); }); expect(probe.outcome).toBe("command-failure"); From 791ae55bc4335d36c88701f2f59a88d3519acdbe Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 22 Sep 2026 23:12:51 -0700 Subject: [PATCH 09/35] test(e2e): preserve Podman context for Hermes ACP recovery Signed-off-by: Deepak Jain --- test/e2e/fixtures/hermes-acp-live.ts | 6 +++++ test/e2e/support/hermes-acp-live.test.ts | 32 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/test/e2e/fixtures/hermes-acp-live.ts b/test/e2e/fixtures/hermes-acp-live.ts index fc02cee5701..54d89912348 100644 --- a/test/e2e/fixtures/hermes-acp-live.ts +++ b/test/e2e/fixtures/hermes-acp-live.ts @@ -57,6 +57,12 @@ export function hermesAcpLiveHostEnv(source: NodeJS.ProcessEnv): NodeJS.ProcessE "NODE_EXTRA_CA_CERTS", "CURL_CA_BUNDLE", "XDG_CONFIG_HOME", + "XDG_RUNTIME_DIR", + "DBUS_SESSION_BUS_ADDRESS", + "CONTAINERS_CONF", + "CONTAINERS_STORAGE_CONF", + "NEMOCLAW_GATEWAY_RUNTIME", + "OPENSHELL_PODMAN_SOCKET", "NEMOCLAW_OPENSHELL_BIN", "OPENSHELL_GATEWAY", "OPENSHELL_WORKSPACE", diff --git a/test/e2e/support/hermes-acp-live.test.ts b/test/e2e/support/hermes-acp-live.test.ts index f493ec77f98..8c4f15b80a2 100644 --- a/test/e2e/support/hermes-acp-live.test.ts +++ b/test/e2e/support/hermes-acp-live.test.ts @@ -7,6 +7,8 @@ import path from "node:path"; import { describe, expect, it, onTestFinished, vi } from "vitest"; +import { resolveNemoClawGatewayRuntime } from "../../../src/lib/onboard/runtime-provider/configured-runtime.ts"; + import { ArtifactSink } from "../fixtures/artifacts.ts"; import { SandboxClient } from "../fixtures/clients/sandbox.ts"; import { startTestProgress } from "../fixtures/progress.ts"; @@ -217,6 +219,36 @@ readline.createInterface({ input: process.stdin }).on("line", line => { }); }); + it("preserves the selected Podman runtime and rootless service context for ACP recovery", () => { + const runtimeEnv = { + NEMOCLAW_GATEWAY_RUNTIME: "podman", + OPENSHELL_PODMAN_SOCKET: "/run/user/1000/podman/podman.sock", + CONTAINERS_CONF: "/tmp/podman/containers.conf", + CONTAINERS_STORAGE_CONF: "/tmp/podman/storage.conf", + XDG_RUNTIME_DIR: "/run/user/1000", + DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus", + }; + const adapterEnv = hermesAcpLiveHostEnv({ + ...runtimeEnv, + NVIDIA_INFERENCE_API_KEY: "secret", + OPENAI_API_KEY: "secret", + OPENSHELL_TOKEN: "secret", + SSH_AUTH_SOCK: "/tmp/agent.sock", + UNRELATED_HOST_SETTING: "excluded", + }); + + expect(resolveNemoClawGatewayRuntime(adapterEnv)).toBe("podman"); + expect(adapterEnv).toEqual(runtimeEnv); + }); + + it("keeps Docker selection explicit or default without adding Podman settings", () => { + expect(hermesAcpLiveHostEnv({})).toEqual({}); + expect(resolveNemoClawGatewayRuntime(hermesAcpLiveHostEnv({}))).toBe("docker"); + const adapterEnv = hermesAcpLiveHostEnv({ NEMOCLAW_GATEWAY_RUNTIME: "docker" }); + expect(adapterEnv).toEqual({ NEMOCLAW_GATEWAY_RUNTIME: "docker" }); + expect(resolveNemoClawGatewayRuntime(adapterEnv)).toBe("docker"); + }); + it("recognizes only the requested JSON-RPC response", () => { expect(isAcpResponse({ jsonrpc: "2.0", id: 3, result: {} }, 3)).toBe(true); expect(isAcpResponse({ jsonrpc: "2.0", id: 4, result: {} }, 3)).toBe(false); From 29b62ca7cc5eb1140f3eb87ae56683bc84f2b50f Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 00:07:50 -0700 Subject: [PATCH 10/35] test(runtime): consolidate auth and retry regression coverage Signed-off-by: Aaron Erickson --- .../runtime/auth-profile-boundary.test.ts | 297 +++++------------- ...h-agent-turn-provider-availability.test.ts | 49 +-- test/e2e/support/launch-agent-turn.test.ts | 8 +- 3 files changed, 98 insertions(+), 256 deletions(-) diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index 5cef74307c9..b9229940b23 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -6,38 +6,37 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; +import { extractShellFunctionFromSource } from "../../../helpers/shell-source"; -const START_SCRIPT = path.join( - import.meta.dirname, - "..", - "../../..", - "scripts", - "nemoclaw-start.sh", -); +const START_SCRIPT = path.resolve(import.meta.dirname, "../../../../scripts/nemoclaw-start.sh"); const START_SOURCE = fs.readFileSync(START_SCRIPT, "utf-8"); +const credentialProbe = + 'bash -c \'printf "%s\\n" "${NVIDIA_INFERENCE_API_KEY-unset}" "${NVIDIA_API_KEY-unset}"\''; +const managedEnv = { + NVIDIA_INFERENCE_API_KEY: "primary-secret", + NVIDIA_API_KEY: "legacy-secret", + NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1", +}; +const homes: string[] = []; +afterEach(() => { + for (const home of homes.splice(0)) fs.rmSync(home, { recursive: true, force: true }); +}); const WRAPPER = [ "set -euo pipefail", - `eval "$(sed -n '/^write_auth_profile() {$/,/^}$/p' "$1")"`, - `eval "$(sed -n '/^clear_managed_inference_credentials() {$/,/^}$/p' "$1")"`, + extractShellFunctionFromSource(START_SOURCE, "write_auth_profile"), + extractShellFunctionFromSource(START_SOURCE, "clear_managed_inference_credentials"), "write_auth_profile", "clear_managed_inference_credentials", - 'bash -c \'printf "NVIDIA_INFERENCE_API_KEY=%s\\\\nNVIDIA_API_KEY=%s\\\\n" "${NVIDIA_INFERENCE_API_KEY-unset}" "${NVIDIA_API_KEY-unset}"\'', + credentialProbe, ].join("\n"); -type AuthFixture = { - home: string; - authPath: string; - status: number; - stdout: string; - stderr: string; -}; - function runWriteAuthProfile( env: Record, prepare: (authPath: string) => void = () => undefined, -): AuthFixture { +) { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-test-")); + homes.push(home); const authPath = path.join(home, ".openclaw", "agents", "main", "agent", "auth-profiles.json"); prepare(authPath); const result = spawnSync("bash", ["-s", "--", START_SCRIPT], { @@ -45,13 +44,7 @@ function runWriteAuthProfile( env: { PATH: process.env.PATH, HOME: home, ...env }, encoding: "utf-8", }); - return { - home, - authPath, - status: result.status ?? -1, - stdout: result.stdout ?? "", - stderr: result.stderr ?? "", - }; + return { authPath, ...result }; } function seedAuthProfile(profile: Record): (authPath: string) => void { @@ -85,7 +78,7 @@ function startupCredentialBoundaryBlock(kind: "non-root" | "root"): string { function runStartupCredentialBoundary(kind: "non-root" | "root") { const wrapper = [ "set -euo pipefail", - `eval "$(sed -n '/^clear_managed_inference_credentials() {$/,/^}$/p' "$1")"`, + extractShellFunctionFromSource(START_SOURCE, "clear_managed_inference_credentials"), "NEMOCLAW_CMD=(probe)", "STEP_DOWN_PREFIX_SANDBOX=(env)", "apply_messaging_runtime_env_aliases() { :; }", @@ -94,17 +87,12 @@ function runStartupCredentialBoundary(kind: "non-root" | "root") { "setup_auth_profile_as_sandbox() { :; }", "install_messaging_runtime_preloads() { :; }", "verify_messaging_runtime_secret_scans() { :; }", - 'run_oneshot_command() { bash -c \'printf "NVIDIA_INFERENCE_API_KEY=%s\\\\nNVIDIA_API_KEY=%s\\\\n" "${NVIDIA_INFERENCE_API_KEY-unset}" "${NVIDIA_API_KEY-unset}"\'; }', + `run_oneshot_command() { ${credentialProbe}; }`, startupCredentialBoundaryBlock(kind), ].join("\n"); return spawnSync("bash", ["-s", "--", START_SCRIPT], { input: wrapper, - env: { - PATH: process.env.PATH, - NVIDIA_INFERENCE_API_KEY: "primary-secret", - NVIDIA_API_KEY: "legacy-secret", - NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1", - }, + env: { PATH: process.env.PATH, ...managedEnv }, encoding: "utf-8", }); } @@ -116,214 +104,97 @@ const legacyManagedProfile = { profileId: "inference:manual", }; -describe("write_auth_profile (#1332)", () => { - it("writes profile under the route identifier from NEMOCLAW_INFERENCE_PROVIDER_ID", () => { +describe("OpenClaw auth-profile boundary", () => { + it.each([ + ["default", undefined, "inference"], + ["configured", "openai", "openai"], + ["literal", "$(echo pwned)", "$(echo pwned)"], + ] as const)("writes a private direct profile for the %s route", (_label, route, provider) => { const fixture = runWriteAuthProfile({ NVIDIA_INFERENCE_API_KEY: "secret", - NEMOCLAW_INFERENCE_PROVIDER_ID: "openai", + ...(route === undefined ? {} : { NEMOCLAW_INFERENCE_PROVIDER_ID: route }), }); - try { - expect(fixture.status, fixture.stderr).toBe(0); - expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ - "openai:manual": { - type: "api_key", - provider: "openai", - keyRef: { source: "env", id: "NVIDIA_INFERENCE_API_KEY" }, - profileId: "openai:manual", - }, - }); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } - }); - - it("falls back to 'inference' when neither route identifier is set", () => { - const fixture = runWriteAuthProfile({ NVIDIA_INFERENCE_API_KEY: "secret" }); - try { - expect(fixture.status, fixture.stderr).toBe(0); - const profile = JSON.parse(fs.readFileSync(fixture.authPath, "utf-8")); - expect(profile).toHaveProperty("inference:manual"); - expect(profile["inference:manual"].provider).toBe("inference"); - expect(profile).not.toHaveProperty("nvidia:manual"); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } - }); - - it("does not use 'nvidia' as the default provider key", () => { - const fixture = runWriteAuthProfile({ NVIDIA_INFERENCE_API_KEY: "secret" }); - try { - expect(fixture.status).toBe(0); - const profile = JSON.parse(fs.readFileSync(fixture.authPath, "utf-8")); - expect(Object.keys(profile).every((key) => !/^nvidia:/.test(key))).toBe(true); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } - }); - - it("treats provider_key as a literal (no shell command substitution)", () => { - const fixture = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - NEMOCLAW_INFERENCE_PROVIDER_ID: "$(echo pwned)", + expect(fixture.status, fixture.stderr).toBe(0); + expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ + [`${provider}:manual`]: { + ...legacyManagedProfile, + provider, + profileId: `${provider}:manual`, + }, }); - try { - expect(fixture.status, fixture.stderr).toBe(0); - const profile = JSON.parse(fs.readFileSync(fixture.authPath, "utf-8")); - expect(profile).toHaveProperty("$(echo pwned):manual"); - expect(profile["$(echo pwned):manual"].provider).toBe("$(echo pwned)"); - expect(profile).not.toHaveProperty("pwned:manual"); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } + expect(fs.statSync(fixture.authPath).mode & 0o777).toBe(0o600); }); - it("is a no-op when NVIDIA_INFERENCE_API_KEY is unset", () => { + it("leaves direct auth state absent when no credential is supplied", () => { const fixture = runWriteAuthProfile({}); - try { - expect(fixture.status).toBe(0); - expect(fs.existsSync(fixture.authPath)).toBe(false); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } - }); - - it("writes the auth profile with 0600 permissions", () => { - const fixture = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - NEMOCLAW_INFERENCE_PROVIDER_ID: "openai", - }); - try { - expect(fixture.status).toBe(0); - expect(fs.statSync(fixture.authPath).mode & 0o777).toBe(0o600); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } - }); - - it("does not create an auth profile for the inference.local route", () => { - const fixture = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "secret", - NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1", - NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", - }); - try { - expect(fixture.status, fixture.stderr).toBe(0); - expect(fs.existsSync(fixture.authPath)).toBe(false); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } + expect(fixture.status, fixture.stderr).toBe(0); + expect(fs.existsSync(fixture.authPath)).toBe(false); }); - it("removes a stale NemoClaw-generated profile from a proxy-routed sandbox", () => { - const fixture = runWriteAuthProfile( - { NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1" }, - seedAuthProfile({ "inference:manual": legacyManagedProfile }), - ); - try { + it.each(["fresh", "legacy"] as const)( + "leaves no managed profile or inherited credentials in %s state", + (state) => { + const fixture = runWriteAuthProfile( + state === "fresh" + ? managedEnv + : { NEMOCLAW_INFERENCE_BASE_URL: managedEnv.NEMOCLAW_INFERENCE_BASE_URL }, + state === "legacy" + ? seedAuthProfile({ "inference:manual": legacyManagedProfile }) + : undefined, + ); expect(fixture.status, fixture.stderr).toBe(0); expect(fs.existsSync(fixture.authPath)).toBe(false); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } - }); + expect(fixture.stdout.trim()).toBe("unset\nunset"); + }, + ); - it("preserves user-managed profiles while removing the stale managed entry", () => { + it("preserves other profiles when removing the managed entry", () => { const customProfile = { - type: "api_key", + ...legacyManagedProfile, provider: "custom", - keyRef: { source: "env", id: "NVIDIA_INFERENCE_API_KEY" }, profileId: "custom:manual", }; const fixture = runWriteAuthProfile( - { NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1" }, - seedAuthProfile({ - "inference:manual": legacyManagedProfile, - "custom:manual": customProfile, - }), - ); - try { - expect(fixture.status, fixture.stderr).toBe(0); - expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ - "custom:manual": customProfile, - }); - expect(fs.statSync(fixture.authPath).mode & 0o777).toBe(0o600); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } - }); - - it("preserves a near-match user-managed profile for the managed provider", () => { - const userManagedProfile = { ...legacyManagedProfile, label: "user-managed" }; - const original = JSON.stringify({ "inference:manual": userManagedProfile }); - const fixture = runWriteAuthProfile( - { NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1" }, - (authPath) => { - fs.mkdirSync(path.dirname(authPath), { recursive: true }); - fs.writeFileSync(authPath, original); - }, + managedEnv, + seedAuthProfile({ "inference:manual": legacyManagedProfile, "custom:manual": customProfile }), ); - try { - expect(fixture.status, fixture.stderr).toBe(0); - expect(fs.readFileSync(fixture.authPath, "utf-8")).toBe(original); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } + expect(fixture.status, fixture.stderr).toBe(0); + expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ + "custom:manual": customProfile, + }); + expect(fs.statSync(fixture.authPath).mode & 0o777).toBe(0o600); }); - it("clears both managed credential aliases before a child process starts", () => { - const fixture = runWriteAuthProfile({ - NVIDIA_INFERENCE_API_KEY: "primary-secret", - NVIDIA_API_KEY: "legacy-secret", - NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1", - }); - try { - expect(fixture.status, fixture.stderr).toBe(0); - expect(fixture.stdout).toContain("NVIDIA_INFERENCE_API_KEY=unset"); - expect(fixture.stdout).toContain("NVIDIA_API_KEY=unset"); - expect(fixture.stdout).not.toContain("primary-secret"); - expect(fixture.stdout).not.toContain("legacy-secret"); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } + it("preserves a near-match profile byte for byte", () => { + const profiles = { "inference:manual": { ...legacyManagedProfile, label: "user-managed" } }; + const fixture = runWriteAuthProfile(managedEnv, seedAuthProfile(profiles)); + expect(fixture.status, fixture.stderr).toBe(0); + expect(fs.readFileSync(fixture.authPath, "utf-8")).toBe(JSON.stringify(profiles)); }); it.each(["non-root", "root"] as const)( - "clears both managed credential aliases in the %s startup ordering before one-shot execution", + "clears credential aliases before the %s startup launches a command", (kind) => { const result = runStartupCredentialBoundary(kind); - expect(result.status, result.stderr).toBe(0); - expect(result.stdout).toContain("NVIDIA_INFERENCE_API_KEY=unset"); - expect(result.stdout).toContain("NVIDIA_API_KEY=unset"); - expect(result.stdout).not.toContain("primary-secret"); - expect(result.stdout).not.toContain("legacy-secret"); + expect(result.stdout.trim()).toBe("unset\nunset"); }, ); - it("rejects a symlinked auth-profile parent without changing its target", () => { + it("rejects a symlinked parent without changing its target", () => { const externalContents = JSON.stringify({ "inference:manual": legacyManagedProfile }); let externalProfile = ""; - const fixture = runWriteAuthProfile( - { NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1" }, - (authPath) => { - const openclawDir = path.resolve(authPath, "../../../../"); - const externalAgents = path.join( - path.resolve(authPath, "../../../../../"), - "external-agents", - ); - externalProfile = path.join(externalAgents, "main", "agent", "auth-profiles.json"); - fs.mkdirSync(path.dirname(externalProfile), { recursive: true }); - fs.writeFileSync(externalProfile, externalContents); - fs.mkdirSync(openclawDir, { recursive: true }); - fs.symlinkSync(externalAgents, path.join(openclawDir, "agents")); - }, - ); - try { - expect(fixture.status).not.toBe(0); - expect(fixture.stderr).toContain("[SECURITY] Refusing auth-profile cleanup"); - expect(fs.readFileSync(externalProfile, "utf-8")).toBe(externalContents); - } finally { - fs.rmSync(fixture.home, { recursive: true, force: true }); - } + const fixture = runWriteAuthProfile(managedEnv, (authPath) => { + const openclawDir = path.resolve(authPath, "../../../../"); + const externalAgents = path.join(path.dirname(openclawDir), "external-agents"); + externalProfile = path.join(externalAgents, "main", "agent", "auth-profiles.json"); + fs.mkdirSync(path.dirname(externalProfile), { recursive: true }); + fs.writeFileSync(externalProfile, externalContents); + fs.mkdirSync(openclawDir, { recursive: true }); + fs.symlinkSync(externalAgents, path.join(openclawDir, "agents")); + }); + expect(fixture.status).not.toBe(0); + expect(fixture.stderr).toContain("[SECURITY] Refusing auth-profile cleanup"); + expect(fs.readFileSync(externalProfile, "utf-8")).toBe(externalContents); }); }); diff --git a/test/e2e/support/launch-agent-turn-provider-availability.test.ts b/test/e2e/support/launch-agent-turn-provider-availability.test.ts index 33176ff2036..89783751747 100644 --- a/test/e2e/support/launch-agent-turn-provider-availability.test.ts +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -18,12 +18,16 @@ function launchOptions(host: unknown) { }; } -it.each(["500", "503"] as const)( - "retries a transient HTTP %s provider failure in a fresh launch session (#10978)", +it.each(["500", "503", "message_content_empty"] as const)( + "retries transient provider failure %s in a fresh launch session (#10978)", async (status) => { const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); vi.useFakeTimers(); const calls: Array<{ artifactName?: string; env?: NodeJS.ProcessEnv }> = []; + const diagnostic = + status === "message_content_empty" + ? '{"reason":"message_content_empty","sessionId":"ed80ef8e-a026-424f-8ca4-669f6060e046"}' + : `litellm.ServiceUnavailableError: HTTP ${status}; NVIDIA upstream unavailable`; const host = { command: async ( _command: string, @@ -35,7 +39,7 @@ it.each(["500", "503"] as const)( ? { exitCode: 1, signal: null, - stderr: `launch did not record the required structured session turns\nlitellm.ServiceUnavailableError: HTTP ${status}; NVIDIA upstream unavailable\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, + stderr: `launch did not record the required structured session turns\n${diagnostic}\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, stdout: "", } : { exitCode: 0, signal: null, stderr: "", stdout: "" }; @@ -64,45 +68,6 @@ it.each(["500", "503"] as const)( }, ); -it("retries an exact empty assistant provider response in a fresh launch session", async () => { - const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); - vi.useFakeTimers(); - const calls: Array<{ artifactName?: string; env?: NodeJS.ProcessEnv }> = []; - const host = { - command: async ( - _command: string, - _args: string[], - options?: { artifactName?: string; env?: NodeJS.ProcessEnv }, - ) => { - calls.push({ artifactName: options?.artifactName, env: options?.env }); - return calls.length === 1 - ? { - exitCode: 1, - signal: null, - stderr: `launch did not record the required structured session turns\n{"reason":"message_content_empty","sessionId":"ed80ef8e-a026-424f-8ca4-669f6060e046"}\n\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, - stdout: "", - } - : { exitCode: 0, signal: null, stderr: "", stdout: "" }; - }, - openshellCommandPath: "/usr/bin/openshell", - }; - - try { - const launch = runOpenClawLaunchSession(launchOptions(host)); - await vi.advanceTimersByTimeAsync(1_000); - const result = await launch; - expect(result.exitCode).toBe(0); - expect(calls.map((call) => call.artifactName)).toEqual([ - "provider-turn", - "provider-turn-provider-retry-02", - ]); - expect(new Set(calls.map((call) => call.env?.NEMOCLAW_LAUNCH_RUN_ID)).size).toBe(2); - } finally { - vi.useRealTimers(); - platform.mockRestore(); - } -}); - it("classifies exhausted transient launch attempts as provider unavailable (#10978)", async () => { const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); vi.useFakeTimers(); diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index dc943314faf..1901182624f 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -346,7 +346,12 @@ const exitWithStatus = process.exit.bind(process); if (mode === "invalid-order") { append("assistant", "response before input"); append("user", firstInput); - } else if (mode === "provider-empty-message" || mode === "provider-cleanup-failure" || mode === "provider-exit-after-recording") { + } else if (mode === "provider-empty-message") { + append("user", firstInput); + fs.appendFileSync(sessionFile, JSON.stringify({ + type: "message", message: { role: "assistant", content: [] }, + }) + "\n"); + } else if (mode === "provider-cleanup-failure" || mode === "provider-exit-after-recording") { append("user", firstInput); appendProviderError(); new Map([["provider-exit-after-recording", () => exitWithStatus(23)]]).get(mode)?.(); @@ -1075,6 +1080,7 @@ it.runIf(process.platform === "linux").concurrent( expect(ttyObserved).toBe(true); expect(baselineRemoved).toBe(true); expect(result.status).toBe(1); + expect(result.stderr).toContain('"reason":"message_content_empty"'); expect(result.stderr).toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); }, testTimeout(30_000), From 0ddadd917232a630646c490d95c4b8780f2e09db Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 23 Sep 2026 00:07:56 -0700 Subject: [PATCH 11/35] test(e2e): retain bounded Hermes ACP startup diagnostics Signed-off-by: Deepak Jain --- test/e2e/fixtures/hermes-acp-diagnostics.ts | 72 +++++++++++++++++ test/e2e/fixtures/hermes-acp-live.ts | 15 +++- .../support/hermes-acp-diagnostics.test.ts | 80 +++++++++++++++++++ test/e2e/support/hermes-acp-live.test.ts | 80 ++++++++++++++++++- 4 files changed, 241 insertions(+), 6 deletions(-) create mode 100644 test/e2e/fixtures/hermes-acp-diagnostics.ts create mode 100644 test/e2e/support/hermes-acp-diagnostics.test.ts diff --git a/test/e2e/fixtures/hermes-acp-diagnostics.ts b/test/e2e/fixtures/hermes-acp-diagnostics.ts new file mode 100644 index 00000000000..eb80893014b --- /dev/null +++ b/test/e2e/fixtures/hermes-acp-diagnostics.ts @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { ArtifactSink } from "./artifacts.ts"; + +const MAX_LINE_BYTES = 4096; +const MAX_TOTAL_BYTES = 16 * 1024; +const MAX_LINES = 32; +const DISCARDED = + "[ACP stderr diagnostics discarded: oversized, incomplete, or capture limit reached]\n"; + +/** Buffer complete diagnostic lines before redaction, never partial secret fragments. */ +export function createHermesAcpDiagnostics(artifacts: ArtifactSink) { + const lines: string[] = []; + let pending = ""; + let droppingLine = false; + let discarded = false; + let retainedBytes = 0; + let stopped = false; + return { + stop(): void { + stopped = true; + if (pending || droppingLine) discarded = true; + pending = ""; + droppingLine = false; + }, + append(chunk: string): void { + if (stopped) return; + for (const segment of chunk.match(/[^\n]*\n|[^\n]+$/gu) ?? []) { + const complete = segment.endsWith("\n"); + if (!droppingLine) { + if ( + Buffer.byteLength(pending, "utf8") + Buffer.byteLength(segment, "utf8") > + MAX_LINE_BYTES + ) { + pending = ""; + droppingLine = true; + discarded = true; + } else { + pending += segment; + } + } + if (!complete) continue; + if ( + !droppingLine && + (/"jsonrpc"\s*:/u.test(pending) || + (/^\s*[[\]{}"]/u.test(pending) && !/^\[\d{1,3}\/\d{1,3}\] /u.test(pending))) + ) { + discarded = true; + } else if (!droppingLine) { + const line = artifacts.redact(pending); + const bytes = Buffer.byteLength(line, "utf8"); + if ( + lines.length < MAX_LINES && + retainedBytes + bytes <= MAX_TOTAL_BYTES - Buffer.byteLength(DISCARDED) + ) { + lines.push(line); + retainedBytes += bytes; + } else { + discarded = true; + } + } + pending = ""; + droppingLine = false; + } + }, + async write(relativePath: string): Promise { + if (pending || droppingLine) discarded = true; + await artifacts.writeText(relativePath, lines.join("") + (discarded ? DISCARDED : "")); + }, + }; +} diff --git a/test/e2e/fixtures/hermes-acp-live.ts b/test/e2e/fixtures/hermes-acp-live.ts index 54d89912348..9e50514a26a 100644 --- a/test/e2e/fixtures/hermes-acp-live.ts +++ b/test/e2e/fixtures/hermes-acp-live.ts @@ -4,6 +4,7 @@ import { setTimeout as sleep } from "node:timers/promises"; import type { ArtifactSink } from "./artifacts.ts"; +import { createHermesAcpDiagnostics } from "./hermes-acp-diagnostics.ts"; import type { SandboxClient } from "./clients/sandbox.ts"; import { type ChildProcessProgress, spawnObservedChild } from "./observed-child-process.ts"; import type { ShellProbeResult } from "./shell-probe.ts"; @@ -272,7 +273,7 @@ async function writeHermesAcpLiveReceipt( }); } -/** Drive the real packaged adapter while retaining only fixed boolean and exit evidence. */ +/** Drive the real packaged adapter while retaining fixed protocol evidence and bounded, redacted startup stderr diagnostics. */ export async function runHermesAcpLiveScenario(options: HermesAcpLiveOptions): Promise { const now = options.now ?? Date.now; const scenarioTimeoutMs = @@ -329,6 +330,7 @@ export async function runHermesAcpLiveScenario(options: HermesAcpLiveOptions): P let protocolValid = true; const promptEvidence = createHermesAcpPromptEvidenceTracker(); let stderrObserved = false; + const diagnostics = createHermesAcpDiagnostics(options.artifacts); let childClosed = false; const inbox: JsonObject[] = []; const waiters = new Set<() => void>(); @@ -348,6 +350,13 @@ export async function runHermesAcpLiveScenario(options: HermesAcpLiveOptions): P if (typeof message !== "object" || message === null || Array.isArray(message)) { protocolValid = false; } else { + if ( + isAcpResponse(message, 1) && + typeof message.result === "object" && + message.result !== null + ) { + diagnostics.stop(); + } promptEvidence.observe(message as JsonObject); inbox.push(message as JsonObject); } @@ -373,8 +382,9 @@ export async function runHermesAcpLiveScenario(options: HermesAcpLiveOptions): P buffered = lines.pop() ?? ""; for (const line of lines) consumeLine(line); }, - onStderr: () => { + onStderr: (chunk) => { stderrObserved = true; + diagnostics.append(chunk); }, }); child.once("close", () => { @@ -509,6 +519,7 @@ export async function runHermesAcpLiveScenario(options: HermesAcpLiveOptions): P sessionCreated, })); + await diagnostics.write(`hermes-acp-${options.scenario}.stderr.txt`); await writeHermesAcpLiveReceipt(options, { adapterProcessAbsent, deadlineExpired: options.deadlineAtMs !== undefined && now() >= options.deadlineAtMs, diff --git a/test/e2e/support/hermes-acp-diagnostics.test.ts b/test/e2e/support/hermes-acp-diagnostics.test.ts new file mode 100644 index 00000000000..f7fbd204c3d --- /dev/null +++ b/test/e2e/support/hermes-acp-diagnostics.test.ts @@ -0,0 +1,80 @@ +// 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 { expect, it, onTestFinished } from "vitest"; +import { ArtifactSink } from "../fixtures/artifacts.ts"; +import { createHermesAcpDiagnostics } from "../fixtures/hermes-acp-diagnostics.ts"; + +function fixture() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "acp-diagnostics-")); + onTestFinished(() => fs.rmSync(root, { recursive: true, force: true })); + const diagnostics = createHermesAcpDiagnostics(new ArtifactSink(root, ["explicit-secret"])); + const read = async () => { + await diagnostics.write("stderr.txt"); + return fs.readFileSync(path.join(root, "stderr.txt"), "utf8"); + }; + return { diagnostics, read }; +} + +it("redacts complete diagnostic lines after split secrets arrive", async () => { + const { diagnostics, read } = fixture(); + diagnostics.append("gateway recovery failed: explicit-"); + diagnostics.append( + "secret Authorization: Bearer bearer-secret\nhttps://host.invalid/?token=query-secret\n", + ); + const output = await read(); + expect(output).toContain("gateway recovery failed:"); + expect(output).not.toMatch(/explicit-secret|bearer-secret|query-secret/u); +}); + +it("discards oversized and incomplete lines without retaining secret fragments", async () => { + const { diagnostics, read } = fixture(); + diagnostics.append("unsafe-prefix" + "x".repeat(4096)); + diagnostics.append("secret-tail\nuseful complete diagnostic\nunfinished-secret"); + const output = await read(); + expect(output).toContain("useful complete diagnostic"); + expect(output).toContain("diagnostics discarded"); + expect(output).not.toMatch(/unsafe-prefix|secret-tail|unfinished-secret/u); +}); + +it("bounds the retained diagnostic line count", async () => { + const { diagnostics, read } = fixture(); + diagnostics.append("safe diagnostic\n".repeat(40)); + const output = await read(); + expect(output.match(/safe diagnostic/gu)).toHaveLength(32); + expect(output).toContain("diagnostics discarded"); +}); + +it("bounds retained UTF-8 bytes including the discard marker", async () => { + const { diagnostics, read } = fixture(); + diagnostics.append(("é".repeat(1500) + "\n").repeat(10)); + const output = await read(); + expect(Buffer.byteLength(output, "utf8")).toBeLessThanOrEqual(16 * 1024); + expect(output).toContain("diagnostics discarded"); +}); + +it("drops protocol-shaped stderr and stops recording after initialization", async () => { + const { diagnostics, read } = fixture(); + diagnostics.append('gateway starting\n{"jsonrpc":"2.0","result":"private payload"}\n'); + diagnostics.append(' "prompt": "private continuation",\n'); + diagnostics.append("partial startup"); + diagnostics.stop(); + diagnostics.append("later agent output\n"); + const output = await read(); + expect(output).toContain("gateway starting"); + expect(output).toContain("diagnostics discarded"); + expect(output).not.toMatch(/private|partial startup|later agent/u); +}); + +it("retains the recovery producer's numeric progress lines while rejecting JSON arrays", async () => { + const { diagnostics, read } = fixture(); + diagnostics.append('[1/3] Starting gateway\n[2/3] Waiting for readiness\n["private payload"]\n'); + const output = await read(); + expect(output).toContain("[1/3] Starting gateway"); + expect(output).toContain("[2/3] Waiting for readiness"); + expect(output).not.toContain("private payload"); + expect(output).toContain("diagnostics discarded"); +}); diff --git a/test/e2e/support/hermes-acp-live.test.ts b/test/e2e/support/hermes-acp-live.test.ts index 8c4f15b80a2..ba1023eb424 100644 --- a/test/e2e/support/hermes-acp-live.test.ts +++ b/test/e2e/support/hermes-acp-live.test.ts @@ -103,11 +103,12 @@ describe("Hermes ACP live evidence boundary", () => { }); it.each([ - ["installed", "initialize", 0], - ["checkout", "client-disconnect", 1], + ["installed", "initialize", 0, {}], + ["checkout", "client-disconnect", 1, {}], + ["checkout", "exchange", 0, { stderrObserved: true }], ] as const)( "%s adapter initializes and completes %s", - async (installation, scenario, exitCode) => { + async (installation, scenario, exitCode, scenarioEvidence) => { const artifactDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-acp-launch-")); const adapterEntrypoint = path.join(artifactDir, "nemoclaw-acp"); fs.writeFileSync( @@ -120,7 +121,12 @@ process.stdout.on("error", () => { }); readline.createInterface({ input: process.stdin }).on("line", line => { const request = JSON.parse(line); - process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result: {} }) + "\\n"); + if (request.method === "session/new") process.stderr.write("later agent stderr\\n"); + if (request.method === "session/prompt") process.stdout.write(JSON.stringify({ + jsonrpc: "2.0", method: "session/update", params: { sessionId: "session-a", update: { text: "PONG" } } + }) + "\\n"); + const result = request.method === "session/new" ? { sessionId: "session-a" } : {}; + process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }) + "\\n"); }); `, { mode: 0o700 }, @@ -154,6 +160,7 @@ readline.createInterface({ input: process.stdin }).on("line", line => { expect( JSON.parse(fs.readFileSync(path.join(artifactDir, `hermes-acp-${scenario}.json`), "utf8")), ).toMatchObject({ + ...scenarioEvidence, passed: true, initialized: true, exitCode, @@ -161,10 +168,75 @@ readline.createInterface({ input: process.stdin }).on("line", line => { remoteProcessAbsent: true, timedOut: false, }); + expect( + fs.readFileSync(path.join(artifactDir, `hermes-acp-${scenario}.stderr.txt`), "utf8"), + ).not.toContain("later agent stderr"); }, 2_000, ); + it("retains redacted child stderr without persisting ACP stdout", async () => { + const artifactDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-acp-diagnostics-")); + const adapterEntrypoint = path.join(artifactDir, "adapter.cjs"); + fs.writeFileSync( + adapterEntrypoint, + ` +process.stdin.resume(); +process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: 99, result: "private ACP payload" }) + "\\n"); +process.stderr.write("gateway recovery failed: explicit-"); +setTimeout(() => { + process.stderr.write("secret Authorization: Bearer bearer-secret\\nhttps://host.invalid/?token=query-secret\\n"); + process.stderr.write("x".repeat(5000) + "oversized-secret\\n"); + process.stderr.write("incomplete-secret"); + process.exitCode = 1; + process.stdin.destroy(); +}, 20); +`, + ); + const progress = startTestProgress( + "ACP diagnostics", + ["launch adapter", "verify diagnostics"], + { + logLine: () => undefined, + }, + ); + onTestFinished(() => { + progress.stop(); + fs.rmSync(artifactDir, { force: true, recursive: true }); + }); + await expect( + runHermesAcpLiveScenario({ + adapterEntrypoint, + artifacts: new ArtifactSink(artifactDir, ["explicit-secret"]), + env: {}, + progress, + sandbox: new SandboxClient({ + run: vi.fn().mockResolvedValue({ exitCode: 1, stdout: "", stderr: "" }), + }), + sandboxName: "e2e-hermes", + scenario: "initialize", + }), + ).resolves.toBe(false); + const diagnostics = fs.readFileSync( + path.join(artifactDir, "hermes-acp-initialize.stderr.txt"), + "utf8", + ); + expect(diagnostics).toContain("gateway recovery failed:"); + expect(diagnostics).toContain("diagnostics discarded"); + expect(diagnostics).not.toMatch( + /explicit-secret|bearer-secret|query-secret|oversized-secret|incomplete-secret|private ACP payload/u, + ); + expect( + JSON.parse(fs.readFileSync(path.join(artifactDir, "hermes-acp-initialize.json"), "utf8")), + ).toMatchObject({ + passed: false, + stderrObserved: true, + rawAcpPayloadRetained: false, + adapterProcessAbsent: true, + remoteProcessAbsent: true, + }); + }); + it("records a failed scenario when the adapter executable is missing", async () => { const artifactDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-acp-missing-")); const progress = startTestProgress("missing ACP adapter", ["launch adapter", "verify result"], { From f1db46aaa8a71ee51e85c14159b7d29d2dc9078a Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 23 Sep 2026 00:43:13 -0700 Subject: [PATCH 12/35] fix(gateway): preserve host runtime during selected recovery Signed-off-by: Deepak Jain --- .../onboard/gateway/docker-driver-start.ts | 6 +- src/lib/onboard/gateway/late-binding.test.ts | 67 ++++++++++++++++++- .../runtime-provider/configured-runtime.ts | 18 +++++ test/e2e/fixtures/availability-env.ts | 9 +-- test/e2e/fixtures/hermes-acp-live.ts | 8 +-- test/e2e/support/hermes-acp-live.test.ts | 24 ++++++- 6 files changed, 117 insertions(+), 15 deletions(-) diff --git a/src/lib/onboard/gateway/docker-driver-start.ts b/src/lib/onboard/gateway/docker-driver-start.ts index ef90319aa82..6a663be1b18 100644 --- a/src/lib/onboard/gateway/docker-driver-start.ts +++ b/src/lib/onboard/gateway/docker-driver-start.ts @@ -9,6 +9,7 @@ import { buildSelectedOpenShellSubprocessEnv, type OpenShellRuntimeSelection, } from "../../adapters/openshell/command-argv"; +import { gatewayHostRuntimeEnvironment } from "../runtime-provider/configured-runtime"; import { trackChildExit } from "../child-exit-tracker"; import * as dockerDriverGatewayCutover from "../docker-driver-gateway-cutover"; import { reportDockerDriverGatewayStartFailure } from "../docker-driver-gateway-failure"; @@ -194,7 +195,10 @@ export function createDockerDriverGatewayStart( ); } const selectedRuntimeEnv = runtimeSelection - ? buildSelectedOpenShellSubprocessEnv(runtimeSelection) + ? { + ...buildSelectedOpenShellSubprocessEnv(runtimeSelection), + ...gatewayHostRuntimeEnvironment(process.env), + } : undefined; const runtimeOptions = selectedRuntimeEnv ? { diff --git a/src/lib/onboard/gateway/late-binding.test.ts b/src/lib/onboard/gateway/late-binding.test.ts index e6d988ea6fd..286aa56c30e 100644 --- a/src/lib/onboard/gateway/late-binding.test.ts +++ b/src/lib/onboard/gateway/late-binding.test.ts @@ -13,6 +13,9 @@ import { } from "../docker-driver-gateway-config"; import * as dockerDriverGatewayCutover from "../docker-driver-gateway-cutover"; import * as dockerDriverGatewayLaunch from "../docker-driver-gateway-launch"; +import { assertDockerDriverGatewayBindAddressSafe } from "../docker-driver-gateway-env"; +import { buildSelectedOpenShellSubprocessEnv } from "../../adapters/openshell/command-argv"; +import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; import * as gatewayBinding from "../gateway-binding"; import { createDockerDriverGatewayStart, @@ -45,7 +48,10 @@ describe("gateway lifecycle late binding", () => { ).toBe("https://127.0.0.1:8080"); }); - async function captureFailedStartRecovery(ownsSelectedState: boolean) { + async function captureFailedStartRecovery( + ownsSelectedState: boolean, + runtimeSelection?: OpenShellRuntimeSelection, + ) { const root = fs.mkdtempSync(path.join(process.cwd(), "nemoclaw-gateway-port-recovery-")); const stateDir = path.join(root, "gateway"); const adapters = gatewayAdaptersForTest(); @@ -156,6 +162,7 @@ describe("gateway lifecycle late binding", () => { await expect( start.startDockerDriverGateway({ + runtimeSelection, exitOnFailure: false, output: { error: (message) => lines.push(message), @@ -167,6 +174,7 @@ describe("gateway lifecycle late binding", () => { ).rejects.toThrow(/failed to start within/); return { + runtimeEnvironment: runtimeIdentitySpy.mock.calls[0]?.[0].env, output: lines.join("\n"), processEnvironmentCalls: readProcessEnvironment.mock.calls, serviceTargetCalls: serviceTarget.mock.calls.length, @@ -181,6 +189,63 @@ describe("gateway lifecycle late binding", () => { } } + it("preserves native Podman context through selected-target gateway startup", async () => { + vi.stubEnv("NEMOCLAW_GATEWAY_RUNTIME", "podman"); + vi.stubEnv("OPENSHELL_PODMAN_SOCKET", "/run/user/1000/podman/podman.sock"); + vi.stubEnv("CONTAINERS_CONF", "/tmp/containers.conf"); + vi.stubEnv("CONTAINERS_STORAGE_CONF", "/tmp/storage.conf"); + vi.stubEnv("XDG_RUNTIME_DIR", "/run/user/1000"); + vi.stubEnv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"); + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://hostile.invalid"); + vi.stubEnv("OPENSHELL_TOKEN", "hostile-token"); + vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "provider-secret"); + const clientOnlyEnvironment = buildSelectedOpenShellSubprocessEnv({ + gatewayName: "nemoclaw-9777", + workspace: "default", + }); + const result = await captureFailedStartRecovery(true, { + gatewayName: "nemoclaw-9777", + workspace: "default", + }); + expect(result.runtimeEnvironment).toMatchObject({ + NEMOCLAW_GATEWAY_RUNTIME: "podman", + OPENSHELL_PODMAN_SOCKET: "/run/user/1000/podman/podman.sock", + CONTAINERS_CONF: "/tmp/containers.conf", + CONTAINERS_STORAGE_CONF: "/tmp/storage.conf", + XDG_RUNTIME_DIR: "/run/user/1000", + DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus", + OPENSHELL_GATEWAY: "nemoclaw-9777", + OPENSHELL_WORKSPACE: "default", + }); + expect(result.runtimeEnvironment).not.toHaveProperty("OPENSHELL_GATEWAY_ENDPOINT"); + expect(result.runtimeEnvironment).not.toHaveProperty("OPENSHELL_TOKEN"); + expect(result.runtimeEnvironment).not.toHaveProperty("NVIDIA_INFERENCE_API_KEY"); + expect(() => + assertDockerDriverGatewayBindAddressSafe( + { + OPENSHELL_BIND_ADDRESS: "0.0.0.0", + OPENSHELL_GRPC_ENDPOINT: "https://169.254.2.2:8080", + OPENSHELL_SSH_GATEWAY_HOST: "127.0.0.1", + OPENSHELL_SERVER_PORT: "8080", + }, + clientOnlyEnvironment, + "linux", + ), + ).toThrow(/not supported for the OpenShell Docker-driver gateway/u); + expect(() => + assertDockerDriverGatewayBindAddressSafe( + { + OPENSHELL_BIND_ADDRESS: "0.0.0.0", + OPENSHELL_GRPC_ENDPOINT: "https://169.254.2.2:8080", + OPENSHELL_SSH_GATEWAY_HOST: "127.0.0.1", + OPENSHELL_SERVER_PORT: "8080", + }, + result.runtimeEnvironment, + "linux", + ), + ).not.toThrow(); + }); + it("withholds a stop command when the active service uses another state (#11720)", async () => { const result = await captureFailedStartRecovery(false); diff --git a/src/lib/onboard/runtime-provider/configured-runtime.ts b/src/lib/onboard/runtime-provider/configured-runtime.ts index 5763138e8a6..e6ee6ad4fa3 100644 --- a/src/lib/onboard/runtime-provider/configured-runtime.ts +++ b/src/lib/onboard/runtime-provider/configured-runtime.ts @@ -27,3 +27,21 @@ export function resolveNemoClawGatewayRuntime( export function isPodmanGatewayRuntimeEnabled(env: NodeJS.ProcessEnv = process.env): boolean { return resolveNemoClawGatewayRuntime(env) === "podman"; } + +/** Host lifecycle context, separate from generic OpenShell client target selection. */ +export const GATEWAY_HOST_RUNTIME_ENV_KEYS = [ + NEMOCLAW_GATEWAY_RUNTIME_ENV, + "OPENSHELL_PODMAN_SOCKET", + "CONTAINERS_CONF", + "CONTAINERS_STORAGE_CONF", + "XDG_RUNTIME_DIR", + "DBUS_SESSION_BUS_ADDRESS", +] as const; + +export function gatewayHostRuntimeEnvironment(source: NodeJS.ProcessEnv): Record { + return Object.fromEntries( + GATEWAY_HOST_RUNTIME_ENV_KEYS.flatMap((name) => + source[name] === undefined ? [] : [[name, source[name]]], + ), + ); +} diff --git a/test/e2e/fixtures/availability-env.ts b/test/e2e/fixtures/availability-env.ts index eddbb3cce92..169a41693ac 100644 --- a/test/e2e/fixtures/availability-env.ts +++ b/test/e2e/fixtures/availability-env.ts @@ -1,12 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { GATEWAY_HOST_RUNTIME_ENV_KEYS } from "../../../src/lib/onboard/runtime-provider/configured-runtime.ts"; + import { buildChildEnv } from "./redaction.ts"; const AVAILABILITY_PROBE_EXTRA_ENV_KEYS = [ - "CONTAINERS_CONF", - "CONTAINERS_STORAGE_CONF", - "DBUS_SESSION_BUS_ADDRESS", + ...GATEWAY_HOST_RUNTIME_ENV_KEYS, "DOCKER_CONFIG", "DOCKER_CONTEXT", "DOCKER_HOST", @@ -17,17 +17,14 @@ const AVAILABILITY_PROBE_EXTRA_ENV_KEYS = [ "E2E_MANAGED_IMAGE_COHORT_RECEIPT", "GITHUB_WORKSPACE", "XDG_CONFIG_HOME", - "XDG_RUNTIME_DIR", "NEMOCLAW_E2E_EXPECTED_SHA", "NEMOCLAW_E2E_MANAGED_IMAGE_CATALOG", "NEMOCLAW_E2E_MANAGED_IMAGE_CATALOG_JSON", "NEMOCLAW_E2E_MANAGED_IMAGE_REVISION", "NEMOCLAW_OLLAMA_PULL_TIMEOUT", "NEMOCLAW_EXPERIMENTAL_PROFILE", - "NEMOCLAW_GATEWAY_RUNTIME", "NEMOCLAW_RUN_LIVE_E2E", "NEMOCLAW_TRACE_DIR", - "OPENSHELL_PODMAN_SOCKET", ]; export function buildAvailabilityProbeEnv( diff --git a/test/e2e/fixtures/hermes-acp-live.ts b/test/e2e/fixtures/hermes-acp-live.ts index 9e50514a26a..b0a296dde78 100644 --- a/test/e2e/fixtures/hermes-acp-live.ts +++ b/test/e2e/fixtures/hermes-acp-live.ts @@ -3,6 +3,7 @@ import { setTimeout as sleep } from "node:timers/promises"; +import { GATEWAY_HOST_RUNTIME_ENV_KEYS } from "../../../src/lib/onboard/runtime-provider/configured-runtime.ts"; import type { ArtifactSink } from "./artifacts.ts"; import { createHermesAcpDiagnostics } from "./hermes-acp-diagnostics.ts"; import type { SandboxClient } from "./clients/sandbox.ts"; @@ -45,6 +46,7 @@ export interface HermesAcpLiveOptions { export function hermesAcpLiveHostEnv(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv { const result: NodeJS.ProcessEnv = {}; for (const name of [ + ...GATEWAY_HOST_RUNTIME_ENV_KEYS, "HOME", "USER", "LOGNAME", @@ -58,12 +60,6 @@ export function hermesAcpLiveHostEnv(source: NodeJS.ProcessEnv): NodeJS.ProcessE "NODE_EXTRA_CA_CERTS", "CURL_CA_BUNDLE", "XDG_CONFIG_HOME", - "XDG_RUNTIME_DIR", - "DBUS_SESSION_BUS_ADDRESS", - "CONTAINERS_CONF", - "CONTAINERS_STORAGE_CONF", - "NEMOCLAW_GATEWAY_RUNTIME", - "OPENSHELL_PODMAN_SOCKET", "NEMOCLAW_OPENSHELL_BIN", "OPENSHELL_GATEWAY", "OPENSHELL_WORKSPACE", diff --git a/test/e2e/support/hermes-acp-live.test.ts b/test/e2e/support/hermes-acp-live.test.ts index ba1023eb424..caed808ae70 100644 --- a/test/e2e/support/hermes-acp-live.test.ts +++ b/test/e2e/support/hermes-acp-live.test.ts @@ -111,10 +111,20 @@ describe("Hermes ACP live evidence boundary", () => { async (installation, scenario, exitCode, scenarioEvidence) => { const artifactDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-acp-launch-")); const adapterEntrypoint = path.join(artifactDir, "nemoclaw-acp"); + const environmentReceipt = path.join(artifactDir, "child-env.json"); + const runtimeEnv: NodeJS.ProcessEnv = { + NEMOCLAW_GATEWAY_RUNTIME: "podman", + OPENSHELL_PODMAN_SOCKET: "/run/user/1000/podman/podman.sock", + CONTAINERS_CONF: "/tmp/containers.conf", + CONTAINERS_STORAGE_CONF: "/tmp/storage.conf", + XDG_RUNTIME_DIR: "/run/user/1000", + DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus", + }; fs.writeFileSync( adapterEntrypoint, `#!${process.execPath} const readline = require("node:readline"); +require("node:fs").writeFileSync(${JSON.stringify(environmentReceipt)}, JSON.stringify(process.env)); process.stdout.on("error", () => { process.exitCode = 1; process.stdin.destroy(); @@ -150,13 +160,25 @@ readline.createInterface({ input: process.stdin }).on("line", line => { runHermesAcpLiveScenario({ adapterEntrypoint: installation === "checkout" ? adapterEntrypoint : undefined, artifacts: new ArtifactSink(artifactDir), - env: { PATH: installation === "installed" ? artifactDir : "" }, + env: { + ...runtimeEnv, + PATH: installation === "installed" ? artifactDir : "", + NVIDIA_INFERENCE_API_KEY: "provider-secret", + OPENSHELL_TOKEN: "openshell-secret", + SSH_AUTH_SOCK: "/tmp/private-agent.sock", + }, progress, sandbox, sandboxName: "e2e-hermes", scenario, }), ).resolves.toBe(true); + const childEnv = JSON.parse(fs.readFileSync(environmentReceipt, "utf8")); + expect(childEnv).toMatchObject(runtimeEnv); + expect(resolveNemoClawGatewayRuntime(childEnv)).toBe("podman"); + expect(childEnv).not.toHaveProperty("NVIDIA_INFERENCE_API_KEY"); + expect(childEnv).not.toHaveProperty("OPENSHELL_TOKEN"); + expect(childEnv).not.toHaveProperty("SSH_AUTH_SOCK"); expect( JSON.parse(fs.readFileSync(path.join(artifactDir, `hermes-acp-${scenario}.json`), "utf8")), ).toMatchObject({ From 4e3886d27e19308b8210b360765b58680def6436 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 01:06:06 -0700 Subject: [PATCH 13/35] fix(runtime): clear managed credentials before startup helpers Signed-off-by: Aaron Erickson --- docs/security/process-controls.mdx | 5 +- scripts/nemoclaw-start.sh | 27 ++++---- .../runtime/auth-profile-boundary.test.ts | 68 +++++++++++++++---- 3 files changed, 71 insertions(+), 29 deletions(-) diff --git a/docs/security/process-controls.mdx b/docs/security/process-controls.mdx index 079d8c33b88..a1b04345f14 100644 --- a/docs/security/process-controls.mdx +++ b/docs/security/process-controls.mdx @@ -290,7 +290,10 @@ A registry-side tag change cannot silently select another managed sandbox image. ## Auth Profile Permissions -For managed `inference.local` routes, the entrypoint removes the exact legacy NemoClaw-generated profile, preserves non-matching user-managed profiles, and clears credential environment aliases before launching sandbox processes. Direct custom-image routes create or replace `auth-profiles.json` with the generated direct-route profile. The entrypoint and migration flows enforce `chmod 600` on auth-profile files under `~/.openclaw`. +For managed `inference.local` routes, the entrypoint clears the NVIDIA credential aliases before setup and command execution. +It removes only the exact legacy NemoClaw-generated profile and preserves other profiles. +Direct inference routes outside `inference.local` retain their credentials and create or replace `auth-profiles.json` with the generated direct-route profile. +The entrypoint and migration flows enforce `chmod 600` on auth-profile files under `~/.openclaw`. This prevents other users on the host from reading stored credentials that remain. | Aspect | Detail | diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 59f5c4c2c78..d090e44bcef 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -74,6 +74,18 @@ unset NEMOCLAW_ENTRYPOINT_NORMALIZED_ARGC NEMOCLAW_ENTRYPOINT_NORMALIZED_ARGV \ unset -f nemoclaw_normalize_entrypoint_env_wrapper # managed-entrypoint-env-wrapper end +# OpenShell owns inference.local authentication. Clear its credential aliases +# after entrypoint overrides are normalized, before setup can launch children. +# Direct inference routes retain their credentials. +clear_managed_inference_credentials() { + case "${NEMOCLAW_INFERENCE_BASE_URL:-}" in + https://inference.local | https://inference.local/*) + unset NVIDIA_INFERENCE_API_KEY NVIDIA_API_KEY + ;; + esac +} +clear_managed_inference_credentials + # Reject an invalid explicit dashboard port before installing the tee/fd startup # capture below. Some CI Docker runners can drop very early fd4 output from # short-lived containers, and this validation is meant to be fail-fast and @@ -2413,7 +2425,7 @@ prepare_gateway_token_for_current_command() { # Reconcile the legacy OpenClaw auth profile used by direct inference routes. # Managed OpenShell routes authenticate at the inference.local proxy, so the # sandbox must not retain even an environment-variable reference to the host -# credential. Direct custom-image routes still need the profile for OpenClaw. +# credential. Direct inference routes still need the profile for OpenClaw. write_auth_profile() { local provider_key="${NEMOCLAW_INFERENCE_PROVIDER_ID:-${NEMOCLAW_PROVIDER_KEY:-inference}}" @@ -2582,17 +2594,6 @@ os.chmod(path, 0o600) PYAUTH } -# Managed OpenShell routes authenticate at the host-owned proxy. Remove both -# accepted input aliases from the parent entrypoint environment after profile -# reconciliation succeeds, before any sandbox-user process can inherit them. -clear_managed_inference_credentials() { - case "${NEMOCLAW_INFERENCE_BASE_URL:-}" in - https://inference.local | https://inference.local/*) - unset NVIDIA_INFERENCE_API_KEY NVIDIA_API_KEY - ;; - esac -} - harden_auth_profiles() { if [ -d "${HOME}/.openclaw" ]; then # Enforce 600 for all auth profiles across all agents @@ -5551,7 +5552,6 @@ if [ "$(id -u)" -ne 0 ]; then # env. This covers both one-shot commands and the gateway launch. apply_messaging_runtime_env_aliases write_auth_profile - clear_managed_inference_credentials harden_auth_profiles if [ ${#NEMOCLAW_CMD[@]} -gt 0 ]; then @@ -5667,7 +5667,6 @@ verify_messaging_runtime_secret_scans # auth-profiles.json files under ~/.openclaw. See # setup_auth_profile_as_sandbox for the HOME-handling rationale. setup_auth_profile_as_sandbox -clear_managed_inference_credentials # If a command was passed (e.g., "openclaw agent ..."), run it as sandbox user if [ ${#NEMOCLAW_CMD[@]} -gt 0 ]; then diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index b9229940b23..26ccafb6135 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -26,8 +26,8 @@ const WRAPPER = [ "set -euo pipefail", extractShellFunctionFromSource(START_SOURCE, "write_auth_profile"), extractShellFunctionFromSource(START_SOURCE, "clear_managed_inference_credentials"), - "write_auth_profile", "clear_managed_inference_credentials", + "write_auth_profile", credentialProbe, ].join("\n"); @@ -75,24 +75,47 @@ function startupCredentialBoundaryBlock(kind: "non-root" | "root"): string { return START_SOURCE.slice(start, end); } -function runStartupCredentialBoundary(kind: "non-root" | "root") { +function runStartupCredentialBoundary( + kind: "non-root" | "root", + route = "managed", + failCleanup = false, +) { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-startup-")); + homes.push(home); + const script = path.join(home, "run.sh"); + const bootstrap = START_SOURCE.slice( + START_SOURCE.indexOf("# managed-entrypoint-env-wrapper end"), + START_SOURCE.indexOf("# Reject an invalid explicit dashboard port"), + ); const wrapper = [ - "set -euo pipefail", - extractShellFunctionFromSource(START_SOURCE, "clear_managed_inference_credentials"), + START_SOURCE.match(/^set -[a-z]+ pipefail$/m)?.[0] ?? "", + ...[ + "clear_managed_inference_credentials", + "_step_down_extract_function", + "run_step_down_as_sandbox", + "setup_auth_profile_as_sandbox", + ].map((name) => extractShellFunctionFromSource(START_SOURCE, name)), "NEMOCLAW_CMD=(probe)", "STEP_DOWN_PREFIX_SANDBOX=(env)", "apply_messaging_runtime_env_aliases() { :; }", - "write_auth_profile() { :; }", + "openclaw_config_dir_owner() { echo sandbox; }", + `write_auth_profile() { ${credentialProbe}; return ${failCleanup ? 41 : 0}; }`, "harden_auth_profiles() { :; }", - "setup_auth_profile_as_sandbox() { :; }", "install_messaging_runtime_preloads() { :; }", "verify_messaging_runtime_secret_scans() { :; }", - `run_oneshot_command() { ${credentialProbe}; }`, + `run_oneshot_command() { echo command; ${credentialProbe}; }`, + bootstrap, + credentialProbe, startupCredentialBoundaryBlock(kind), ].join("\n"); - return spawnSync("bash", ["-s", "--", START_SCRIPT], { - input: wrapper, - env: { PATH: process.env.PATH, ...managedEnv }, + fs.writeFileSync(script, wrapper); + return spawnSync("bash", [script], { + env: { + PATH: process.env.PATH, + HOME: home, + ...managedEnv, + ...(route === "direct" ? { NEMOCLAW_INFERENCE_BASE_URL: "https://direct.example/v1" } : {}), + }, encoding: "utf-8", }); } @@ -172,12 +195,29 @@ describe("OpenClaw auth-profile boundary", () => { expect(fs.readFileSync(fixture.authPath, "utf-8")).toBe(JSON.stringify(profiles)); }); + it.each([ + ["non-root", "managed"], + ["root", "managed"], + ["non-root", "direct"], + ["root", "direct"], + ] as const)( + "passes only allowed credentials to setup and command children in %s startup for %s routes", + (kind, route) => { + const result = runStartupCredentialBoundary(kind, route); + const credentials = route === "managed" ? "unset\nunset" : "primary-secret\nlegacy-secret"; + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe( + [credentials, credentials, "command", credentials].join("\n"), + ); + }, + ); + it.each(["non-root", "root"] as const)( - "clears credential aliases before the %s startup launches a command", + "stops %s startup when auth-profile reconciliation fails", (kind) => { - const result = runStartupCredentialBoundary(kind); - expect(result.status, result.stderr).toBe(0); - expect(result.stdout.trim()).toBe("unset\nunset"); + const result = runStartupCredentialBoundary(kind, "managed", true); + expect(result.status, result.stderr).toBe(41); + expect(result.stdout).not.toContain("command"); }, ); From 9e28a3f5f16d85b6515d1c36369f1fbba7fb7bc3 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 23 Sep 2026 01:35:21 -0700 Subject: [PATCH 14/35] test(hermes): recognize exact Podman export refusal Signed-off-by: Deepak Jain --- .../e2e/fixtures/hermes-config-export-live.ts | 18 +++-- .../support/hermes-config-export-live.test.ts | 65 +++++++++++++++++++ 2 files changed, 78 insertions(+), 5 deletions(-) diff --git a/test/e2e/fixtures/hermes-config-export-live.ts b/test/e2e/fixtures/hermes-config-export-live.ts index c3ffa4d286f..857486e371e 100644 --- a/test/e2e/fixtures/hermes-config-export-live.ts +++ b/test/e2e/fixtures/hermes-config-export-live.ts @@ -74,7 +74,8 @@ export type HermesConfigExportLiveEvidence = const CREDENTIAL_HTTP_REFUSAL = "V1alpha1 requires HTTPS when an inference provider declares a credential."; -const CREDENTIAL_HTTP_REFUSAL_DIAGNOSTIC = `Config export failed (unsupported).\n${CREDENTIAL_HTTP_REFUSAL}`; +const PODMAN_REFUSAL = + "V1alpha1 export currently supports the Docker runtime; Podman compatibility is deferred."; function normalizeCommandDiagnostics(stdout: string, stderr: string): string { return [stdout, stderr] @@ -250,16 +251,23 @@ export async function verifyHermesConfigExportLive( typeof entry.credentialEnv === "string" && entry.credentialEnv.length > 0 && entry.endpointUrl?.toLowerCase().startsWith("http:") === true; - if (expectsCredentialHttpRefusal) { + const expectedRefusals = [ + ...(entry.openshellDriver === "podman" ? [PODMAN_REFUSAL] : []), + ...(expectsCredentialHttpRefusal ? [CREDENTIAL_HTTP_REFUSAL] : []), + ]; + if (expectedRefusals.length > 0) { + const expectedDiagnostic = ["Config export failed (unsupported).", ...expectedRefusals].join( + "\n", + ); const refusalDiagnosticMatches = [nemoclawDiagnostics, nemohermesDiagnostics].every( - (diagnostic) => diagnostic === CREDENTIAL_HTTP_REFUSAL_DIAGNOSTIC, + (diagnostic) => diagnostic === expectedDiagnostic, ); const refusalCategory = refusalDiagnosticMatches ? "unsupported" : null; const evidence: HermesConfigExportExpectedRefusalEvidence = { outcome: "expected-refusal", aliasesEquivalent: - nemoclaw.exitCode !== 0 && - nemohermes.exitCode !== 0 && + nemoclaw.exitCode === 2 && + nemohermes.exitCode === 2 && nemoclawDiagnostics === nemohermesDiagnostics, checked: true, credentialValuesOmitted: !containsCredential, diff --git a/test/e2e/support/hermes-config-export-live.test.ts b/test/e2e/support/hermes-config-export-live.test.ts index 4ae0ece5d9a..2d187982a2b 100644 --- a/test/e2e/support/hermes-config-export-live.test.ts +++ b/test/e2e/support/hermes-config-export-live.test.ts @@ -230,6 +230,71 @@ describe("Hermes config export live evidence", () => { expect(mocks.asExportedConfig).not.toHaveBeenCalled(); }); + it.each(["http", "https"])("accepts the exact Podman %s export refusal", async (scheme) => { + mocks.load.mockReturnValue({ + sandboxes: { + hermes: { + openshellDriver: "podman", + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: `${scheme}://host.openshell.internal:35271/v1`, + gatewayName: "nemoclaw", + workload: { kind: "managed-image", reference: IMAGE_REF }, + }, + }, + }); + const diagnostics = [ + "Config export failed (unsupported).", + "V1alpha1 export currently supports the Docker runtime; Podman compatibility is deferred.", + ...(scheme === "http" + ? ["V1alpha1 requires HTTPS when an inference provider declares a credential."] + : []), + ].join("\n"); + mocks.command.mockResolvedValue({ exitCode: 2, stdout: "", stderr: diagnostics }); + await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); + expect(mocks.save).not.toHaveBeenCalled(); + expect(mocks.asExportedConfig).not.toHaveBeenCalled(); + }); + + it.each([ + { + label: "unrelated failure", + exitCode: 2, + extra: "\nunrelated failure", + writeOutput: (_args: string[]) => undefined, + }, + { label: "wrong exit", exitCode: 1, extra: "", writeOutput: (_args: string[]) => undefined }, + { + label: "published file", + exitCode: 2, + extra: "", + writeOutput: (args: string[]) => + fs.writeFileSync(args.at(args.indexOf("--output") + 1)!, "{}"), + }, + ])("rejects Podman refusal with $label", async ({ exitCode, extra, writeOutput }) => { + mocks.load.mockReturnValue({ + sandboxes: { + hermes: { + openshellDriver: "podman", + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: "https://integrate.api.nvidia.com/v1", + gatewayName: "nemoclaw", + workload: { kind: "managed-image", reference: IMAGE_REF }, + }, + }, + }); + mocks.command.mockImplementation(async (_command: string, args: string[]) => { + writeOutput(args); + return { + exitCode, + stdout: "", + stderr: + "Config export failed (unsupported).\nV1alpha1 export currently supports the Docker runtime; Podman compatibility is deferred." + + extra, + }; + }); + await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: false }); + }); + it("rejects a credential-bearing HTTP refusal when one alias publishes output", async () => { mocks.load.mockReturnValue({ sandboxes: { From db200be25c0bae62e8975f31dd94d905132a682d Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 01:55:25 -0700 Subject: [PATCH 15/35] fix(runtime): recognize the managed inference default port Signed-off-by: Aaron Erickson --- docs/security/process-controls.mdx | 4 +-- scripts/nemoclaw-start.sh | 4 +-- .../runtime/auth-profile-boundary.test.ts | 26 +++++++++++++------ 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/docs/security/process-controls.mdx b/docs/security/process-controls.mdx index a1b04345f14..30cfd460fc1 100644 --- a/docs/security/process-controls.mdx +++ b/docs/security/process-controls.mdx @@ -291,14 +291,14 @@ A registry-side tag change cannot silently select another managed sandbox image. ## Auth Profile Permissions For managed `inference.local` routes, the entrypoint clears the NVIDIA credential aliases before setup and command execution. -It removes only the exact legacy NemoClaw-generated profile and preserves other profiles. +It removes only the exact legacy NemoClaw-generated profile for the selected managed provider and preserves other profiles. Direct inference routes outside `inference.local` retain their credentials and create or replace `auth-profiles.json` with the generated direct-route profile. The entrypoint and migration flows enforce `chmod 600` on auth-profile files under `~/.openclaw`. This prevents other users on the host from reading stored credentials that remain. | Aspect | Detail | |---|---| -| Default | Managed routes retain no legacy host-credential reference. Remaining auth profiles receive `600` permissions recursively at startup and after migration restores. | +| Default | The selected managed provider's generated profile is removed. Other auth profiles receive `600` permissions recursively at startup and after migration restores. | | What you can change | This is not a user-facing knob. The entrypoint enforces it. | | Risk if relaxed | Looser permissions let other users or processes on the host read provider API keys and tokens stored in auth profiles. | | Recommendation | No action needed. If you see a `permission denied` error when reading auth profiles, verify that you are running as the same user who created them. | diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index d090e44bcef..68f8a825d12 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -79,7 +79,7 @@ unset -f nemoclaw_normalize_entrypoint_env_wrapper # Direct inference routes retain their credentials. clear_managed_inference_credentials() { case "${NEMOCLAW_INFERENCE_BASE_URL:-}" in - https://inference.local | https://inference.local/*) + https://inference.local | https://inference.local/* | https://inference.local:443 | https://inference.local:443/*) unset NVIDIA_INFERENCE_API_KEY NVIDIA_API_KEY ;; esac @@ -2430,7 +2430,7 @@ write_auth_profile() { local provider_key="${NEMOCLAW_INFERENCE_PROVIDER_ID:-${NEMOCLAW_PROVIDER_KEY:-inference}}" case "${NEMOCLAW_INFERENCE_BASE_URL:-}" in - https://inference.local | https://inference.local/*) + https://inference.local | https://inference.local/* | https://inference.local:443 | https://inference.local:443/*) # Remove only the exact entries this function historically generated. # Preserve user-managed direct-provider profiles if they share the file. python3 - "$provider_key" <<'PYAUTH' diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index 26ccafb6135..a96e78021e9 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -83,6 +83,10 @@ function runStartupCredentialBoundary( const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-startup-")); homes.push(home); const script = path.join(home, "run.sh"); + const command = path.join(home, "command.sh"); + fs.writeFileSync(command, `#!/usr/bin/env bash\necho command\n${credentialProbe}\n`, { + mode: 0o700, + }); const bootstrap = START_SOURCE.slice( START_SOURCE.indexOf("# managed-entrypoint-env-wrapper end"), START_SOURCE.indexOf("# Reject an invalid explicit dashboard port"), @@ -94,8 +98,10 @@ function runStartupCredentialBoundary( "_step_down_extract_function", "run_step_down_as_sandbox", "setup_auth_profile_as_sandbox", + "run_oneshot_command", ].map((name) => extractShellFunctionFromSource(START_SOURCE, name)), - "NEMOCLAW_CMD=(probe)", + 'NEMOCLAW_CMD=("$AUTH_TEST_COMMAND")', + '_RUNTIME_SHELL_ENV_FILE="$HOME/no-runtime-env"', "STEP_DOWN_PREFIX_SANDBOX=(env)", "apply_messaging_runtime_env_aliases() { :; }", "openclaw_config_dir_owner() { echo sandbox; }", @@ -103,7 +109,7 @@ function runStartupCredentialBoundary( "harden_auth_profiles() { :; }", "install_messaging_runtime_preloads() { :; }", "verify_messaging_runtime_secret_scans() { :; }", - `run_oneshot_command() { echo command; ${credentialProbe}; }`, + "normalize_mutable_config_perms() { :; }", bootstrap, credentialProbe, startupCredentialBoundaryBlock(kind), @@ -113,6 +119,7 @@ function runStartupCredentialBoundary( env: { PATH: process.env.PATH, HOME: home, + AUTH_TEST_COMMAND: command, ...managedEnv, ...(route === "direct" ? { NEMOCLAW_INFERENCE_BASE_URL: "https://direct.example/v1" } : {}), }, @@ -154,13 +161,16 @@ describe("OpenClaw auth-profile boundary", () => { expect(fs.existsSync(fixture.authPath)).toBe(false); }); - it.each(["fresh", "legacy"] as const)( - "leaves no managed profile or inherited credentials in %s state", - (state) => { + it.each([ + ["fresh", "https://inference.local/v1"], + ["legacy", "https://inference.local/v1"], + ["fresh", "https://inference.local:443/v1"], + ["legacy", "https://inference.local:443"], + ] as const)( + "leaves no managed profile or inherited credentials in %s state at %s", + (state, baseUrl) => { const fixture = runWriteAuthProfile( - state === "fresh" - ? managedEnv - : { NEMOCLAW_INFERENCE_BASE_URL: managedEnv.NEMOCLAW_INFERENCE_BASE_URL }, + { ...(state === "fresh" ? managedEnv : {}), NEMOCLAW_INFERENCE_BASE_URL: baseUrl }, state === "legacy" ? seedAuthProfile({ "inference:manual": legacyManagedProfile }) : undefined, From 9db5560d63bdb2fcbb3d5454790f564fb2f1058d Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 03:01:14 -0700 Subject: [PATCH 16/35] fix(runtime): reconcile managed profiles before root doctor Signed-off-by: Aaron Erickson --- ci/test-file-size-budget.json | 2 +- scripts/nemoclaw-start.sh | 38 +++++--- .../runtime/auth-profile-boundary.test.ts | 90 +++++++++++++------ .../openclaw/runtime/nemoclaw-start.test.ts | 13 ++- 4 files changed, 96 insertions(+), 47 deletions(-) diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index b872b359c07..1a2181684a4 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -7,7 +7,7 @@ "src/lib/onboard/preflight.test.ts": 1875, "test/generation/generate-openclaw-config.test.ts": 1844, "test/installer-integration/install-preflight.test.ts": 2995, - "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 4188, + "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 4187, "test/onboarding/onboard-messaging.test.ts": 1960, "test/onboarding/onboard-selection.test.ts": 4125 } diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 68f8a825d12..739aad13d01 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -77,12 +77,19 @@ unset -f nemoclaw_normalize_entrypoint_env_wrapper # OpenShell owns inference.local authentication. Clear its credential aliases # after entrypoint overrides are normalized, before setup can launch children. # Direct inference routes retain their credentials. -clear_managed_inference_credentials() { +is_managed_inference_route() { case "${NEMOCLAW_INFERENCE_BASE_URL:-}" in https://inference.local | https://inference.local/* | https://inference.local:443 | https://inference.local:443/*) - unset NVIDIA_INFERENCE_API_KEY NVIDIA_API_KEY + return 0 ;; esac + return 1 +} + +clear_managed_inference_credentials() { + if is_managed_inference_route; then + unset NVIDIA_INFERENCE_API_KEY NVIDIA_API_KEY + fi } clear_managed_inference_credentials @@ -2429,11 +2436,10 @@ prepare_gateway_token_for_current_command() { write_auth_profile() { local provider_key="${NEMOCLAW_INFERENCE_PROVIDER_ID:-${NEMOCLAW_PROVIDER_KEY:-inference}}" - case "${NEMOCLAW_INFERENCE_BASE_URL:-}" in - https://inference.local | https://inference.local/* | https://inference.local:443 | https://inference.local:443/*) - # Remove only the exact entries this function historically generated. - # Preserve user-managed direct-provider profiles if they share the file. - python3 - "$provider_key" <<'PYAUTH' + if is_managed_inference_route; then + # Remove only the exact entries this function historically generated. + # Preserve user-managed direct-provider profiles if they share the file. + python3 - "$provider_key" <<'PYAUTH' import json import os import secrets @@ -2554,9 +2560,8 @@ try: finally: os.close(directory_fd) PYAUTH - return - ;; - esac + return + fi if [ -z "${NVIDIA_INFERENCE_API_KEY:-}" ] && [ -n "${NVIDIA_API_KEY:-}" ]; then export NVIDIA_INFERENCE_API_KEY="$NVIDIA_API_KEY" @@ -4881,6 +4886,7 @@ setup_auth_profile_as_sandbox() { run_step_down_as_sandbox \ "export HOME=/sandbox; write_auth_profile; harden_auth_profiles" \ openclaw_config_dir_owner \ + is_managed_inference_route \ write_auth_profile \ harden_auth_profiles } @@ -5641,6 +5647,10 @@ apply_model_override reconcile_agent_model_with_provider apply_cors_override configure_messaging_channels +# Remove the obsolete managed reference before Doctor can import it into SQLite. +if is_managed_inference_route; then + setup_auth_profile_as_sandbox +fi run_requested_openclaw_post_upgrade_doctor || exit 1 refresh_openclaw_provider_placeholders ensure_mutable_openclaw_config_hash @@ -5663,10 +5673,10 @@ apply_messaging_runtime_env_aliases install_messaging_runtime_preloads verify_messaging_runtime_secret_scans -# Write auth profile as sandbox user and recursively re-tighten any -# auth-profiles.json files under ~/.openclaw. See -# setup_auth_profile_as_sandbox for the HOME-handling rationale. -setup_auth_profile_as_sandbox +# Write direct-route profiles after Doctor has migrated existing user profiles. +if ! is_managed_inference_route; then + setup_auth_profile_as_sandbox +fi # If a command was passed (e.g., "openclaw agent ..."), run it as sandbox user if [ ${#NEMOCLAW_CMD[@]} -gt 0 ]; then diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index a96e78021e9..b4ec43a484e 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -22,25 +22,24 @@ const homes: string[] = []; afterEach(() => { for (const home of homes.splice(0)) fs.rmSync(home, { recursive: true, force: true }); }); -const WRAPPER = [ +const AUTH_FUNCTIONS = [ "set -euo pipefail", + extractShellFunctionFromSource(START_SOURCE, "is_managed_inference_route"), extractShellFunctionFromSource(START_SOURCE, "write_auth_profile"), extractShellFunctionFromSource(START_SOURCE, "clear_managed_inference_credentials"), - "clear_managed_inference_credentials", - "write_auth_profile", - credentialProbe, ].join("\n"); -function runWriteAuthProfile( +function runBashAuthFixture( env: Record, prepare: (authPath: string) => void = () => undefined, + commands = `clear_managed_inference_credentials\nwrite_auth_profile\n${credentialProbe}`, ) { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-test-")); homes.push(home); const authPath = path.join(home, ".openclaw", "agents", "main", "agent", "auth-profiles.json"); prepare(authPath); const result = spawnSync("bash", ["-s", "--", START_SCRIPT], { - input: WRAPPER, + input: `${AUTH_FUNCTIONS}\n${commands}`, env: { PATH: process.env.PATH, HOME: home, ...env }, encoding: "utf-8", }); @@ -54,27 +53,35 @@ function seedAuthProfile(profile: Record): (authPath: string) = }; } -function startupCredentialBoundaryBlock(kind: "non-root" | "root"): string { - const regionStart = START_SOURCE.indexOf( - kind === "non-root" - ? "# ── Non-root fallback" - : "# ── Root path (full privilege separation via setpriv)", - ); - const startMarker = - kind === "non-root" - ? " apply_messaging_runtime_env_aliases\n" - : "setup_auth_profile_as_sandbox\n"; - const endMarker = - kind === "non-root" ? "\n configure_messaging_channels" : "\nprepare_auto_pair_log"; +function startupSection(startMarker: string, endMarker: string, region: string): string { + const regionStart = START_SOURCE.indexOf(region); const start = START_SOURCE.indexOf(startMarker, regionStart); const end = START_SOURCE.indexOf(endMarker, start); expect( regionStart !== -1 && start !== -1 && end !== -1 && end > start, - `Expected ${kind} credential-boundary block in scripts/nemoclaw-start.sh`, + `Expected startup section ${startMarker}`, ).toBe(true); return START_SOURCE.slice(start, end); } +function rootDoctorBlock(): string { + return startupSection( + "configure_messaging_channels\n", + "refresh_openclaw_provider_placeholders\n", + "# ── Root path", + ); +} + +function startupCredentialBoundaryBlock(kind: "non-root" | "root"): string { + return kind === "root" + ? `${rootDoctorBlock()}\n${startupSection("# Write direct-route profiles after Doctor", "\nprepare_auto_pair_log", "# ── Root path")}` + : startupSection( + " apply_messaging_runtime_env_aliases\n", + "\n configure_messaging_channels", + "# ── Non-root fallback", + ); +} + function runStartupCredentialBoundary( kind: "non-root" | "root", route = "managed", @@ -94,6 +101,7 @@ function runStartupCredentialBoundary( const wrapper = [ START_SOURCE.match(/^set -[a-z]+ pipefail$/m)?.[0] ?? "", ...[ + "is_managed_inference_route", "clear_managed_inference_credentials", "_step_down_extract_function", "run_step_down_as_sandbox", @@ -110,6 +118,8 @@ function runStartupCredentialBoundary( "install_messaging_runtime_preloads() { :; }", "verify_messaging_runtime_secret_scans() { :; }", "normalize_mutable_config_perms() { :; }", + "configure_messaging_channels() { :; }", + "run_requested_openclaw_post_upgrade_doctor() { :; }", bootstrap, credentialProbe, startupCredentialBoundaryBlock(kind), @@ -140,7 +150,7 @@ describe("OpenClaw auth-profile boundary", () => { ["configured", "openai", "openai"], ["literal", "$(echo pwned)", "$(echo pwned)"], ] as const)("writes a private direct profile for the %s route", (_label, route, provider) => { - const fixture = runWriteAuthProfile({ + const fixture = runBashAuthFixture({ NVIDIA_INFERENCE_API_KEY: "secret", ...(route === undefined ? {} : { NEMOCLAW_INFERENCE_PROVIDER_ID: route }), }); @@ -156,7 +166,7 @@ describe("OpenClaw auth-profile boundary", () => { }); it("leaves direct auth state absent when no credential is supplied", () => { - const fixture = runWriteAuthProfile({}); + const fixture = runBashAuthFixture({}); expect(fixture.status, fixture.stderr).toBe(0); expect(fs.existsSync(fixture.authPath)).toBe(false); }); @@ -169,7 +179,7 @@ describe("OpenClaw auth-profile boundary", () => { ] as const)( "leaves no managed profile or inherited credentials in %s state at %s", (state, baseUrl) => { - const fixture = runWriteAuthProfile( + const fixture = runBashAuthFixture( { ...(state === "fresh" ? managedEnv : {}), NEMOCLAW_INFERENCE_BASE_URL: baseUrl }, state === "legacy" ? seedAuthProfile({ "inference:manual": legacyManagedProfile }) @@ -187,7 +197,7 @@ describe("OpenClaw auth-profile boundary", () => { provider: "custom", profileId: "custom:manual", }; - const fixture = runWriteAuthProfile( + const fixture = runBashAuthFixture( managedEnv, seedAuthProfile({ "inference:manual": legacyManagedProfile, "custom:manual": customProfile }), ); @@ -200,11 +210,41 @@ describe("OpenClaw auth-profile boundary", () => { it("preserves a near-match profile byte for byte", () => { const profiles = { "inference:manual": { ...legacyManagedProfile, label: "user-managed" } }; - const fixture = runWriteAuthProfile(managedEnv, seedAuthProfile(profiles)); + const fixture = runBashAuthFixture(managedEnv, seedAuthProfile(profiles)); expect(fixture.status, fixture.stderr).toBe(0); expect(fs.readFileSync(fixture.authPath, "utf-8")).toBe(JSON.stringify(profiles)); }); + it.each(["managed", "direct"])("presents the correct %s profiles to root Doctor", (route) => { + const custom = { + ...legacyManagedProfile, + provider: "custom", + profileId: "custom:manual", + keyRef: { source: "env", id: "CUSTOM_API_KEY" }, + }; + const profiles = { "inference:manual": legacyManagedProfile, "custom:manual": custom }; + const fixture = runBashAuthFixture( + { + ...managedEnv, + ...(route === "direct" ? { NEMOCLAW_INFERENCE_BASE_URL: "https://direct.example/v1" } : {}), + }, + seedAuthProfile(profiles), + [ + extractShellFunctionFromSource(START_SOURCE, "setup_auth_profile_as_sandbox"), + // Keep fixture HOME instead of switching users; reconciliation remains real. + "run_step_down_as_sandbox() { write_auth_profile; }", + "configure_messaging_channels() { :; }", + 'run_requested_openclaw_post_upgrade_doctor() { cat "$HOME/.openclaw/agents/main/agent/auth-profiles.json"; }', + "clear_managed_inference_credentials", + rootDoctorBlock(), + ].join("\n"), + ); + expect(fixture.status, fixture.stderr).toBe(0); + expect(JSON.parse(fixture.stdout)).toEqual( + route === "managed" ? { "custom:manual": custom } : profiles, + ); + }); + it.each([ ["non-root", "managed"], ["root", "managed"], @@ -234,7 +274,7 @@ describe("OpenClaw auth-profile boundary", () => { it("rejects a symlinked parent without changing its target", () => { const externalContents = JSON.stringify({ "inference:manual": legacyManagedProfile }); let externalProfile = ""; - const fixture = runWriteAuthProfile(managedEnv, (authPath) => { + const fixture = runBashAuthFixture(managedEnv, (authPath) => { const openclawDir = path.resolve(authPath, "../../../../"); const externalAgents = path.join(path.dirname(openclawDir), "external-agents"); externalProfile = path.join(externalAgents, "main", "agent", "auth-profiles.json"); diff --git a/test/agents/openclaw/runtime/nemoclaw-start.test.ts b/test/agents/openclaw/runtime/nemoclaw-start.test.ts index ed6a0f0bfdc..e045f2d6ecd 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start.test.ts @@ -3868,17 +3868,13 @@ describe("run_step_down_as_sandbox", () => { describe("setup_auth_profile_as_sandbox", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); const helper = [ + extractShellFunctionFromSource(src, "is_managed_inference_route"), extractShellFunctionFromSource(src, "_step_down_extract_function"), extractShellFunctionFromSource(src, "run_step_down_as_sandbox"), ].join("\n"); const setup = extractShellFunctionFromSource(src, "setup_auth_profile_as_sandbox"); it("runs the auth-profile setup under HOME=/sandbox even when the parent env has HOME=/root", () => { - // setpriv preserves the parent shell's environment, so the root - // entrypoint's HOME=/root would otherwise leak into the step-down - // shell and `write_auth_profile`'s `~/.openclaw/...` expansion - // would target /root. Stub `write_auth_profile` to record the - // HOME the step-down shell actually observed and assert it was - // overridden to /sandbox. + // setpriv preserves HOME; profile setup must replace /root with /sandbox. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-setup-auth-profile-")); const observedHome = path.join(tmpDir, "observed-home"); const scriptPath = path.join(tmpDir, "run.sh"); @@ -4114,7 +4110,10 @@ describe("direct-root entrypoint composition under CAP_DAC_OVERRIDE drop", () => extractShellFunctionFromSource(src, "_step_down_extract_function"), extractShellFunctionFromSource(src, "run_step_down_as_sandbox"), ].join("\n"); - const setupAuth = extractShellFunctionFromSource(src, "setup_auth_profile_as_sandbox"); + const setupAuth = [ + extractShellFunctionFromSource(src, "is_managed_inference_route"), + extractShellFunctionFromSource(src, "setup_auth_profile_as_sandbox"), + ].join("\n"); fs.writeFileSync( scriptPath, [ From ab77d25de82ed2167d0cca099bc9768f1b2dbcb0 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 03:38:37 -0700 Subject: [PATCH 17/35] test(e2e): reject unexplained empty assistant responses Signed-off-by: Aaron Erickson --- test/e2e/live/launch-agent-turn.ts | 18 ++++++++---------- ...ch-agent-turn-provider-availability.test.ts | 11 ++++++----- test/e2e/support/launch-agent-turn.test.ts | 14 +++++++------- 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index f0fc6da0dd9..92931151da1 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -1472,13 +1472,11 @@ fail_provider_unavailable() { fail_launch_session "launch did not record the required structured session turns" } -# OpenClaw can persist either a structurally complete provider error or an -# assistant record without content. Treat only those exact, bounded diagnostics -# as provider-response transients. The fresh-session retry below is safe because -# cleanup removes the baseline and PTY monitor before emitting the marker. -is_retryable_provider_evidence() { - awk ' - NR == 1 && /^\{"reason":"(message_content_empty|provider_unavailable)","sessionId":"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"\}$/ { matched = 1 } +# Retry only a structured provider failure, including when OpenShell normalizes +# its exit status. Empty content alone does not establish a provider failure. +has_structured_evidence_reason() { + awk -v reason="$1" ' + NR == 1 && /^\{"reason":"[a-z_]+","sessionId":"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"\}$/ && index($0, "\"reason\":\"" reason "\"") { matched = 1 } END { exit !(NR == 1 && matched == 1) } ' "$evidence_error" } @@ -1529,10 +1527,10 @@ wait_for_turn_count() { # OpenShell normalizes a nonzero sandbox child status to 1. Classify the # exact bounded diagnostic for both the direct and transport-level status. case "$evidence_status" in - 1|2) is_retryable_provider_evidence && fail_provider_unavailable ;; + 1|2) has_structured_evidence_reason provider_unavailable && fail_provider_unavailable ;; 3) fail_provider_unavailable ;; esac - if [[ "$evidence_status" != 1 ]]; then + if [[ "$evidence_status" != 1 ]] || has_structured_evidence_reason message_content_empty; then fail_launch_session \ "structured session evidence was invalid or unavailable (status $evidence_status)" fi @@ -1685,7 +1683,7 @@ if session_evidence qualify 2 >/dev/null 2>"$evidence_error"; then else evidence_status=$? case "$evidence_status" in - 1|2) is_retryable_provider_evidence && fail_provider_unavailable ;; + 1|2) has_structured_evidence_reason provider_unavailable && fail_provider_unavailable ;; 3) fail_provider_unavailable ;; esac fail_launch_session "launch final structured session evidence did not qualify (status $evidence_status)" diff --git a/test/e2e/support/launch-agent-turn-provider-availability.test.ts b/test/e2e/support/launch-agent-turn-provider-availability.test.ts index 89783751747..0849a5914a9 100644 --- a/test/e2e/support/launch-agent-turn-provider-availability.test.ts +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -18,16 +18,13 @@ function launchOptions(host: unknown) { }; } -it.each(["500", "503", "message_content_empty"] as const)( +it.each(["500", "503"] as const)( "retries transient provider failure %s in a fresh launch session (#10978)", async (status) => { const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); vi.useFakeTimers(); const calls: Array<{ artifactName?: string; env?: NodeJS.ProcessEnv }> = []; - const diagnostic = - status === "message_content_empty" - ? '{"reason":"message_content_empty","sessionId":"ed80ef8e-a026-424f-8ca4-669f6060e046"}' - : `litellm.ServiceUnavailableError: HTTP ${status}; NVIDIA upstream unavailable`; + const diagnostic = `litellm.ServiceUnavailableError: HTTP ${status}; NVIDIA upstream unavailable`; const host = { command: async ( _command: string, @@ -102,6 +99,10 @@ it("classifies exhausted transient launch attempts as provider unavailable (#109 }); it.each([ + [ + "unexplained empty assistant content", + '{"reason":"message_content_empty","sessionId":"ed80ef8e-a026-424f-8ca4-669f6060e046"}', + ], [ "marker from another launch run", `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:different-run-id\n`, diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index 1901182624f..701156c0382 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -449,6 +449,8 @@ if [[ ( "$NEMOCLAW_FIXTURE_MODE" == "delayed-recording" || "$NEMOCLAW_FIXTURE_MO set -e [[ "$status" != "1" ]] || : > "$NEMOCLAW_FIXTURE_PENDING_QUALIFICATION_MARKER" [[ "$NEMOCLAW_FIXTURE_MODE" != "provider-exit-after-recording" ]] || sleep 0.2 + # OpenShell preserves the diagnostic but normalizes nonzero child statuses. + [[ "$NEMOCLAW_FIXTURE_MODE" != "provider-exit-after-recording" || "$status" == "0" ]] || exit 1 exit "$status" fi if [[ "$NEMOCLAW_FIXTURE_MODE" == "provider-empty-message" && "$4" == "qualify" ]]; then @@ -499,9 +501,7 @@ exec "$@" NEMOCLAW_FIXTURE_PTY_SOCKET_RECEIPT: ptySocketReceiptPath, NEMOCLAW_FIXTURE_SESSION_FILE: join( sessionRoot, - mode === "provider-empty-message" - ? "ed80ef8e-a026-424f-8ca4-669f6060e046.jsonl" - : "session-a.jsonl", + "ed80ef8e-a026-424f-8ca4-669f6060e046.jsonl", ), NEMOCLAW_FIXTURE_TERMINAL_COPY: terminalCopy, NEMOCLAW_FIXTURE_RUN_ID: runId, @@ -1071,7 +1071,7 @@ it.runIf(process.platform === "linux").concurrent( ); it.runIf(process.platform === "linux").concurrent( - "marks provider unavailability when it leaves an empty structured turn (#9160, #10978)", + "fails an unexplained empty structured turn without a provider retry (#12254)", async ({ expect }) => { const { baselineRemoved, result, ttyObserved } = await runLaunchSessionFixture( "provider-empty-message", @@ -1081,7 +1081,7 @@ it.runIf(process.platform === "linux").concurrent( expect(baselineRemoved).toBe(true); expect(result.status).toBe(1); expect(result.stderr).toContain('"reason":"message_content_empty"'); - expect(result.stderr).toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); + expect(result.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); }, testTimeout(30_000), ); @@ -1097,7 +1097,7 @@ it.runIf(process.platform === "linux").each([ ] as const)( "executes the real $1 HTTP $0 launch producer through $2 (#10978)", async (providerCode, providerError, secondMode) => { - const expectedError = secondMode === "valid" ? null : "provider unavailable after 2 attempts"; + const expectedError = secondMode === "valid" ? null : "launch session failed"; const secondTerminal = secondMode === "valid" ? "absent" : "provider"; const calls: Array<{ artifactName?: string; @@ -1172,7 +1172,7 @@ it.runIf(process.platform === "linux").each([ ); expect( calls[1]?.stderr.includes(`${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${calls[1]?.runId}`), - ).toBe(expectedError !== null); + ).toBe(false); } finally { vi.useRealTimers(); } From e1ab9d0b2ef12d87c119a07fc6bb878aa73291df Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 04:12:20 -0700 Subject: [PATCH 18/35] test(e2e): keep provider diagnostics portable Signed-off-by: Aaron Erickson --- test/e2e/README.md | 5 ++++- test/e2e/live/full-e2e.test.ts | 2 +- test/e2e/live/launch-agent-turn.ts | 7 +++++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/test/e2e/README.md b/test/e2e/README.md index 6f151acfd3c..ab8be6b7955 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -854,10 +854,13 @@ supported outcomes now have these owners: | Removed assertion | Retained owner | |---|---| | Install, PATH setup, list, status, hosted inference, and sandbox inference succeed. | `full-e2e` | -| Sandbox state contains no `auth-profiles.json` or secret-shaped credential values. | `full-e2e` and `test/e2e/support/sandbox-credential-boundary.test.ts` | +| Fresh managed sandbox state contains no `auth-profiles.json` or secret-shaped credential values. | `full-e2e` and `test/e2e/support/sandbox-credential-boundary.test.ts` | | Repository skills contain valid frontmatter and content. | `test/repository/repo-skills-validation.test.ts` | | `/sandbox/.openclaw` and `openclaw.json` have the required image layout. | `test/e2e-runtime/managed-image-openclaw-security.test.ts` | +The fresh-sandbox check starts without user-managed profiles. Existing-state cleanup preserves +unrelated profiles, as covered by `test/agents/openclaw/runtime/auth-profile-boundary.test.ts`. + The optional `/sandbox/.openclaw/skills` directory had no pass or fail state. The deleted provider retry classifier and sandbox-layout wrapper served only the retired target. diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index 9b0a3d87194..ef53f5cca28 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -736,7 +736,7 @@ test( "sandbox appears in list/status and has policy/inference configuration", "native OpenClaw install, invoke, update, self-update, restart, discovery, and removal are not intercepted", "direct hosted inference and sandbox inference.local both respond", - "sandbox state contains neither auth-profiles.json nor secret-shaped credential values", + "fresh managed sandbox state contains neither auth-profiles.json nor secret-shaped credential values", ...(process.platform === "linux" ? [ "each of two PTY launches records two ordered structured turns and restores the mutable config permission contract", diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 92931151da1..b8091e774ee 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -1475,8 +1475,11 @@ fail_provider_unavailable() { # Retry only a structured provider failure, including when OpenShell normalizes # its exit status. Empty content alone does not establish a provider failure. has_structured_evidence_reason() { - awk -v reason="$1" ' - NR == 1 && /^\{"reason":"[a-z_]+","sessionId":"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"\}$/ && index($0, "\"reason\":\"" reason "\"") { matched = 1 } + awk -F '"' -v reason="$1" ' + NR == 1 && /^\{"reason":"[a-z_]+","sessionId":"[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+"\}$/ && $4 == reason { + split($8, groups, "-") + matched = length(groups[1]) == 8 && length(groups[2]) == 4 && length(groups[3]) == 4 && length(groups[4]) == 4 && length(groups[5]) == 12 + } END { exit !(NR == 1 && matched == 1) } ' "$evidence_error" } From 35dbb1368a3bab9d0177ad7a19e5355f6335c793 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 04:47:56 -0700 Subject: [PATCH 19/35] test(runtime): reuse doctor fixture for configured providers Signed-off-by: Aaron Erickson --- .../runtime/auth-profile-boundary.test.ts | 44 ++++++++----------- 1 file changed, 19 insertions(+), 25 deletions(-) diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index b4ec43a484e..a53dffcc0f1 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -137,12 +137,15 @@ function runStartupCredentialBoundary( }); } -const legacyManagedProfile = { - type: "api_key", - provider: "inference", - keyRef: { source: "env", id: "NVIDIA_INFERENCE_API_KEY" }, - profileId: "inference:manual", -}; +function legacyProfile(provider = "inference", keyId = "NVIDIA_INFERENCE_API_KEY") { + return { + type: "api_key", + provider, + keyRef: { source: "env", id: keyId }, + profileId: `${provider}:manual`, + }; +} +const legacyManagedProfile = legacyProfile(); describe("OpenClaw auth-profile boundary", () => { it.each([ @@ -156,11 +159,7 @@ describe("OpenClaw auth-profile boundary", () => { }); expect(fixture.status, fixture.stderr).toBe(0); expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ - [`${provider}:manual`]: { - ...legacyManagedProfile, - provider, - profileId: `${provider}:manual`, - }, + [`${provider}:manual`]: legacyProfile(provider), }); expect(fs.statSync(fixture.authPath).mode & 0o777).toBe(0o600); }); @@ -192,11 +191,7 @@ describe("OpenClaw auth-profile boundary", () => { ); it("preserves other profiles when removing the managed entry", () => { - const customProfile = { - ...legacyManagedProfile, - provider: "custom", - profileId: "custom:manual", - }; + const customProfile = legacyProfile("custom"); const fixture = runBashAuthFixture( managedEnv, seedAuthProfile({ "inference:manual": legacyManagedProfile, "custom:manual": customProfile }), @@ -215,17 +210,13 @@ describe("OpenClaw auth-profile boundary", () => { expect(fs.readFileSync(fixture.authPath, "utf-8")).toBe(JSON.stringify(profiles)); }); - it.each(["managed", "direct"])("presents the correct %s profiles to root Doctor", (route) => { - const custom = { - ...legacyManagedProfile, - provider: "custom", - profileId: "custom:manual", - keyRef: { source: "env", id: "CUSTOM_API_KEY" }, - }; - const profiles = { "inference:manual": legacyManagedProfile, "custom:manual": custom }; + it.each(["managed", "direct"])("presents configured %s profiles to root Doctor", (route) => { + const custom = legacyProfile("custom", "CUSTOM_API_KEY"); + const profiles = { "openai:manual": legacyProfile("openai"), "custom:manual": custom }; const fixture = runBashAuthFixture( { ...managedEnv, + NEMOCLAW_INFERENCE_PROVIDER_ID: "openai", ...(route === "direct" ? { NEMOCLAW_INFERENCE_BASE_URL: "https://direct.example/v1" } : {}), }, seedAuthProfile(profiles), @@ -234,7 +225,7 @@ describe("OpenClaw auth-profile boundary", () => { // Keep fixture HOME instead of switching users; reconciliation remains real. "run_step_down_as_sandbox() { write_auth_profile; }", "configure_messaging_channels() { :; }", - 'run_requested_openclaw_post_upgrade_doctor() { cat "$HOME/.openclaw/agents/main/agent/auth-profiles.json"; }', + `run_requested_openclaw_post_upgrade_doctor() { ${credentialProbe} >&2; cat "$HOME/.openclaw/agents/main/agent/auth-profiles.json"; }`, "clear_managed_inference_credentials", rootDoctorBlock(), ].join("\n"), @@ -243,6 +234,9 @@ describe("OpenClaw auth-profile boundary", () => { expect(JSON.parse(fixture.stdout)).toEqual( route === "managed" ? { "custom:manual": custom } : profiles, ); + expect(fixture.stderr.trim()).toBe( + route === "managed" ? "unset\nunset" : "primary-secret\nlegacy-secret", + ); }); it.each([ From 100f7664642527cbaea3fced90273dd8957febd1 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 07:14:39 -0700 Subject: [PATCH 20/35] fix(runtime): recognize native Podman gateway readiness Signed-off-by: Aaron Erickson --- ...aunch-readiness-observation-timing.test.ts | 5 ++ .../actions/sandbox/launch-readiness.test.ts | 5 ++ src/lib/actions/sandbox/launch-readiness.ts | 15 ++++-- .../sandbox/launch-readiness/health.ts | 5 +- src/lib/actions/sandbox/probe/timing.ts | 14 +++-- src/lib/onboard/runtime-provider/contract.ts | 3 ++ .../podman-gateway-readiness.test.ts | 6 ++- .../podman-gateway-readiness.ts | 5 +- src/lib/readiness/gateway-production.test.ts | 54 ++++++++++++++----- src/lib/readiness/gateway-production.ts | 41 ++++++++++++-- 10 files changed, 124 insertions(+), 29 deletions(-) diff --git a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts index 73528472dee..f7daef2dd1c 100644 --- a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts +++ b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts @@ -193,6 +193,8 @@ describe("launch readiness observation timing", () => { return lease(identity); }); const currentDeps = publicationDeps(assertPublicationCurrent, publishLease); + const recordObservationFailure = vi.fn(); + currentDeps.recordObservationFailure = recordObservationFailure; const decision = await inspectLaunchReadiness(SANDBOX, currentDeps); await expect( @@ -201,6 +203,9 @@ describe("launch readiness observation timing", () => { expect(publishLease).toHaveBeenCalledTimes(expectedPublicationAttempts); expect(committed).toBe(false); + expect(recordObservationFailure).toHaveBeenCalledWith( + failureCall <= 2 ? "publication-observation" : "publication-store", + ); }, ); diff --git a/src/lib/actions/sandbox/launch-readiness.test.ts b/src/lib/actions/sandbox/launch-readiness.test.ts index d6c0fcae442..1469c11e7f4 100644 --- a/src/lib/actions/sandbox/launch-readiness.test.ts +++ b/src/lib/actions/sandbox/launch-readiness.test.ts @@ -1370,12 +1370,17 @@ describe("launch readiness validation", () => { }); const pairingObservationUnavailable = deps(); + pairingObservationUnavailable.recordObservationFailure = vi.fn(); pairingObservationUnavailable.observeOpenClawPairingQualification = () => { throw new Error("pairing observation unavailable"); }; expect(await publishLaunchReadiness(publication, pairingObservationUnavailable)).toEqual({ kind: "evidence-failed", }); + expect(pairingObservationUnavailable.recordObservationFailure).toHaveBeenNthCalledWith( + 1, + "pairing-qualification", + ); const hashUnavailable = deps(); hashUnavailable.capture = (args) => ({ diff --git a/src/lib/actions/sandbox/launch-readiness.ts b/src/lib/actions/sandbox/launch-readiness.ts index 1219bad31f2..1e675fb83fb 100644 --- a/src/lib/actions/sandbox/launch-readiness.ts +++ b/src/lib/actions/sandbox/launch-readiness.ts @@ -415,11 +415,12 @@ function projectMessagingState(entry: SandboxEntry): unknown { }; } -function projectAgent(agent: AgentDefinition): unknown { +function projectAgent(agent: AgentDefinition, deps: LaunchReadinessDeps): unknown { let manifestSha256: string; try { manifestSha256 = exactContentDigest(fs.readFileSync(agent.manifestPath, "utf8")); } catch { + recordLaunchReadinessObservationFailure(deps, "agent-definition"); throw new LaunchReadinessEvidenceError(); } return { @@ -840,6 +841,7 @@ async function captureLaunchIdentity( // receipt binds the sandbox's recorded version, including supported stale // versions that the normal launch warning permits. if (!openclawVersion || !normalizedString(agent.expected_version) || !stateDirectory) { + recordLaunchReadinessObservationFailure(deps, "pairing-qualification"); throw new OpenClawPairingQualificationError(); } try { @@ -850,6 +852,7 @@ async function captureLaunchIdentity( stateDirectory, ); } catch { + recordLaunchReadinessObservationFailure(deps, "pairing-qualification"); throw new OpenClawPairingQualificationError(); } } @@ -857,7 +860,7 @@ async function captureLaunchIdentity( return { identity: { registry: launchReadinessDigest(projection), - agent: launchReadinessDigest(projectAgent(agent)), + agent: launchReadinessDigest(projectAgent(agent, deps)), liveInference: launchReadinessDigest({ selection: inferenceSelection, live: liveInference @@ -1387,7 +1390,10 @@ export async function publishLaunchReadiness( deps: LaunchReadinessDeps = {}, ): Promise { const { sandboxName, gatewayName, gatewayPort, epochId } = publication; - if (!gatewayName || !gatewayPort || !epochId) return { kind: "evidence-failed" }; + if (!gatewayName || !gatewayPort || !epochId) { + recordLaunchReadinessObservationFailure(deps, "publication-authority"); + return { kind: "evidence-failed" }; + } const withSandboxLock = deps.withSandboxLock ?? withSandboxMutationLock; const withGatewayLock = deps.withGatewayLock ?? withGatewayRouteMutationLock; try { @@ -1421,6 +1427,7 @@ export async function publishLaunchReadiness( } as const; } const validation = publicationValidationCategory(error); + if (!validation) recordLaunchReadinessObservationFailure(deps, "publication-observation"); return validation ? ({ kind: "validation-failed", ...validation } as const) : ({ kind: "evidence-failed" } as const); @@ -1441,6 +1448,7 @@ export async function publishLaunchReadiness( deps.assertPublicationCurrent, ); } catch { + recordLaunchReadinessObservationFailure(deps, "publication-store"); publicationFailed = true; } finally { recordPerformanceStage("publication-store", publicationStartedAt); @@ -1450,6 +1458,7 @@ export async function publishLaunchReadiness( }); }); } catch { + recordLaunchReadinessObservationFailure(deps, "publication-lock"); return { kind: "evidence-failed" }; } } diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index b8ea5952782..f3c03e2a703 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -32,6 +32,7 @@ import { isSandboxGatewayHttpReachableForStatus, isSandboxGatewayRunningForStatus, } from "../process-recovery"; +import type { ProbeReadinessObservationFailureStage } from "../probe/timing"; export type LaunchReadinessObservationCategory = | "missing" @@ -74,7 +75,7 @@ export interface LaunchReadinessHealthDeps { ) => Promise>; inferenceInvocationProbe?: typeof runSandboxInferenceInvocationProbe; recordObservationTiming?: (stage: LaunchReadinessObservationStage, elapsedMs: number) => void; - recordObservationFailure?: (stage: LaunchReadinessObservationStage) => void; + recordObservationFailure?: (stage: ProbeReadinessObservationFailureStage) => void; } export type LaunchReadinessBoundCapture = ( @@ -145,7 +146,7 @@ function recordObservationTiming( export function recordLaunchReadinessObservationFailure( deps: LaunchReadinessHealthDeps, - stage: LaunchReadinessObservationStage, + stage: ProbeReadinessObservationFailureStage, ): void { try { deps.recordObservationFailure?.(stage); diff --git a/src/lib/actions/sandbox/probe/timing.ts b/src/lib/actions/sandbox/probe/timing.ts index 98e4eeb5325..26fa25c1fbd 100644 --- a/src/lib/actions/sandbox/probe/timing.ts +++ b/src/lib/actions/sandbox/probe/timing.ts @@ -26,6 +26,14 @@ export const PROBE_READINESS_OBSERVATION_STAGES = [ export type ProbeTimingStage = (typeof PROBE_TIMING_STAGES)[number]; export type ProbeReadinessObservationStage = (typeof PROBE_READINESS_OBSERVATION_STAGES)[number]; +export type ProbeReadinessObservationFailureStage = + | ProbeReadinessObservationStage + | "agent-definition" + | "pairing-qualification" + | "publication-authority" + | "publication-observation" + | "publication-store" + | "publication-lock"; export type ProbeTimingResult = "ready" | "failed"; export type ProbeLifecycleAction = "skipped" | "reused" | "recovered" | "failed"; export type ProbeForwardAction = "skipped" | "verified" | "restored" | "failed"; @@ -47,7 +55,7 @@ export type ProbeTimingRecorder = { setForwardAction(action: ProbeForwardAction): void; markFailureStage(stage: ProbeTimingStage): void; recordReadinessObservation(stage: ProbeReadinessObservationStage, elapsedMs: number): void; - recordReadinessObservationFailure(stage: ProbeReadinessObservationStage): void; + recordReadinessObservationFailure(stage: ProbeReadinessObservationFailureStage): void; recordReadinessDecision(category: ProbeReadinessDecisionCategory): void; finish(result: ProbeTimingResult, failedStage?: ProbeTimingStage): void; finishOnExit(result: ProbeTimingResult, failedStage?: ProbeTimingStage): void; @@ -80,7 +88,7 @@ export function createProbeTimingRecorder(deps: ProbeTimingDeps = {}): ProbeTimi let lifecycleAction: ProbeLifecycleAction = "skipped"; let forwardAction: ProbeForwardAction = "skipped"; let recordedFailureStage: ProbeTimingStage | null = null; - let firstReadinessObservationFailure: ProbeReadinessObservationStage | null = null; + let firstReadinessObservationFailure: ProbeReadinessObservationFailureStage | null = null; let firstReadinessDecision: ProbeReadinessDecisionCategory | null = null; let firstReadinessFallbackDecision: Exclude | null = null; @@ -179,7 +187,7 @@ export function createProbeTimingRecorder(deps: ProbeTimingDeps = {}): ProbeTimi (readinessObservationDurations.get(stage) ?? 0) + Math.max(0, elapsedMs), ); }, - recordReadinessObservationFailure(stage: ProbeReadinessObservationStage): void { + recordReadinessObservationFailure(stage: ProbeReadinessObservationFailureStage): void { firstReadinessObservationFailure ??= stage; }, recordReadinessDecision(category: ProbeReadinessDecisionCategory): void { diff --git a/src/lib/onboard/runtime-provider/contract.ts b/src/lib/onboard/runtime-provider/contract.ts index 541c1994d12..83d7bc50d7c 100644 --- a/src/lib/onboard/runtime-provider/contract.ts +++ b/src/lib/onboard/runtime-provider/contract.ts @@ -107,7 +107,10 @@ export interface RuntimeProviderOwnedGatewayReadinessInput { readonly architecture: NodeJS.Architecture; readonly gatewayName: string; readonly gatewayPort: number; + /** Sandbox-facing transport origin recorded by the gateway runtime marker. */ readonly expectedEndpoint: string; + /** Host CLI registration origin; it can differ from the sandbox transport. */ + readonly expectedClientEndpoint: string; readonly managedGatewayEndpoints: readonly (string | null)[]; readonly portAvailable: boolean; readonly installedOpenShellVersion: string | null; diff --git a/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts b/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts index 805a0cbf6be..9fa5b7fcf96 100644 --- a/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts +++ b/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts @@ -4,6 +4,7 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; +import { getGatewayHttpsEndpoint } from "../../core/gateway-address"; import { buildDockerDriverGatewayRuntimeMarker, @@ -33,9 +34,10 @@ function input() { gatewayName: GATEWAY_NAME, gatewayPort: GATEWAY_PORT, expectedEndpoint: `https://169.254.2.2:${String(GATEWAY_PORT)}`, + expectedClientEndpoint: getGatewayHttpsEndpoint(GATEWAY_PORT), managedGatewayEndpoints: [ - `https://169.254.2.2:${String(GATEWAY_PORT)}`, - `https://169.254.2.2:${String(GATEWAY_PORT)}`, + getGatewayHttpsEndpoint(GATEWAY_PORT), + getGatewayHttpsEndpoint(GATEWAY_PORT), ], portAvailable: false, installedOpenShellVersion: "0.0.116", diff --git a/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts b/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts index 952b1cf3eb5..501f73c5752 100644 --- a/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts +++ b/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts @@ -206,7 +206,10 @@ export function observeNativePodmanGatewayReadiness( ? "compatible" : "drift"; return Object.freeze({ - endpointBinding: classifyEndpointBinding(input.managedGatewayEndpoints, input.expectedEndpoint), + endpointBinding: classifyEndpointBinding( + input.managedGatewayEndpoints, + input.expectedClientEndpoint, + ), listenerScan: Object.freeze({ pids: Object.freeze(pids), unverifiedPids: Object.freeze(unverifiedPids), diff --git a/src/lib/readiness/gateway-production.test.ts b/src/lib/readiness/gateway-production.test.ts index 9ffdb8a99bb..5f4fdb91547 100644 --- a/src/lib/readiness/gateway-production.test.ts +++ b/src/lib/readiness/gateway-production.test.ts @@ -9,6 +9,7 @@ import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { getGatewayHttpsEndpoint } from "../core/gateway-address"; import { isDockerDriverGatewayProcessIdentity } from "../onboard/docker-driver-gateway-process-identity"; import { resolveDockerDriverGatewayStateDir, @@ -17,6 +18,7 @@ import { } from "../onboard/docker-driver-gateway-runtime-marker"; import type { GatewayOwner } from "../onboard/gateway-ownership"; import { createCurrentPodmanRuntimeProviderBundle } from "../onboard/runtime-provider/podman"; +import * as gatewayService from "../onboard/docker-driver-gateway-service"; import { resetTraceForTests, TRACE_FILE_ENV } from "../trace"; import { collectGatewayObservations, projectGatewayReadiness } from "./gateway"; @@ -729,7 +731,7 @@ describe("managed gateway port readiness (#7411)", () => { }); const gatewayPort = (gatewayListener.address() as AddressInfo).port; const gatewayName = `nemoclaw-${String(gatewayPort)}`; - const endpoint = `https://169.254.2.2:${String(gatewayPort)}`; + const endpoint = getGatewayHttpsEndpoint(gatewayPort); const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-podman-readiness-")); const openshell = path.join(root, "openshell"); fs.writeFileSync(openshell, "#!/bin/sh\nexit 1\n", { mode: 0o700 }); @@ -813,7 +815,8 @@ describe("managed gateway port readiness (#7411)", () => { }), gatewayName, gatewayPort, - expectedEndpoint: endpoint, + expectedEndpoint: `https://169.254.2.2:${String(gatewayPort)}`, + expectedClientEndpoint: endpoint, managedGatewayEndpoints: expect.arrayContaining([endpoint]), portAvailable: false, }), @@ -826,9 +829,14 @@ describe("managed gateway port readiness (#7411)", () => { } }, 30_000); - it.runIf(process.platform === "linux")( - "projects a real marker-owned native Podman listener through production readiness (#10984)", - async ({ onTestFinished }) => { + it.runIf(process.platform === "linux").for([ + ["marker", "podman", "none", "present", "present"], + ["service", "podman", "none", "present", "present"], + ["service", "docker", "owner-mismatch", "unknown", "absent"], + ] as const)( + "projects a real %s-owned %s listener through Podman readiness (#10984)", + { timeout: 30_000 }, + async ([ownership, driver, conflict, versionState, portState], { onTestFinished }) => { const actualChildProcess = await vi.importActual("node:child_process"); subprocess.spawnSync.mockImplementation(actualChildProcess.spawnSync); @@ -840,7 +848,7 @@ describe("managed gateway port readiness (#7411)", () => { const gatewayPort = (reservation.address() as AddressInfo).port; await new Promise((resolve) => reservation.close(() => resolve())); const gatewayName = `nemoclaw-${String(gatewayPort)}`; - const endpoint = `https://169.254.2.2:${String(gatewayPort)}`; + const endpoint = getGatewayHttpsEndpoint(gatewayPort); const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-podman-readiness-real-")); const stateDir = path.join(root, "gateway-state"); const openshell = path.join(root, "openshell"); @@ -870,7 +878,15 @@ esac String(gatewayPort), ], { - argv0: `openshell-gateway[nemoclaw=${gatewayName};port=${String(gatewayPort)}]`, + ...(ownership === "marker" + ? { argv0: `openshell-gateway[nemoclaw=${gatewayName};port=${String(gatewayPort)}]` } + : {}), + env: { + OPENSHELL_DRIVERS: driver, + OPENSHELL_BIND_ADDRESS: "0.0.0.0", + OPENSHELL_SERVER_PORT: String(gatewayPort), + OPENSHELL_GRPC_ENDPOINT: `https://169.254.2.2:${String(gatewayPort)}`, + }, stdio: ["ignore", "pipe", "pipe"], }, ); @@ -883,17 +899,24 @@ esac fs.writeFileSync(lsof, `#!/bin/sh\nprintf '%s\\n' '${String(listener.pid)}'\n`, { mode: 0o700, }); - writeDockerDriverGatewayPidFile(path.join(stateDir, "openshell-gateway.pid"), listener.pid!); - writeDockerDriverGatewayRuntimeMarkerForStateDir(stateDir, { + const markerDir = ownership === "marker" ? stateDir : path.join(root, "other-gateway-state"); + writeDockerDriverGatewayPidFile(path.join(markerDir, "openshell-gateway.pid"), listener.pid!); + writeDockerDriverGatewayRuntimeMarkerForStateDir(markerDir, { pid: listener.pid!, desiredEnv: {}, - endpoint, + endpoint: `https://169.254.2.2:${String(gatewayPort)}`, gatewayBin: process.execPath, openshellVersion: "0.0.116", platform: "linux", arch: process.arch, runtimeProviderId: "podman", }); + vi.spyOn( + gatewayService, + "getTrustedActiveOpenShellGatewayUserServiceIdentity", + ).mockReturnValue( + ownership === "service" ? { pid: listener.pid!, executablePath: process.execPath } : null, + ); const environment = { HOME: root, PATH: `${root}:/usr/bin:/bin`, @@ -911,22 +934,25 @@ esac gatewayPort: () => gatewayPort, platform: "linux", resolveRuntimeProviderGateway: () => gateway, + observeVersionCompatibility: () => "compatible", }); const now = new Date("2026-09-08T17:00:00.000Z"); const snapshot = await collectGatewayObservations(deps, { now: () => now }); const projection = projectGatewayReadiness(snapshot, { now: () => now }); expect(snapshot.failure).toBeUndefined(); + expect(snapshot.observations?.portConflictState).toBe(conflict); expect(projection.capabilities).toEqual( expect.arrayContaining( - ["gateway.reuse.ready", "gateway.version.compatible", "gateway.port.uncontested"].map( - (id) => expect.objectContaining({ id, state: "present" }), - ), + [ + ["gateway.reuse.ready", "present"], + ["gateway.version.compatible", versionState], + ["gateway.port.uncontested", portState], + ].map(([id, state]) => expect.objectContaining({ id, state })), ), ); expect(subprocess.spawnSync.mock.calls.some(([command]) => command === "docker")).toBe(false); }, - 30_000, ); it("keeps portable readiness on the portable gateway topology", async () => { diff --git a/src/lib/readiness/gateway-production.ts b/src/lib/readiness/gateway-production.ts index be6e06217d0..1dadd77f948 100644 --- a/src/lib/readiness/gateway-production.ts +++ b/src/lib/readiness/gateway-production.ts @@ -6,6 +6,7 @@ import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { getGatewayHttpsEndpoint } from "../core/gateway-address"; import { classifyManagedGatewayEndpointBinding, type ManagedGatewayEndpointBinding, @@ -701,6 +702,19 @@ export function createProductionGatewayReadinessDependencies( platform === "linux" ? readLinuxProcessExecutable(pid) : readDarwinProcessExecutable(pid, probeEnv); + // A service owns no standalone PID/marker files. Bind its live environment + // to the selected provider before accepting the service's process identity. + const providerRuntime = resolveRuntimeProviderGateway().ownsHostReadiness + ? observeGatewayHostRuntime() + : null; + const serviceEnv = providerRuntime ? readDockerDriverGatewayProcessEnvironment(pid) : null; + const providerMatches = + !providerRuntime || + (serviceEnv?.OPENSHELL_DRIVERS === providerRuntime.openShellDriver && + serviceEnv.OPENSHELL_BIND_ADDRESS === providerRuntime.bindAddress && + serviceEnv.OPENSHELL_SERVER_PORT === String(gatewayPort) && + serviceEnv.OPENSHELL_GRPC_ENDPOINT === + `https://${providerRuntime.grpcHost}:${String(gatewayPort)}`); const serviceAfter = getTrustedActiveOpenShellGatewayUserServiceIdentity({ env: probeEnv, homebrewFormulaOperation: runObservedHomebrewFormulaOperation, @@ -724,6 +738,7 @@ export function createProductionGatewayReadinessDependencies( !expected || confirmed !== expected || !stableGeneration || + !providerMatches || !gatewayExecutableSamplesMatchTrustedBinary(executableBefore, executableAfter, expected) ) { return null; @@ -813,6 +828,7 @@ export function createProductionGatewayReadinessDependencies( gatewayName, gatewayPort, expectedEndpoint: `https://${observeGatewayHostRuntime().grpcHost}:${String(gatewayPort)}`, + expectedClientEndpoint: getGatewayHttpsEndpoint(gatewayPort), managedGatewayEndpoints, portAvailable: portCheck.ok, installedOpenShellVersion: getInstalledOpenShellVersion(), @@ -828,6 +844,23 @@ export function createProductionGatewayReadinessDependencies( : listenerHelpers.getDockerDriverGatewayPortListenerScan(portCheck, { gatewayBin: trustedGatewayBin, }); + let verifiedProviderService = false; + if ( + providerObservation && + listenerScan.complete && + listenerScan.pids.length === 0 && + listenerScan.unverifiedPids.length === 1 + ) { + const pid = listenerScan.unverifiedPids[0]!; + const serviceBinary = observePackagedServiceGatewayBinary(pid); + if (serviceBinary) { + listenerScan.pids = [pid]; + listenerScan.unverifiedPids = []; + trustedVersionBinaryByPid.set(pid, serviceBinary); + trustedTargetBoundPids.add(pid); + verifiedProviderService = true; + } + } const managedGatewayCanBeRunning = reuseState === "healthy" || reuseState === "stale" || reuseState === "active-unnamed"; let legacyClusterBound = false; @@ -854,7 +887,7 @@ export function createProductionGatewayReadinessDependencies( } let compatibility: GatewayVersionCompatibility | null = providerObservation?.versionCompatibility ?? null; - if (!portCheck.ok && !providerObservation) { + if (!portCheck.ok && (!providerObservation || verifiedProviderService)) { const source = classifyManagedGatewayVersionSource( legacyClusterBound, listenerScan, @@ -900,9 +933,9 @@ export function createProductionGatewayReadinessDependencies( legacyClusterBound, effectiveEndpointBinding, listenerScan.pids.length === 1 && - (providerObservation - ? providerObservation.targetBoundListenerPids.includes(listenerScan.pids[0] ?? -1) - : trustedTargetBoundPids.has(listenerScan.pids[0] ?? -1)), + (trustedTargetBoundPids.has(listenerScan.pids[0] ?? -1) || + (providerObservation?.targetBoundListenerPids.includes(listenerScan.pids[0] ?? -1) ?? + false)), ); const portConflictOwners = portConflictState === "none" From 00899cae9f8a50f9da8065ce6e651a3d271b48e4 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 07:35:14 -0700 Subject: [PATCH 21/35] fix(runtime): retain Podman context through lifecycle scopes Signed-off-by: Aaron Erickson --- src/lib/actions/sandbox/rebuild-flow-helpers.ts | 2 +- src/lib/gateway-runtime-action.ts | 4 ++-- .../onboard/authoritative-rebuild-target.test.ts | 4 ++++ src/lib/onboard/authoritative-rebuild-target.ts | 2 +- .../runtime-provider/configured-runtime.ts | 15 +++++++++++++++ 5 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-flow-helpers.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.ts index bde8c66ee5e..8a0ad90439e 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.ts @@ -4,10 +4,10 @@ import { dockerRmi } from "../../adapters/docker/image"; import { printOpenShellStateRpcIssue } from "../../adapters/openshell/gateway-drift"; import { - replaceOpenShellRuntimeSelectionEnv, snapshotOpenShellEnv, type OpenShellRuntimeSelection, } from "../../adapters/openshell/runtime-selection"; +import { replaceGatewayHostRuntimeSelectionEnv as replaceOpenShellRuntimeSelectionEnv } from "../../onboard/runtime-provider/configured-runtime"; import { loadAgent } from "../../agent/defs"; import { bindLocalAgentBaseImageHandoffToResolution, diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index 147b40d89ff..50d562167eb 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -12,12 +12,12 @@ import { resolveSandboxGatewayName, } from "./onboard/gateway-binding"; import type { GatewayRecoveryOutput } from "./onboard/gateway-recovery"; +import { replaceGatewayHostRuntimeSelectionEnv } from "./onboard/runtime-provider/configured-runtime"; import { sanitizeReadinessText } from "./readiness/sanitize"; export { resolveGatewayName, resolveSandboxGatewayName }; -export const replaceOpenShellRuntimeSelectionEnv = - openshellRuntime.replaceOpenShellRuntimeSelectionEnv; +export const replaceOpenShellRuntimeSelectionEnv = replaceGatewayHostRuntimeSelectionEnv; export const snapshotOpenShellEnv = openshellRuntime.snapshotOpenShellEnv; type StartGatewayForRecoveryOptions = { diff --git a/src/lib/onboard/authoritative-rebuild-target.test.ts b/src/lib/onboard/authoritative-rebuild-target.test.ts index 996a882b997..73cd6b251a2 100644 --- a/src/lib/onboard/authoritative-rebuild-target.test.ts +++ b/src/lib/onboard/authoritative-rebuild-target.test.ts @@ -225,6 +225,8 @@ describe("authoritative rebuild OpenShell runtime selection", () => { it("replaces hostile ambient selectors for inner onboard and restores them (#10514)", () => { const env: NodeJS.ProcessEnv = { PATH: "/usr/bin", + NEMOCLAW_GATEWAY_RUNTIME: "podman", + OPENSHELL_PODMAN_SOCKET: "/custom/run/podman.sock", OPENSHELL_GATEWAY: "hostile-gateway", OPENSHELL_GATEWAY_AUTH_TOKEN: "hostile-token", OPENSHELL_GATEWAY_ENDPOINT: "https://hostile.invalid", @@ -251,6 +253,8 @@ describe("authoritative rebuild OpenShell runtime selection", () => { expect(env).toMatchObject({ PATH: "/usr/bin", + NEMOCLAW_GATEWAY_RUNTIME: "podman", + OPENSHELL_PODMAN_SOCKET: "/custom/run/podman.sock", OPENSHELL_GATEWAY: "nemoclaw-8081", OPENSHELL_LOCAL_TLS_DIR: "/authority/tls", OPENSHELL_WORKSPACE: "default", diff --git a/src/lib/onboard/authoritative-rebuild-target.ts b/src/lib/onboard/authoritative-rebuild-target.ts index 292c765441c..366bc22d741 100644 --- a/src/lib/onboard/authoritative-rebuild-target.ts +++ b/src/lib/onboard/authoritative-rebuild-target.ts @@ -2,10 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { - replaceOpenShellRuntimeSelectionEnv, snapshotOpenShellEnv, type OpenShellRuntimeSelection, } from "../adapters/openshell/runtime-selection"; +import { replaceGatewayHostRuntimeSelectionEnv as replaceOpenShellRuntimeSelectionEnv } from "./runtime-provider/configured-runtime"; import { createOpenShellForwardPortObserver, type OpenShellForwardPortObserver, diff --git a/src/lib/onboard/runtime-provider/configured-runtime.ts b/src/lib/onboard/runtime-provider/configured-runtime.ts index e6ee6ad4fa3..a88927ae365 100644 --- a/src/lib/onboard/runtime-provider/configured-runtime.ts +++ b/src/lib/onboard/runtime-provider/configured-runtime.ts @@ -1,6 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + replaceOpenShellRuntimeSelectionEnv, + type OpenShellRuntimeSelection, +} from "../../adapters/openshell/runtime-selection"; + export const NEMOCLAW_GATEWAY_RUNTIME_ENV = "NEMOCLAW_GATEWAY_RUNTIME"; export type NemoClawGatewayRuntime = "docker" | "podman"; @@ -45,3 +50,13 @@ export function gatewayHostRuntimeEnvironment(source: NodeJS.ProcessEnv): Record ), ); } + +/** Pin client authority without discarding the host runtime used by lifecycle operations. */ +export function replaceGatewayHostRuntimeSelectionEnv( + environment: NodeJS.ProcessEnv, + selection: OpenShellRuntimeSelection, +): void { + const hostRuntime = gatewayHostRuntimeEnvironment(environment); + replaceOpenShellRuntimeSelectionEnv(environment, selection); + Object.assign(environment, hostRuntime); +} From 107b00335ab5cd727d28ed4b278b924c6f2c9da1 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 07:50:03 -0700 Subject: [PATCH 22/35] fix(runtime): bind service readiness to the selected socket Signed-off-by: Aaron Erickson --- src/lib/readiness/gateway-production.test.ts | 17 +++++++++++------ src/lib/readiness/gateway-production.ts | 1 + 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/lib/readiness/gateway-production.test.ts b/src/lib/readiness/gateway-production.test.ts index 5f4fdb91547..a27f693b85b 100644 --- a/src/lib/readiness/gateway-production.test.ts +++ b/src/lib/readiness/gateway-production.test.ts @@ -830,13 +830,17 @@ describe("managed gateway port readiness (#7411)", () => { }, 30_000); it.runIf(process.platform === "linux").for([ - ["marker", "podman", "none", "present", "present"], - ["service", "podman", "none", "present", "present"], - ["service", "docker", "owner-mismatch", "unknown", "absent"], + ["marker", "podman", "selected", "none", "present", "present"], + ["service", "podman", "selected", "none", "present", "present"], + ["service", "docker", "selected", "owner-mismatch", "unknown", "absent"], + ["service", "podman", "other", "owner-mismatch", "unknown", "absent"], ] as const)( - "projects a real %s-owned %s listener through Podman readiness (#10984)", + "projects a real %s-owned %s listener with %s socket through Podman readiness (#10984)", { timeout: 30_000 }, - async ([ownership, driver, conflict, versionState, portState], { onTestFinished }) => { + async ( + [ownership, driver, socketDirectory, conflict, versionState, portState], + { onTestFinished }, + ) => { const actualChildProcess = await vi.importActual("node:child_process"); subprocess.spawnSync.mockImplementation(actualChildProcess.spawnSync); @@ -883,6 +887,7 @@ esac : {}), env: { OPENSHELL_DRIVERS: driver, + OPENSHELL_PODMAN_SOCKET: `/nonexistent/run/${socketDirectory}/podman.sock`, OPENSHELL_BIND_ADDRESS: "0.0.0.0", OPENSHELL_SERVER_PORT: String(gatewayPort), OPENSHELL_GRPC_ENDPOINT: `https://169.254.2.2:${String(gatewayPort)}`, @@ -924,7 +929,7 @@ esac NEMOCLAW_OPENSHELL_BIN: openshell, NEMOCLAW_OPENSHELL_GATEWAY_BIN: process.execPath, NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR: stateDir, - OPENSHELL_PODMAN_SOCKET: "/nonexistent/run/podman/podman.sock", + OPENSHELL_PODMAN_SOCKET: "/nonexistent/run/selected/podman.sock", }; const gateway = createCurrentPodmanRuntimeProviderBundle(environment).gateway; const deps = createProductionGatewayReadinessDependencies({ diff --git a/src/lib/readiness/gateway-production.ts b/src/lib/readiness/gateway-production.ts index 1dadd77f948..f03d6a2a4d9 100644 --- a/src/lib/readiness/gateway-production.ts +++ b/src/lib/readiness/gateway-production.ts @@ -711,6 +711,7 @@ export function createProductionGatewayReadinessDependencies( const providerMatches = !providerRuntime || (serviceEnv?.OPENSHELL_DRIVERS === providerRuntime.openShellDriver && + serviceEnv.OPENSHELL_PODMAN_SOCKET === (providerRuntime.socketPath ?? undefined) && serviceEnv.OPENSHELL_BIND_ADDRESS === providerRuntime.bindAddress && serviceEnv.OPENSHELL_SERVER_PORT === String(gatewayPort) && serviceEnv.OPENSHELL_GRPC_ENDPOINT === From efeed69595c716fe3e332e165ea4aeacecf5aacd Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 08:06:58 -0700 Subject: [PATCH 23/35] fix(runtime): retain managed loopback endpoint aliases Signed-off-by: Aaron Erickson --- .../podman-gateway-readiness.test.ts | 31 +++++++++++++------ .../podman-gateway-readiness.ts | 19 ++++++++++-- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts b/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts index 9fa5b7fcf96..ba9823ea5d8 100644 --- a/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts +++ b/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts @@ -99,14 +99,25 @@ function readinessDeps( } describe("native Podman gateway readiness", () => { - it("recognizes one target-bound listener and its recorded OpenShell version (#10984)", () => { - expect(observeNativePodmanGatewayReadiness(input(), readinessDeps())).toEqual({ - endpointBinding: "match", - listenerScan: { pids: [PID], unverifiedPids: [], complete: true }, - targetBoundListenerPids: [PID], - versionCompatibility: "compatible", - }); - }); + it.each(["127.0.0.1", "localhost", "[::1]"])( + "recognizes a target-bound listener through %s (#10984)", + (host) => { + expect( + observeNativePodmanGatewayReadiness( + { + ...input(), + managedGatewayEndpoints: [`https://${host}:${String(GATEWAY_PORT)}`], + }, + readinessDeps(), + ), + ).toEqual({ + endpointBinding: "match", + listenerScan: { pids: [PID], unverifiedPids: [], complete: true }, + targetBoundListenerPids: [PID], + versionCompatibility: "compatible", + }); + }, + ); it.each([ ["another provider", { driver: "docker" }], @@ -138,11 +149,11 @@ describe("native Podman gateway readiness", () => { }); }); - it("rejects managed endpoint output outside the provider endpoint (#10984)", () => { + it.each([8080, 8990])("rejects non-client endpoint output on port %s (#10984)", (port) => { const observation = observeNativePodmanGatewayReadiness( { ...input(), - managedGatewayEndpoints: [`https://169.254.2.2:8990`], + managedGatewayEndpoints: [`https://169.254.2.2:${String(port)}`], }, readinessDeps(), ); diff --git a/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts b/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts index 501f73c5752..1e85c28f58e 100644 --- a/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts +++ b/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts @@ -5,6 +5,7 @@ import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { isManagedGatewayEndpointHost } from "../../../../nemoclaw/dist/shared/openshell-gateway-endpoint-boundary.cjs"; import { getDockerDriverGatewayRuntimeMarkerPath, @@ -108,9 +109,23 @@ function classifyEndpointBinding( endpoints: readonly (string | null)[], expectedEndpoint: string, ): RuntimeProviderOwnedGatewayReadinessObservation["endpointBinding"] { - const expected = new URL(expectedEndpoint).origin; + const expected = new URL(expectedEndpoint); if (!endpoints.length) return "unknown"; - return endpoints.every((endpoint) => endpoint !== null && endpoint === expected) + return endpoints.every((endpoint) => { + if (endpoint === null) return false; + try { + const observed = new URL(endpoint); + return ( + endpoint === observed.origin && + observed.protocol === expected.protocol && + observed.port === expected.port && + isManagedGatewayEndpointHost(observed.hostname) && + isManagedGatewayEndpointHost(expected.hostname) + ); + } catch { + return false; + } + }) ? "match" : "mismatch"; } From aa17fbfe3ddb89321d00aa236f1f507edfc1f4b7 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 08:46:14 -0700 Subject: [PATCH 24/35] fix(runtime): bind service readiness and retain portable context --- ...aunch-readiness-observation-timing.test.ts | 4 +- .../actions/sandbox/launch-readiness.test.ts | 13 ++ src/lib/actions/sandbox/launch-readiness.ts | 35 +++- src/lib/onboard/gateway/late-binding.test.ts | 154 ++++++++++-------- .../runtime-provider/configured-runtime.ts | 1 + src/lib/readiness/gateway-production.test.ts | 16 +- src/lib/readiness/gateway-production.ts | 3 +- 7 files changed, 135 insertions(+), 91 deletions(-) diff --git a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts index f7daef2dd1c..25334632258 100644 --- a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts +++ b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts @@ -203,9 +203,7 @@ describe("launch readiness observation timing", () => { expect(publishLease).toHaveBeenCalledTimes(expectedPublicationAttempts); expect(committed).toBe(false); - expect(recordObservationFailure).toHaveBeenCalledWith( - failureCall <= 2 ? "publication-observation" : "publication-store", - ); + expect(recordObservationFailure).toHaveBeenNthCalledWith(1, "publication-authority"); }, ); diff --git a/src/lib/actions/sandbox/launch-readiness.test.ts b/src/lib/actions/sandbox/launch-readiness.test.ts index 1469c11e7f4..5f4e558f14c 100644 --- a/src/lib/actions/sandbox/launch-readiness.test.ts +++ b/src/lib/actions/sandbox/launch-readiness.test.ts @@ -1369,6 +1369,19 @@ describe("launch readiness validation", () => { kind: "evidence-failed", }); + const registryUnavailable = deps(); + registryUnavailable.recordObservationFailure = vi.fn(); + registryUnavailable.getSandbox = () => { + throw new Error("registry unavailable"); + }; + expect(await publishLaunchReadiness(publication, registryUnavailable)).toEqual({ + kind: "evidence-failed", + }); + expect(registryUnavailable.recordObservationFailure).toHaveBeenNthCalledWith( + 1, + "publication-observation", + ); + const pairingObservationUnavailable = deps(); pairingObservationUnavailable.recordObservationFailure = vi.fn(); pairingObservationUnavailable.observeOpenClawPairingQualification = () => { diff --git a/src/lib/actions/sandbox/launch-readiness.ts b/src/lib/actions/sandbox/launch-readiness.ts index 1e675fb83fb..050271f53e5 100644 --- a/src/lib/actions/sandbox/launch-readiness.ts +++ b/src/lib/actions/sandbox/launch-readiness.ts @@ -1396,9 +1396,24 @@ export async function publishLaunchReadiness( } const withSandboxLock = deps.withSandboxLock ?? withSandboxMutationLock; const withGatewayLock = deps.withGatewayLock ?? withGatewayRouteMutationLock; + let failedOperation: "publication-authority" | "publication-observation" | undefined; + const assertPublicationCurrent = () => { + try { + deps.assertPublicationCurrent?.(); + } catch (error) { + failedOperation = "publication-authority"; + throw error; + } + }; try { return await withSandboxLock(sandboxName, async () => { - const entry = (deps.getSandbox ?? registry.getSandbox)(sandboxName); + let entry: SandboxEntry | null; + try { + entry = (deps.getSandbox ?? registry.getSandbox)(sandboxName); + } catch (error) { + failedOperation = "publication-observation"; + throw error; + } if (entry?.gatewayPort !== gatewayPort || entry.gatewayName !== gatewayName) { return { kind: "validation-failed", category: "identity" } as const; } @@ -1407,14 +1422,14 @@ export async function publishLaunchReadiness( let captured: Awaited> | undefined; let captureFailure: unknown; try { - deps.assertPublicationCurrent?.(); + assertPublicationCurrent(); try { captured = await captureLaunchIdentity(sandboxName, gatewayName, gatewayPort, deps); } catch (error) { captureFailure = error; } try { - deps.assertPublicationCurrent?.(); + assertPublicationCurrent(); } catch (error) { captureFailure = error; } @@ -1427,7 +1442,11 @@ export async function publishLaunchReadiness( } as const; } const validation = publicationValidationCategory(error); - if (!validation) recordLaunchReadinessObservationFailure(deps, "publication-observation"); + if (!validation) + recordLaunchReadinessObservationFailure( + deps, + failedOperation ?? "publication-observation", + ); return validation ? ({ kind: "validation-failed", ...validation } as const) : ({ kind: "evidence-failed" } as const); @@ -1437,7 +1456,7 @@ export async function publishLaunchReadiness( const publicationStartedAt = performance.now(); let publicationFailed = false; try { - deps.assertPublicationCurrent?.(); + assertPublicationCurrent(); (deps.publishLease ?? publishLaunchReadinessLease)( sandboxName, gatewayName, @@ -1445,10 +1464,10 @@ export async function publishLaunchReadiness( epochId, captured!.identity, deps.storeOptions, - deps.assertPublicationCurrent, + assertPublicationCurrent, ); } catch { - recordLaunchReadinessObservationFailure(deps, "publication-store"); + recordLaunchReadinessObservationFailure(deps, failedOperation ?? "publication-store"); publicationFailed = true; } finally { recordPerformanceStage("publication-store", publicationStartedAt); @@ -1458,7 +1477,7 @@ export async function publishLaunchReadiness( }); }); } catch { - recordLaunchReadinessObservationFailure(deps, "publication-lock"); + recordLaunchReadinessObservationFailure(deps, failedOperation ?? "publication-lock"); return { kind: "evidence-failed" }; } } diff --git a/src/lib/onboard/gateway/late-binding.test.ts b/src/lib/onboard/gateway/late-binding.test.ts index 286aa56c30e..d875e45a0aa 100644 --- a/src/lib/onboard/gateway/late-binding.test.ts +++ b/src/lib/onboard/gateway/late-binding.test.ts @@ -13,7 +13,10 @@ import { } from "../docker-driver-gateway-config"; import * as dockerDriverGatewayCutover from "../docker-driver-gateway-cutover"; import * as dockerDriverGatewayLaunch from "../docker-driver-gateway-launch"; -import { assertDockerDriverGatewayBindAddressSafe } from "../docker-driver-gateway-env"; +import { + assertDockerDriverGatewayBindAddressSafe, + observeConfiguredGatewayHostRuntime, +} from "../docker-driver-gateway-env"; import { buildSelectedOpenShellSubprocessEnv } from "../../adapters/openshell/command-argv"; import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; import * as gatewayBinding from "../gateway-binding"; @@ -72,21 +75,18 @@ describe("gateway lifecycle late binding", () => { const managedFallbackSpy = vi .spyOn(dockerDriverGatewayCutover, "runDockerDriverGatewayManagedFallback") .mockResolvedValue("launch"); + const buildRuntimeIdentity = dockerDriverGatewayLaunch.buildDockerDriverGatewayRuntimeIdentity; const runtimeIdentitySpy = vi .spyOn(dockerDriverGatewayLaunch, "buildDockerDriverGatewayRuntimeIdentity") - .mockReturnValue({ - launch: { - command: "/opt/openshell/openshell-gateway", - args: [], - argv0: "openshell-gateway[nemoclaw=nemoclaw-9777;port=9777]", - env: {}, - mode: "host", - processGatewayBin: "/opt/openshell/openshell-gateway", - }, - desiredEnv: {}, - driftGatewayBin: "/opt/openshell/openshell-gateway", - identityGatewayBin: "/opt/openshell/openshell-gateway", - }); + .mockImplementation((options) => + buildRuntimeIdentity({ + ...options, + ensureLocalTlsBundle: false, + platform: "linux", + hostGlibcVersion: "2.39", + requiredGlibcVersions: ["2.39"], + }), + ); const prepareSpy = vi .spyOn(dockerDriverGatewayLaunch, "prepareAndLogDockerDriverGatewayLaunch") .mockImplementation(() => undefined); @@ -130,7 +130,20 @@ describe("gateway lifecycle late binding", () => { gatewayName: () => "nemoclaw-9777", gatewayPort: () => 9777, getDockerDriverGatewayEndpoint: () => "https://127.0.0.1:9777", - getDockerDriverGatewayEnv: () => ({}), + getDockerDriverGatewayEnv: () => { + const runtime = observeConfiguredGatewayHostRuntime({ + environment: process.env, + platform: "linux", + }); + return { + OPENSHELL_DRIVERS: runtime.openShellDriver, + OPENSHELL_BIND_ADDRESS: runtime.bindAddress, + OPENSHELL_SERVER_PORT: "9777", + OPENSHELL_GRPC_ENDPOINT: `https://${runtime.grpcHost}:9777`, + OPENSHELL_SSH_GATEWAY_HOST: runtime.sshGatewayHost, + ...(runtime.socketPath ? { OPENSHELL_PODMAN_SOCKET: runtime.socketPath } : {}), + }; + }, getDockerDriverGatewayPid: () => null, getDockerDriverGatewayPortListenerScan: () => ({ complete: true, @@ -174,7 +187,7 @@ describe("gateway lifecycle late binding", () => { ).rejects.toThrow(/failed to start within/); return { - runtimeEnvironment: runtimeIdentitySpy.mock.calls[0]?.[0].env, + runtimeEnvironment: spawnSpy.mock.calls[0]?.[0].env, output: lines.join("\n"), processEnvironmentCalls: readProcessEnvironment.mock.calls, serviceTargetCalls: serviceTarget.mock.calls.length, @@ -189,62 +202,59 @@ describe("gateway lifecycle late binding", () => { } } - it("preserves native Podman context through selected-target gateway startup", async () => { - vi.stubEnv("NEMOCLAW_GATEWAY_RUNTIME", "podman"); - vi.stubEnv("OPENSHELL_PODMAN_SOCKET", "/run/user/1000/podman/podman.sock"); - vi.stubEnv("CONTAINERS_CONF", "/tmp/containers.conf"); - vi.stubEnv("CONTAINERS_STORAGE_CONF", "/tmp/storage.conf"); - vi.stubEnv("XDG_RUNTIME_DIR", "/run/user/1000"); - vi.stubEnv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"); - vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://hostile.invalid"); - vi.stubEnv("OPENSHELL_TOKEN", "hostile-token"); - vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "provider-secret"); - const clientOnlyEnvironment = buildSelectedOpenShellSubprocessEnv({ - gatewayName: "nemoclaw-9777", - workspace: "default", - }); - const result = await captureFailedStartRecovery(true, { - gatewayName: "nemoclaw-9777", - workspace: "default", - }); - expect(result.runtimeEnvironment).toMatchObject({ - NEMOCLAW_GATEWAY_RUNTIME: "podman", - OPENSHELL_PODMAN_SOCKET: "/run/user/1000/podman/podman.sock", - CONTAINERS_CONF: "/tmp/containers.conf", - CONTAINERS_STORAGE_CONF: "/tmp/storage.conf", - XDG_RUNTIME_DIR: "/run/user/1000", - DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus", - OPENSHELL_GATEWAY: "nemoclaw-9777", - OPENSHELL_WORKSPACE: "default", - }); - expect(result.runtimeEnvironment).not.toHaveProperty("OPENSHELL_GATEWAY_ENDPOINT"); - expect(result.runtimeEnvironment).not.toHaveProperty("OPENSHELL_TOKEN"); - expect(result.runtimeEnvironment).not.toHaveProperty("NVIDIA_INFERENCE_API_KEY"); - expect(() => - assertDockerDriverGatewayBindAddressSafe( - { - OPENSHELL_BIND_ADDRESS: "0.0.0.0", - OPENSHELL_GRPC_ENDPOINT: "https://169.254.2.2:8080", - OPENSHELL_SSH_GATEWAY_HOST: "127.0.0.1", - OPENSHELL_SERVER_PORT: "8080", - }, - clientOnlyEnvironment, - "linux", - ), - ).toThrow(/not supported for the OpenShell Docker-driver gateway/u); - expect(() => - assertDockerDriverGatewayBindAddressSafe( - { - OPENSHELL_BIND_ADDRESS: "0.0.0.0", - OPENSHELL_GRPC_ENDPOINT: "https://169.254.2.2:8080", - OPENSHELL_SSH_GATEWAY_HOST: "127.0.0.1", - OPENSHELL_SERVER_PORT: "8080", - }, - result.runtimeEnvironment, - "linux", - ), - ).not.toThrow(); - }); + it.runIf(process.platform === "linux").each([ + ["podman", ""], + ["docker", "portable"], + ])( + "preserves %s context for profile %s through selected-target gateway startup", + async (configuredRuntime, profile) => { + vi.stubEnv("NEMOCLAW_EXPERIMENTAL_PROFILE", profile); + vi.stubEnv("NEMOCLAW_GATEWAY_RUNTIME", configuredRuntime); + vi.stubEnv("OPENSHELL_PODMAN_SOCKET", "/run/user/1000/podman/podman.sock"); + vi.stubEnv("CONTAINERS_CONF", "/tmp/containers.conf"); + vi.stubEnv("CONTAINERS_STORAGE_CONF", "/tmp/storage.conf"); + vi.stubEnv("XDG_RUNTIME_DIR", "/run/user/1000"); + vi.stubEnv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"); + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://hostile.invalid"); + vi.stubEnv("OPENSHELL_TOKEN", "hostile-token"); + vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "provider-secret"); + const clientOnlyEnvironment = buildSelectedOpenShellSubprocessEnv({ + gatewayName: "nemoclaw-9777", + workspace: "default", + }); + const result = await captureFailedStartRecovery(true, { + gatewayName: "nemoclaw-9777", + workspace: "default", + }); + expect(result.runtimeEnvironment).toMatchObject({ + NEMOCLAW_GATEWAY_RUNTIME: configuredRuntime, + OPENSHELL_DRIVERS: "podman", + OPENSHELL_GRPC_ENDPOINT: "https://169.254.2.2:9777", + OPENSHELL_PODMAN_SOCKET: "/run/user/1000/podman/podman.sock", + CONTAINERS_CONF: "/tmp/containers.conf", + CONTAINERS_STORAGE_CONF: "/tmp/storage.conf", + XDG_RUNTIME_DIR: "/run/user/1000", + DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus", + OPENSHELL_GATEWAY: "nemoclaw-9777", + OPENSHELL_WORKSPACE: "default", + }); + expect(result.runtimeEnvironment).not.toHaveProperty("OPENSHELL_GATEWAY_ENDPOINT"); + expect(result.runtimeEnvironment).not.toHaveProperty("OPENSHELL_TOKEN"); + expect(result.runtimeEnvironment).not.toHaveProperty("NVIDIA_INFERENCE_API_KEY"); + expect(() => + assertDockerDriverGatewayBindAddressSafe( + { + OPENSHELL_BIND_ADDRESS: "0.0.0.0", + OPENSHELL_GRPC_ENDPOINT: "https://169.254.2.2:8080", + OPENSHELL_SSH_GATEWAY_HOST: "127.0.0.1", + OPENSHELL_SERVER_PORT: "8080", + }, + clientOnlyEnvironment, + "linux", + ), + ).toThrow(/not supported for the OpenShell Docker-driver gateway/u); + }, + ); it("withholds a stop command when the active service uses another state (#11720)", async () => { const result = await captureFailedStartRecovery(false); diff --git a/src/lib/onboard/runtime-provider/configured-runtime.ts b/src/lib/onboard/runtime-provider/configured-runtime.ts index a88927ae365..5a1ef35ae3d 100644 --- a/src/lib/onboard/runtime-provider/configured-runtime.ts +++ b/src/lib/onboard/runtime-provider/configured-runtime.ts @@ -36,6 +36,7 @@ export function isPodmanGatewayRuntimeEnabled(env: NodeJS.ProcessEnv = process.e /** Host lifecycle context, separate from generic OpenShell client target selection. */ export const GATEWAY_HOST_RUNTIME_ENV_KEYS = [ NEMOCLAW_GATEWAY_RUNTIME_ENV, + "NEMOCLAW_EXPERIMENTAL_PROFILE", "OPENSHELL_PODMAN_SOCKET", "CONTAINERS_CONF", "CONTAINERS_STORAGE_CONF", diff --git a/src/lib/readiness/gateway-production.test.ts b/src/lib/readiness/gateway-production.test.ts index a27f693b85b..a1f5d934227 100644 --- a/src/lib/readiness/gateway-production.test.ts +++ b/src/lib/readiness/gateway-production.test.ts @@ -830,15 +830,16 @@ describe("managed gateway port readiness (#7411)", () => { }, 30_000); it.runIf(process.platform === "linux").for([ - ["marker", "podman", "selected", "none", "present", "present"], - ["service", "podman", "selected", "none", "present", "present"], - ["service", "docker", "selected", "owner-mismatch", "unknown", "absent"], - ["service", "podman", "other", "owner-mismatch", "unknown", "absent"], + ["marker", "podman", "selected", "selected", "none", "present", "present"], + ["service", "podman", "selected", "selected", "none", "present", "present"], + ["service", "docker", "selected", "selected", "owner-mismatch", "unknown", "absent"], + ["service", "podman", "other", "selected", "owner-mismatch", "unknown", "absent"], + ["service", "podman", "selected", "other", "owner-mismatch", "unknown", "absent"], ] as const)( - "projects a real %s-owned %s listener with %s socket through Podman readiness (#10984)", + "projects a real %s-owned %s listener with %s socket and %s name through Podman readiness (#10984)", { timeout: 30_000 }, async ( - [ownership, driver, socketDirectory, conflict, versionState, portState], + [ownership, driver, socketDirectory, selectedName, conflict, versionState, portState], { onTestFinished }, ) => { const actualChildProcess = @@ -851,7 +852,8 @@ describe("managed gateway port readiness (#7411)", () => { }); const gatewayPort = (reservation.address() as AddressInfo).port; await new Promise((resolve) => reservation.close(() => resolve())); - const gatewayName = `nemoclaw-${String(gatewayPort)}`; + const gatewayName = + selectedName === "selected" ? `nemoclaw-${String(gatewayPort)}` : "another-gateway"; const endpoint = getGatewayHttpsEndpoint(gatewayPort); const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-podman-readiness-real-")); const stateDir = path.join(root, "gateway-state"); diff --git a/src/lib/readiness/gateway-production.ts b/src/lib/readiness/gateway-production.ts index f03d6a2a4d9..5c66d59ddf5 100644 --- a/src/lib/readiness/gateway-production.ts +++ b/src/lib/readiness/gateway-production.ts @@ -710,7 +710,8 @@ export function createProductionGatewayReadinessDependencies( const serviceEnv = providerRuntime ? readDockerDriverGatewayProcessEnvironment(pid) : null; const providerMatches = !providerRuntime || - (serviceEnv?.OPENSHELL_DRIVERS === providerRuntime.openShellDriver && + (gatewayName === resolveDockerDriverGatewayName(gatewayPort) && + serviceEnv?.OPENSHELL_DRIVERS === providerRuntime.openShellDriver && serviceEnv.OPENSHELL_PODMAN_SOCKET === (providerRuntime.socketPath ?? undefined) && serviceEnv.OPENSHELL_BIND_ADDRESS === providerRuntime.bindAddress && serviceEnv.OPENSHELL_SERVER_PORT === String(gatewayPort) && From a5d13d730e47b5ac0912189dc092e81b537d539a Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 09:21:20 -0700 Subject: [PATCH 25/35] fix(runtime): recognize managed inference URLs regardless of case --- docs/security/process-controls.mdx | 3 ++- scripts/nemoclaw-start.sh | 8 ++------ .../agents/openclaw/runtime/auth-profile-boundary.test.ts | 6 +++--- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/docs/security/process-controls.mdx b/docs/security/process-controls.mdx index 30cfd460fc1..44756a78623 100644 --- a/docs/security/process-controls.mdx +++ b/docs/security/process-controls.mdx @@ -292,7 +292,8 @@ A registry-side tag change cannot silently select another managed sandbox image. For managed `inference.local` routes, the entrypoint clears the NVIDIA credential aliases before setup and command execution. It removes only the exact legacy NemoClaw-generated profile for the selected managed provider and preserves other profiles. -Direct inference routes outside `inference.local` retain their credentials and create or replace `auth-profiles.json` with the generated direct-route profile. +Direct inference routes outside `inference.local` retain supplied credentials. +When `NVIDIA_INFERENCE_API_KEY` is available, the entrypoint creates or replaces `auth-profiles.json` with the generated direct-route profile. The entrypoint and migration flows enforce `chmod 600` on auth-profile files under `~/.openclaw`. This prevents other users on the host from reading stored credentials that remain. diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 739aad13d01..f5d077b5f0e 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -78,12 +78,8 @@ unset -f nemoclaw_normalize_entrypoint_env_wrapper # after entrypoint overrides are normalized, before setup can launch children. # Direct inference routes retain their credentials. is_managed_inference_route() { - case "${NEMOCLAW_INFERENCE_BASE_URL:-}" in - https://inference.local | https://inference.local/* | https://inference.local:443 | https://inference.local:443/*) - return 0 - ;; - esac - return 1 + # Match URL scheme and host case without spawning a credential-bearing child. + [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Ff][Ee][Rr][Ee][Nn][Cc][Ee]\.[Ll][Oo][Cc][Aa][Ll](:443)?(/.*)?$ ]] } clear_managed_inference_credentials() { diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index a53dffcc0f1..524b45f5bec 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -16,7 +16,7 @@ const credentialProbe = const managedEnv = { NVIDIA_INFERENCE_API_KEY: "primary-secret", NVIDIA_API_KEY: "legacy-secret", - NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1", + NEMOCLAW_INFERENCE_BASE_URL: "hTtPs://InFeReNcE.LoCaL/v1", }; const homes: string[] = []; afterEach(() => { @@ -173,8 +173,8 @@ describe("OpenClaw auth-profile boundary", () => { it.each([ ["fresh", "https://inference.local/v1"], ["legacy", "https://inference.local/v1"], - ["fresh", "https://inference.local:443/v1"], - ["legacy", "https://inference.local:443"], + ["fresh", "HTTPS://inference.local:443/v1"], + ["legacy", "https://INFERENCE.LOCAL:443"], ] as const)( "leaves no managed profile or inherited credentials in %s state at %s", (state, baseUrl) => { From 52486b2a16d479acb691d66d6b11f9ed46f76da6 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 11:19:09 -0700 Subject: [PATCH 26/35] fix(runtime): retain diagnostics when maintenance release stalls --- .../process-recovery-openclaw-doctor.test.ts | 99 ++++++++++--------- src/lib/actions/sandbox/process-recovery.ts | 62 +++++++----- 2 files changed, 88 insertions(+), 73 deletions(-) diff --git a/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts b/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts index 58f085c61ce..88aeb9b9fbf 100644 --- a/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts +++ b/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts @@ -688,55 +688,58 @@ describe("OpenClaw post-upgrade recovery doctor", () => { expect(execute.mock.calls[1]?.[2]).toBe(1_000); }); - it("returns redacted OpenShell startup logs when the released gateway never serves", async () => { - const execute = vi - .fn() - .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) - .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) - .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) - .mockResolvedValue({ status: 42, stdout: "", stderr: "" }); - let now = 0; - const collectFailureLogs = vi.fn(async () => [ - "[setup] OpenClaw post-upgrade offline restore released gateway launch", - "[gateway] startup failed after restored-state validation", - ]); - const collectRuntimeFailureLogs = vi.fn(async () => [ - "gateway startup failed: restored plugin state is invalid", - ]); + it.each(["release", "restart"] as const)( + "returns redacted startup logs when recovery fails during %s", + async (stage) => { + const execute = vi + .fn() + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ status: stage === "release" ? 40 : 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ status: stage === "release" ? 40 : 0, stdout: "", stderr: "" }) + .mockResolvedValue({ status: 42, stdout: "", stderr: "" }); + let now = 0; + const collectFailureLogs = vi.fn(async () => [ + "[setup] OpenClaw post-upgrade offline restore released gateway launch", + "[gateway] startup failed after restored-state validation", + ]); + const collectRuntimeFailureLogs = vi.fn(async () => [ + "gateway startup failed: restored plugin state is invalid", + ]); - await expect( - finishOpenClawPostRestoreDoctor( - { - sandboxName: "alpha", - runtimeSelection: { gatewayName: "recorded-gateway", workspace: "default" }, - }, - { - captureOpenshell: vi.fn() as never, - collectFailureLogs, - collectRuntimeFailureLogs, - executeSandboxExecCommand: execute, - now: () => now, - sleep: vi.fn(async () => { - now = 180_000; - }), - }, - ), - ).resolves.toEqual({ - ok: false, - stage: "restart", - detail: expect.stringMatching( - /gateway startup failed: restored plugin state is invalid[\s\S]*\[gateway\] startup failed after restored-state validation/u, - ), - }); - expect(collectRuntimeFailureLogs).toHaveBeenCalledExactlyOnceWith("alpha", { - gatewayName: "recorded-gateway", - workspace: "default", - }); - expect(collectFailureLogs).toHaveBeenCalledExactlyOnceWith("alpha", { - kind: "named", - gatewayName: "recorded-gateway", - }); - }); + await expect( + finishOpenClawPostRestoreDoctor( + { + sandboxName: "alpha", + runtimeSelection: { gatewayName: "recorded-gateway", workspace: "default" }, + }, + { + captureOpenshell: vi.fn() as never, + collectFailureLogs, + collectRuntimeFailureLogs, + executeSandboxExecCommand: execute, + now: () => now, + sleep: vi.fn(async () => { + now = 180_000; + }), + }, + ), + ).resolves.toEqual({ + ok: false, + stage, + detail: expect.stringMatching( + /gateway startup failed: restored plugin state is invalid[\s\S]*\[gateway\] startup failed after restored-state validation/u, + ), + }); + expect(collectRuntimeFailureLogs).toHaveBeenCalledExactlyOnceWith("alpha", { + gatewayName: "recorded-gateway", + workspace: "default", + }); + expect(collectFailureLogs).toHaveBeenCalledExactlyOnceWith("alpha", { + kind: "named", + gatewayName: "recorded-gateway", + }); + }, + ); it("keeps the gateway gated when the verified release cannot be published", async () => { const execute = vi.fn(async () => ({ status: 35, stdout: "", stderr: "" })); diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index a74bbc5125d..379397ddb42 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -396,7 +396,9 @@ async function collectOpenClawRuntimeFailureLogs( 'direct_status="$?"', 'printf \'[nemoclaw-health-probe] url=%s ambient_status=%s ambient_http=%s direct_status=%s direct_http=%s\\n\' "$probe_url" "$ambient_status" "$ambient_code" "$direct_status" "$direct_code"', "if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null; elif command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null; fi", - "tail -n 120 /tmp/gateway.log 2>/dev/null || true", + "tail -c 8192 /tmp/gateway.log /tmp/nemoclaw-start.log 2>/dev/null || true", + 'startup_status=0; startup_count="$(pgrep -fc \'[n]emoclaw-start\' 2>/dev/null)" || startup_status=$?; printf "[nemoclaw-maintenance] startup_status=%s startup_count=%s\\n" "$startup_status" "$startup_count"', + 'for state_path in /sandbox/.openclaw /sandbox/.openclaw/.nemoclaw-post-upgrade-doctor /tmp/nemoclaw-post-upgrade-doctor-ready; do printf "[nemoclaw-maintenance] %s " "$state_path"; stat -c "type=%F uid=%u gid=%g mode=%a links=%h" "$state_path" 2>/dev/null || printf "absent\\n"; done', ].join("; "), 15_000, runtimeSelection, @@ -408,6 +410,36 @@ async function collectOpenClawRuntimeFailureLogs( } } +async function collectOpenClawRecoveryFailureDetail( + sandboxName: string, + runtimeSelection: OpenShellRuntimeSelection | undefined, + deps: OpenClawPostRestoreDoctorDeps, +): Promise { + const runtimeFailureLogs = await ( + deps.collectRuntimeFailureLogs ?? + ((name, selection) => collectOpenClawRuntimeFailureLogs(name, selection, deps)) + )(sandboxName, runtimeSelection); + const failureLogs = await (deps.collectFailureLogs ?? collectRedactedOpenShellSandboxLogs)( + sandboxName, + runtimeSelection + ? namedOpenShellGateway(runtimeSelection.gatewayName) + : selectedOpenShellGateway(), + ); + const logDetail = [ + ...(runtimeFailureLogs.length > 0 + ? [ + `Recent redacted OpenClaw runtime diagnostics:\n${runtimeFailureLogs.map((line) => ` ${line}`).join("\n")}`, + ] + : []), + ...(failureLogs.length > 0 + ? [ + `Recent redacted OpenShell sandbox logs:\n${failureLogs.map((line) => ` ${line}`).join("\n")}`, + ] + : []), + ]; + return logDetail.length > 0 ? `\n${logDetail.join("\n")}` : ""; +} + function captureOpenClawDoctorLifecycle( deps: OpenClawPostRestoreDoctorDeps, args: string[], @@ -1055,10 +1087,11 @@ export async function releaseOpenClawPostRestoreDoctorForDelete( }, ); if (consumed) return { ok: true }; + const logDetail = await collectOpenClawRecoveryFailureDetail(sandboxName, runtimeSelection, deps); return { ok: false, stage: "release", - detail: "the released maintenance request was not consumed before source deletion", + detail: `the released maintenance request was not consumed before source deletion${logDetail}`, }; } @@ -1123,32 +1156,11 @@ export async function finishOpenClawPostRestoreDoctor( }, ); if (completed) return { ok: true }; - const runtimeFailureLogs = await ( - deps.collectRuntimeFailureLogs ?? - ((name, selection) => collectOpenClawRuntimeFailureLogs(name, selection, deps)) - )(sandboxName, runtimeSelection); - const failureLogs = await (deps.collectFailureLogs ?? collectRedactedOpenShellSandboxLogs)( - sandboxName, - runtimeSelection - ? namedOpenShellGateway(runtimeSelection.gatewayName) - : selectedOpenShellGateway(), - ); - const logDetail = [ - ...(runtimeFailureLogs.length > 0 - ? [ - `Recent redacted OpenClaw runtime diagnostics:\n${runtimeFailureLogs.map((line) => ` ${line}`).join("\n")}`, - ] - : []), - ...(failureLogs.length > 0 - ? [ - `Recent redacted OpenShell sandbox logs:\n${failureLogs.map((line) => ` ${line}`).join("\n")}`, - ] - : []), - ]; + const logDetail = await collectOpenClawRecoveryFailureDetail(sandboxName, runtimeSelection, deps); return { ok: false, stage: "restart", - detail: `the released sandbox did not return a healthy gateway${logDetail.length > 0 ? `\n${logDetail.join("\n")}` : ""}`, + detail: `the released sandbox did not return a healthy gateway${logDetail}`, }; } From 9406f8b5ff05ec3848ec9c40762535b551db27c1 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 12:16:58 -0700 Subject: [PATCH 27/35] fix(e2e): recognize native provider error status prefixes --- test/e2e/live/launch-agent-turn.ts | 10 +++++-- test/e2e/support/launch-agent-turn.test.ts | 34 ++++++++++++---------- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index b8091e774ee..7a2bdba9862 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -1166,6 +1166,11 @@ const providerNonRetryableError = function isStructuredProviderUnavailable(message) { const errorMessage = typeof message.errorMessage === "string" ? message.errorMessage.trim() : ""; + const errorCode = typeof message.errorCode === "string" ? message.errorCode.trim() : ""; + // The pinned OpenAI SDK prefixes its error message with the HTTP status. + const providerMessage = errorMessage.replace(/^([0-9]{3}):?\s+/, (prefix, status) => + status === errorCode ? "" : prefix, + ); const validEmptyContent = JSON.stringify(message.content) === "[]"; const identity = [ message.role, @@ -1176,9 +1181,8 @@ function isStructuredProviderUnavailable(message) { ].join("\n"); return ( identity === "assistant\ntrue\nerror\nopenai-completions\ninference" && - typeof message.errorCode === "string" && - providerUnavailableCodes.has(message.errorCode.trim()) && - providerUnavailableError.test(errorMessage) && + providerUnavailableCodes.has(errorCode) && + providerUnavailableError.test(providerMessage) && !providerNonRetryableError.test(errorMessage) ); } diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index 701156c0382..27e68ef7246 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -61,6 +61,7 @@ type FixtureMode = | "provider-terminal-spoof" | "provider-wrong-api" | "provider-wrong-route" + | "provider-wrong-status" | "recording-timeout" | "restored-canonical-timeout" | "supervisor-timeout" @@ -335,6 +336,11 @@ const exitWithStatus = process.exit.bind(process); } if (terminalCopy === "reordered") process.stdout.write("idle | gateway connected\n"); + const wrongProviderMessages = new Map([ + ["provider-wrong-api", { api: "openai-responses" }], + ["provider-wrong-route", { provider: "attacker-controlled" }], + ["provider-wrong-status", { errorCode: "503", errorMessage: "401 litellm.ServiceUnavailableError: upstream unavailable" }], + ]); if (mode === "delayed-recording" || mode === "provider-exit-after-recording") { const publicationDeadline = Date.now() + 2_000; while (!fs.existsSync(process.env.NEMOCLAW_FIXTURE_PENDING_QUALIFICATION_MARKER)) { @@ -358,12 +364,9 @@ const exitWithStatus = process.exit.bind(process); } else if (mode === "provider-terminal-spoof") { append("user", firstInput); appendProviderError({ errorCode: "400" }); - } else if (mode === "provider-wrong-api") { + } else if (wrongProviderMessages.has(mode)) { append("user", firstInput); - appendProviderError({ api: "openai-responses" }); - } else if (mode === "provider-wrong-route") { - append("user", firstInput); - appendProviderError({ provider: "attacker-controlled" }); + appendProviderError(wrongProviderMessages.get(mode)); } else { append("user", firstInput); append("assistant", "first response"); @@ -1087,16 +1090,16 @@ it.runIf(process.platform === "linux").concurrent( ); it.runIf(process.platform === "linux").each([ - ["500", "ServiceUnavailableError", "valid"], - ["502", "ServiceUnavailableError", "valid"], - ["503", "ServiceUnavailableError", "valid"], - ["504", "ServiceUnavailableError", "valid"], - ["529", "ServiceUnavailableError", "valid"], - ["500", "InternalServerError", "valid"], - ["503", "ServiceUnavailableError", "provider-empty-message"], + ["500", "ServiceUnavailableError", "valid", "500: "], + ["502", "ServiceUnavailableError", "valid", "502 "], + ["503", "ServiceUnavailableError", "valid", "503 "], + ["504", "ServiceUnavailableError", "valid", "504 "], + ["529", "ServiceUnavailableError", "valid", "529 "], + ["500", "InternalServerError", "valid", ""], + ["503", "ServiceUnavailableError", "provider-empty-message", "503 "], ] as const)( "executes the real $1 HTTP $0 launch producer through $2 (#10978)", - async (providerCode, providerError, secondMode) => { + async (providerCode, providerError, secondMode, statusPrefix) => { const expectedError = secondMode === "valid" ? null : "launch session failed"; const secondTerminal = secondMode === "valid" ? "absent" : "provider"; const calls: Array<{ @@ -1124,7 +1127,7 @@ it.runIf(process.platform === "linux").each([ env: { ...options?.env, NEMOCLAW_FIXTURE_PROVIDER_ERROR_CODE: providerCode, - NEMOCLAW_FIXTURE_PROVIDER_ERROR_MESSAGE: `litellm.${providerError}: ${providerError}: upstream unavailable`, + NEMOCLAW_FIXTURE_PROVIDER_ERROR_MESSAGE: `${statusPrefix}litellm.${providerError}: ${providerError}: upstream unavailable`, }, }, ); @@ -1250,8 +1253,9 @@ it.runIf(process.platform === "linux").concurrent( it.runIf(process.platform === "linux").concurrent.for([ { mismatch: "API", mode: "provider-wrong-api" }, { mismatch: "route", mode: "provider-wrong-route" }, + { mismatch: "status", mode: "provider-wrong-status" }, ] as const)( - "does not retry a structured provider error with the wrong $mismatch identity (#10978)", + "does not retry a structured provider error with mismatched $mismatch evidence (#10978)", { timeout: testTimeout(30_000) }, async ({ mode }, { expect }) => { const produced = (await runLaunchSessionFixture(mode, "provider")).result; From 4206fe612e24d2d0de428ba5d06d1676bfbc37c8 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 13:34:28 -0700 Subject: [PATCH 28/35] fix(runtime): preserve recovery diagnostics across exec failures --- .../process-recovery-openclaw-doctor.test.ts | 88 +++++++++++++------ src/lib/actions/sandbox/process-recovery.ts | 35 +++++--- .../support/hermes-config-export-live.test.ts | 1 - 3 files changed, 81 insertions(+), 43 deletions(-) diff --git a/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts b/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts index 88aeb9b9fbf..b0e2029fc7b 100644 --- a/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts +++ b/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts @@ -691,49 +691,79 @@ describe("OpenClaw post-upgrade recovery doctor", () => { it.each(["release", "restart"] as const)( "returns redacted startup logs when recovery fails during %s", async (stage) => { + const credential = `nvapi-${"a".repeat(64)}`; + const diagnostics = { + status: 0, + stdout: `gateway startup failed: restored plugin state is invalid\nAuthorization: Bearer ${credential}`, + stderr: "", + }; + const executeSsh = vi.fn(async () => diagnostics); const execute = vi .fn() .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) - .mockResolvedValueOnce({ status: stage === "release" ? 40 : 0, stdout: "", stderr: "" }) - .mockResolvedValueOnce({ status: stage === "release" ? 40 : 0, stdout: "", stderr: "" }) - .mockResolvedValue({ status: 42, stdout: "", stderr: "" }); + .mockImplementation(async (_name: string, command: string) => + command.includes("probe_url=") + ? stage === "release" + ? null + : diagnostics + : { + status: stage === "release" || command.includes("curl") ? 42 : 0, + stdout: "", + stderr: "", + }, + ); let now = 0; const collectFailureLogs = vi.fn(async () => [ "[setup] OpenClaw post-upgrade offline restore released gateway launch", "[gateway] startup failed after restored-state validation", ]); - const collectRuntimeFailureLogs = vi.fn(async () => [ - "gateway startup failed: restored plugin state is invalid", - ]); - - await expect( - finishOpenClawPostRestoreDoctor( - { - sandboxName: "alpha", - runtimeSelection: { gatewayName: "recorded-gateway", workspace: "default" }, - }, - { - captureOpenshell: vi.fn() as never, - collectFailureLogs, - collectRuntimeFailureLogs, - executeSandboxExecCommand: execute, - now: () => now, - sleep: vi.fn(async () => { - now = 180_000; - }), - }, - ), - ).resolves.toEqual({ + const result = await finishOpenClawPostRestoreDoctor( + { + sandboxName: "alpha", + runtimeSelection: { gatewayName: "recorded-gateway", workspace: "default" }, + }, + { + captureOpenshell: vi.fn() as never, + collectFailureLogs, + executeSandboxCommand: executeSsh, + executeSandboxExecCommand: execute, + now: () => now, + sleep: vi.fn(async () => { + now = 180_000; + }), + }, + ); + expect(result).toEqual({ ok: false, stage, detail: expect.stringMatching( /gateway startup failed: restored plugin state is invalid[\s\S]*\[gateway\] startup failed after restored-state validation/u, ), }); - expect(collectRuntimeFailureLogs).toHaveBeenCalledExactlyOnceWith("alpha", { - gatewayName: "recorded-gateway", - workspace: "default", - }); + expect(JSON.stringify(result)).not.toContain(credential); + expect(executeSsh.mock.calls).toEqual( + stage === "release" + ? [ + [ + "alpha", + expect.stringContaining("/tmp/nemoclaw-start.log"), + { + timeout: 15_000, + runtimeSelection: { gatewayName: "recorded-gateway", workspace: "default" }, + }, + ], + ] + : [], + ); + expect(execute).toHaveBeenLastCalledWith( + "alpha", + expect.stringContaining("/tmp/nemoclaw-start.log"), + 15_000, + { + localDockerFallbackPolicy: "never", + runtimeSelection: { gatewayName: "recorded-gateway", workspace: "default" }, + }, + ); expect(collectFailureLogs).toHaveBeenCalledExactlyOnceWith("alpha", { kind: "named", gatewayName: "recorded-gateway", diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 75cbc179874..20be3963da0 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -333,6 +333,7 @@ interface OpenClawPostRestoreDoctorDeps { runtimeSelection?: OpenShellRuntimeSelection, ) => Promise; executePrivilegedSandboxCommand?: typeof executePrivilegedSandboxCommand; + executeSandboxCommand?: typeof executeSandboxCommand; executeSandboxExecCommand: typeof executeSandboxExecCommand; lookupSandbox?: CliOpenShellSandboxLookup; now: () => number; @@ -401,24 +402,31 @@ async function collectOpenClawRuntimeFailureLogs( ): Promise { try { const probeUrl = shellQuote(resolveSandboxHealthProbeUrl(sandboxName)); - const result = await executeOpenClawDoctorGateCommand( + const command = [ + `probe_url=${probeUrl}`, + 'ambient_code="$(curl -so /dev/null -w \'%{http_code}\' --max-time 3 "$probe_url" 2>/dev/null)"', + 'ambient_status="$?"', + "direct_code=\"$(curl --noproxy '*' -so /dev/null -w '%{http_code}' --max-time 3 \"$probe_url\" 2>/dev/null)\"", + 'direct_status="$?"', + 'printf \'[nemoclaw-health-probe] url=%s ambient_status=%s ambient_http=%s direct_status=%s direct_http=%s\\n\' "$probe_url" "$ambient_status" "$ambient_code" "$direct_status" "$direct_code"', + "if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null; elif command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null; fi", + 'for log_path in /tmp/gateway.log /tmp/nemoclaw-start.log; do printf "==> %s <==\\n" "$log_path"; tail -c 8192 "$log_path" 2>/dev/null | tail -n 24; done', + 'startup_status=0; startup_count="$(pgrep -fc \'/[n]emoclaw-start(\\.sh)?([[:space:]]|$)\' 2>/dev/null)" || startup_status=$?; printf "[nemoclaw-maintenance] startup_status=%s startup_count=%s\\n" "$startup_status" "$startup_count"', + 'for state_path in /sandbox/.openclaw /sandbox/.openclaw/.nemoclaw-post-upgrade-doctor /tmp/nemoclaw-post-upgrade-doctor-ready; do printf "[nemoclaw-maintenance] %s " "$state_path"; stat -c "type=%F uid=%u gid=%g mode=%a links=%h" "$state_path" 2>/dev/null || printf "absent\\n"; done', + ].join("; "); + let result = await executeOpenClawDoctorGateCommand( deps, sandboxName, - [ - `probe_url=${probeUrl}`, - 'ambient_code="$(curl -so /dev/null -w \'%{http_code}\' --max-time 3 "$probe_url" 2>/dev/null)"', - 'ambient_status="$?"', - "direct_code=\"$(curl --noproxy '*' -so /dev/null -w '%{http_code}' --max-time 3 \"$probe_url\" 2>/dev/null)\"", - 'direct_status="$?"', - 'printf \'[nemoclaw-health-probe] url=%s ambient_status=%s ambient_http=%s direct_status=%s direct_http=%s\\n\' "$probe_url" "$ambient_status" "$ambient_code" "$direct_status" "$direct_code"', - "if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null; elif command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null; fi", - "tail -c 8192 /tmp/gateway.log /tmp/nemoclaw-start.log 2>/dev/null || true", - 'startup_status=0; startup_count="$(pgrep -fc \'/[n]emoclaw-start(\\.sh)?([[:space:]]|$)\' 2>/dev/null)" || startup_status=$?; printf "[nemoclaw-maintenance] startup_status=%s startup_count=%s\\n" "$startup_status" "$startup_count"', - 'for state_path in /sandbox/.openclaw /sandbox/.openclaw/.nemoclaw-post-upgrade-doctor /tmp/nemoclaw-post-upgrade-doctor-ready; do printf "[nemoclaw-maintenance] %s " "$state_path"; stat -c "type=%F uid=%u gid=%g mode=%a links=%h" "$state_path" 2>/dev/null || printf "absent\\n"; done', - ].join("; "), + command, 15_000, runtimeSelection, ); + if (!result?.stdout.trim() && deps.executeSandboxCommand) { + result = await deps.executeSandboxCommand(sandboxName, command, { + timeout: 15_000, + ...(runtimeSelection ? { runtimeSelection } : {}), + }); + } if (!result?.stdout.trim()) return []; return result.stdout.split("\n").map(sanitizeWedgeLogLine).filter(Boolean).slice(-60); } catch { @@ -1182,6 +1190,7 @@ export async function finishOpenClawPostRestoreDoctor( const OPENCLAW_UNREGISTERED_POST_RESTORE_DOCTOR_DEPS: OpenClawPostRestoreDoctorDeps = { captureOpenshell, + executeSandboxCommand, executeSandboxExecCommand, now: Date.now, sleep: sleepSeconds, diff --git a/test/e2e/support/hermes-config-export-live.test.ts b/test/e2e/support/hermes-config-export-live.test.ts index 2d187982a2b..4f70862253b 100644 --- a/test/e2e/support/hermes-config-export-live.test.ts +++ b/test/e2e/support/hermes-config-export-live.test.ts @@ -252,7 +252,6 @@ describe("Hermes config export live evidence", () => { mocks.command.mockResolvedValue({ exitCode: 2, stdout: "", stderr: diagnostics }); await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); expect(mocks.save).not.toHaveBeenCalled(); - expect(mocks.asExportedConfig).not.toHaveBeenCalled(); }); it.each([ From bb0ea607949b344102e2f2f8ea8317ef88a79118 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 14:11:48 -0700 Subject: [PATCH 29/35] fix(runtime): retain complete diagnostic lines and native errors --- .../process-recovery-openclaw-doctor.test.ts | 98 +++++++++++-------- src/lib/actions/sandbox/process-recovery.ts | 57 ++++++++--- 2 files changed, 103 insertions(+), 52 deletions(-) diff --git a/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts b/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts index b0e2029fc7b..caa698e8383 100644 --- a/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts +++ b/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts @@ -6,7 +6,9 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it, onTestFinished, vi } from "vitest"; + +import { shellQuote } from "../../runner"; import { abortOpenClawPostRestoreDoctor, @@ -691,27 +693,53 @@ describe("OpenClaw post-upgrade recovery doctor", () => { it.each(["release", "restart"] as const)( "returns redacted startup logs when recovery fails during %s", async (stage) => { - const credential = `nvapi-${"a".repeat(64)}`; - const diagnostics = { - status: 0, - stdout: `gateway startup failed: restored plugin state is invalid\nAuthorization: Bearer ${credential}`, - stderr: "", + const credential = `nvapi-${"q".repeat(100)}`; + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recovery-logs-")); + onTestFinished(() => fs.rmSync(root, { recursive: true, force: true })); + const gatewayLog = path.join(root, "gateway.log"); + const startupLog = path.join(root, "startup.log"); + fs.writeFileSync( + gatewayLog, + `safe start\nAuthorization: Bearer ${credential}\n${"z".repeat(8030)}\ngateway startup failed: restored plugin state is invalid\n`, + ); + fs.writeFileSync(startupLog, `Authorization: Bearer ${credential}\n`); + const runDiagnostics = (command: string) => { + const result = spawnSync( + "sh", + [ + "-c", + "curl() { return 7; }; ss() { :; }; pgrep() { return 1; }; stat() { return 1; }; " + + command + .replaceAll("/tmp/gateway.log", shellQuote(gatewayLog)) + .replaceAll("/tmp/nemoclaw-start.log", shellQuote(startupLog)), + ], + { encoding: "utf8" }, + ); + return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr }; }; - const executeSsh = vi.fn(async () => diagnostics); + const runBuffered = vi.fn(async ({ command }: { command: readonly string[] }) => { + const result = runDiagnostics(command[2]!); + return { + outcome: + stage === "release" + ? { + kind: "failed" as const, + error: { + kind: "unavailable" as const, + message: `native diagnostic fixture failed: ${credential}`, + }, + } + : { kind: "completed" as const, exitCode: result.status }, + stdout: result.stdout, + stderr: result.stderr, + }; + }); const execute = vi .fn() .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) - .mockImplementation(async (_name: string, command: string) => - command.includes("probe_url=") - ? stage === "release" - ? null - : diagnostics - : { - status: stage === "release" || command.includes("curl") ? 42 : 0, - stdout: "", - stderr: "", - }, - ); + .mockResolvedValueOnce({ status: stage === "release" ? 40 : 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ status: stage === "release" ? 40 : 0, stdout: "", stderr: "" }) + .mockResolvedValue({ status: 42, stdout: "", stderr: "" }); let now = 0; const collectFailureLogs = vi.fn(async () => [ "[setup] OpenClaw post-upgrade offline restore released gateway launch", @@ -725,7 +753,7 @@ describe("OpenClaw post-upgrade recovery doctor", () => { { captureOpenshell: vi.fn() as never, collectFailureLogs, - executeSandboxCommand: executeSsh, + commandExecutor: { runBuffered }, executeSandboxExecCommand: execute, now: () => now, sleep: vi.fn(async () => { @@ -741,29 +769,19 @@ describe("OpenClaw post-upgrade recovery doctor", () => { ), }); expect(JSON.stringify(result)).not.toContain(credential); - expect(executeSsh.mock.calls).toEqual( + expect(JSON.stringify(result)).not.toContain("q".repeat(50)); + expect(JSON.stringify(result)).toContain( stage === "release" - ? [ - [ - "alpha", - expect.stringContaining("/tmp/nemoclaw-start.log"), - { - timeout: 15_000, - runtimeSelection: { gatewayName: "recorded-gateway", workspace: "default" }, - }, - ], - ] - : [], - ); - expect(execute).toHaveBeenLastCalledWith( - "alpha", - expect.stringContaining("/tmp/nemoclaw-start.log"), - 15_000, - { - localDockerFallbackPolicy: "never", - runtimeSelection: { gatewayName: "recorded-gateway", workspace: "default" }, - }, + ? "unavailable: native diagnostic fixture failed:" + : "[nemoclaw-runtime-diagnostics] exit=0", ); + expect(runBuffered).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "recorded-gateway" }, + command: ["sh", "-c", expect.stringContaining("/tmp/nemoclaw-start.log")], + environment: expect.objectContaining({ OPENSHELL_WORKSPACE: "default" }), + timeoutMilliseconds: 15_000, + }); expect(collectFailureLogs).toHaveBeenCalledExactlyOnceWith("alpha", { kind: "named", gatewayName: "recorded-gateway", diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 20be3963da0..aecc2aff656 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -333,7 +333,7 @@ interface OpenClawPostRestoreDoctorDeps { runtimeSelection?: OpenShellRuntimeSelection, ) => Promise; executePrivilegedSandboxCommand?: typeof executePrivilegedSandboxCommand; - executeSandboxCommand?: typeof executeSandboxCommand; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; executeSandboxExecCommand: typeof executeSandboxExecCommand; lookupSandbox?: CliOpenShellSandboxLookup; now: () => number; @@ -402,6 +402,19 @@ async function collectOpenClawRuntimeFailureLogs( ): Promise { try { const probeUrl = shellQuote(resolveSandboxHealthProbeUrl(sandboxName)); + const logTail = shellQuote( + [ + "import sys", + "with open(sys.argv[1], 'rb') as log:", + " log.seek(0, 2)", + " start = max(0, log.tell() - 8192)", + " log.seek(max(0, start - 1))", + " data = log.read(8193 if start else 8192)", + // Keep credential prefixes intact for redaction, including across rotation/truncation. + "if start: data = data.partition(b'\\n')[2]", + "sys.stdout.buffer.write(b'\\n'.join(data.split(b'\\n')[-25:-1]) + b'\\n')", + ].join("\n"), + ); const command = [ `probe_url=${probeUrl}`, 'ambient_code="$(curl -so /dev/null -w \'%{http_code}\' --max-time 3 "$probe_url" 2>/dev/null)"', @@ -410,27 +423,48 @@ async function collectOpenClawRuntimeFailureLogs( 'direct_status="$?"', 'printf \'[nemoclaw-health-probe] url=%s ambient_status=%s ambient_http=%s direct_status=%s direct_http=%s\\n\' "$probe_url" "$ambient_status" "$ambient_code" "$direct_status" "$direct_code"', "if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null; elif command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null; fi", - 'for log_path in /tmp/gateway.log /tmp/nemoclaw-start.log; do printf "==> %s <==\\n" "$log_path"; tail -c 8192 "$log_path" 2>/dev/null | tail -n 24; done', + `for log_path in /tmp/gateway.log /tmp/nemoclaw-start.log; do printf "==> %s <==\\n" "$log_path"; python3 -I -S -c ${logTail} "$log_path" 2>/dev/null || true; done`, 'startup_status=0; startup_count="$(pgrep -fc \'/[n]emoclaw-start(\\.sh)?([[:space:]]|$)\' 2>/dev/null)" || startup_status=$?; printf "[nemoclaw-maintenance] startup_status=%s startup_count=%s\\n" "$startup_status" "$startup_count"', 'for state_path in /sandbox/.openclaw /sandbox/.openclaw/.nemoclaw-post-upgrade-doctor /tmp/nemoclaw-post-upgrade-doctor-ready; do printf "[nemoclaw-maintenance] %s " "$state_path"; stat -c "type=%F uid=%u gid=%g mode=%a links=%h" "$state_path" 2>/dev/null || printf "absent\\n"; done', ].join("; "); - let result = await executeOpenClawDoctorGateCommand( + if (!deps.executePrivilegedSandboxCommand) { + const result = await ( + deps.commandExecutor ?? createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }) + ).runBuffered({ + sandboxName, + target: runtimeSelection + ? namedOpenShellGateway(runtimeSelection.gatewayName) + : selectedOpenShellGateway(), + command: ["sh", "-c", command], + environment: runtimeSelection + ? buildOpenShellRuntimeSelectionEnv(buildSubprocessEnv(), runtimeSelection) + : buildSubprocessEnv(), + timeoutMilliseconds: 15_000, + }); + const outcome = + result.outcome.kind === "completed" + ? `exit=${result.outcome.exitCode}` + : `${result.outcome.error.kind}: ${result.outcome.error.message}`; + return [ + ...result.stdout.split("\n"), + ...result.stderr.split("\n").slice(-5), + `[nemoclaw-runtime-diagnostics] ${outcome}`, + ] + .map(sanitizeWedgeLogLine) + .filter(Boolean) + .slice(-60); + } + const result = await executeOpenClawDoctorGateCommand( deps, sandboxName, command, 15_000, runtimeSelection, ); - if (!result?.stdout.trim() && deps.executeSandboxCommand) { - result = await deps.executeSandboxCommand(sandboxName, command, { - timeout: 15_000, - ...(runtimeSelection ? { runtimeSelection } : {}), - }); - } if (!result?.stdout.trim()) return []; return result.stdout.split("\n").map(sanitizeWedgeLogLine).filter(Boolean).slice(-60); - } catch { - return []; + } catch (error) { + return [sanitizeWedgeLogLine(`OpenClaw runtime diagnostics unavailable: ${String(error)}`)]; } } @@ -1190,7 +1224,6 @@ export async function finishOpenClawPostRestoreDoctor( const OPENCLAW_UNREGISTERED_POST_RESTORE_DOCTOR_DEPS: OpenClawPostRestoreDoctorDeps = { captureOpenshell, - executeSandboxCommand, executeSandboxExecCommand, now: Date.now, sleep: sleepSeconds, From 1beb47d8f50519a397b866eb07d00e63f4550715 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 14:37:00 -0700 Subject: [PATCH 30/35] refactor: separate Podman recovery from the credential fix --- ...aunch-readiness-observation-timing.test.ts | 3 - .../actions/sandbox/launch-readiness.test.ts | 18 --- src/lib/actions/sandbox/launch-readiness.ts | 44 ++---- .../sandbox/launch-readiness/health.ts | 5 +- src/lib/actions/sandbox/probe/timing.ts | 14 +- .../process-recovery-openclaw-doctor.test.ts | 125 +++++----------- src/lib/actions/sandbox/process-recovery.ts | 126 +++++----------- .../actions/sandbox/rebuild-flow-helpers.ts | 2 +- src/lib/agent/base-image.test.ts | 3 +- .../agent/deep-agents-code-base-image.test.ts | 37 ++--- src/lib/agent/deep-agents-code-base-image.ts | 37 ++--- src/lib/gateway-runtime-action.ts | 4 +- .../authoritative-rebuild-target.test.ts | 4 - .../onboard/authoritative-rebuild-target.ts | 2 +- .../onboard/gateway/docker-driver-start.ts | 6 +- src/lib/onboard/gateway/late-binding.test.ts | 105 ++------------ .../runtime-provider/configured-runtime.ts | 34 ----- src/lib/onboard/runtime-provider/contract.ts | 3 - .../podman-gateway-readiness.test.ts | 37 ++--- .../podman-gateway-readiness.ts | 24 +--- src/lib/readiness/gateway-production.test.ts | 65 +++------ src/lib/readiness/gateway-production.ts | 43 +----- test/e2e/fixtures/availability-env.ts | 9 +- test/e2e/fixtures/hermes-acp-diagnostics.ts | 72 ---------- test/e2e/fixtures/hermes-acp-live.ts | 17 +-- .../e2e/fixtures/hermes-config-export-live.ts | 18 +-- test/e2e/live/full-e2e-inference-probe.ts | 29 +--- test/e2e/live/launch-agent-turn.ts | 34 +---- .../support/full-e2e-inference-probe.test.ts | 54 +------ .../support/hermes-acp-diagnostics.test.ts | 80 ----------- test/e2e/support/hermes-acp-live.test.ts | 136 +----------------- .../support/hermes-config-export-live.test.ts | 64 --------- ...h-agent-turn-provider-availability.test.ts | 9 +- test/e2e/support/launch-agent-turn.test.ts | 68 +++------ 34 files changed, 218 insertions(+), 1113 deletions(-) delete mode 100644 test/e2e/fixtures/hermes-acp-diagnostics.ts delete mode 100644 test/e2e/support/hermes-acp-diagnostics.test.ts diff --git a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts index 25334632258..73528472dee 100644 --- a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts +++ b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts @@ -193,8 +193,6 @@ describe("launch readiness observation timing", () => { return lease(identity); }); const currentDeps = publicationDeps(assertPublicationCurrent, publishLease); - const recordObservationFailure = vi.fn(); - currentDeps.recordObservationFailure = recordObservationFailure; const decision = await inspectLaunchReadiness(SANDBOX, currentDeps); await expect( @@ -203,7 +201,6 @@ describe("launch readiness observation timing", () => { expect(publishLease).toHaveBeenCalledTimes(expectedPublicationAttempts); expect(committed).toBe(false); - expect(recordObservationFailure).toHaveBeenNthCalledWith(1, "publication-authority"); }, ); diff --git a/src/lib/actions/sandbox/launch-readiness.test.ts b/src/lib/actions/sandbox/launch-readiness.test.ts index 5f4e558f14c..d6c0fcae442 100644 --- a/src/lib/actions/sandbox/launch-readiness.test.ts +++ b/src/lib/actions/sandbox/launch-readiness.test.ts @@ -1369,31 +1369,13 @@ describe("launch readiness validation", () => { kind: "evidence-failed", }); - const registryUnavailable = deps(); - registryUnavailable.recordObservationFailure = vi.fn(); - registryUnavailable.getSandbox = () => { - throw new Error("registry unavailable"); - }; - expect(await publishLaunchReadiness(publication, registryUnavailable)).toEqual({ - kind: "evidence-failed", - }); - expect(registryUnavailable.recordObservationFailure).toHaveBeenNthCalledWith( - 1, - "publication-observation", - ); - const pairingObservationUnavailable = deps(); - pairingObservationUnavailable.recordObservationFailure = vi.fn(); pairingObservationUnavailable.observeOpenClawPairingQualification = () => { throw new Error("pairing observation unavailable"); }; expect(await publishLaunchReadiness(publication, pairingObservationUnavailable)).toEqual({ kind: "evidence-failed", }); - expect(pairingObservationUnavailable.recordObservationFailure).toHaveBeenNthCalledWith( - 1, - "pairing-qualification", - ); const hashUnavailable = deps(); hashUnavailable.capture = (args) => ({ diff --git a/src/lib/actions/sandbox/launch-readiness.ts b/src/lib/actions/sandbox/launch-readiness.ts index 050271f53e5..1219bad31f2 100644 --- a/src/lib/actions/sandbox/launch-readiness.ts +++ b/src/lib/actions/sandbox/launch-readiness.ts @@ -415,12 +415,11 @@ function projectMessagingState(entry: SandboxEntry): unknown { }; } -function projectAgent(agent: AgentDefinition, deps: LaunchReadinessDeps): unknown { +function projectAgent(agent: AgentDefinition): unknown { let manifestSha256: string; try { manifestSha256 = exactContentDigest(fs.readFileSync(agent.manifestPath, "utf8")); } catch { - recordLaunchReadinessObservationFailure(deps, "agent-definition"); throw new LaunchReadinessEvidenceError(); } return { @@ -841,7 +840,6 @@ async function captureLaunchIdentity( // receipt binds the sandbox's recorded version, including supported stale // versions that the normal launch warning permits. if (!openclawVersion || !normalizedString(agent.expected_version) || !stateDirectory) { - recordLaunchReadinessObservationFailure(deps, "pairing-qualification"); throw new OpenClawPairingQualificationError(); } try { @@ -852,7 +850,6 @@ async function captureLaunchIdentity( stateDirectory, ); } catch { - recordLaunchReadinessObservationFailure(deps, "pairing-qualification"); throw new OpenClawPairingQualificationError(); } } @@ -860,7 +857,7 @@ async function captureLaunchIdentity( return { identity: { registry: launchReadinessDigest(projection), - agent: launchReadinessDigest(projectAgent(agent, deps)), + agent: launchReadinessDigest(projectAgent(agent)), liveInference: launchReadinessDigest({ selection: inferenceSelection, live: liveInference @@ -1390,30 +1387,12 @@ export async function publishLaunchReadiness( deps: LaunchReadinessDeps = {}, ): Promise { const { sandboxName, gatewayName, gatewayPort, epochId } = publication; - if (!gatewayName || !gatewayPort || !epochId) { - recordLaunchReadinessObservationFailure(deps, "publication-authority"); - return { kind: "evidence-failed" }; - } + if (!gatewayName || !gatewayPort || !epochId) return { kind: "evidence-failed" }; const withSandboxLock = deps.withSandboxLock ?? withSandboxMutationLock; const withGatewayLock = deps.withGatewayLock ?? withGatewayRouteMutationLock; - let failedOperation: "publication-authority" | "publication-observation" | undefined; - const assertPublicationCurrent = () => { - try { - deps.assertPublicationCurrent?.(); - } catch (error) { - failedOperation = "publication-authority"; - throw error; - } - }; try { return await withSandboxLock(sandboxName, async () => { - let entry: SandboxEntry | null; - try { - entry = (deps.getSandbox ?? registry.getSandbox)(sandboxName); - } catch (error) { - failedOperation = "publication-observation"; - throw error; - } + const entry = (deps.getSandbox ?? registry.getSandbox)(sandboxName); if (entry?.gatewayPort !== gatewayPort || entry.gatewayName !== gatewayName) { return { kind: "validation-failed", category: "identity" } as const; } @@ -1422,14 +1401,14 @@ export async function publishLaunchReadiness( let captured: Awaited> | undefined; let captureFailure: unknown; try { - assertPublicationCurrent(); + deps.assertPublicationCurrent?.(); try { captured = await captureLaunchIdentity(sandboxName, gatewayName, gatewayPort, deps); } catch (error) { captureFailure = error; } try { - assertPublicationCurrent(); + deps.assertPublicationCurrent?.(); } catch (error) { captureFailure = error; } @@ -1442,11 +1421,6 @@ export async function publishLaunchReadiness( } as const; } const validation = publicationValidationCategory(error); - if (!validation) - recordLaunchReadinessObservationFailure( - deps, - failedOperation ?? "publication-observation", - ); return validation ? ({ kind: "validation-failed", ...validation } as const) : ({ kind: "evidence-failed" } as const); @@ -1456,7 +1430,7 @@ export async function publishLaunchReadiness( const publicationStartedAt = performance.now(); let publicationFailed = false; try { - assertPublicationCurrent(); + deps.assertPublicationCurrent?.(); (deps.publishLease ?? publishLaunchReadinessLease)( sandboxName, gatewayName, @@ -1464,10 +1438,9 @@ export async function publishLaunchReadiness( epochId, captured!.identity, deps.storeOptions, - assertPublicationCurrent, + deps.assertPublicationCurrent, ); } catch { - recordLaunchReadinessObservationFailure(deps, failedOperation ?? "publication-store"); publicationFailed = true; } finally { recordPerformanceStage("publication-store", publicationStartedAt); @@ -1477,7 +1450,6 @@ export async function publishLaunchReadiness( }); }); } catch { - recordLaunchReadinessObservationFailure(deps, failedOperation ?? "publication-lock"); return { kind: "evidence-failed" }; } } diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index f3c03e2a703..b8ea5952782 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -32,7 +32,6 @@ import { isSandboxGatewayHttpReachableForStatus, isSandboxGatewayRunningForStatus, } from "../process-recovery"; -import type { ProbeReadinessObservationFailureStage } from "../probe/timing"; export type LaunchReadinessObservationCategory = | "missing" @@ -75,7 +74,7 @@ export interface LaunchReadinessHealthDeps { ) => Promise>; inferenceInvocationProbe?: typeof runSandboxInferenceInvocationProbe; recordObservationTiming?: (stage: LaunchReadinessObservationStage, elapsedMs: number) => void; - recordObservationFailure?: (stage: ProbeReadinessObservationFailureStage) => void; + recordObservationFailure?: (stage: LaunchReadinessObservationStage) => void; } export type LaunchReadinessBoundCapture = ( @@ -146,7 +145,7 @@ function recordObservationTiming( export function recordLaunchReadinessObservationFailure( deps: LaunchReadinessHealthDeps, - stage: ProbeReadinessObservationFailureStage, + stage: LaunchReadinessObservationStage, ): void { try { deps.recordObservationFailure?.(stage); diff --git a/src/lib/actions/sandbox/probe/timing.ts b/src/lib/actions/sandbox/probe/timing.ts index 26fa25c1fbd..98e4eeb5325 100644 --- a/src/lib/actions/sandbox/probe/timing.ts +++ b/src/lib/actions/sandbox/probe/timing.ts @@ -26,14 +26,6 @@ export const PROBE_READINESS_OBSERVATION_STAGES = [ export type ProbeTimingStage = (typeof PROBE_TIMING_STAGES)[number]; export type ProbeReadinessObservationStage = (typeof PROBE_READINESS_OBSERVATION_STAGES)[number]; -export type ProbeReadinessObservationFailureStage = - | ProbeReadinessObservationStage - | "agent-definition" - | "pairing-qualification" - | "publication-authority" - | "publication-observation" - | "publication-store" - | "publication-lock"; export type ProbeTimingResult = "ready" | "failed"; export type ProbeLifecycleAction = "skipped" | "reused" | "recovered" | "failed"; export type ProbeForwardAction = "skipped" | "verified" | "restored" | "failed"; @@ -55,7 +47,7 @@ export type ProbeTimingRecorder = { setForwardAction(action: ProbeForwardAction): void; markFailureStage(stage: ProbeTimingStage): void; recordReadinessObservation(stage: ProbeReadinessObservationStage, elapsedMs: number): void; - recordReadinessObservationFailure(stage: ProbeReadinessObservationFailureStage): void; + recordReadinessObservationFailure(stage: ProbeReadinessObservationStage): void; recordReadinessDecision(category: ProbeReadinessDecisionCategory): void; finish(result: ProbeTimingResult, failedStage?: ProbeTimingStage): void; finishOnExit(result: ProbeTimingResult, failedStage?: ProbeTimingStage): void; @@ -88,7 +80,7 @@ export function createProbeTimingRecorder(deps: ProbeTimingDeps = {}): ProbeTimi let lifecycleAction: ProbeLifecycleAction = "skipped"; let forwardAction: ProbeForwardAction = "skipped"; let recordedFailureStage: ProbeTimingStage | null = null; - let firstReadinessObservationFailure: ProbeReadinessObservationFailureStage | null = null; + let firstReadinessObservationFailure: ProbeReadinessObservationStage | null = null; let firstReadinessDecision: ProbeReadinessDecisionCategory | null = null; let firstReadinessFallbackDecision: Exclude | null = null; @@ -187,7 +179,7 @@ export function createProbeTimingRecorder(deps: ProbeTimingDeps = {}): ProbeTimi (readinessObservationDurations.get(stage) ?? 0) + Math.max(0, elapsedMs), ); }, - recordReadinessObservationFailure(stage: ProbeReadinessObservationFailureStage): void { + recordReadinessObservationFailure(stage: ProbeReadinessObservationStage): void { firstReadinessObservationFailure ??= stage; }, recordReadinessDecision(category: ProbeReadinessDecisionCategory): void { diff --git a/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts b/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts index caa698e8383..58f085c61ce 100644 --- a/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts +++ b/src/lib/actions/sandbox/process-recovery-openclaw-doctor.test.ts @@ -6,9 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it, onTestFinished, vi } from "vitest"; - -import { shellQuote } from "../../runner"; +import { describe, expect, it, vi } from "vitest"; import { abortOpenClawPostRestoreDoctor, @@ -690,62 +688,24 @@ describe("OpenClaw post-upgrade recovery doctor", () => { expect(execute.mock.calls[1]?.[2]).toBe(1_000); }); - it.each(["release", "restart"] as const)( - "returns redacted startup logs when recovery fails during %s", - async (stage) => { - const credential = `nvapi-${"q".repeat(100)}`; - const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recovery-logs-")); - onTestFinished(() => fs.rmSync(root, { recursive: true, force: true })); - const gatewayLog = path.join(root, "gateway.log"); - const startupLog = path.join(root, "startup.log"); - fs.writeFileSync( - gatewayLog, - `safe start\nAuthorization: Bearer ${credential}\n${"z".repeat(8030)}\ngateway startup failed: restored plugin state is invalid\n`, - ); - fs.writeFileSync(startupLog, `Authorization: Bearer ${credential}\n`); - const runDiagnostics = (command: string) => { - const result = spawnSync( - "sh", - [ - "-c", - "curl() { return 7; }; ss() { :; }; pgrep() { return 1; }; stat() { return 1; }; " + - command - .replaceAll("/tmp/gateway.log", shellQuote(gatewayLog)) - .replaceAll("/tmp/nemoclaw-start.log", shellQuote(startupLog)), - ], - { encoding: "utf8" }, - ); - return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr }; - }; - const runBuffered = vi.fn(async ({ command }: { command: readonly string[] }) => { - const result = runDiagnostics(command[2]!); - return { - outcome: - stage === "release" - ? { - kind: "failed" as const, - error: { - kind: "unavailable" as const, - message: `native diagnostic fixture failed: ${credential}`, - }, - } - : { kind: "completed" as const, exitCode: result.status }, - stdout: result.stdout, - stderr: result.stderr, - }; - }); - const execute = vi - .fn() - .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) - .mockResolvedValueOnce({ status: stage === "release" ? 40 : 0, stdout: "", stderr: "" }) - .mockResolvedValueOnce({ status: stage === "release" ? 40 : 0, stdout: "", stderr: "" }) - .mockResolvedValue({ status: 42, stdout: "", stderr: "" }); - let now = 0; - const collectFailureLogs = vi.fn(async () => [ - "[setup] OpenClaw post-upgrade offline restore released gateway launch", - "[gateway] startup failed after restored-state validation", - ]); - const result = await finishOpenClawPostRestoreDoctor( + it("returns redacted OpenShell startup logs when the released gateway never serves", async () => { + const execute = vi + .fn() + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValue({ status: 42, stdout: "", stderr: "" }); + let now = 0; + const collectFailureLogs = vi.fn(async () => [ + "[setup] OpenClaw post-upgrade offline restore released gateway launch", + "[gateway] startup failed after restored-state validation", + ]); + const collectRuntimeFailureLogs = vi.fn(async () => [ + "gateway startup failed: restored plugin state is invalid", + ]); + + await expect( + finishOpenClawPostRestoreDoctor( { sandboxName: "alpha", runtimeSelection: { gatewayName: "recorded-gateway", workspace: "default" }, @@ -753,41 +713,30 @@ describe("OpenClaw post-upgrade recovery doctor", () => { { captureOpenshell: vi.fn() as never, collectFailureLogs, - commandExecutor: { runBuffered }, + collectRuntimeFailureLogs, executeSandboxExecCommand: execute, now: () => now, sleep: vi.fn(async () => { now = 180_000; }), }, - ); - expect(result).toEqual({ - ok: false, - stage, - detail: expect.stringMatching( - /gateway startup failed: restored plugin state is invalid[\s\S]*\[gateway\] startup failed after restored-state validation/u, - ), - }); - expect(JSON.stringify(result)).not.toContain(credential); - expect(JSON.stringify(result)).not.toContain("q".repeat(50)); - expect(JSON.stringify(result)).toContain( - stage === "release" - ? "unavailable: native diagnostic fixture failed:" - : "[nemoclaw-runtime-diagnostics] exit=0", - ); - expect(runBuffered).toHaveBeenCalledExactlyOnceWith({ - sandboxName: "alpha", - target: { kind: "named", gatewayName: "recorded-gateway" }, - command: ["sh", "-c", expect.stringContaining("/tmp/nemoclaw-start.log")], - environment: expect.objectContaining({ OPENSHELL_WORKSPACE: "default" }), - timeoutMilliseconds: 15_000, - }); - expect(collectFailureLogs).toHaveBeenCalledExactlyOnceWith("alpha", { - kind: "named", - gatewayName: "recorded-gateway", - }); - }, - ); + ), + ).resolves.toEqual({ + ok: false, + stage: "restart", + detail: expect.stringMatching( + /gateway startup failed: restored plugin state is invalid[\s\S]*\[gateway\] startup failed after restored-state validation/u, + ), + }); + expect(collectRuntimeFailureLogs).toHaveBeenCalledExactlyOnceWith("alpha", { + gatewayName: "recorded-gateway", + workspace: "default", + }); + expect(collectFailureLogs).toHaveBeenCalledExactlyOnceWith("alpha", { + kind: "named", + gatewayName: "recorded-gateway", + }); + }); it("keeps the gateway gated when the verified release cannot be published", async () => { const execute = vi.fn(async () => ({ status: 35, stdout: "", stderr: "" })); diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index aecc2aff656..f6bb6f2f6f2 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -333,7 +333,6 @@ interface OpenClawPostRestoreDoctorDeps { runtimeSelection?: OpenShellRuntimeSelection, ) => Promise; executePrivilegedSandboxCommand?: typeof executePrivilegedSandboxCommand; - commandExecutor?: OpenShellSandboxBufferedCommandExecutor; executeSandboxExecCommand: typeof executeSandboxExecCommand; lookupSandbox?: CliOpenShellSandboxLookup; now: () => number; @@ -402,102 +401,29 @@ async function collectOpenClawRuntimeFailureLogs( ): Promise { try { const probeUrl = shellQuote(resolveSandboxHealthProbeUrl(sandboxName)); - const logTail = shellQuote( - [ - "import sys", - "with open(sys.argv[1], 'rb') as log:", - " log.seek(0, 2)", - " start = max(0, log.tell() - 8192)", - " log.seek(max(0, start - 1))", - " data = log.read(8193 if start else 8192)", - // Keep credential prefixes intact for redaction, including across rotation/truncation. - "if start: data = data.partition(b'\\n')[2]", - "sys.stdout.buffer.write(b'\\n'.join(data.split(b'\\n')[-25:-1]) + b'\\n')", - ].join("\n"), - ); - const command = [ - `probe_url=${probeUrl}`, - 'ambient_code="$(curl -so /dev/null -w \'%{http_code}\' --max-time 3 "$probe_url" 2>/dev/null)"', - 'ambient_status="$?"', - "direct_code=\"$(curl --noproxy '*' -so /dev/null -w '%{http_code}' --max-time 3 \"$probe_url\" 2>/dev/null)\"", - 'direct_status="$?"', - 'printf \'[nemoclaw-health-probe] url=%s ambient_status=%s ambient_http=%s direct_status=%s direct_http=%s\\n\' "$probe_url" "$ambient_status" "$ambient_code" "$direct_status" "$direct_code"', - "if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null; elif command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null; fi", - `for log_path in /tmp/gateway.log /tmp/nemoclaw-start.log; do printf "==> %s <==\\n" "$log_path"; python3 -I -S -c ${logTail} "$log_path" 2>/dev/null || true; done`, - 'startup_status=0; startup_count="$(pgrep -fc \'/[n]emoclaw-start(\\.sh)?([[:space:]]|$)\' 2>/dev/null)" || startup_status=$?; printf "[nemoclaw-maintenance] startup_status=%s startup_count=%s\\n" "$startup_status" "$startup_count"', - 'for state_path in /sandbox/.openclaw /sandbox/.openclaw/.nemoclaw-post-upgrade-doctor /tmp/nemoclaw-post-upgrade-doctor-ready; do printf "[nemoclaw-maintenance] %s " "$state_path"; stat -c "type=%F uid=%u gid=%g mode=%a links=%h" "$state_path" 2>/dev/null || printf "absent\\n"; done', - ].join("; "); - if (!deps.executePrivilegedSandboxCommand) { - const result = await ( - deps.commandExecutor ?? createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }) - ).runBuffered({ - sandboxName, - target: runtimeSelection - ? namedOpenShellGateway(runtimeSelection.gatewayName) - : selectedOpenShellGateway(), - command: ["sh", "-c", command], - environment: runtimeSelection - ? buildOpenShellRuntimeSelectionEnv(buildSubprocessEnv(), runtimeSelection) - : buildSubprocessEnv(), - timeoutMilliseconds: 15_000, - }); - const outcome = - result.outcome.kind === "completed" - ? `exit=${result.outcome.exitCode}` - : `${result.outcome.error.kind}: ${result.outcome.error.message}`; - return [ - ...result.stdout.split("\n"), - ...result.stderr.split("\n").slice(-5), - `[nemoclaw-runtime-diagnostics] ${outcome}`, - ] - .map(sanitizeWedgeLogLine) - .filter(Boolean) - .slice(-60); - } const result = await executeOpenClawDoctorGateCommand( deps, sandboxName, - command, + [ + `probe_url=${probeUrl}`, + 'ambient_code="$(curl -so /dev/null -w \'%{http_code}\' --max-time 3 "$probe_url" 2>/dev/null)"', + 'ambient_status="$?"', + "direct_code=\"$(curl --noproxy '*' -so /dev/null -w '%{http_code}' --max-time 3 \"$probe_url\" 2>/dev/null)\"", + 'direct_status="$?"', + 'printf \'[nemoclaw-health-probe] url=%s ambient_status=%s ambient_http=%s direct_status=%s direct_http=%s\\n\' "$probe_url" "$ambient_status" "$ambient_code" "$direct_status" "$direct_code"', + "if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null; elif command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null; fi", + "tail -n 120 /tmp/gateway.log 2>/dev/null || true", + ].join("; "), 15_000, runtimeSelection, ); if (!result?.stdout.trim()) return []; return result.stdout.split("\n").map(sanitizeWedgeLogLine).filter(Boolean).slice(-60); - } catch (error) { - return [sanitizeWedgeLogLine(`OpenClaw runtime diagnostics unavailable: ${String(error)}`)]; + } catch { + return []; } } -async function collectOpenClawRecoveryFailureDetail( - sandboxName: string, - runtimeSelection: OpenShellRuntimeSelection | undefined, - deps: OpenClawPostRestoreDoctorDeps, -): Promise { - const runtimeFailureLogs = await ( - deps.collectRuntimeFailureLogs ?? - ((name, selection) => collectOpenClawRuntimeFailureLogs(name, selection, deps)) - )(sandboxName, runtimeSelection); - const failureLogs = await (deps.collectFailureLogs ?? collectRedactedOpenShellSandboxLogs)( - sandboxName, - runtimeSelection - ? namedOpenShellGateway(runtimeSelection.gatewayName) - : selectedOpenShellGateway(), - ); - const logDetail = [ - ...(runtimeFailureLogs.length > 0 - ? [ - `Recent redacted OpenClaw runtime diagnostics:\n${runtimeFailureLogs.map((line) => ` ${line}`).join("\n")}`, - ] - : []), - ...(failureLogs.length > 0 - ? [ - `Recent redacted OpenShell sandbox logs:\n${failureLogs.map((line) => ` ${line}`).join("\n")}`, - ] - : []), - ]; - return logDetail.length > 0 ? `\n${logDetail.join("\n")}` : ""; -} - function captureOpenClawDoctorLifecycle( deps: OpenClawPostRestoreDoctorDeps, args: string[], @@ -1145,11 +1071,10 @@ export async function releaseOpenClawPostRestoreDoctorForDelete( }, ); if (consumed) return { ok: true }; - const logDetail = await collectOpenClawRecoveryFailureDetail(sandboxName, runtimeSelection, deps); return { ok: false, stage: "release", - detail: `the released maintenance request was not consumed before source deletion${logDetail}`, + detail: "the released maintenance request was not consumed before source deletion", }; } @@ -1214,11 +1139,32 @@ export async function finishOpenClawPostRestoreDoctor( }, ); if (completed) return { ok: true }; - const logDetail = await collectOpenClawRecoveryFailureDetail(sandboxName, runtimeSelection, deps); + const runtimeFailureLogs = await ( + deps.collectRuntimeFailureLogs ?? + ((name, selection) => collectOpenClawRuntimeFailureLogs(name, selection, deps)) + )(sandboxName, runtimeSelection); + const failureLogs = await (deps.collectFailureLogs ?? collectRedactedOpenShellSandboxLogs)( + sandboxName, + runtimeSelection + ? namedOpenShellGateway(runtimeSelection.gatewayName) + : selectedOpenShellGateway(), + ); + const logDetail = [ + ...(runtimeFailureLogs.length > 0 + ? [ + `Recent redacted OpenClaw runtime diagnostics:\n${runtimeFailureLogs.map((line) => ` ${line}`).join("\n")}`, + ] + : []), + ...(failureLogs.length > 0 + ? [ + `Recent redacted OpenShell sandbox logs:\n${failureLogs.map((line) => ` ${line}`).join("\n")}`, + ] + : []), + ]; return { ok: false, stage: "restart", - detail: `the released sandbox did not return a healthy gateway${logDetail}`, + detail: `the released sandbox did not return a healthy gateway${logDetail.length > 0 ? `\n${logDetail.join("\n")}` : ""}`, }; } diff --git a/src/lib/actions/sandbox/rebuild-flow-helpers.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.ts index 239ba78f6f5..692944820d7 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.ts @@ -4,6 +4,7 @@ import { dockerRmi } from "../../adapters/docker/image"; import { printOpenShellStateRpcIssue } from "../../adapters/openshell/gateway-drift"; import { + replaceOpenShellRuntimeSelectionEnv, snapshotOpenShellEnv, type OpenShellRuntimeSelection, } from "../../adapters/openshell/runtime-selection"; @@ -27,7 +28,6 @@ import { import { getNamedGatewayLifecycleState, recoverNamedGatewayRuntime, - replaceOpenShellRuntimeSelectionEnv, } from "../../gateway-runtime-action"; import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { diff --git a/src/lib/agent/base-image.test.ts b/src/lib/agent/base-image.test.ts index 6fe3d6f338a..bf2ae649fbc 100644 --- a/src/lib/agent/base-image.test.ts +++ b/src/lib/agent/base-image.test.ts @@ -494,11 +494,10 @@ describe("agent base image provisioning", () => { inputPaths: [ "/test/root/agents/langchain-deepagents-code/manifest.yaml", "/test/root/agents/langchain-deepagents-code/requirements.lock", - "/test/root/agents/langchain-deepagents-code/validate-runtime-contract.py", ], validateImage: expect.any(Function), validationDescription: - "deepagents-code==0.1.55 runtime contract, dos2unix, and the immutable security package inventory", + "deepagents-code==0.1.55, dos2unix, and the immutable security package inventory", }), ); }); diff --git a/src/lib/agent/deep-agents-code-base-image.test.ts b/src/lib/agent/deep-agents-code-base-image.test.ts index 692b46df297..c74568f04aa 100644 --- a/src/lib/agent/deep-agents-code-base-image.test.ts +++ b/src/lib/agent/deep-agents-code-base-image.test.ts @@ -23,21 +23,13 @@ describe("Deep Agents Code base image compatibility", () => { mocks.dockerCapture.mockReset(); }); - it("accepts only a complete installed runtime contract (#6456)", () => { - mocks.dockerCapture - .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok\n0.1.55\n") - .mockReturnValueOnce("0.1.55\n"); + it("accepts only the exact installed distribution version (#6456)", () => { + mocks.dockerCapture.mockReturnValueOnce("0.1.55\n").mockReturnValueOnce("0.1.12\n"); expect(deepAgentsCodeBaseImageMatchesVersion("dcode-base:current", "0.1.55")).toBe(true); expect(deepAgentsCodeBaseImageMatchesVersion("dcode-base:stale", "0.1.55")).toBe(false); }); - it("rejects a valid runtime contract for a different manifest version (#6456)", () => { - mocks.dockerCapture.mockReturnValue("nemoclaw-dcode-runtime-contract-ok\n0.1.55\n"); - - expect(deepAgentsCodeBaseImageMatchesVersion("dcode-base:mismatched", "0.1.56")).toBe(false); - }); - it("binds the manifest version and source files into resolution options (#6456)", () => { const options = createDeepAgentsCodeBaseImageResolutionOptions( makeAgent({ @@ -48,7 +40,7 @@ describe("Deep Agents Code base image compatibility", () => { "/test/root/agents/langchain-deepagents-code/Dockerfile.base", ); mocks.dockerCapture - .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok\n9.8.7") + .mockReturnValueOnce("9.8.7") .mockReturnValueOnce("nemoclaw-dcode-dos2unix-ok") .mockReturnValueOnce("nemoclaw-security-inventory-ok"); @@ -56,10 +48,9 @@ describe("Deep Agents Code base image compatibility", () => { inputPaths: [ "/test/root/agents/langchain-deepagents-code/manifest.yaml", "/test/root/agents/langchain-deepagents-code/requirements.lock", - "/test/root/agents/langchain-deepagents-code/validate-runtime-contract.py", ], validationDescription: - "deepagents-code==9.8.7 runtime contract, dos2unix, and the immutable security package inventory", + "deepagents-code==9.8.7, dos2unix, and the immutable security package inventory", }); expect(options?.validateImage?.("dcode-base:manifest-version")).toBe(true); }); @@ -73,9 +64,7 @@ describe("Deep Agents Code base image compatibility", () => { }), "/test/root/agents/langchain-deepagents-code/Dockerfile.base", ); - mocks.dockerCapture - .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok\n0.1.34") - .mockReturnValueOnce(""); + mocks.dockerCapture.mockReturnValueOnce("0.1.34").mockReturnValueOnce(""); expect(options?.validateImage?.("dcode-base:missing-dos2unix")).toBe(false); expect(mocks.dockerCapture).toHaveBeenCalledTimes(2); @@ -112,7 +101,7 @@ describe("Deep Agents Code base image compatibility", () => { "/test/root/agents/langchain-deepagents-code/Dockerfile.base", ); mocks.dockerCapture - .mockReturnValueOnce("nemoclaw-dcode-runtime-contract-ok\n0.1.55") + .mockReturnValueOnce("0.1.55") .mockReturnValueOnce("nemoclaw-dcode-dos2unix-ok") .mockReturnValueOnce(""); @@ -139,8 +128,8 @@ describe("Deep Agents Code base image compatibility", () => { ); }); - it("runs the runtime contract probe in a locked-down container (#6456)", () => { - mocks.dockerCapture.mockReturnValue("nemoclaw-dcode-runtime-contract-ok\n0.1.55"); + it("runs the version probe in a locked-down container (#6456)", () => { + mocks.dockerCapture.mockReturnValue("0.1.55"); deepAgentsCodeBaseImageMatchesVersion("dcode-base:current", "0.1.55"); @@ -160,24 +149,22 @@ describe("Deep Agents Code base image compatibility", () => { "dcode-base:current", "-I", "-c", - 'import importlib.metadata; import runpy; runpy.run_path("/usr/local/lib/nemoclaw/validate-dcode-runtime-contract.py", run_name="__main__"); print(importlib.metadata.version("deepagents-code"))', + 'import importlib.metadata; print(importlib.metadata.version("deepagents-code"))', ], { ignoreError: true, timeout: 20_000 }, ); }); - it("warns and fails closed when the probe returns no contract output (#6456)", () => { + it("warns and fails closed when the probe returns no version (#6456)", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); mocks.dockerCapture.mockReturnValue(""); expect(deepAgentsCodeBaseImageMatchesVersion("dcode-base:unreadable", "0.1.55")).toBe(false); expect(warn).toHaveBeenCalledWith( - expect.stringContaining( - "dcode-base:unreadable returned no Deep Agents Code runtime contract output", - ), + expect.stringContaining("dcode-base:unreadable returned no Deep Agents Code version output"), ); expect(warn).toHaveBeenCalledWith( - expect.stringContaining("the container or contract validator may have failed"), + expect.stringContaining("the container or metadata probe may have failed"), ); expect(warn).toHaveBeenCalledWith(expect.stringContaining("deepagents-code==0.1.55")); warn.mockRestore(); diff --git a/src/lib/agent/deep-agents-code-base-image.ts b/src/lib/agent/deep-agents-code-base-image.ts index 60d39d98ca4..dbb84c1b1a9 100644 --- a/src/lib/agent/deep-agents-code-base-image.ts +++ b/src/lib/agent/deep-agents-code-base-image.ts @@ -9,15 +9,6 @@ import { sandboxBaseImageHasSecurityInventory } from "../sandbox-base-image/secu import type { AgentDefinition } from "./defs"; const DEEPAGENTS_CODE_DISTRIBUTION = "deepagents-code"; -const DEEPAGENTS_CODE_RUNTIME_CONTRACT_PATH = - "/usr/local/lib/nemoclaw/validate-dcode-runtime-contract.py"; -const DEEPAGENTS_CODE_RUNTIME_CONTRACT_OK = "nemoclaw-dcode-runtime-contract-ok"; -const DEEPAGENTS_CODE_RUNTIME_CONTRACT_PROBE = [ - "import importlib.metadata", - "import runpy", - `runpy.run_path("${DEEPAGENTS_CODE_RUNTIME_CONTRACT_PATH}", run_name="__main__")`, - `print(importlib.metadata.version("${DEEPAGENTS_CODE_DISTRIBUTION}"))`, -].join("; "); const DEEPAGENTS_CODE_DOS2UNIX_PROBE_OK = "nemoclaw-dcode-dos2unix-ok"; const DEEPAGENTS_CODE_BASE_IMAGE_PROBE_GUARDS = [ "--network", @@ -35,10 +26,10 @@ type DeepAgentsCodeResolutionOptions = Pick< >; /** - * Reject a published or cached Deep Agents Code base whose installed runtime - * does not satisfy the active contract. The final image intentionally reruns - * this validator, so probing it here prevents a stale base from failing only - * after the expensive final-image build (#6456). + * Reject a published or cached Deep Agents Code base whose installed package + * does not match the active manifest. The final image patchers intentionally + * require this exact source pairing, so accepting a merely runnable older base + * only defers the failure until the expensive final-image build (#6456). */ export function deepAgentsCodeBaseImageMatchesVersion( imageRef: string, @@ -54,20 +45,20 @@ export function deepAgentsCodeBaseImageMatchesVersion( imageRef, "-I", "-c", - DEEPAGENTS_CODE_RUNTIME_CONTRACT_PROBE, + `import importlib.metadata; print(importlib.metadata.version("${DEEPAGENTS_CODE_DISTRIBUTION}"))`, ], { ignoreError: true, timeout: 20_000 }, ); - const contractOutput = output.trim(); - if (!contractOutput) { + const installedVersion = output.trim(); + if (!installedVersion) { console.warn( - ` Warning: ${imageRef} returned no Deep Agents Code runtime contract output; ` + - "the container or contract validator may have failed. " + + ` Warning: ${imageRef} returned no Deep Agents Code version output; ` + + "the container or metadata probe may have failed. " + `Rejecting the base image (expected ${DEEPAGENTS_CODE_DISTRIBUTION}==${expectedVersion}).`, ); return false; } - return contractOutput === `${DEEPAGENTS_CODE_RUNTIME_CONTRACT_OK}\n${expectedVersion}`; + return installedVersion === expectedVersion; } /** @@ -115,17 +106,13 @@ export function createDeepAgentsCodeBaseImageResolutionOptions( return { // Retain the resolver's pre-existing global inputs alongside these agent // inputs. Per-agent cache-policy isolation is a separate cross-agent change. - inputPaths: [ - path.join(agentRoot, "manifest.yaml"), - path.join(agentRoot, "requirements.lock"), - path.join(agentRoot, "validate-runtime-contract.py"), - ], + inputPaths: [path.join(agentRoot, "manifest.yaml"), path.join(agentRoot, "requirements.lock")], validateImage: (imageRef) => deepAgentsCodeBaseImageMatchesVersion(imageRef, expectedVersion) && deepAgentsCodeBaseImageHasDos2Unix(imageRef) && sandboxBaseImageHasSecurityInventory(imageRef), validationDescription: - `${DEEPAGENTS_CODE_DISTRIBUTION}==${expectedVersion} runtime contract, dos2unix, and ` + + `${DEEPAGENTS_CODE_DISTRIBUTION}==${expectedVersion}, dos2unix, and ` + "the immutable security package inventory", }; } diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index 50d562167eb..147b40d89ff 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -12,12 +12,12 @@ import { resolveSandboxGatewayName, } from "./onboard/gateway-binding"; import type { GatewayRecoveryOutput } from "./onboard/gateway-recovery"; -import { replaceGatewayHostRuntimeSelectionEnv } from "./onboard/runtime-provider/configured-runtime"; import { sanitizeReadinessText } from "./readiness/sanitize"; export { resolveGatewayName, resolveSandboxGatewayName }; -export const replaceOpenShellRuntimeSelectionEnv = replaceGatewayHostRuntimeSelectionEnv; +export const replaceOpenShellRuntimeSelectionEnv = + openshellRuntime.replaceOpenShellRuntimeSelectionEnv; export const snapshotOpenShellEnv = openshellRuntime.snapshotOpenShellEnv; type StartGatewayForRecoveryOptions = { diff --git a/src/lib/onboard/authoritative-rebuild-target.test.ts b/src/lib/onboard/authoritative-rebuild-target.test.ts index 73cd6b251a2..996a882b997 100644 --- a/src/lib/onboard/authoritative-rebuild-target.test.ts +++ b/src/lib/onboard/authoritative-rebuild-target.test.ts @@ -225,8 +225,6 @@ describe("authoritative rebuild OpenShell runtime selection", () => { it("replaces hostile ambient selectors for inner onboard and restores them (#10514)", () => { const env: NodeJS.ProcessEnv = { PATH: "/usr/bin", - NEMOCLAW_GATEWAY_RUNTIME: "podman", - OPENSHELL_PODMAN_SOCKET: "/custom/run/podman.sock", OPENSHELL_GATEWAY: "hostile-gateway", OPENSHELL_GATEWAY_AUTH_TOKEN: "hostile-token", OPENSHELL_GATEWAY_ENDPOINT: "https://hostile.invalid", @@ -253,8 +251,6 @@ describe("authoritative rebuild OpenShell runtime selection", () => { expect(env).toMatchObject({ PATH: "/usr/bin", - NEMOCLAW_GATEWAY_RUNTIME: "podman", - OPENSHELL_PODMAN_SOCKET: "/custom/run/podman.sock", OPENSHELL_GATEWAY: "nemoclaw-8081", OPENSHELL_LOCAL_TLS_DIR: "/authority/tls", OPENSHELL_WORKSPACE: "default", diff --git a/src/lib/onboard/authoritative-rebuild-target.ts b/src/lib/onboard/authoritative-rebuild-target.ts index 366bc22d741..292c765441c 100644 --- a/src/lib/onboard/authoritative-rebuild-target.ts +++ b/src/lib/onboard/authoritative-rebuild-target.ts @@ -2,10 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { + replaceOpenShellRuntimeSelectionEnv, snapshotOpenShellEnv, type OpenShellRuntimeSelection, } from "../adapters/openshell/runtime-selection"; -import { replaceGatewayHostRuntimeSelectionEnv as replaceOpenShellRuntimeSelectionEnv } from "./runtime-provider/configured-runtime"; import { createOpenShellForwardPortObserver, type OpenShellForwardPortObserver, diff --git a/src/lib/onboard/gateway/docker-driver-start.ts b/src/lib/onboard/gateway/docker-driver-start.ts index 6a663be1b18..ef90319aa82 100644 --- a/src/lib/onboard/gateway/docker-driver-start.ts +++ b/src/lib/onboard/gateway/docker-driver-start.ts @@ -9,7 +9,6 @@ import { buildSelectedOpenShellSubprocessEnv, type OpenShellRuntimeSelection, } from "../../adapters/openshell/command-argv"; -import { gatewayHostRuntimeEnvironment } from "../runtime-provider/configured-runtime"; import { trackChildExit } from "../child-exit-tracker"; import * as dockerDriverGatewayCutover from "../docker-driver-gateway-cutover"; import { reportDockerDriverGatewayStartFailure } from "../docker-driver-gateway-failure"; @@ -195,10 +194,7 @@ export function createDockerDriverGatewayStart( ); } const selectedRuntimeEnv = runtimeSelection - ? { - ...buildSelectedOpenShellSubprocessEnv(runtimeSelection), - ...gatewayHostRuntimeEnvironment(process.env), - } + ? buildSelectedOpenShellSubprocessEnv(runtimeSelection) : undefined; const runtimeOptions = selectedRuntimeEnv ? { diff --git a/src/lib/onboard/gateway/late-binding.test.ts b/src/lib/onboard/gateway/late-binding.test.ts index d875e45a0aa..e6d988ea6fd 100644 --- a/src/lib/onboard/gateway/late-binding.test.ts +++ b/src/lib/onboard/gateway/late-binding.test.ts @@ -13,12 +13,6 @@ import { } from "../docker-driver-gateway-config"; import * as dockerDriverGatewayCutover from "../docker-driver-gateway-cutover"; import * as dockerDriverGatewayLaunch from "../docker-driver-gateway-launch"; -import { - assertDockerDriverGatewayBindAddressSafe, - observeConfiguredGatewayHostRuntime, -} from "../docker-driver-gateway-env"; -import { buildSelectedOpenShellSubprocessEnv } from "../../adapters/openshell/command-argv"; -import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; import * as gatewayBinding from "../gateway-binding"; import { createDockerDriverGatewayStart, @@ -51,10 +45,7 @@ describe("gateway lifecycle late binding", () => { ).toBe("https://127.0.0.1:8080"); }); - async function captureFailedStartRecovery( - ownsSelectedState: boolean, - runtimeSelection?: OpenShellRuntimeSelection, - ) { + async function captureFailedStartRecovery(ownsSelectedState: boolean) { const root = fs.mkdtempSync(path.join(process.cwd(), "nemoclaw-gateway-port-recovery-")); const stateDir = path.join(root, "gateway"); const adapters = gatewayAdaptersForTest(); @@ -75,18 +66,21 @@ describe("gateway lifecycle late binding", () => { const managedFallbackSpy = vi .spyOn(dockerDriverGatewayCutover, "runDockerDriverGatewayManagedFallback") .mockResolvedValue("launch"); - const buildRuntimeIdentity = dockerDriverGatewayLaunch.buildDockerDriverGatewayRuntimeIdentity; const runtimeIdentitySpy = vi .spyOn(dockerDriverGatewayLaunch, "buildDockerDriverGatewayRuntimeIdentity") - .mockImplementation((options) => - buildRuntimeIdentity({ - ...options, - ensureLocalTlsBundle: false, - platform: "linux", - hostGlibcVersion: "2.39", - requiredGlibcVersions: ["2.39"], - }), - ); + .mockReturnValue({ + launch: { + command: "/opt/openshell/openshell-gateway", + args: [], + argv0: "openshell-gateway[nemoclaw=nemoclaw-9777;port=9777]", + env: {}, + mode: "host", + processGatewayBin: "/opt/openshell/openshell-gateway", + }, + desiredEnv: {}, + driftGatewayBin: "/opt/openshell/openshell-gateway", + identityGatewayBin: "/opt/openshell/openshell-gateway", + }); const prepareSpy = vi .spyOn(dockerDriverGatewayLaunch, "prepareAndLogDockerDriverGatewayLaunch") .mockImplementation(() => undefined); @@ -130,20 +124,7 @@ describe("gateway lifecycle late binding", () => { gatewayName: () => "nemoclaw-9777", gatewayPort: () => 9777, getDockerDriverGatewayEndpoint: () => "https://127.0.0.1:9777", - getDockerDriverGatewayEnv: () => { - const runtime = observeConfiguredGatewayHostRuntime({ - environment: process.env, - platform: "linux", - }); - return { - OPENSHELL_DRIVERS: runtime.openShellDriver, - OPENSHELL_BIND_ADDRESS: runtime.bindAddress, - OPENSHELL_SERVER_PORT: "9777", - OPENSHELL_GRPC_ENDPOINT: `https://${runtime.grpcHost}:9777`, - OPENSHELL_SSH_GATEWAY_HOST: runtime.sshGatewayHost, - ...(runtime.socketPath ? { OPENSHELL_PODMAN_SOCKET: runtime.socketPath } : {}), - }; - }, + getDockerDriverGatewayEnv: () => ({}), getDockerDriverGatewayPid: () => null, getDockerDriverGatewayPortListenerScan: () => ({ complete: true, @@ -175,7 +156,6 @@ describe("gateway lifecycle late binding", () => { await expect( start.startDockerDriverGateway({ - runtimeSelection, exitOnFailure: false, output: { error: (message) => lines.push(message), @@ -187,7 +167,6 @@ describe("gateway lifecycle late binding", () => { ).rejects.toThrow(/failed to start within/); return { - runtimeEnvironment: spawnSpy.mock.calls[0]?.[0].env, output: lines.join("\n"), processEnvironmentCalls: readProcessEnvironment.mock.calls, serviceTargetCalls: serviceTarget.mock.calls.length, @@ -202,60 +181,6 @@ describe("gateway lifecycle late binding", () => { } } - it.runIf(process.platform === "linux").each([ - ["podman", ""], - ["docker", "portable"], - ])( - "preserves %s context for profile %s through selected-target gateway startup", - async (configuredRuntime, profile) => { - vi.stubEnv("NEMOCLAW_EXPERIMENTAL_PROFILE", profile); - vi.stubEnv("NEMOCLAW_GATEWAY_RUNTIME", configuredRuntime); - vi.stubEnv("OPENSHELL_PODMAN_SOCKET", "/run/user/1000/podman/podman.sock"); - vi.stubEnv("CONTAINERS_CONF", "/tmp/containers.conf"); - vi.stubEnv("CONTAINERS_STORAGE_CONF", "/tmp/storage.conf"); - vi.stubEnv("XDG_RUNTIME_DIR", "/run/user/1000"); - vi.stubEnv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"); - vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://hostile.invalid"); - vi.stubEnv("OPENSHELL_TOKEN", "hostile-token"); - vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "provider-secret"); - const clientOnlyEnvironment = buildSelectedOpenShellSubprocessEnv({ - gatewayName: "nemoclaw-9777", - workspace: "default", - }); - const result = await captureFailedStartRecovery(true, { - gatewayName: "nemoclaw-9777", - workspace: "default", - }); - expect(result.runtimeEnvironment).toMatchObject({ - NEMOCLAW_GATEWAY_RUNTIME: configuredRuntime, - OPENSHELL_DRIVERS: "podman", - OPENSHELL_GRPC_ENDPOINT: "https://169.254.2.2:9777", - OPENSHELL_PODMAN_SOCKET: "/run/user/1000/podman/podman.sock", - CONTAINERS_CONF: "/tmp/containers.conf", - CONTAINERS_STORAGE_CONF: "/tmp/storage.conf", - XDG_RUNTIME_DIR: "/run/user/1000", - DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus", - OPENSHELL_GATEWAY: "nemoclaw-9777", - OPENSHELL_WORKSPACE: "default", - }); - expect(result.runtimeEnvironment).not.toHaveProperty("OPENSHELL_GATEWAY_ENDPOINT"); - expect(result.runtimeEnvironment).not.toHaveProperty("OPENSHELL_TOKEN"); - expect(result.runtimeEnvironment).not.toHaveProperty("NVIDIA_INFERENCE_API_KEY"); - expect(() => - assertDockerDriverGatewayBindAddressSafe( - { - OPENSHELL_BIND_ADDRESS: "0.0.0.0", - OPENSHELL_GRPC_ENDPOINT: "https://169.254.2.2:8080", - OPENSHELL_SSH_GATEWAY_HOST: "127.0.0.1", - OPENSHELL_SERVER_PORT: "8080", - }, - clientOnlyEnvironment, - "linux", - ), - ).toThrow(/not supported for the OpenShell Docker-driver gateway/u); - }, - ); - it("withholds a stop command when the active service uses another state (#11720)", async () => { const result = await captureFailedStartRecovery(false); diff --git a/src/lib/onboard/runtime-provider/configured-runtime.ts b/src/lib/onboard/runtime-provider/configured-runtime.ts index 5a1ef35ae3d..5763138e8a6 100644 --- a/src/lib/onboard/runtime-provider/configured-runtime.ts +++ b/src/lib/onboard/runtime-provider/configured-runtime.ts @@ -1,11 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { - replaceOpenShellRuntimeSelectionEnv, - type OpenShellRuntimeSelection, -} from "../../adapters/openshell/runtime-selection"; - export const NEMOCLAW_GATEWAY_RUNTIME_ENV = "NEMOCLAW_GATEWAY_RUNTIME"; export type NemoClawGatewayRuntime = "docker" | "podman"; @@ -32,32 +27,3 @@ export function resolveNemoClawGatewayRuntime( export function isPodmanGatewayRuntimeEnabled(env: NodeJS.ProcessEnv = process.env): boolean { return resolveNemoClawGatewayRuntime(env) === "podman"; } - -/** Host lifecycle context, separate from generic OpenShell client target selection. */ -export const GATEWAY_HOST_RUNTIME_ENV_KEYS = [ - NEMOCLAW_GATEWAY_RUNTIME_ENV, - "NEMOCLAW_EXPERIMENTAL_PROFILE", - "OPENSHELL_PODMAN_SOCKET", - "CONTAINERS_CONF", - "CONTAINERS_STORAGE_CONF", - "XDG_RUNTIME_DIR", - "DBUS_SESSION_BUS_ADDRESS", -] as const; - -export function gatewayHostRuntimeEnvironment(source: NodeJS.ProcessEnv): Record { - return Object.fromEntries( - GATEWAY_HOST_RUNTIME_ENV_KEYS.flatMap((name) => - source[name] === undefined ? [] : [[name, source[name]]], - ), - ); -} - -/** Pin client authority without discarding the host runtime used by lifecycle operations. */ -export function replaceGatewayHostRuntimeSelectionEnv( - environment: NodeJS.ProcessEnv, - selection: OpenShellRuntimeSelection, -): void { - const hostRuntime = gatewayHostRuntimeEnvironment(environment); - replaceOpenShellRuntimeSelectionEnv(environment, selection); - Object.assign(environment, hostRuntime); -} diff --git a/src/lib/onboard/runtime-provider/contract.ts b/src/lib/onboard/runtime-provider/contract.ts index 0d717f4e829..0a780a65b41 100644 --- a/src/lib/onboard/runtime-provider/contract.ts +++ b/src/lib/onboard/runtime-provider/contract.ts @@ -112,10 +112,7 @@ export interface RuntimeProviderOwnedGatewayReadinessInput { readonly architecture: NodeJS.Architecture; readonly gatewayName: string; readonly gatewayPort: number; - /** Sandbox-facing transport origin recorded by the gateway runtime marker. */ readonly expectedEndpoint: string; - /** Host CLI registration origin; it can differ from the sandbox transport. */ - readonly expectedClientEndpoint: string; readonly managedGatewayEndpoints: readonly (string | null)[]; readonly portAvailable: boolean; readonly installedOpenShellVersion: string | null; diff --git a/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts b/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts index ba9823ea5d8..805a0cbf6be 100644 --- a/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts +++ b/src/lib/onboard/runtime-provider/podman-gateway-readiness.test.ts @@ -4,7 +4,6 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; -import { getGatewayHttpsEndpoint } from "../../core/gateway-address"; import { buildDockerDriverGatewayRuntimeMarker, @@ -34,10 +33,9 @@ function input() { gatewayName: GATEWAY_NAME, gatewayPort: GATEWAY_PORT, expectedEndpoint: `https://169.254.2.2:${String(GATEWAY_PORT)}`, - expectedClientEndpoint: getGatewayHttpsEndpoint(GATEWAY_PORT), managedGatewayEndpoints: [ - getGatewayHttpsEndpoint(GATEWAY_PORT), - getGatewayHttpsEndpoint(GATEWAY_PORT), + `https://169.254.2.2:${String(GATEWAY_PORT)}`, + `https://169.254.2.2:${String(GATEWAY_PORT)}`, ], portAvailable: false, installedOpenShellVersion: "0.0.116", @@ -99,25 +97,14 @@ function readinessDeps( } describe("native Podman gateway readiness", () => { - it.each(["127.0.0.1", "localhost", "[::1]"])( - "recognizes a target-bound listener through %s (#10984)", - (host) => { - expect( - observeNativePodmanGatewayReadiness( - { - ...input(), - managedGatewayEndpoints: [`https://${host}:${String(GATEWAY_PORT)}`], - }, - readinessDeps(), - ), - ).toEqual({ - endpointBinding: "match", - listenerScan: { pids: [PID], unverifiedPids: [], complete: true }, - targetBoundListenerPids: [PID], - versionCompatibility: "compatible", - }); - }, - ); + it("recognizes one target-bound listener and its recorded OpenShell version (#10984)", () => { + expect(observeNativePodmanGatewayReadiness(input(), readinessDeps())).toEqual({ + endpointBinding: "match", + listenerScan: { pids: [PID], unverifiedPids: [], complete: true }, + targetBoundListenerPids: [PID], + versionCompatibility: "compatible", + }); + }); it.each([ ["another provider", { driver: "docker" }], @@ -149,11 +136,11 @@ describe("native Podman gateway readiness", () => { }); }); - it.each([8080, 8990])("rejects non-client endpoint output on port %s (#10984)", (port) => { + it("rejects managed endpoint output outside the provider endpoint (#10984)", () => { const observation = observeNativePodmanGatewayReadiness( { ...input(), - managedGatewayEndpoints: [`https://169.254.2.2:${String(port)}`], + managedGatewayEndpoints: [`https://169.254.2.2:8990`], }, readinessDeps(), ); diff --git a/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts b/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts index 1e85c28f58e..952b1cf3eb5 100644 --- a/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts +++ b/src/lib/onboard/runtime-provider/podman-gateway-readiness.ts @@ -5,7 +5,6 @@ import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { isManagedGatewayEndpointHost } from "../../../../nemoclaw/dist/shared/openshell-gateway-endpoint-boundary.cjs"; import { getDockerDriverGatewayRuntimeMarkerPath, @@ -109,23 +108,9 @@ function classifyEndpointBinding( endpoints: readonly (string | null)[], expectedEndpoint: string, ): RuntimeProviderOwnedGatewayReadinessObservation["endpointBinding"] { - const expected = new URL(expectedEndpoint); + const expected = new URL(expectedEndpoint).origin; if (!endpoints.length) return "unknown"; - return endpoints.every((endpoint) => { - if (endpoint === null) return false; - try { - const observed = new URL(endpoint); - return ( - endpoint === observed.origin && - observed.protocol === expected.protocol && - observed.port === expected.port && - isManagedGatewayEndpointHost(observed.hostname) && - isManagedGatewayEndpointHost(expected.hostname) - ); - } catch { - return false; - } - }) + return endpoints.every((endpoint) => endpoint !== null && endpoint === expected) ? "match" : "mismatch"; } @@ -221,10 +206,7 @@ export function observeNativePodmanGatewayReadiness( ? "compatible" : "drift"; return Object.freeze({ - endpointBinding: classifyEndpointBinding( - input.managedGatewayEndpoints, - input.expectedClientEndpoint, - ), + endpointBinding: classifyEndpointBinding(input.managedGatewayEndpoints, input.expectedEndpoint), listenerScan: Object.freeze({ pids: Object.freeze(pids), unverifiedPids: Object.freeze(unverifiedPids), diff --git a/src/lib/readiness/gateway-production.test.ts b/src/lib/readiness/gateway-production.test.ts index a1f5d934227..9ffdb8a99bb 100644 --- a/src/lib/readiness/gateway-production.test.ts +++ b/src/lib/readiness/gateway-production.test.ts @@ -9,7 +9,6 @@ import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { getGatewayHttpsEndpoint } from "../core/gateway-address"; import { isDockerDriverGatewayProcessIdentity } from "../onboard/docker-driver-gateway-process-identity"; import { resolveDockerDriverGatewayStateDir, @@ -18,7 +17,6 @@ import { } from "../onboard/docker-driver-gateway-runtime-marker"; import type { GatewayOwner } from "../onboard/gateway-ownership"; import { createCurrentPodmanRuntimeProviderBundle } from "../onboard/runtime-provider/podman"; -import * as gatewayService from "../onboard/docker-driver-gateway-service"; import { resetTraceForTests, TRACE_FILE_ENV } from "../trace"; import { collectGatewayObservations, projectGatewayReadiness } from "./gateway"; @@ -731,7 +729,7 @@ describe("managed gateway port readiness (#7411)", () => { }); const gatewayPort = (gatewayListener.address() as AddressInfo).port; const gatewayName = `nemoclaw-${String(gatewayPort)}`; - const endpoint = getGatewayHttpsEndpoint(gatewayPort); + const endpoint = `https://169.254.2.2:${String(gatewayPort)}`; const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-podman-readiness-")); const openshell = path.join(root, "openshell"); fs.writeFileSync(openshell, "#!/bin/sh\nexit 1\n", { mode: 0o700 }); @@ -815,8 +813,7 @@ describe("managed gateway port readiness (#7411)", () => { }), gatewayName, gatewayPort, - expectedEndpoint: `https://169.254.2.2:${String(gatewayPort)}`, - expectedClientEndpoint: endpoint, + expectedEndpoint: endpoint, managedGatewayEndpoints: expect.arrayContaining([endpoint]), portAvailable: false, }), @@ -829,19 +826,9 @@ describe("managed gateway port readiness (#7411)", () => { } }, 30_000); - it.runIf(process.platform === "linux").for([ - ["marker", "podman", "selected", "selected", "none", "present", "present"], - ["service", "podman", "selected", "selected", "none", "present", "present"], - ["service", "docker", "selected", "selected", "owner-mismatch", "unknown", "absent"], - ["service", "podman", "other", "selected", "owner-mismatch", "unknown", "absent"], - ["service", "podman", "selected", "other", "owner-mismatch", "unknown", "absent"], - ] as const)( - "projects a real %s-owned %s listener with %s socket and %s name through Podman readiness (#10984)", - { timeout: 30_000 }, - async ( - [ownership, driver, socketDirectory, selectedName, conflict, versionState, portState], - { onTestFinished }, - ) => { + it.runIf(process.platform === "linux")( + "projects a real marker-owned native Podman listener through production readiness (#10984)", + async ({ onTestFinished }) => { const actualChildProcess = await vi.importActual("node:child_process"); subprocess.spawnSync.mockImplementation(actualChildProcess.spawnSync); @@ -852,9 +839,8 @@ describe("managed gateway port readiness (#7411)", () => { }); const gatewayPort = (reservation.address() as AddressInfo).port; await new Promise((resolve) => reservation.close(() => resolve())); - const gatewayName = - selectedName === "selected" ? `nemoclaw-${String(gatewayPort)}` : "another-gateway"; - const endpoint = getGatewayHttpsEndpoint(gatewayPort); + const gatewayName = `nemoclaw-${String(gatewayPort)}`; + const endpoint = `https://169.254.2.2:${String(gatewayPort)}`; const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-podman-readiness-real-")); const stateDir = path.join(root, "gateway-state"); const openshell = path.join(root, "openshell"); @@ -884,16 +870,7 @@ esac String(gatewayPort), ], { - ...(ownership === "marker" - ? { argv0: `openshell-gateway[nemoclaw=${gatewayName};port=${String(gatewayPort)}]` } - : {}), - env: { - OPENSHELL_DRIVERS: driver, - OPENSHELL_PODMAN_SOCKET: `/nonexistent/run/${socketDirectory}/podman.sock`, - OPENSHELL_BIND_ADDRESS: "0.0.0.0", - OPENSHELL_SERVER_PORT: String(gatewayPort), - OPENSHELL_GRPC_ENDPOINT: `https://169.254.2.2:${String(gatewayPort)}`, - }, + argv0: `openshell-gateway[nemoclaw=${gatewayName};port=${String(gatewayPort)}]`, stdio: ["ignore", "pipe", "pipe"], }, ); @@ -906,24 +883,17 @@ esac fs.writeFileSync(lsof, `#!/bin/sh\nprintf '%s\\n' '${String(listener.pid)}'\n`, { mode: 0o700, }); - const markerDir = ownership === "marker" ? stateDir : path.join(root, "other-gateway-state"); - writeDockerDriverGatewayPidFile(path.join(markerDir, "openshell-gateway.pid"), listener.pid!); - writeDockerDriverGatewayRuntimeMarkerForStateDir(markerDir, { + writeDockerDriverGatewayPidFile(path.join(stateDir, "openshell-gateway.pid"), listener.pid!); + writeDockerDriverGatewayRuntimeMarkerForStateDir(stateDir, { pid: listener.pid!, desiredEnv: {}, - endpoint: `https://169.254.2.2:${String(gatewayPort)}`, + endpoint, gatewayBin: process.execPath, openshellVersion: "0.0.116", platform: "linux", arch: process.arch, runtimeProviderId: "podman", }); - vi.spyOn( - gatewayService, - "getTrustedActiveOpenShellGatewayUserServiceIdentity", - ).mockReturnValue( - ownership === "service" ? { pid: listener.pid!, executablePath: process.execPath } : null, - ); const environment = { HOME: root, PATH: `${root}:/usr/bin:/bin`, @@ -931,7 +901,7 @@ esac NEMOCLAW_OPENSHELL_BIN: openshell, NEMOCLAW_OPENSHELL_GATEWAY_BIN: process.execPath, NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR: stateDir, - OPENSHELL_PODMAN_SOCKET: "/nonexistent/run/selected/podman.sock", + OPENSHELL_PODMAN_SOCKET: "/nonexistent/run/podman/podman.sock", }; const gateway = createCurrentPodmanRuntimeProviderBundle(environment).gateway; const deps = createProductionGatewayReadinessDependencies({ @@ -941,25 +911,22 @@ esac gatewayPort: () => gatewayPort, platform: "linux", resolveRuntimeProviderGateway: () => gateway, - observeVersionCompatibility: () => "compatible", }); const now = new Date("2026-09-08T17:00:00.000Z"); const snapshot = await collectGatewayObservations(deps, { now: () => now }); const projection = projectGatewayReadiness(snapshot, { now: () => now }); expect(snapshot.failure).toBeUndefined(); - expect(snapshot.observations?.portConflictState).toBe(conflict); expect(projection.capabilities).toEqual( expect.arrayContaining( - [ - ["gateway.reuse.ready", "present"], - ["gateway.version.compatible", versionState], - ["gateway.port.uncontested", portState], - ].map(([id, state]) => expect.objectContaining({ id, state })), + ["gateway.reuse.ready", "gateway.version.compatible", "gateway.port.uncontested"].map( + (id) => expect.objectContaining({ id, state: "present" }), + ), ), ); expect(subprocess.spawnSync.mock.calls.some(([command]) => command === "docker")).toBe(false); }, + 30_000, ); it("keeps portable readiness on the portable gateway topology", async () => { diff --git a/src/lib/readiness/gateway-production.ts b/src/lib/readiness/gateway-production.ts index 5c66d59ddf5..be6e06217d0 100644 --- a/src/lib/readiness/gateway-production.ts +++ b/src/lib/readiness/gateway-production.ts @@ -6,7 +6,6 @@ import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { getGatewayHttpsEndpoint } from "../core/gateway-address"; import { classifyManagedGatewayEndpointBinding, type ManagedGatewayEndpointBinding, @@ -702,21 +701,6 @@ export function createProductionGatewayReadinessDependencies( platform === "linux" ? readLinuxProcessExecutable(pid) : readDarwinProcessExecutable(pid, probeEnv); - // A service owns no standalone PID/marker files. Bind its live environment - // to the selected provider before accepting the service's process identity. - const providerRuntime = resolveRuntimeProviderGateway().ownsHostReadiness - ? observeGatewayHostRuntime() - : null; - const serviceEnv = providerRuntime ? readDockerDriverGatewayProcessEnvironment(pid) : null; - const providerMatches = - !providerRuntime || - (gatewayName === resolveDockerDriverGatewayName(gatewayPort) && - serviceEnv?.OPENSHELL_DRIVERS === providerRuntime.openShellDriver && - serviceEnv.OPENSHELL_PODMAN_SOCKET === (providerRuntime.socketPath ?? undefined) && - serviceEnv.OPENSHELL_BIND_ADDRESS === providerRuntime.bindAddress && - serviceEnv.OPENSHELL_SERVER_PORT === String(gatewayPort) && - serviceEnv.OPENSHELL_GRPC_ENDPOINT === - `https://${providerRuntime.grpcHost}:${String(gatewayPort)}`); const serviceAfter = getTrustedActiveOpenShellGatewayUserServiceIdentity({ env: probeEnv, homebrewFormulaOperation: runObservedHomebrewFormulaOperation, @@ -740,7 +724,6 @@ export function createProductionGatewayReadinessDependencies( !expected || confirmed !== expected || !stableGeneration || - !providerMatches || !gatewayExecutableSamplesMatchTrustedBinary(executableBefore, executableAfter, expected) ) { return null; @@ -830,7 +813,6 @@ export function createProductionGatewayReadinessDependencies( gatewayName, gatewayPort, expectedEndpoint: `https://${observeGatewayHostRuntime().grpcHost}:${String(gatewayPort)}`, - expectedClientEndpoint: getGatewayHttpsEndpoint(gatewayPort), managedGatewayEndpoints, portAvailable: portCheck.ok, installedOpenShellVersion: getInstalledOpenShellVersion(), @@ -846,23 +828,6 @@ export function createProductionGatewayReadinessDependencies( : listenerHelpers.getDockerDriverGatewayPortListenerScan(portCheck, { gatewayBin: trustedGatewayBin, }); - let verifiedProviderService = false; - if ( - providerObservation && - listenerScan.complete && - listenerScan.pids.length === 0 && - listenerScan.unverifiedPids.length === 1 - ) { - const pid = listenerScan.unverifiedPids[0]!; - const serviceBinary = observePackagedServiceGatewayBinary(pid); - if (serviceBinary) { - listenerScan.pids = [pid]; - listenerScan.unverifiedPids = []; - trustedVersionBinaryByPid.set(pid, serviceBinary); - trustedTargetBoundPids.add(pid); - verifiedProviderService = true; - } - } const managedGatewayCanBeRunning = reuseState === "healthy" || reuseState === "stale" || reuseState === "active-unnamed"; let legacyClusterBound = false; @@ -889,7 +854,7 @@ export function createProductionGatewayReadinessDependencies( } let compatibility: GatewayVersionCompatibility | null = providerObservation?.versionCompatibility ?? null; - if (!portCheck.ok && (!providerObservation || verifiedProviderService)) { + if (!portCheck.ok && !providerObservation) { const source = classifyManagedGatewayVersionSource( legacyClusterBound, listenerScan, @@ -935,9 +900,9 @@ export function createProductionGatewayReadinessDependencies( legacyClusterBound, effectiveEndpointBinding, listenerScan.pids.length === 1 && - (trustedTargetBoundPids.has(listenerScan.pids[0] ?? -1) || - (providerObservation?.targetBoundListenerPids.includes(listenerScan.pids[0] ?? -1) ?? - false)), + (providerObservation + ? providerObservation.targetBoundListenerPids.includes(listenerScan.pids[0] ?? -1) + : trustedTargetBoundPids.has(listenerScan.pids[0] ?? -1)), ); const portConflictOwners = portConflictState === "none" diff --git a/test/e2e/fixtures/availability-env.ts b/test/e2e/fixtures/availability-env.ts index 169a41693ac..eddbb3cce92 100644 --- a/test/e2e/fixtures/availability-env.ts +++ b/test/e2e/fixtures/availability-env.ts @@ -1,12 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { GATEWAY_HOST_RUNTIME_ENV_KEYS } from "../../../src/lib/onboard/runtime-provider/configured-runtime.ts"; - import { buildChildEnv } from "./redaction.ts"; const AVAILABILITY_PROBE_EXTRA_ENV_KEYS = [ - ...GATEWAY_HOST_RUNTIME_ENV_KEYS, + "CONTAINERS_CONF", + "CONTAINERS_STORAGE_CONF", + "DBUS_SESSION_BUS_ADDRESS", "DOCKER_CONFIG", "DOCKER_CONTEXT", "DOCKER_HOST", @@ -17,14 +17,17 @@ const AVAILABILITY_PROBE_EXTRA_ENV_KEYS = [ "E2E_MANAGED_IMAGE_COHORT_RECEIPT", "GITHUB_WORKSPACE", "XDG_CONFIG_HOME", + "XDG_RUNTIME_DIR", "NEMOCLAW_E2E_EXPECTED_SHA", "NEMOCLAW_E2E_MANAGED_IMAGE_CATALOG", "NEMOCLAW_E2E_MANAGED_IMAGE_CATALOG_JSON", "NEMOCLAW_E2E_MANAGED_IMAGE_REVISION", "NEMOCLAW_OLLAMA_PULL_TIMEOUT", "NEMOCLAW_EXPERIMENTAL_PROFILE", + "NEMOCLAW_GATEWAY_RUNTIME", "NEMOCLAW_RUN_LIVE_E2E", "NEMOCLAW_TRACE_DIR", + "OPENSHELL_PODMAN_SOCKET", ]; export function buildAvailabilityProbeEnv( diff --git a/test/e2e/fixtures/hermes-acp-diagnostics.ts b/test/e2e/fixtures/hermes-acp-diagnostics.ts deleted file mode 100644 index eb80893014b..00000000000 --- a/test/e2e/fixtures/hermes-acp-diagnostics.ts +++ /dev/null @@ -1,72 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import type { ArtifactSink } from "./artifacts.ts"; - -const MAX_LINE_BYTES = 4096; -const MAX_TOTAL_BYTES = 16 * 1024; -const MAX_LINES = 32; -const DISCARDED = - "[ACP stderr diagnostics discarded: oversized, incomplete, or capture limit reached]\n"; - -/** Buffer complete diagnostic lines before redaction, never partial secret fragments. */ -export function createHermesAcpDiagnostics(artifacts: ArtifactSink) { - const lines: string[] = []; - let pending = ""; - let droppingLine = false; - let discarded = false; - let retainedBytes = 0; - let stopped = false; - return { - stop(): void { - stopped = true; - if (pending || droppingLine) discarded = true; - pending = ""; - droppingLine = false; - }, - append(chunk: string): void { - if (stopped) return; - for (const segment of chunk.match(/[^\n]*\n|[^\n]+$/gu) ?? []) { - const complete = segment.endsWith("\n"); - if (!droppingLine) { - if ( - Buffer.byteLength(pending, "utf8") + Buffer.byteLength(segment, "utf8") > - MAX_LINE_BYTES - ) { - pending = ""; - droppingLine = true; - discarded = true; - } else { - pending += segment; - } - } - if (!complete) continue; - if ( - !droppingLine && - (/"jsonrpc"\s*:/u.test(pending) || - (/^\s*[[\]{}"]/u.test(pending) && !/^\[\d{1,3}\/\d{1,3}\] /u.test(pending))) - ) { - discarded = true; - } else if (!droppingLine) { - const line = artifacts.redact(pending); - const bytes = Buffer.byteLength(line, "utf8"); - if ( - lines.length < MAX_LINES && - retainedBytes + bytes <= MAX_TOTAL_BYTES - Buffer.byteLength(DISCARDED) - ) { - lines.push(line); - retainedBytes += bytes; - } else { - discarded = true; - } - } - pending = ""; - droppingLine = false; - } - }, - async write(relativePath: string): Promise { - if (pending || droppingLine) discarded = true; - await artifacts.writeText(relativePath, lines.join("") + (discarded ? DISCARDED : "")); - }, - }; -} diff --git a/test/e2e/fixtures/hermes-acp-live.ts b/test/e2e/fixtures/hermes-acp-live.ts index b0a296dde78..fc02cee5701 100644 --- a/test/e2e/fixtures/hermes-acp-live.ts +++ b/test/e2e/fixtures/hermes-acp-live.ts @@ -3,9 +3,7 @@ import { setTimeout as sleep } from "node:timers/promises"; -import { GATEWAY_HOST_RUNTIME_ENV_KEYS } from "../../../src/lib/onboard/runtime-provider/configured-runtime.ts"; import type { ArtifactSink } from "./artifacts.ts"; -import { createHermesAcpDiagnostics } from "./hermes-acp-diagnostics.ts"; import type { SandboxClient } from "./clients/sandbox.ts"; import { type ChildProcessProgress, spawnObservedChild } from "./observed-child-process.ts"; import type { ShellProbeResult } from "./shell-probe.ts"; @@ -46,7 +44,6 @@ export interface HermesAcpLiveOptions { export function hermesAcpLiveHostEnv(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv { const result: NodeJS.ProcessEnv = {}; for (const name of [ - ...GATEWAY_HOST_RUNTIME_ENV_KEYS, "HOME", "USER", "LOGNAME", @@ -269,7 +266,7 @@ async function writeHermesAcpLiveReceipt( }); } -/** Drive the real packaged adapter while retaining fixed protocol evidence and bounded, redacted startup stderr diagnostics. */ +/** Drive the real packaged adapter while retaining only fixed boolean and exit evidence. */ export async function runHermesAcpLiveScenario(options: HermesAcpLiveOptions): Promise { const now = options.now ?? Date.now; const scenarioTimeoutMs = @@ -326,7 +323,6 @@ export async function runHermesAcpLiveScenario(options: HermesAcpLiveOptions): P let protocolValid = true; const promptEvidence = createHermesAcpPromptEvidenceTracker(); let stderrObserved = false; - const diagnostics = createHermesAcpDiagnostics(options.artifacts); let childClosed = false; const inbox: JsonObject[] = []; const waiters = new Set<() => void>(); @@ -346,13 +342,6 @@ export async function runHermesAcpLiveScenario(options: HermesAcpLiveOptions): P if (typeof message !== "object" || message === null || Array.isArray(message)) { protocolValid = false; } else { - if ( - isAcpResponse(message, 1) && - typeof message.result === "object" && - message.result !== null - ) { - diagnostics.stop(); - } promptEvidence.observe(message as JsonObject); inbox.push(message as JsonObject); } @@ -378,9 +367,8 @@ export async function runHermesAcpLiveScenario(options: HermesAcpLiveOptions): P buffered = lines.pop() ?? ""; for (const line of lines) consumeLine(line); }, - onStderr: (chunk) => { + onStderr: () => { stderrObserved = true; - diagnostics.append(chunk); }, }); child.once("close", () => { @@ -515,7 +503,6 @@ export async function runHermesAcpLiveScenario(options: HermesAcpLiveOptions): P sessionCreated, })); - await diagnostics.write(`hermes-acp-${options.scenario}.stderr.txt`); await writeHermesAcpLiveReceipt(options, { adapterProcessAbsent, deadlineExpired: options.deadlineAtMs !== undefined && now() >= options.deadlineAtMs, diff --git a/test/e2e/fixtures/hermes-config-export-live.ts b/test/e2e/fixtures/hermes-config-export-live.ts index 857486e371e..c3ffa4d286f 100644 --- a/test/e2e/fixtures/hermes-config-export-live.ts +++ b/test/e2e/fixtures/hermes-config-export-live.ts @@ -74,8 +74,7 @@ export type HermesConfigExportLiveEvidence = const CREDENTIAL_HTTP_REFUSAL = "V1alpha1 requires HTTPS when an inference provider declares a credential."; -const PODMAN_REFUSAL = - "V1alpha1 export currently supports the Docker runtime; Podman compatibility is deferred."; +const CREDENTIAL_HTTP_REFUSAL_DIAGNOSTIC = `Config export failed (unsupported).\n${CREDENTIAL_HTTP_REFUSAL}`; function normalizeCommandDiagnostics(stdout: string, stderr: string): string { return [stdout, stderr] @@ -251,23 +250,16 @@ export async function verifyHermesConfigExportLive( typeof entry.credentialEnv === "string" && entry.credentialEnv.length > 0 && entry.endpointUrl?.toLowerCase().startsWith("http:") === true; - const expectedRefusals = [ - ...(entry.openshellDriver === "podman" ? [PODMAN_REFUSAL] : []), - ...(expectsCredentialHttpRefusal ? [CREDENTIAL_HTTP_REFUSAL] : []), - ]; - if (expectedRefusals.length > 0) { - const expectedDiagnostic = ["Config export failed (unsupported).", ...expectedRefusals].join( - "\n", - ); + if (expectsCredentialHttpRefusal) { const refusalDiagnosticMatches = [nemoclawDiagnostics, nemohermesDiagnostics].every( - (diagnostic) => diagnostic === expectedDiagnostic, + (diagnostic) => diagnostic === CREDENTIAL_HTTP_REFUSAL_DIAGNOSTIC, ); const refusalCategory = refusalDiagnosticMatches ? "unsupported" : null; const evidence: HermesConfigExportExpectedRefusalEvidence = { outcome: "expected-refusal", aliasesEquivalent: - nemoclaw.exitCode === 2 && - nemohermes.exitCode === 2 && + nemoclaw.exitCode !== 0 && + nemohermes.exitCode !== 0 && nemoclawDiagnostics === nemohermesDiagnostics, checked: true, credentialValuesOmitted: !containsCredential, diff --git a/test/e2e/live/full-e2e-inference-probe.ts b/test/e2e/live/full-e2e-inference-probe.ts index 22ace98dcd0..e73cf9e38b7 100644 --- a/test/e2e/live/full-e2e-inference-probe.ts +++ b/test/e2e/live/full-e2e-inference-probe.ts @@ -9,7 +9,6 @@ const ARITHMETIC_PROMPT = "What is 6 multiplied by 7? Reply with only the intege export const FULL_E2E_INFERENCE_REPLY_BUDGETS = [512, 1024] as const; export const FULL_E2E_INFERENCE_CAPTURE_LIMIT_BYTES = 256 * 1024; export const FULL_E2E_INFERENCE_EVIDENCE_LIMIT_BYTES = 32 * 1024; -export const FULL_E2E_INFERENCE_TRANSIENT_RETRY_DELAY_MS = 5_000; const EVIDENCE_TEXT_LIMIT_BYTES = 4 * 1024; const EVIDENCE_PARSE_ERROR_LIMIT_BYTES = 2 * 1024; @@ -68,10 +67,6 @@ export interface FullE2eInferenceAttemptInput { requestBody: string; } -export interface FullE2eInferenceProbeOptions { - sleep?: (delayMs: number) => Promise; -} - function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } @@ -176,16 +171,11 @@ export function parseFullE2eInferenceResponse(body: string): FullE2eInferenceRes export async function runFullE2eInferenceProbe( model: string, execute: (input: FullE2eInferenceAttemptInput) => Promise, - options: FullE2eInferenceProbeOptions = {}, ): Promise> { const attempts: FullE2eInferenceAttempt[] = []; - const sleep = - options.sleep ?? ((delayMs: number) => new Promise((resolve) => setTimeout(resolve, delayMs))); - let transientRetryUsed = false; - for (let budgetIndex = 0; budgetIndex < FULL_E2E_INFERENCE_REPLY_BUDGETS.length;) { - const maxTokens = FULL_E2E_INFERENCE_REPLY_BUDGETS[budgetIndex]!; - const attempt = attempts.length + 1; + for (const [index, maxTokens] of FULL_E2E_INFERENCE_REPLY_BUDGETS.entries()) { + const attempt = index + 1; const result = await execute({ artifactName: `phase-4-sandbox-inference-local-attempt-${String(attempt).padStart(2, "0")}`, attempt, @@ -194,11 +184,6 @@ export async function runFullE2eInferenceProbe( probe: FullE2eInferenceProbeResult, ): Record { diff --git a/test/e2e/live/launch-agent-turn.ts b/test/e2e/live/launch-agent-turn.ts index 7a2bdba9862..1f6f67d12ed 100644 --- a/test/e2e/live/launch-agent-turn.ts +++ b/test/e2e/live/launch-agent-turn.ts @@ -1166,11 +1166,6 @@ const providerNonRetryableError = function isStructuredProviderUnavailable(message) { const errorMessage = typeof message.errorMessage === "string" ? message.errorMessage.trim() : ""; - const errorCode = typeof message.errorCode === "string" ? message.errorCode.trim() : ""; - // The pinned OpenAI SDK prefixes its error message with the HTTP status. - const providerMessage = errorMessage.replace(/^([0-9]{3}):?\s+/, (prefix, status) => - status === errorCode ? "" : prefix, - ); const validEmptyContent = JSON.stringify(message.content) === "[]"; const identity = [ message.role, @@ -1181,8 +1176,9 @@ function isStructuredProviderUnavailable(message) { ].join("\n"); return ( identity === "assistant\ntrue\nerror\nopenai-completions\ninference" && - providerUnavailableCodes.has(errorCode) && - providerUnavailableError.test(providerMessage) && + typeof message.errorCode === "string" && + providerUnavailableCodes.has(message.errorCode.trim()) && + providerUnavailableError.test(errorMessage) && !providerNonRetryableError.test(errorMessage) ); } @@ -1476,18 +1472,6 @@ fail_provider_unavailable() { fail_launch_session "launch did not record the required structured session turns" } -# Retry only a structured provider failure, including when OpenShell normalizes -# its exit status. Empty content alone does not establish a provider failure. -has_structured_evidence_reason() { - awk -F '"' -v reason="$1" ' - NR == 1 && /^\{"reason":"[a-z_]+","sessionId":"[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+"\}$/ && $4 == reason { - split($8, groups, "-") - matched = length(groups[1]) == 8 && length(groups[2]) == 4 && length(groups[3]) == 4 && length(groups[4]) == 4 && length(groups[5]) == 12 - } - END { exit !(NR == 1 && matched == 1) } - ' "$evidence_error" -} - session_evidence() { local mode="$1" local expected_turns="" @@ -1531,13 +1515,10 @@ wait_for_turn_count() { else evidence_status=$? fi - # OpenShell normalizes a nonzero sandbox child status to 1. Classify the - # exact bounded diagnostic for both the direct and transport-level status. - case "$evidence_status" in - 1|2) has_structured_evidence_reason provider_unavailable && fail_provider_unavailable ;; - 3) fail_provider_unavailable ;; - esac - if [[ "$evidence_status" != 1 ]] || has_structured_evidence_reason message_content_empty; then + if [[ "$evidence_status" != 1 ]]; then + case "$evidence_status" in + 3) fail_provider_unavailable ;; + esac fail_launch_session \ "structured session evidence was invalid or unavailable (status $evidence_status)" fi @@ -1690,7 +1671,6 @@ if session_evidence qualify 2 >/dev/null 2>"$evidence_error"; then else evidence_status=$? case "$evidence_status" in - 1|2) has_structured_evidence_reason provider_unavailable && fail_provider_unavailable ;; 3) fail_provider_unavailable ;; esac fail_launch_session "launch final structured session evidence did not qualify (status $evidence_status)" diff --git a/test/e2e/support/full-e2e-inference-probe.test.ts b/test/e2e/support/full-e2e-inference-probe.test.ts index 274d86d0e33..f1c5f03d653 100644 --- a/test/e2e/support/full-e2e-inference-probe.test.ts +++ b/test/e2e/support/full-e2e-inference-probe.test.ts @@ -227,61 +227,11 @@ describe("full E2E sandbox inference probe", () => { expect(calls).toBe(1); }); - it("retries one transient HTTP command failure with the same reply budget", async () => { - const requests: FullE2eInferenceAttemptInput[] = []; - const delays: number[] = []; - const probe = await runFullE2eInferenceProbe( - "nvidia/nvidia/nemotron-3-ultra", - async (input) => { - requests.push(input); - return input.attempt === 1 - ? commandResult("", 22, "curl: (22) The requested URL returned error: 503") - : commandResult(completion("42")); - }, - { sleep: async (delayMs) => void delays.push(delayMs) }, - ); - - expect(probe.outcome).toBe("passed"); - expect(requests.map(({ attempt, maxTokens }) => ({ attempt, maxTokens }))).toEqual([ - { attempt: 1, maxTokens: 512 }, - { attempt: 2, maxTokens: 512 }, - ]); - expect(requests.map(({ artifactName }) => artifactName)).toEqual([ - "phase-4-sandbox-inference-local-attempt-01", - "phase-4-sandbox-inference-local-attempt-02", - ]); - expect(delays).toEqual([5_000]); - }); - - it.each([429, 502, 503, 504])( - "retries HTTP %i once, then preserves the command failure", - async (status) => { - let calls = 0; - const probe = await runFullE2eInferenceProbe( - "nvidia/nvidia/nemotron-3-ultra", - async () => { - calls += 1; - return commandResult("", 22, `curl: (22) The requested URL returned error: ${status}`); - }, - { sleep: async () => undefined }, - ); - - expect(probe.outcome).toBe("command-failure"); - expect(probe.attempts).toHaveLength(2); - expect(calls).toBe(2); - }, - ); - - it.each([ - [22, "curl: (22) The requested URL returned error: 401"], - [22, "curl: (22) The requested URL returned error: 403"], - [7, "curl: (7) Failed to connect"], - [28, "curl: (28) Operation timed out"], - ])("does not retry non-transient command failure exit=%i", async (exitCode, stderr) => { + it("does not retry command, HTTP, or transport failures", async () => { let calls = 0; const probe = await runFullE2eInferenceProbe("nvidia/nvidia/nemotron-3-ultra", async () => { calls += 1; - return commandResult("", exitCode, stderr); + return commandResult("", 22, "curl: (22) HTTP 403"); }); expect(probe.outcome).toBe("command-failure"); diff --git a/test/e2e/support/hermes-acp-diagnostics.test.ts b/test/e2e/support/hermes-acp-diagnostics.test.ts deleted file mode 100644 index f7fbd204c3d..00000000000 --- a/test/e2e/support/hermes-acp-diagnostics.test.ts +++ /dev/null @@ -1,80 +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 { expect, it, onTestFinished } from "vitest"; -import { ArtifactSink } from "../fixtures/artifacts.ts"; -import { createHermesAcpDiagnostics } from "../fixtures/hermes-acp-diagnostics.ts"; - -function fixture() { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "acp-diagnostics-")); - onTestFinished(() => fs.rmSync(root, { recursive: true, force: true })); - const diagnostics = createHermesAcpDiagnostics(new ArtifactSink(root, ["explicit-secret"])); - const read = async () => { - await diagnostics.write("stderr.txt"); - return fs.readFileSync(path.join(root, "stderr.txt"), "utf8"); - }; - return { diagnostics, read }; -} - -it("redacts complete diagnostic lines after split secrets arrive", async () => { - const { diagnostics, read } = fixture(); - diagnostics.append("gateway recovery failed: explicit-"); - diagnostics.append( - "secret Authorization: Bearer bearer-secret\nhttps://host.invalid/?token=query-secret\n", - ); - const output = await read(); - expect(output).toContain("gateway recovery failed:"); - expect(output).not.toMatch(/explicit-secret|bearer-secret|query-secret/u); -}); - -it("discards oversized and incomplete lines without retaining secret fragments", async () => { - const { diagnostics, read } = fixture(); - diagnostics.append("unsafe-prefix" + "x".repeat(4096)); - diagnostics.append("secret-tail\nuseful complete diagnostic\nunfinished-secret"); - const output = await read(); - expect(output).toContain("useful complete diagnostic"); - expect(output).toContain("diagnostics discarded"); - expect(output).not.toMatch(/unsafe-prefix|secret-tail|unfinished-secret/u); -}); - -it("bounds the retained diagnostic line count", async () => { - const { diagnostics, read } = fixture(); - diagnostics.append("safe diagnostic\n".repeat(40)); - const output = await read(); - expect(output.match(/safe diagnostic/gu)).toHaveLength(32); - expect(output).toContain("diagnostics discarded"); -}); - -it("bounds retained UTF-8 bytes including the discard marker", async () => { - const { diagnostics, read } = fixture(); - diagnostics.append(("é".repeat(1500) + "\n").repeat(10)); - const output = await read(); - expect(Buffer.byteLength(output, "utf8")).toBeLessThanOrEqual(16 * 1024); - expect(output).toContain("diagnostics discarded"); -}); - -it("drops protocol-shaped stderr and stops recording after initialization", async () => { - const { diagnostics, read } = fixture(); - diagnostics.append('gateway starting\n{"jsonrpc":"2.0","result":"private payload"}\n'); - diagnostics.append(' "prompt": "private continuation",\n'); - diagnostics.append("partial startup"); - diagnostics.stop(); - diagnostics.append("later agent output\n"); - const output = await read(); - expect(output).toContain("gateway starting"); - expect(output).toContain("diagnostics discarded"); - expect(output).not.toMatch(/private|partial startup|later agent/u); -}); - -it("retains the recovery producer's numeric progress lines while rejecting JSON arrays", async () => { - const { diagnostics, read } = fixture(); - diagnostics.append('[1/3] Starting gateway\n[2/3] Waiting for readiness\n["private payload"]\n'); - const output = await read(); - expect(output).toContain("[1/3] Starting gateway"); - expect(output).toContain("[2/3] Waiting for readiness"); - expect(output).not.toContain("private payload"); - expect(output).toContain("diagnostics discarded"); -}); diff --git a/test/e2e/support/hermes-acp-live.test.ts b/test/e2e/support/hermes-acp-live.test.ts index caed808ae70..f493ec77f98 100644 --- a/test/e2e/support/hermes-acp-live.test.ts +++ b/test/e2e/support/hermes-acp-live.test.ts @@ -7,8 +7,6 @@ import path from "node:path"; import { describe, expect, it, onTestFinished, vi } from "vitest"; -import { resolveNemoClawGatewayRuntime } from "../../../src/lib/onboard/runtime-provider/configured-runtime.ts"; - import { ArtifactSink } from "../fixtures/artifacts.ts"; import { SandboxClient } from "../fixtures/clients/sandbox.ts"; import { startTestProgress } from "../fixtures/progress.ts"; @@ -103,40 +101,24 @@ describe("Hermes ACP live evidence boundary", () => { }); it.each([ - ["installed", "initialize", 0, {}], - ["checkout", "client-disconnect", 1, {}], - ["checkout", "exchange", 0, { stderrObserved: true }], + ["installed", "initialize", 0], + ["checkout", "client-disconnect", 1], ] as const)( "%s adapter initializes and completes %s", - async (installation, scenario, exitCode, scenarioEvidence) => { + async (installation, scenario, exitCode) => { const artifactDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-acp-launch-")); const adapterEntrypoint = path.join(artifactDir, "nemoclaw-acp"); - const environmentReceipt = path.join(artifactDir, "child-env.json"); - const runtimeEnv: NodeJS.ProcessEnv = { - NEMOCLAW_GATEWAY_RUNTIME: "podman", - OPENSHELL_PODMAN_SOCKET: "/run/user/1000/podman/podman.sock", - CONTAINERS_CONF: "/tmp/containers.conf", - CONTAINERS_STORAGE_CONF: "/tmp/storage.conf", - XDG_RUNTIME_DIR: "/run/user/1000", - DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus", - }; fs.writeFileSync( adapterEntrypoint, `#!${process.execPath} const readline = require("node:readline"); -require("node:fs").writeFileSync(${JSON.stringify(environmentReceipt)}, JSON.stringify(process.env)); process.stdout.on("error", () => { process.exitCode = 1; process.stdin.destroy(); }); readline.createInterface({ input: process.stdin }).on("line", line => { const request = JSON.parse(line); - if (request.method === "session/new") process.stderr.write("later agent stderr\\n"); - if (request.method === "session/prompt") process.stdout.write(JSON.stringify({ - jsonrpc: "2.0", method: "session/update", params: { sessionId: "session-a", update: { text: "PONG" } } - }) + "\\n"); - const result = request.method === "session/new" ? { sessionId: "session-a" } : {}; - process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }) + "\\n"); + process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result: {} }) + "\\n"); }); `, { mode: 0o700 }, @@ -160,29 +142,16 @@ readline.createInterface({ input: process.stdin }).on("line", line => { runHermesAcpLiveScenario({ adapterEntrypoint: installation === "checkout" ? adapterEntrypoint : undefined, artifacts: new ArtifactSink(artifactDir), - env: { - ...runtimeEnv, - PATH: installation === "installed" ? artifactDir : "", - NVIDIA_INFERENCE_API_KEY: "provider-secret", - OPENSHELL_TOKEN: "openshell-secret", - SSH_AUTH_SOCK: "/tmp/private-agent.sock", - }, + env: { PATH: installation === "installed" ? artifactDir : "" }, progress, sandbox, sandboxName: "e2e-hermes", scenario, }), ).resolves.toBe(true); - const childEnv = JSON.parse(fs.readFileSync(environmentReceipt, "utf8")); - expect(childEnv).toMatchObject(runtimeEnv); - expect(resolveNemoClawGatewayRuntime(childEnv)).toBe("podman"); - expect(childEnv).not.toHaveProperty("NVIDIA_INFERENCE_API_KEY"); - expect(childEnv).not.toHaveProperty("OPENSHELL_TOKEN"); - expect(childEnv).not.toHaveProperty("SSH_AUTH_SOCK"); expect( JSON.parse(fs.readFileSync(path.join(artifactDir, `hermes-acp-${scenario}.json`), "utf8")), ).toMatchObject({ - ...scenarioEvidence, passed: true, initialized: true, exitCode, @@ -190,75 +159,10 @@ readline.createInterface({ input: process.stdin }).on("line", line => { remoteProcessAbsent: true, timedOut: false, }); - expect( - fs.readFileSync(path.join(artifactDir, `hermes-acp-${scenario}.stderr.txt`), "utf8"), - ).not.toContain("later agent stderr"); }, 2_000, ); - it("retains redacted child stderr without persisting ACP stdout", async () => { - const artifactDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-acp-diagnostics-")); - const adapterEntrypoint = path.join(artifactDir, "adapter.cjs"); - fs.writeFileSync( - adapterEntrypoint, - ` -process.stdin.resume(); -process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: 99, result: "private ACP payload" }) + "\\n"); -process.stderr.write("gateway recovery failed: explicit-"); -setTimeout(() => { - process.stderr.write("secret Authorization: Bearer bearer-secret\\nhttps://host.invalid/?token=query-secret\\n"); - process.stderr.write("x".repeat(5000) + "oversized-secret\\n"); - process.stderr.write("incomplete-secret"); - process.exitCode = 1; - process.stdin.destroy(); -}, 20); -`, - ); - const progress = startTestProgress( - "ACP diagnostics", - ["launch adapter", "verify diagnostics"], - { - logLine: () => undefined, - }, - ); - onTestFinished(() => { - progress.stop(); - fs.rmSync(artifactDir, { force: true, recursive: true }); - }); - await expect( - runHermesAcpLiveScenario({ - adapterEntrypoint, - artifacts: new ArtifactSink(artifactDir, ["explicit-secret"]), - env: {}, - progress, - sandbox: new SandboxClient({ - run: vi.fn().mockResolvedValue({ exitCode: 1, stdout: "", stderr: "" }), - }), - sandboxName: "e2e-hermes", - scenario: "initialize", - }), - ).resolves.toBe(false); - const diagnostics = fs.readFileSync( - path.join(artifactDir, "hermes-acp-initialize.stderr.txt"), - "utf8", - ); - expect(diagnostics).toContain("gateway recovery failed:"); - expect(diagnostics).toContain("diagnostics discarded"); - expect(diagnostics).not.toMatch( - /explicit-secret|bearer-secret|query-secret|oversized-secret|incomplete-secret|private ACP payload/u, - ); - expect( - JSON.parse(fs.readFileSync(path.join(artifactDir, "hermes-acp-initialize.json"), "utf8")), - ).toMatchObject({ - passed: false, - stderrObserved: true, - rawAcpPayloadRetained: false, - adapterProcessAbsent: true, - remoteProcessAbsent: true, - }); - }); - it("records a failed scenario when the adapter executable is missing", async () => { const artifactDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-acp-missing-")); const progress = startTestProgress("missing ACP adapter", ["launch adapter", "verify result"], { @@ -313,36 +217,6 @@ setTimeout(() => { }); }); - it("preserves the selected Podman runtime and rootless service context for ACP recovery", () => { - const runtimeEnv = { - NEMOCLAW_GATEWAY_RUNTIME: "podman", - OPENSHELL_PODMAN_SOCKET: "/run/user/1000/podman/podman.sock", - CONTAINERS_CONF: "/tmp/podman/containers.conf", - CONTAINERS_STORAGE_CONF: "/tmp/podman/storage.conf", - XDG_RUNTIME_DIR: "/run/user/1000", - DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus", - }; - const adapterEnv = hermesAcpLiveHostEnv({ - ...runtimeEnv, - NVIDIA_INFERENCE_API_KEY: "secret", - OPENAI_API_KEY: "secret", - OPENSHELL_TOKEN: "secret", - SSH_AUTH_SOCK: "/tmp/agent.sock", - UNRELATED_HOST_SETTING: "excluded", - }); - - expect(resolveNemoClawGatewayRuntime(adapterEnv)).toBe("podman"); - expect(adapterEnv).toEqual(runtimeEnv); - }); - - it("keeps Docker selection explicit or default without adding Podman settings", () => { - expect(hermesAcpLiveHostEnv({})).toEqual({}); - expect(resolveNemoClawGatewayRuntime(hermesAcpLiveHostEnv({}))).toBe("docker"); - const adapterEnv = hermesAcpLiveHostEnv({ NEMOCLAW_GATEWAY_RUNTIME: "docker" }); - expect(adapterEnv).toEqual({ NEMOCLAW_GATEWAY_RUNTIME: "docker" }); - expect(resolveNemoClawGatewayRuntime(adapterEnv)).toBe("docker"); - }); - it("recognizes only the requested JSON-RPC response", () => { expect(isAcpResponse({ jsonrpc: "2.0", id: 3, result: {} }, 3)).toBe(true); expect(isAcpResponse({ jsonrpc: "2.0", id: 4, result: {} }, 3)).toBe(false); diff --git a/test/e2e/support/hermes-config-export-live.test.ts b/test/e2e/support/hermes-config-export-live.test.ts index 4f70862253b..4ae0ece5d9a 100644 --- a/test/e2e/support/hermes-config-export-live.test.ts +++ b/test/e2e/support/hermes-config-export-live.test.ts @@ -230,70 +230,6 @@ describe("Hermes config export live evidence", () => { expect(mocks.asExportedConfig).not.toHaveBeenCalled(); }); - it.each(["http", "https"])("accepts the exact Podman %s export refusal", async (scheme) => { - mocks.load.mockReturnValue({ - sandboxes: { - hermes: { - openshellDriver: "podman", - credentialEnv: "NVIDIA_API_KEY", - endpointUrl: `${scheme}://host.openshell.internal:35271/v1`, - gatewayName: "nemoclaw", - workload: { kind: "managed-image", reference: IMAGE_REF }, - }, - }, - }); - const diagnostics = [ - "Config export failed (unsupported).", - "V1alpha1 export currently supports the Docker runtime; Podman compatibility is deferred.", - ...(scheme === "http" - ? ["V1alpha1 requires HTTPS when an inference provider declares a credential."] - : []), - ].join("\n"); - mocks.command.mockResolvedValue({ exitCode: 2, stdout: "", stderr: diagnostics }); - await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); - expect(mocks.save).not.toHaveBeenCalled(); - }); - - it.each([ - { - label: "unrelated failure", - exitCode: 2, - extra: "\nunrelated failure", - writeOutput: (_args: string[]) => undefined, - }, - { label: "wrong exit", exitCode: 1, extra: "", writeOutput: (_args: string[]) => undefined }, - { - label: "published file", - exitCode: 2, - extra: "", - writeOutput: (args: string[]) => - fs.writeFileSync(args.at(args.indexOf("--output") + 1)!, "{}"), - }, - ])("rejects Podman refusal with $label", async ({ exitCode, extra, writeOutput }) => { - mocks.load.mockReturnValue({ - sandboxes: { - hermes: { - openshellDriver: "podman", - credentialEnv: "NVIDIA_API_KEY", - endpointUrl: "https://integrate.api.nvidia.com/v1", - gatewayName: "nemoclaw", - workload: { kind: "managed-image", reference: IMAGE_REF }, - }, - }, - }); - mocks.command.mockImplementation(async (_command: string, args: string[]) => { - writeOutput(args); - return { - exitCode, - stdout: "", - stderr: - "Config export failed (unsupported).\nV1alpha1 export currently supports the Docker runtime; Podman compatibility is deferred." + - extra, - }; - }); - await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: false }); - }); - it("rejects a credential-bearing HTTP refusal when one alias publishes output", async () => { mocks.load.mockReturnValue({ sandboxes: { diff --git a/test/e2e/support/launch-agent-turn-provider-availability.test.ts b/test/e2e/support/launch-agent-turn-provider-availability.test.ts index 0849a5914a9..f7c73cc1fea 100644 --- a/test/e2e/support/launch-agent-turn-provider-availability.test.ts +++ b/test/e2e/support/launch-agent-turn-provider-availability.test.ts @@ -19,12 +19,11 @@ function launchOptions(host: unknown) { } it.each(["500", "503"] as const)( - "retries transient provider failure %s in a fresh launch session (#10978)", + "retries a transient HTTP %s provider failure in a fresh launch session (#10978)", async (status) => { const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); vi.useFakeTimers(); const calls: Array<{ artifactName?: string; env?: NodeJS.ProcessEnv }> = []; - const diagnostic = `litellm.ServiceUnavailableError: HTTP ${status}; NVIDIA upstream unavailable`; const host = { command: async ( _command: string, @@ -36,7 +35,7 @@ it.each(["500", "503"] as const)( ? { exitCode: 1, signal: null, - stderr: `launch did not record the required structured session turns\n${diagnostic}\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, + stderr: `launch did not record the required structured session turns\nlitellm.ServiceUnavailableError: HTTP ${status}; NVIDIA upstream unavailable\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${options?.env?.NEMOCLAW_LAUNCH_RUN_ID}\n`, stdout: "", } : { exitCode: 0, signal: null, stderr: "", stdout: "" }; @@ -99,10 +98,6 @@ it("classifies exhausted transient launch attempts as provider unavailable (#109 }); it.each([ - [ - "unexplained empty assistant content", - '{"reason":"message_content_empty","sessionId":"ed80ef8e-a026-424f-8ca4-669f6060e046"}', - ], [ "marker from another launch run", `launch did not record the required structured session turns\n${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:different-run-id\n`, diff --git a/test/e2e/support/launch-agent-turn.test.ts b/test/e2e/support/launch-agent-turn.test.ts index 27e68ef7246..5fdc597bb48 100644 --- a/test/e2e/support/launch-agent-turn.test.ts +++ b/test/e2e/support/launch-agent-turn.test.ts @@ -61,7 +61,6 @@ type FixtureMode = | "provider-terminal-spoof" | "provider-wrong-api" | "provider-wrong-route" - | "provider-wrong-status" | "recording-timeout" | "restored-canonical-timeout" | "supervisor-timeout" @@ -336,11 +335,6 @@ const exitWithStatus = process.exit.bind(process); } if (terminalCopy === "reordered") process.stdout.write("idle | gateway connected\n"); - const wrongProviderMessages = new Map([ - ["provider-wrong-api", { api: "openai-responses" }], - ["provider-wrong-route", { provider: "attacker-controlled" }], - ["provider-wrong-status", { errorCode: "503", errorMessage: "401 litellm.ServiceUnavailableError: upstream unavailable" }], - ]); if (mode === "delayed-recording" || mode === "provider-exit-after-recording") { const publicationDeadline = Date.now() + 2_000; while (!fs.existsSync(process.env.NEMOCLAW_FIXTURE_PENDING_QUALIFICATION_MARKER)) { @@ -352,21 +346,19 @@ const exitWithStatus = process.exit.bind(process); if (mode === "invalid-order") { append("assistant", "response before input"); append("user", firstInput); - } else if (mode === "provider-empty-message") { - append("user", firstInput); - fs.appendFileSync(sessionFile, JSON.stringify({ - type: "message", message: { role: "assistant", content: [] }, - }) + "\n"); - } else if (mode === "provider-cleanup-failure" || mode === "provider-exit-after-recording") { + } else if (mode === "provider-empty-message" || mode === "provider-cleanup-failure" || mode === "provider-exit-after-recording") { append("user", firstInput); appendProviderError(); new Map([["provider-exit-after-recording", () => exitWithStatus(23)]]).get(mode)?.(); } else if (mode === "provider-terminal-spoof") { append("user", firstInput); appendProviderError({ errorCode: "400" }); - } else if (wrongProviderMessages.has(mode)) { + } else if (mode === "provider-wrong-api") { + append("user", firstInput); + appendProviderError({ api: "openai-responses" }); + } else if (mode === "provider-wrong-route") { append("user", firstInput); - appendProviderError(wrongProviderMessages.get(mode)); + appendProviderError({ provider: "attacker-controlled" }); } else { append("user", firstInput); append("assistant", "first response"); @@ -452,20 +444,8 @@ if [[ ( "$NEMOCLAW_FIXTURE_MODE" == "delayed-recording" || "$NEMOCLAW_FIXTURE_MO set -e [[ "$status" != "1" ]] || : > "$NEMOCLAW_FIXTURE_PENDING_QUALIFICATION_MARKER" [[ "$NEMOCLAW_FIXTURE_MODE" != "provider-exit-after-recording" ]] || sleep 0.2 - # OpenShell preserves the diagnostic but normalizes nonzero child statuses. - [[ "$NEMOCLAW_FIXTURE_MODE" != "provider-exit-after-recording" || "$status" == "0" ]] || exit 1 exit "$status" fi -if [[ "$NEMOCLAW_FIXTURE_MODE" == "provider-empty-message" && "$4" == "qualify" ]]; then - set +e - "$@" - status=$? - set -e - [[ "$status" == "0" ]] && exit 0 - # Match OpenShell's sandbox-exec boundary, which reports any nonzero child - # status as a generic 1 while preserving the child's stderr diagnostic. - exit 1 -fi exec "$@" `, ); @@ -502,10 +482,7 @@ exec "$@" NEMOCLAW_FIXTURE_PTY_MONITOR_ROOT: ptyMonitorRoot, NEMOCLAW_FIXTURE_PTY_PATH_UNREADABLE_MARKER: ptyPathUnreadableMarker, NEMOCLAW_FIXTURE_PTY_SOCKET_RECEIPT: ptySocketReceiptPath, - NEMOCLAW_FIXTURE_SESSION_FILE: join( - sessionRoot, - "ed80ef8e-a026-424f-8ca4-669f6060e046.jsonl", - ), + NEMOCLAW_FIXTURE_SESSION_FILE: join(sessionRoot, "session-a.jsonl"), NEMOCLAW_FIXTURE_TERMINAL_COPY: terminalCopy, NEMOCLAW_FIXTURE_RUN_ID: runId, NEMOCLAW_FIXTURE_TUI_PIDS: tuiPidsPath, @@ -1074,7 +1051,7 @@ it.runIf(process.platform === "linux").concurrent( ); it.runIf(process.platform === "linux").concurrent( - "fails an unexplained empty structured turn without a provider retry (#12254)", + "marks provider unavailability when it leaves an empty structured turn (#9160, #10978)", async ({ expect }) => { const { baselineRemoved, result, ttyObserved } = await runLaunchSessionFixture( "provider-empty-message", @@ -1083,24 +1060,22 @@ it.runIf(process.platform === "linux").concurrent( expect(ttyObserved).toBe(true); expect(baselineRemoved).toBe(true); expect(result.status).toBe(1); - expect(result.stderr).toContain('"reason":"message_content_empty"'); - expect(result.stderr).not.toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); + expect(result.stderr).toContain("nemoclaw.e2e.launch-failure=provider-unavailable"); }, - testTimeout(30_000), ); it.runIf(process.platform === "linux").each([ - ["500", "ServiceUnavailableError", "valid", "500: "], - ["502", "ServiceUnavailableError", "valid", "502 "], - ["503", "ServiceUnavailableError", "valid", "503 "], - ["504", "ServiceUnavailableError", "valid", "504 "], - ["529", "ServiceUnavailableError", "valid", "529 "], - ["500", "InternalServerError", "valid", ""], - ["503", "ServiceUnavailableError", "provider-empty-message", "503 "], + ["500", "ServiceUnavailableError", "valid"], + ["502", "ServiceUnavailableError", "valid"], + ["503", "ServiceUnavailableError", "valid"], + ["504", "ServiceUnavailableError", "valid"], + ["529", "ServiceUnavailableError", "valid"], + ["500", "InternalServerError", "valid"], + ["503", "ServiceUnavailableError", "provider-empty-message"], ] as const)( "executes the real $1 HTTP $0 launch producer through $2 (#10978)", - async (providerCode, providerError, secondMode, statusPrefix) => { - const expectedError = secondMode === "valid" ? null : "launch session failed"; + async (providerCode, providerError, secondMode) => { + const expectedError = secondMode === "valid" ? null : "provider unavailable after 2 attempts"; const secondTerminal = secondMode === "valid" ? "absent" : "provider"; const calls: Array<{ artifactName?: string; @@ -1127,7 +1102,7 @@ it.runIf(process.platform === "linux").each([ env: { ...options?.env, NEMOCLAW_FIXTURE_PROVIDER_ERROR_CODE: providerCode, - NEMOCLAW_FIXTURE_PROVIDER_ERROR_MESSAGE: `${statusPrefix}litellm.${providerError}: ${providerError}: upstream unavailable`, + NEMOCLAW_FIXTURE_PROVIDER_ERROR_MESSAGE: `litellm.${providerError}: ${providerError}: upstream unavailable`, }, }, ); @@ -1175,7 +1150,7 @@ it.runIf(process.platform === "linux").each([ ); expect( calls[1]?.stderr.includes(`${OPENCLAW_PROVIDER_UNAVAILABLE_MARKER}:${calls[1]?.runId}`), - ).toBe(false); + ).toBe(expectedError !== null); } finally { vi.useRealTimers(); } @@ -1253,9 +1228,8 @@ it.runIf(process.platform === "linux").concurrent( it.runIf(process.platform === "linux").concurrent.for([ { mismatch: "API", mode: "provider-wrong-api" }, { mismatch: "route", mode: "provider-wrong-route" }, - { mismatch: "status", mode: "provider-wrong-status" }, ] as const)( - "does not retry a structured provider error with mismatched $mismatch evidence (#10978)", + "does not retry a structured provider error with the wrong $mismatch identity (#10978)", { timeout: testTimeout(30_000) }, async ({ mode }, { expect }) => { const produced = (await runLaunchSessionFixture(mode, "provider")).result; From dc57c373caff289b996b2039e841d0757ec76e95 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 14:53:59 -0700 Subject: [PATCH 31/35] test: keep the credential fix out of unrelated E2E metadata --- test/e2e/live/full-e2e.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index ef53f5cca28..9b0a3d87194 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -736,7 +736,7 @@ test( "sandbox appears in list/status and has policy/inference configuration", "native OpenClaw install, invoke, update, self-update, restart, discovery, and removal are not intercepted", "direct hosted inference and sandbox inference.local both respond", - "fresh managed sandbox state contains neither auth-profiles.json nor secret-shaped credential values", + "sandbox state contains neither auth-profiles.json nor secret-shaped credential values", ...(process.platform === "linux" ? [ "each of two PTY launches records two ordered structured turns and restores the mutable config permission contract", From b9974fd2f8288a8280bec6ff9511c0e9c1445dd6 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 15:15:08 -0700 Subject: [PATCH 32/35] fix(openclaw): reject FIFO auth profiles without blocking startup --- scripts/nemoclaw-start.sh | 2 +- .../runtime/auth-profile-boundary.test.ts | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index f5d077b5f0e..5132aeca605 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2478,7 +2478,7 @@ try: try: profile_fd = os.open( profile_name, - os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0), + os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0), dir_fd=directory_fd, ) except FileNotFoundError: diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index 524b45f5bec..f46809a953a 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -42,6 +42,8 @@ function runBashAuthFixture( input: `${AUTH_FUNCTIONS}\n${commands}`, env: { PATH: process.env.PATH, HOME: home, ...env }, encoding: "utf-8", + timeout: 15_000, + killSignal: "SIGKILL", }); return { authPath, ...result }; } @@ -265,6 +267,20 @@ describe("OpenClaw auth-profile boundary", () => { }, ); + it("rejects a FIFO profile without waiting for a writer", () => { + const fixture = runBashAuthFixture( + managedEnv, + (authPath) => { + fs.mkdirSync(path.dirname(authPath), { recursive: true }); + expect(spawnSync("mkfifo", [authPath]).status).toBe(0); + }, + 'python3() { exec python3 "$@"; }; write_auth_profile', + ); + expect(fixture.error).toBeUndefined(); + expect(fixture.status).toBe(1); + expect(fixture.stderr).toContain("auth-profiles.json is not a regular file"); + }); + it("rejects a symlinked parent without changing its target", () => { const externalContents = JSON.stringify({ "inference:manual": legacyManagedProfile }); let externalProfile = ""; From 262ef25b8566e1867c51620bdcbf2a129f108878 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 16:08:36 -0700 Subject: [PATCH 33/35] fix(openclaw): preserve direct profiles until Doctor migration --- scripts/nemoclaw-start.sh | 10 ++++-- .../runtime/auth-profile-boundary.test.ts | 34 ++++++++++++------- test/e2e/README.md | 2 ++ 3 files changed, 32 insertions(+), 14 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 5132aeca605..a1f5952d98d 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -5553,8 +5553,10 @@ if [ "$(id -u)" -ne 0 ]; then # Apply manifest-declared runtime env aliases before any child inherits the # env. This covers both one-shot commands and the gateway launch. apply_messaging_runtime_env_aliases - write_auth_profile - harden_auth_profiles + if is_managed_inference_route; then + write_auth_profile + harden_auth_profiles + fi if [ ${#NEMOCLAW_CMD[@]} -gt 0 ]; then install_messaging_runtime_preloads @@ -5593,6 +5595,10 @@ if [ "$(id -u)" -ne 0 ]; then fix_openclaw_ownership normalize_mutable_config_perms seed_default_workspace_templates /sandbox/.openclaw/workspace "" /sandbox/.openclaw/openclaw.json + if ! is_managed_inference_route; then + write_auth_profile + fi + harden_auth_profiles prepare_auto_pair_log diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index f46809a953a..7974cbcb686 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -66,17 +66,17 @@ function startupSection(startMarker: string, endMarker: string, region: string): return START_SOURCE.slice(start, end); } -function rootDoctorBlock(): string { +function doctorBlock(kind: "non-root" | "root" = "root"): string { return startupSection( - "configure_messaging_channels\n", + kind === "root" ? "configure_messaging_channels\n" : " apply_messaging_runtime_env_aliases\n", "refresh_openclaw_provider_placeholders\n", - "# ── Root path", + kind === "root" ? "# ── Root path" : "# ── Non-root fallback", ); } function startupCredentialBoundaryBlock(kind: "non-root" | "root"): string { return kind === "root" - ? `${rootDoctorBlock()}\n${startupSection("# Write direct-route profiles after Doctor", "\nprepare_auto_pair_log", "# ── Root path")}` + ? `${doctorBlock()}\n${startupSection("# Write direct-route profiles after Doctor", "\nprepare_auto_pair_log", "# ── Root path")}` : startupSection( " apply_messaging_runtime_env_aliases\n", "\n configure_messaging_channels", @@ -212,7 +212,14 @@ describe("OpenClaw auth-profile boundary", () => { expect(fs.readFileSync(fixture.authPath, "utf-8")).toBe(JSON.stringify(profiles)); }); - it.each(["managed", "direct"])("presents configured %s profiles to root Doctor", (route) => { + // This component fixture observes the profiles passed to Doctor. Native Doctor/agent + // compatibility belongs to full-e2e; rebuild-openclaw owns offline Doctor repairs. + it.each([ + ["root", "managed"], + ["root", "direct"], + ["non-root", "managed"], + ["non-root", "direct"], + ] as const)("presents configured %s %s profiles to Doctor", (kind, route) => { const custom = legacyProfile("custom", "CUSTOM_API_KEY"); const profiles = { "openai:manual": legacyProfile("openai"), "custom:manual": custom }; const fixture = runBashAuthFixture( @@ -226,10 +233,13 @@ describe("OpenClaw auth-profile boundary", () => { extractShellFunctionFromSource(START_SOURCE, "setup_auth_profile_as_sandbox"), // Keep fixture HOME instead of switching users; reconciliation remains real. "run_step_down_as_sandbox() { write_auth_profile; }", + "NEMOCLAW_CMD=()", + "apply_messaging_runtime_env_aliases() { :; }", + "harden_auth_profiles() { :; }", "configure_messaging_channels() { :; }", `run_requested_openclaw_post_upgrade_doctor() { ${credentialProbe} >&2; cat "$HOME/.openclaw/agents/main/agent/auth-profiles.json"; }`, "clear_managed_inference_credentials", - rootDoctorBlock(), + doctorBlock(kind), ].join("\n"), ); expect(fixture.status, fixture.stderr).toBe(0); @@ -242,18 +252,18 @@ describe("OpenClaw auth-profile boundary", () => { }); it.each([ - ["non-root", "managed"], - ["root", "managed"], - ["non-root", "direct"], - ["root", "direct"], + ["non-root", "managed", true], + ["root", "managed", true], + ["non-root", "direct", false], + ["root", "direct", true], ] as const)( "passes only allowed credentials to setup and command children in %s startup for %s routes", - (kind, route) => { + (kind, route, writesProfile) => { const result = runStartupCredentialBoundary(kind, route); const credentials = route === "managed" ? "unset\nunset" : "primary-secret\nlegacy-secret"; expect(result.status, result.stderr).toBe(0); expect(result.stdout.trim()).toBe( - [credentials, credentials, "command", credentials].join("\n"), + [credentials, ...(writesProfile ? [credentials] : []), "command", credentials].join("\n"), ); }, ); diff --git a/test/e2e/README.md b/test/e2e/README.md index 0be496050e7..7fdb534a5e4 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -854,6 +854,8 @@ supported outcomes now have these owners: The fresh-sandbox check starts without user-managed profiles. Existing-state cleanup preserves unrelated profiles, as covered by `test/agents/openclaw/runtime/auth-profile-boundary.test.ts`. +That component fixture also observes which profiles reach Doctor in root and non-root startup. +`full-e2e` owns native Doctor lint and agent turns; `rebuild-openclaw` owns offline Doctor repairs. The optional `/sandbox/.openclaw/skills` directory had no pass or fail state. The deleted provider retry classifier and sandbox-layout wrapper served only the From e71bc9732eeb77a544d28a1deb40f4d2578d313a Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 16:40:43 -0700 Subject: [PATCH 34/35] docs: clarify the credential test coverage boundary --- scripts/nemoclaw-start.sh | 8 ++++---- .../agents/openclaw/runtime/auth-profile-boundary.test.ts | 3 +-- test/e2e/README.md | 2 +- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index a1f5952d98d..b6e9459713a 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2425,10 +2425,10 @@ prepare_gateway_token_for_current_command() { fi } -# Reconcile the legacy OpenClaw auth profile used by direct inference routes. -# Managed OpenShell routes authenticate at the inference.local proxy, so the -# sandbox must not retain even an environment-variable reference to the host -# credential. Direct inference routes still need the profile for OpenClaw. +# Reconcile this function's legacy generated auth profile for the selected provider. +# OpenShell authenticates managed inference.local routes on the host, so remove +# that generated credential reference. Preserve other user-managed profiles. +# Direct routes retain their existing profile-writing behavior. write_auth_profile() { local provider_key="${NEMOCLAW_INFERENCE_PROVIDER_ID:-${NEMOCLAW_PROVIDER_KEY:-inference}}" diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index 7974cbcb686..51ad2e4a98f 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -212,8 +212,7 @@ describe("OpenClaw auth-profile boundary", () => { expect(fs.readFileSync(fixture.authPath, "utf-8")).toBe(JSON.stringify(profiles)); }); - // This component fixture observes the profiles passed to Doctor. Native Doctor/agent - // compatibility belongs to full-e2e; rebuild-openclaw owns offline Doctor repairs. + // This component fixture observes the profiles passed to Doctor. it.each([ ["root", "managed"], ["root", "direct"], diff --git a/test/e2e/README.md b/test/e2e/README.md index 7fdb534a5e4..83d8e8fefb5 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -855,7 +855,7 @@ supported outcomes now have these owners: The fresh-sandbox check starts without user-managed profiles. Existing-state cleanup preserves unrelated profiles, as covered by `test/agents/openclaw/runtime/auth-profile-boundary.test.ts`. That component fixture also observes which profiles reach Doctor in root and non-root startup. -`full-e2e` owns native Doctor lint and agent turns; `rebuild-openclaw` owns offline Doctor repairs. +`full-e2e` exercises native Doctor lint and agent turns. The optional `/sandbox/.openclaw/skills` directory had no pass or fail state. The deleted provider retry classifier and sandbox-layout wrapper served only the From e21c1e9a4bbb1501b99b155e5f6e3a8f51da808c Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Wed, 23 Sep 2026 17:22:24 -0700 Subject: [PATCH 35/35] docs(security): remove an overbroad direct-profile claim Signed-off-by: Aaron Erickson --- docs/security/process-controls.mdx | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/security/process-controls.mdx b/docs/security/process-controls.mdx index 44756a78623..04b732338a6 100644 --- a/docs/security/process-controls.mdx +++ b/docs/security/process-controls.mdx @@ -293,7 +293,6 @@ A registry-side tag change cannot silently select another managed sandbox image. For managed `inference.local` routes, the entrypoint clears the NVIDIA credential aliases before setup and command execution. It removes only the exact legacy NemoClaw-generated profile for the selected managed provider and preserves other profiles. Direct inference routes outside `inference.local` retain supplied credentials. -When `NVIDIA_INFERENCE_API_KEY` is available, the entrypoint creates or replaces `auth-profiles.json` with the generated direct-route profile. The entrypoint and migration flows enforce `chmod 600` on auth-profile files under `~/.openclaw`. This prevents other users on the host from reading stored credentials that remain.