diff --git a/docs/manage-sandboxes/update-sandboxes.mdx b/docs/manage-sandboxes/update-sandboxes.mdx index 84f30c85853..ddb9732f90e 100644 --- a/docs/manage-sandboxes/update-sandboxes.mdx +++ b/docs/manage-sandboxes/update-sandboxes.mdx @@ -68,7 +68,13 @@ curl -fsSL https://www.nvidia.com/nemoclaw.sh | bash $$nemoclaw upgrade-sandboxes --check ``` -If a support workflow asks you to pass the maintained tag explicitly, clear any inherited `NEMOCLAW_INSTALL_REF` and set `NEMOCLAW_INSTALL_TAG` on the `bash` side of the install pipeline. +The default installer preserves a newer installed NemoClaw release. When a NemoClaw CLI is installed, it also stops without changing the CLI when it cannot verify the maintained `lkg` release. To intentionally install an older release from a fixed source, select its version tag or full commit SHA with `NEMOCLAW_INSTALL_TAG`. + +```bash +curl -fsSL https://www.nvidia.com/nemoclaw.sh | NEMOCLAW_INSTALL_REF= NEMOCLAW_INSTALL_TAG=vX.Y.Z bash +``` + +If a support workflow asks you to pass the maintained tag explicitly, clear any inherited `NEMOCLAW_INSTALL_REF` and set `NEMOCLAW_INSTALL_TAG` on the `bash` side of the install pipeline. The same downgrade protection applies to an explicit `lkg` selection. ```bash curl -fsSL https://www.nvidia.com/nemoclaw.sh | NEMOCLAW_INSTALL_REF= NEMOCLAW_INSTALL_TAG=lkg bash diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index f8843b63cab..22b90d8659d 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -575,12 +575,13 @@ migration N was previously applied has been modified ``` -The first error means the installed OpenShell migration set does not contain migration N. The second error means that migration set defines migration N with different contents. NemoClaw identifies `/openshell.db` as incompatible with the installed OpenShell migration set for both errors. This failure can happen after an OpenShell downgrade. Installing a NemoClaw release that is older than the installed one performs that downgrade, because each release pins one OpenShell version and the installer reinstalls OpenShell at the pin. You reach that state in one of three ways: +The first error means the installed OpenShell migration set does not contain migration N. The second error means that migration set defines migration N with different contents. NemoClaw identifies `/openshell.db` as incompatible with the installed OpenShell migration set for both errors. This failure can happen after an OpenShell downgrade. Installing a NemoClaw release that is older than the installed one performs that downgrade, because each release pins one OpenShell version and the installer reinstalls OpenShell at the pin. You reach that state in one of two ways: - You select an older release with `NEMOCLAW_INSTALL_TAG` or `NEMOCLAW_INSTALL_REF`. -- The default `lkg` release is older than the NemoClaw release already on the host. - You install an older OpenShell yourself. +The default installer stops before replacing a newer installed NemoClaw release whenever the selected ref is `lkg` or `refs/tags/lkg`, whether it came from `NEMOCLAW_INSTALL_TAG` or the higher-priority `NEMOCLAW_INSTALL_REF`. Other explicit refs can replace the installed release; use a version tag or full commit SHA when you need a fixed source. + The diagnosis always prints the database path. When an unused archive path is available, it also prints that archive path beside the selected state directory and the profile-specific onboarding command. When no unused archive path is available, it asks you to keep the gateway stopped and inspect the state directory instead. diff --git a/docs/resources/local-credential-form.html b/docs/resources/local-credential-form.html index 98ca7a9f91a..8c1016af3bb 100644 --- a/docs/resources/local-credential-form.html +++ b/docs/resources/local-credential-form.html @@ -9,7 +9,7 @@ NemoClaw Local Credential Form @@ -222,6 +222,7 @@

NemoClaw Local Credential Form

"NO_PROXY", "NETRC", "NEMOCLAW_ACCEPT_DEV_UNVERIFIED_INSTALL", + "NEMOCLAW_BOOTSTRAP_FETCH_REF", "NEMOCLAW_BOOTSTRAP_PAYLOAD", "NEMOCLAW_INSTALL_REF", "NEMOCLAW_INSTALL_TAG", diff --git a/docs/resources/starter-prompt.md b/docs/resources/starter-prompt.md index 2738f979d21..9f76c159e44 100644 --- a/docs/resources/starter-prompt.md +++ b/docs/resources/starter-prompt.md @@ -155,8 +155,8 @@ Before collecting secrets, determine every environment-variable name and the com Do not generate, rewrite, or redesign the helper or form. Use this reviewed pair without modification: -- Helper: `https://raw.githubusercontent.com/NVIDIA/NemoClaw/11e0bb209103b03ee8239cbc307d1cb5d3521866/scripts/local-credential-helper.mts` (SHA-256 `72c187067dca6423e7aa7fa4bfab660e4202805f503c79520d8a0cf24869b668`). -- Form: `https://raw.githubusercontent.com/NVIDIA/NemoClaw/11e0bb209103b03ee8239cbc307d1cb5d3521866/docs/resources/local-credential-form.html` (SHA-256 `5512a256e0ad7c63a26ab82cf4f5924e98652097172ab8a5dc9d9358dd4f6ae8`). +- Helper: `https://raw.githubusercontent.com/NVIDIA/NemoClaw/15bd0dd25b185eafae02a067532fe18718b2be23/scripts/local-credential-helper.mts` (SHA-256 `f7c255120735307c93767c348bfcd54e7c7008275f9f5215f249e4c1a9daa9be`). +- Form: `https://raw.githubusercontent.com/NVIDIA/NemoClaw/15bd0dd25b185eafae02a067532fe18718b2be23/docs/resources/local-credential-form.html` (SHA-256 `cdd85dc6a0b31a8b9773e7ddaacb38a4e8162b0a13b70bebef3dc297ae7a6c44`). - Treat the two immutable URL and digest pairs as one reviewed trust boundary; before executing the helper, compute the SHA-256 digest of both downloaded files and compare each result with its pinned digest. - If either digest differs, do not execute the helper; delete both temporary files and stop. diff --git a/install.sh b/install.sh index 26b97a2d54a..4b469a1a435 100755 --- a/install.sh +++ b/install.sh @@ -19,6 +19,10 @@ BOOTSTRAP_TMPDIR="" PAYLOAD_MARKER="NEMOCLAW_VERSIONED_INSTALLER_PAYLOAD=1" DEFAULT_INSTALL_REF="lkg" INSTALL_TAG_EXAMPLE="vX.Y.Z" +BOOTSTRAP_LOOKUP_TIMEOUT_SECONDS=30 +BOOTSTRAP_CLI_LOOKUP_MAX_OUTPUT_BYTES=65536 +BOOTSTRAP_TAG_LOOKUP_MAX_OUTPUT_BYTES=1048576 +SELECTED_PAYLOAD_IDENTITY_REF="" resolve_release_tag() { if [[ -n "${NEMOCLAW_INSTALL_REF:-}" ]]; then @@ -79,17 +83,186 @@ clone_nemoclaw_ref() { ) } +installed_nemoclaw_release_version() { + local cli_name cli_path normalized_agent output status + normalized_agent="$(printf '%s' "${NEMOCLAW_AGENT:-openclaw}" | tr '[:upper:]_ ' '[:lower:]--' | sed -E 's/-+/-/g; s/^-//; s/-$//')" + case "$normalized_agent" in + nemohermes | nemo-hermes | hermes) cli_name="nemohermes" ;; + nemo-deepagents | nemo-deepagent | nemodeepagents | nemodeepagent | dcode | deepagent | deepagents | deep-agent | deep-agents | deepagentcode | deepagentscode | deepagent-code | deepagents-code | deep-agent-code | deep-agents-code | langchain | langchain-code | langchaindeepagent | langchaindeepagents | langchain-deepagent | langchain-deepagents | langchaindeepagentcode | langchaindeepagentscode | langchain-deepagent-code | langchain-deepagents-code | langchain-deep-agent | langchain-deep-agents | langchain-deep-agent-code | langchain-deep-agents-code) cli_name="nemo-deepagents" ;; + *) cli_name="nemoclaw" ;; + esac + cli_path="$(command -v "$cli_name" 2>/dev/null || true)" + [[ -n "$cli_path" ]] || return 3 + output="$(run_bounded_bootstrap_lookup "installed NemoClaw version lookup" "$BOOTSTRAP_CLI_LOOKUP_MAX_OUTPUT_BYTES" "$cli_path" --version)" || { + status=$? + ((status == 124)) && return 124 + ((status >= 128)) && return "$status" + return 2 + } + if [[ "$output" =~ ^${cli_name}[[:space:]]+v([0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?)$ ]]; then + printf '%s' "${BASH_REMATCH[1]}" + return 0 + fi + return 2 +} + +checkout_release_version() { + local source_root="$1" target_commit refs status ref version + target_commit="$(git -C "$source_root" rev-parse HEAD 2>/dev/null || true)" + [[ -n "$target_commit" ]] || return 0 + refs="$(run_bounded_bootstrap_lookup "maintained release tag lookup" "$BOOTSTRAP_TAG_LOOKUP_MAX_OUTPUT_BYTES" git -C "$source_root" ls-remote --tags origin 'refs/tags/v*')" || { + status=$? + ((status == 124)) && exit 1 + ((status >= 128)) && exit "$status" + return 0 + } + while read -r commit ref; do + [[ "$commit" == "$target_commit" ]] || continue + ref="${ref%\^\{\}}" + version="${ref#refs/tags/v}" + # The maintained lkg must resolve to a stable release. Rejecting prerelease + # tags also prevents replacing a stable install with the same core version. + if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + printf '%s' "$version" + return 0 + fi + done <<<"$refs" +} + +release_version_is_newer() { + local left="$1" right="$2" left_major left_minor left_patch right_major right_minor right_patch + left="${left%%+*}" + left="${left%%-*}" + IFS=. read -r left_major left_minor left_patch <<<"$left" + IFS=. read -r right_major right_minor right_patch <<<"$right" + ((10#$left_major > 10#$right_major)) && return 0 + ((10#$left_major < 10#$right_major)) && return 1 + ((10#$left_minor > 10#$right_minor)) && return 0 + ((10#$left_minor < 10#$right_minor)) && return 1 + ((10#$left_patch > 10#$right_patch)) +} + +run_bounded_bootstrap_lookup() ( + local label="$1" max_output_bytes="$2" output_file command_pid="" output_bytes status ticks=0 pending_signal=0 + shift 2 + output_file="$(mktemp "${TMPDIR:-/tmp}/nemoclaw-bootstrap-lookup.XXXXXX")" + # Invoked indirectly by the signal and exit traps below. + # shellcheck disable=SC2329 + cleanup_bootstrap_lookup() { + local cleanup_status="$1" + # Preserve cancellation status without interrupting or reentering cleanup. + trap 'cleanup_status=130' INT + trap 'cleanup_status=143' TERM + trap - EXIT + [[ -z "$command_pid" ]] || terminate_bootstrap_lookup_group "$command_pid" + rm -f "$output_file" + exit "$cleanup_status" + } + # Defer cancellation until the newly launched process group has an owned PID. + trap 'pending_signal=130' INT + trap 'pending_signal=143' TERM + trap 'cleanup_bootstrap_lookup "$?"' EXIT + set -m + ( + set -o pipefail + "$@" 2>/dev/null "$output_file" 2>/dev/null & + command_pid=$! + set +m + trap 'cleanup_bootstrap_lookup 130' INT + trap 'cleanup_bootstrap_lookup 143' TERM + ((pending_signal == 0)) || cleanup_bootstrap_lookup "$pending_signal" + while bootstrap_lookup_group_is_alive "$command_pid"; do + if ((ticks >= BOOTSTRAP_LOOKUP_TIMEOUT_SECONDS * 10)); then + printf '[ERROR] Timed out during %s after %s seconds.\n' "$label" "$BOOTSTRAP_LOOKUP_TIMEOUT_SECONDS" >&2 + printf ' The installed CLI was not changed. Retry or select an explicit immutable release tag.\n' >&2 + return 124 + fi + sleep 0.1 + ticks=$((ticks + 1)) + done + if wait "$command_pid"; then + status=0 + else + status=$? + fi + command_pid="" + output_bytes="$(wc -c <"$output_file")" + if ((output_bytes > max_output_bytes)); then + status=2 + elif ((status == 0)); then + cat "$output_file" + elif ((status >= 128)); then + status=2 + fi + return "$status" +) + +bootstrap_lookup_group_is_alive() { + local command_pid="$1" + kill -0 -- "-$command_pid" 2>/dev/null || kill -0 "$command_pid" 2>/dev/null +} + +terminate_bootstrap_lookup_group() { + local command_pid="$1" grace_ticks + bootstrap_lookup_group_is_alive "$command_pid" || { + wait "$command_pid" 2>/dev/null || true + return + } + kill -TERM -- "-$command_pid" 2>/dev/null || kill -TERM "$command_pid" 2>/dev/null || true + for ((grace_ticks = 0; grace_ticks < 10; grace_ticks++)); do + bootstrap_lookup_group_is_alive "$command_pid" || break + sleep 0.1 + done + if bootstrap_lookup_group_is_alive "$command_pid"; then + kill -KILL -- "-$command_pid" 2>/dev/null || kill -KILL "$command_pid" 2>/dev/null || true + fi + wait "$command_pid" 2>/dev/null || true +} + +guard_implicit_maintained_downgrade() { + local source_root="$1" selected_ref="$2" installed_version target_version status + case "$selected_ref" in + lkg | refs/tags/lkg) ;; + *) return 0 ;; + esac + installed_version="$(installed_nemoclaw_release_version)" || { + status=$? + ((status == 3)) && return 0 + ((status == 124)) && exit 1 + ((status >= 128)) && exit "$status" + printf '[ERROR] Cannot verify the installed NemoClaw version before selecting maintained lkg.\n' >&2 + printf ' The installed CLI was not changed. Repair it or select an explicit immutable release tag.\n' >&2 + exit 1 + } + target_version="$(checkout_release_version "$source_root")" + if [[ -z "$target_version" ]]; then + printf "[ERROR] Cannot verify the maintained lkg version before replacing installed NemoClaw v%s.\n" "$installed_version" >&2 + printf " The installed CLI was not changed. Set NEMOCLAW_INSTALL_TAG=v%s to reinstall this release.\n" "$installed_version" >&2 + exit 1 + fi + SELECTED_PAYLOAD_IDENTITY_REF="v${target_version}" + if release_version_is_newer "$installed_version" "$target_version"; then + printf "[ERROR] Refusing to replace installed NemoClaw v%s with maintained lkg v%s.\n" "$installed_version" "$target_version" >&2 + printf " The installed CLI was not changed. Set NEMOCLAW_INSTALL_TAG=v%s to reinstall this release.\n" "$installed_version" >&2 + exit 1 + fi +} + exec_installer_from_ref() { local ref="$1" shift - local tmpdir source_root payload_script legacy_script + local tmpdir source_root payload_script legacy_script selected_commit tmpdir="$(mktemp -d)" BOOTSTRAP_TMPDIR="$tmpdir" trap 'rm -rf "${BOOTSTRAP_TMPDIR:-}"' EXIT source_root="${tmpdir}/source" clone_nemoclaw_ref "$ref" "$source_root" + selected_commit="$(git -C "$source_root" rev-parse HEAD)" + + guard_implicit_maintained_downgrade "$source_root" "$ref" payload_script="${source_root}/scripts/install.sh" legacy_script="${source_root}/install.sh" @@ -100,7 +273,9 @@ exec_installer_from_ref() { # helpers beside scripts/install.sh (including DGX Station preparation) # are therefore staged from the same ref before payload execution. verify_downloaded_script "$payload_script" "versioned installer" - NEMOCLAW_INSTALL_REF="$ref" NEMOCLAW_INSTALL_TAG="$ref" NEMOCLAW_BOOTSTRAP_PAYLOAD=1 \ + NEMOCLAW_BOOTSTRAP_FETCH_REF="$selected_commit" \ + NEMOCLAW_INSTALL_REF="${SELECTED_PAYLOAD_IDENTITY_REF:-$ref}" \ + NEMOCLAW_INSTALL_TAG="$ref" NEMOCLAW_BOOTSTRAP_PAYLOAD=1 \ bash "$payload_script" "$@" return fi diff --git a/scripts/install.sh b/scripts/install.sh index 32879c9d4ad..48549e4e2fc 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -145,8 +145,12 @@ canonical_agent_name() { } # Resolve which Git ref to install from. -# Priority: NEMOCLAW_INSTALL_TAG env var > lkg tag. +# Priority: bootstrap fetch pin > NEMOCLAW_INSTALL_REF > NEMOCLAW_INSTALL_TAG > lkg tag. resolve_release_tag() { + if [[ -n "${NEMOCLAW_BOOTSTRAP_FETCH_REF:-}" ]]; then + printf "%s" "${NEMOCLAW_BOOTSTRAP_FETCH_REF}" + return + fi if [[ -n "${NEMOCLAW_INSTALL_REF:-}" ]]; then printf "%s" "${NEMOCLAW_INSTALL_REF}" return diff --git a/scripts/local-credential-helper.mts b/scripts/local-credential-helper.mts index 5d3bdacabb1..c7d2a088143 100755 --- a/scripts/local-credential-helper.mts +++ b/scripts/local-credential-helper.mts @@ -23,7 +23,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; export const EXPECTED_LOCAL_CREDENTIAL_FORM_SHA256 = - "5512a256e0ad7c63a26ab82cf4f5924e98652097172ab8a5dc9d9358dd4f6ae8"; // gitleaks:allow -- checked-in SHA-256 integrity pin + "cdd85dc6a0b31a8b9773e7ddaacb38a4e8162b0a13b70bebef3dc297ae7a6c44"; // gitleaks:allow -- checked-in SHA-256 integrity pin export const LOCAL_CREDENTIAL_HELPER_HOST = "127.0.0.1"; export const LOCAL_CREDENTIAL_FORM_PATH = "/local-credential-form.html"; @@ -110,6 +110,7 @@ const FORBIDDEN_CHILD_ENV_NAMES = new Set([ "NO_PROXY", "NETRC", "NEMOCLAW_ACCEPT_DEV_UNVERIFIED_INSTALL", + "NEMOCLAW_BOOTSTRAP_FETCH_REF", "NEMOCLAW_BOOTSTRAP_PAYLOAD", "NEMOCLAW_INSTALL_REF", "NEMOCLAW_INSTALL_TAG", diff --git a/src/lib/security/process-control-env.test.ts b/src/lib/security/process-control-env.test.ts index 53543b49de4..309b562f0dc 100644 --- a/src/lib/security/process-control-env.test.ts +++ b/src/lib/security/process-control-env.test.ts @@ -48,6 +48,7 @@ describe("credential-handoff process-control environment policy", () => { "LOCPATH", "NETRC", "NEMOCLAW_ACCEPT_DEV_UNVERIFIED_INSTALL", + "NEMOCLAW_BOOTSTRAP_FETCH_REF", "NEMOCLAW_BOOTSTRAP_PAYLOAD", "NEMOCLAW_INSTALL_REF", "NEMOCLAW_INSTALL_TAG", diff --git a/src/lib/security/process-control-env.ts b/src/lib/security/process-control-env.ts index 64a2b63524e..aae65973ec5 100644 --- a/src/lib/security/process-control-env.ts +++ b/src/lib/security/process-control-env.ts @@ -72,6 +72,7 @@ export const PROCESS_CONTROL_ENV_NAMES: ReadonlySet = new Set([ "NO_PROXY", "NETRC", "NEMOCLAW_ACCEPT_DEV_UNVERIFIED_INSTALL", + "NEMOCLAW_BOOTSTRAP_FETCH_REF", "NEMOCLAW_BOOTSTRAP_PAYLOAD", "NEMOCLAW_INSTALL_REF", "NEMOCLAW_INSTALL_TAG", diff --git a/test/credentials/local-credential-helper-suite.ts b/test/credentials/local-credential-helper-suite.ts index 4639dafb229..38e45aabbb4 100644 --- a/test/credentials/local-credential-helper-suite.ts +++ b/test/credentials/local-credential-helper-suite.ts @@ -47,6 +47,7 @@ const CONFIG_ROOT_ENV_NAMES = [ "LOCPATH", "NETRC", "NEMOCLAW_ACCEPT_DEV_UNVERIFIED_INSTALL", + "NEMOCLAW_BOOTSTRAP_FETCH_REF", "NEMOCLAW_BOOTSTRAP_PAYLOAD", "NEMOCLAW_INSTALL_REF", "NEMOCLAW_INSTALL_TAG", @@ -527,6 +528,20 @@ export function registerLocalCredentialHelperTests(group: LocalCredentialHelperT expect(csp).toContain("style-src 'sha256-"); }); + it("matches the checked-in form CSP to its inline resources (#11160)", () => { + const formBytes = fs.readFileSync(FORM_PATH); + const formSource = formBytes.toString("utf8"); + const metaCsp = formSource.match( + /http-equiv="Content-Security-Policy"\s+content="([^"]+)"/, + )?.[1]; + const expectedMetaCsp = `${buildCredentialFormCsp(formBytes).replace( + "; frame-ancestors 'none'", + "", + )};`; + + expect(metaCsp).toBe(expectedMetaCsp); + }); + it("drops every ambient entry without mutating the source environment (#5048)", () => { const ambient = { ...CONFIG_ROOT_ENV_OVERRIDES, @@ -624,19 +639,26 @@ export function registerLocalCredentialHelperTests(group: LocalCredentialHelperT ).toThrow(); }); - it("wires field rejection through the CLI entrypoint before listening (#5048)", async () => { - const captured = captureChild( - helperArgs(["PATH:text"], [process.execPath, "-e", "process.exit(0)"]), - ); + it.each(["PATH", "NEMOCLAW_BOOTSTRAP_FETCH_REF"])( + "rejects %s through the CLI entrypoint before listening (#5048)", + async (name) => { + const captured = captureChild( + helperArgs([`${name}:text`], [process.execPath, "-e", "process.exit(0)"]), + ); - const result = await withTimeout(captured.closed, PROCESS_TIMEOUT_MS, "invalid helper CLI"); + const result = await withTimeout( + captured.closed, + PROCESS_TIMEOUT_MS, + "invalid helper CLI", + ); - expect(result.code).not.toBe(0); - expect(captured.output()).toContain( - "--field PATH is a process-control environment variable and is not allowed", - ); - expect(captured.output()).not.toMatch(READINESS_URL_PATTERN); - }); + expect(result.code).not.toBe(0); + expect(captured.output()).toContain( + `--field ${name} is a process-control environment variable and is not allowed`, + ); + expect(captured.output()).not.toMatch(READINESS_URL_PATTERN); + }, + ); it.each([ { executable: "node" }, diff --git a/test/generation/starter-prompt-docs.test.ts b/test/generation/starter-prompt-docs.test.ts index b0f0f4270f8..7de068c03f5 100644 --- a/test/generation/starter-prompt-docs.test.ts +++ b/test/generation/starter-prompt-docs.test.ts @@ -80,6 +80,7 @@ const localCredentialConfigControlNames = [ "LOCPATH", "NETRC", "NEMOCLAW_ACCEPT_DEV_UNVERIFIED_INSTALL", + "NEMOCLAW_BOOTSTRAP_FETCH_REF", "NEMOCLAW_BOOTSTRAP_PAYLOAD", "NEMOCLAW_INSTALL_REF", "NEMOCLAW_INSTALL_TAG", diff --git a/test/installer-integration/install-downgrade-guard.test.ts b/test/installer-integration/install-downgrade-guard.test.ts new file mode 100644 index 00000000000..805aa85a1fb --- /dev/null +++ b/test/installer-integration/install-downgrade-guard.test.ts @@ -0,0 +1,602 @@ +// 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 { afterEach, describe, expect, it } from "vitest"; + +import { AGENT_ALIASES, resolveAgentNameAlias } from "../../src/lib/agent/aliases"; +import { INSTALLER_PAYLOAD } from "../helpers/installer-sourced-env"; + +const INSTALLER = path.join(import.meta.dirname, "../..", "install.sh"); +const temporaryDirectories: string[] = []; + +function writeExecutable(filePath: string, contents: string): void { + fs.writeFileSync(filePath, contents, { mode: 0o755 }); +} + +function replaceRequired(source: string, expected: string, replacement: string): string { + expect(source).toContain(expected); + return source.replace(expected, replacement); +} + +function payloadCanonicalAgent(agent: string): string { + const result = spawnSync( + "bash", + ["-c", 'source "$INSTALLER_PAYLOAD" >/dev/null; canonical_agent_name "$AGENT"'], + { + encoding: "utf8", + env: { ...process.env, AGENT: agent, INSTALLER_PAYLOAD }, + }, + ); + expect(result.status).toBe(0); + return result.stdout; +} + +function runInstall( + installedVersion: string, + targetVersion: string, + extraEnvironment: Record = {}, + options: { + lookupMaxOutputBytes?: number; + lookupSignal?: "INT" | "TERM"; + lookupSignalBeforePid?: boolean; + timeoutCleanupSignal?: "INT" | "TERM"; + tagLookupMaxOutputBytes?: number; + lookupTimeoutSeconds?: number; + useRealSleep?: boolean; + useRealPayload?: boolean; + } = {}, +) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-downgrade-")); + temporaryDirectories.push(root); + const bin = path.join(root, "bin"); + const payloadMarker = path.join(root, "payload-ran"); + const lookupPid = path.join(root, "lookup.pid"); + const requestedAgent = extraEnvironment.NEMOCLAW_AGENT ?? "openclaw"; + const canonicalAgent = resolveAgentNameAlias(requestedAgent, [ + "openclaw", + "hermes", + "langchain-deepagents-code", + ]); + const cliName = + canonicalAgent === "hermes" + ? "nemohermes" + : canonicalAgent === "langchain-deepagents-code" + ? "nemo-deepagents" + : "nemoclaw"; + fs.mkdirSync(bin); + for (const installedCli of installedVersion === "absent" ? [] : [cliName]) { + writeExecutable( + path.join(bin, installedCli), + `#!/usr/bin/env bash +case "${installedVersion}" in + hang) /bin/sleep 60 ;; + ignore-term) trap '' TERM; while :; do :; done ;; + cancel-during-cleanup) trap 'touch "\${LOOKUP_PID:?}.term"' TERM; printf '%s' "$$" >"\${LOOKUP_PID:?}"; while :; do :; done ;; + interrupt) printf '%s' "$$" >"\${LOOKUP_PID:?}"; exec /bin/sleep 60 ;; + terminate) printf '%s' "$$" >"\${LOOKUP_PID:?}"; exec /bin/sleep 60 ;; + descendant-ignore-term) (trap '' TERM; printf '%s' "\${BASHPID}" >"\${LOOKUP_PID:?}"; while :; do :; done) & exit 0 ;; + signaled) kill -KILL "$$" ;; + oversized) printf 'nemoclaw v0.0.108+'; printf '%0100d' 0 ;; + invalid) printf 'not a NemoClaw version\n' ;; + *) printf '${cliName} v%s\n' "${installedVersion}" ;; +esac +`, + ); + } + writeExecutable( + path.join(bin, "git"), + `#!/usr/bin/env bash +repo='' +if [[ "\${1:-}" == '-C' ]]; then + repo="$2" + shift 2 +fi +case "\${1:-}" in + init) + target="\${@: -1}" + mkdir -p "$target/scripts" + cat >"$target/scripts/install.sh" <<'PAYLOAD' +#!/usr/bin/env bash +# NEMOCLAW_VERSIONED_INSTALLER_PAYLOAD=1 +${ + options.useRealPayload + ? `source "$INSTALLER_PAYLOAD" >/dev/null +resolve_repo_root() { printf '%s' "$NON_SOURCE_ROOT"; } +export RECORD_MANAGED_FETCH=1 +install_nemoclaw` + : `printf '%s|%s|%s' "\${NEMOCLAW_BOOTSTRAP_FETCH_REF:-}" "\${NEMOCLAW_INSTALL_REF:-}" "\${NEMOCLAW_INSTALL_TAG:-}" >"\${EXECUTION_MARKER:?}"` +} +PAYLOAD + chmod +x "$target/scripts/install.sh" + ;; + remote) + [[ "$*" == 'remote add origin https://github.com/NVIDIA/NemoClaw.git' ]] || exit 91 + ;; + fetch) + [[ "$2" == '--quiet' && "$3" == '--depth' && "$4" == '1' && "$5" == 'origin' && "$6" == +*:refs/nemoclaw-install/target && -z "\${7:-}" ]] || exit 92 + if [[ "\${RECORD_MANAGED_FETCH:-}" == 1 ]]; then printf '%s' "$6" >"\${EXECUTION_MARKER:?}"; fi + ;; + -c) + [[ "$*" == '-c advice.detachedHead=false checkout --quiet --detach refs/nemoclaw-install/target' ]] || exit 93 + if [[ "\${RECORD_MANAGED_FETCH:-}" == 1 ]]; then exit 73; fi + ;; + rev-parse) + printf 'target-commit\n' + ;; + ls-remote) + if [[ "${targetVersion}" == 'hang' ]]; then + /bin/sleep 60 + elif [[ "${targetVersion}" == annotated-* ]]; then + version="${targetVersion.replace(/^annotated-/, "")}" + printf 'tag-object\trefs/tags/v%s\n' "$version" + printf 'target-commit\trefs/tags/v%s^{}\n' "$version" + elif [[ "${targetVersion}" == 'many-tags' ]]; then + for version in {1..20}; do + printf 'other-%s\trefs/tags/v0.0.%s\n' "$version" "$version" + done + printf 'target-commit\trefs/tags/v0.0.109\n' + else + printf 'target-commit\trefs/tags/v%s\n' "${targetVersion}" + fi + ;; + *) exit 94 ;; +esac +`, + ); + const sleepBody = options.timeoutCleanupSignal + ? `#!/usr/bin/env bash +if [[ -e "\${LOOKUP_PID:?}.term" && ! -e "\${LOOKUP_PID:?}.cancel" ]]; then + touch "\${LOOKUP_PID:?}.cancel" + kill -${options.timeoutCleanupSignal} "$PPID" +fi +exec /bin/sleep "$@" +` + : options.useRealSleep + ? '#!/usr/bin/env bash\nexec /bin/sleep "$@"\n' + : ["hang", "ignore-term", "descendant-ignore-term"].includes(installedVersion) || + targetVersion === "hang" + ? "#!/usr/bin/env bash\nexit 0\n" + : '#!/usr/bin/env bash\nexec /bin/sleep "$@"\n'; + writeExecutable(path.join(bin, "sleep"), sleepBody); + + let installerSource = replaceRequired( + replaceRequired( + fs.readFileSync(INSTALLER, "utf8"), + "BOOTSTRAP_LOOKUP_TIMEOUT_SECONDS=30", + `BOOTSTRAP_LOOKUP_TIMEOUT_SECONDS=${options.lookupTimeoutSeconds ?? 30}`, + ), + "BOOTSTRAP_CLI_LOOKUP_MAX_OUTPUT_BYTES=65536", + `BOOTSTRAP_CLI_LOOKUP_MAX_OUTPUT_BYTES=${options.lookupMaxOutputBytes ?? 65536}`, + ); + installerSource = replaceRequired( + installerSource, + "BOOTSTRAP_TAG_LOOKUP_MAX_OUTPUT_BYTES=1048576", + `BOOTSTRAP_TAG_LOOKUP_MAX_OUTPUT_BYTES=${options.tagLookupMaxOutputBytes ?? 1048576}`, + ); + const signalAnchor = options.lookupSignalBeforePid + ? " command_pid=$!" + : ' while bootstrap_lookup_group_is_alive "$command_pid"; do'; + installerSource = options.lookupSignal + ? replaceRequired( + installerSource, + signalAnchor, + ` + while [[ ! -s "\${LOOKUP_PID:?}" ]]; do :; done + /bin/bash -c 'kill -${options.lookupSignal} "$PPID"' +${signalAnchor}`, + ) + : installerSource; + + const result = spawnSync("bash", [], { + cwd: root, + input: installerSource, + encoding: "utf8", + env: { + HOME: root, + PATH: `${bin}:/usr/bin:/bin`, + EXECUTION_MARKER: payloadMarker, + INSTALLER_PAYLOAD, + NON_SOURCE_ROOT: path.join(root, "not-a-checkout"), + LOOKUP_PID: lookupPid, + TMPDIR: root, + ...extraEnvironment, + }, + }); + return { lookupPid, payloadMarker, result, root }; +} + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +describe("public installer downgrade guard", () => { + it("keeps the installed CLI when the implicit lkg release is older (#11160)", () => { + const { result, payloadMarker } = runInstall("0.0.118", "0.0.109"); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain( + "Refusing to replace installed NemoClaw v0.0.118 with maintained lkg v0.0.109.", + ); + expect(`${result.stdout}${result.stderr}`).toContain("The installed CLI was not changed."); + expect(fs.existsSync(payloadMarker)).toBe(false); + }); + + it.each([ + ["Hermes", "hermes"], + ["Deep Agents", "langchain-deepagents-code"], + ])("keeps the installed %s CLI when the implicit lkg release is older", (_label, agent) => { + const { result, payloadMarker } = runInstall("0.0.118", "0.0.109", { + NEMOCLAW_AGENT: agent, + }); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain( + "Refusing to replace installed NemoClaw v0.0.118 with maintained lkg v0.0.109.", + ); + expect(fs.existsSync(payloadMarker)).toBe(false); + }); + + it.each([ + ...Object.entries(AGENT_ALIASES), + ["Hermes", "hermes"], + ["Nemo Hermes", "hermes"], + ["deep_agents", "langchain-deepagents-code"], + ["NEMO_DEEPAGENTS", "langchain-deepagents-code"], + ["Deep Agents", "langchain-deepagents-code"], + ["LANGCHAIN", "langchain-deepagents-code"], + ])("uses the payload's canonical CLI for the %s alias", (agent, canonicalAgent) => { + expect(payloadCanonicalAgent(agent)).toBe(canonicalAgent); + const { result, payloadMarker } = runInstall("0.0.118", "0.0.109", { + NEMOCLAW_AGENT: agent, + }); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain( + "Refusing to replace installed NemoClaw v0.0.118 with maintained lkg v0.0.109.", + ); + expect(fs.existsSync(payloadMarker)).toBe(false); + }); + + it.each([ + ["the implicit lkg release is newer", "0.0.108", "v0.0.109"], + ["no CLI is installed", "absent", "lkg"], + ])("runs the selected payload when %s", (_condition, installedVersion, selectedRef) => { + const { result, payloadMarker, root } = runInstall(installedVersion, "0.0.109"); + + expect(result.status).toBe(0); + expect(fs.existsSync(payloadMarker)).toBe(true); + expect(fs.readFileSync(payloadMarker, "utf8")).toBe(`target-commit|${selectedRef}|lkg`); + expect( + fs + .readdirSync(root, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name), + ).toEqual(["bin"]); + }); + + it("runs the selected payload when the implicit lkg release is unchanged", () => { + const { result, payloadMarker } = runInstall("0.0.109", "0.0.109"); + + expect(result.status).toBe(0); + expect(fs.existsSync(payloadMarker)).toBe(true); + expect(fs.readFileSync(payloadMarker, "utf8")).toBe("target-commit|v0.0.109|lkg"); + }); + + it("keeps a newer installed prerelease when the implicit lkg release is older", () => { + const { result, payloadMarker } = runInstall("0.0.119-rc.1", "0.0.118"); + + expect(result.status).toBe(1); + expect(fs.existsSync(payloadMarker)).toBe(false); + }); + + it("keeps a stable install when lkg resolves only to the same-core prerelease", () => { + const { result, payloadMarker } = runInstall("0.0.109", "0.0.109-rc.1"); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain( + "Cannot verify the maintained lkg version before replacing installed NemoClaw v0.0.109.", + ); + expect(fs.existsSync(payloadMarker)).toBe(false); + }); + + it("accepts the peeled commit from an annotated maintained release tag", () => { + const { result, payloadMarker } = runInstall("0.0.108", "annotated-0.0.109"); + + expect(result.status).toBe(0); + expect(fs.existsSync(payloadMarker)).toBe(true); + }); + + it("finds the maintained release tag beyond the CLI output bound", () => { + const { result, payloadMarker } = runInstall( + "0.0.108", + "many-tags", + {}, + { + lookupMaxOutputBytes: 32, + tagLookupMaxOutputBytes: 2048, + }, + ); + + expect(result.status).toBe(0); + expect(fs.existsSync(payloadMarker)).toBe(true); + expect(fs.readFileSync(payloadMarker, "utf8")).toBe("target-commit|v0.0.109|lkg"); + }); + + it("fails closed and cleans up when release tag output exceeds its bound", () => { + const { result, payloadMarker, root } = runInstall( + "0.0.108", + "many-tags", + {}, + { + tagLookupMaxOutputBytes: 32, + }, + ); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain( + "Cannot verify the maintained lkg version before replacing installed NemoClaw v0.0.108.", + ); + expect(fs.existsSync(payloadMarker)).toBe(false); + expect( + fs.readdirSync(root).filter((name) => name.startsWith("nemoclaw-bootstrap-lookup.")), + ).toEqual([]); + }); + + it("runs an older release when the user selects its tag", () => { + const { result, payloadMarker } = runInstall("0.0.118", "0.0.109", { + NEMOCLAW_INSTALL_TAG: "v0.0.109", + }); + + expect(result.status).toBe(0); + expect(fs.existsSync(payloadMarker)).toBe(true); + expect(fs.readFileSync(payloadMarker, "utf8")).toBe("target-commit|v0.0.109|v0.0.109"); + }); + + it("runs an older release when the user selects another explicit ref", () => { + const { result, payloadMarker } = runInstall("0.0.118", "0.0.109", { + NEMOCLAW_INSTALL_TAG: "latest", + }); + + expect(result.status).toBe(0); + expect(fs.existsSync(payloadMarker)).toBe(true); + expect(fs.readFileSync(payloadMarker, "utf8")).toBe("target-commit|latest|latest"); + }); + + it("keeps the installed CLI when lkg is selected explicitly", () => { + const { result, payloadMarker } = runInstall("0.0.118", "0.0.109", { + NEMOCLAW_INSTALL_TAG: "lkg", + }); + + expect(result.status).toBe(1); + expect(fs.existsSync(payloadMarker)).toBe(false); + }); + + it("keeps the installed CLI when the fully qualified lkg tag is selected", () => { + const { result, payloadMarker } = runInstall("0.0.118", "0.0.109", { + NEMOCLAW_INSTALL_TAG: "refs/tags/lkg", + }); + + expect(result.status).toBe(1); + expect(fs.existsSync(payloadMarker)).toBe(false); + }); + + it.each(["lkg", "refs/tags/lkg"])( + "keeps the installed CLI when NEMOCLAW_INSTALL_REF selects %s", + (installRef) => { + const { result, payloadMarker } = runInstall("0.0.118", "0.0.109", { + NEMOCLAW_INSTALL_REF: installRef, + }); + + expect(result.status).toBe(1); + expect(fs.existsSync(payloadMarker)).toBe(false); + }, + ); + + it("fails closed when the installed CLI reports an invalid version", () => { + const { result, payloadMarker } = runInstall("invalid", "0.0.109"); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain( + "Cannot verify the installed NemoClaw version", + ); + expect(fs.existsSync(payloadMarker)).toBe(false); + }); + + it("fails closed when the installed version lookup is killed", () => { + const { result, payloadMarker } = runInstall("signaled", "0.0.109"); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain( + "Cannot verify the installed NemoClaw version", + ); + expect(fs.existsSync(payloadMarker)).toBe(false); + }); + + it("fails closed and cleans up when installed CLI output exceeds the bound", () => { + const { result, payloadMarker, root } = runInstall( + "oversized", + "0.0.109", + {}, + { + lookupMaxOutputBytes: 32, + }, + ); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain( + "Cannot verify the installed NemoClaw version", + ); + expect(fs.existsSync(payloadMarker)).toBe(false); + expect( + fs.readdirSync(root).filter((name) => name.startsWith("nemoclaw-bootstrap-lookup.")), + ).toEqual([]); + }); + + it("keeps the installed CLI when the implicit lkg version cannot be verified", () => { + const { result, payloadMarker } = runInstall("0.0.118", "unknown"); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain( + "Cannot verify the maintained lkg version before replacing installed NemoClaw v0.0.118.", + ); + expect(fs.existsSync(payloadMarker)).toBe(false); + }); + + it.each([ + ["installed NemoClaw version lookup", "hang", "0.0.109"], + ["installed NemoClaw version lookup", "ignore-term", "0.0.109"], + ["maintained release tag lookup", "0.0.108", "hang"], + ])( + "bounds the %s", + (label, installedVersion, targetVersion) => { + const { result, payloadMarker } = runInstall(installedVersion, targetVersion); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain(`Timed out during ${label}`); + expect(`${result.stdout}${result.stderr}`).toContain("The installed CLI was not changed."); + expect(fs.existsSync(payloadMarker)).toBe(false); + }, + 15_000, + ); + + it("waits for the configured lookup deadline when real sleep is used", () => { + const startedAt = performance.now(); + const { result, payloadMarker } = runInstall( + "hang", + "0.0.109", + {}, + { + lookupTimeoutSeconds: 1, + useRealSleep: true, + }, + ); + const elapsedMs = performance.now() - startedAt; + + expect(result.status).toBe(1); + expect(elapsedMs).toBeGreaterThanOrEqual(900); + expect(elapsedMs).toBeLessThan(10_000); + expect(fs.existsSync(payloadMarker)).toBe(false); + }, 15_000); + + it.each([ + ["interrupted during lookup", "interrupt", "INT", 130, false], + ["terminated during lookup", "terminate", "TERM", 143, false], + ["interrupted before PID recording", "interrupt", "INT", 130, true], + ["terminated before PID recording", "terminate", "TERM", 143, true], + ] as const)( + "cleans up an active lookup when the installer is %s", + (_label, mode, signal, status, beforePid) => { + const { lookupPid, payloadMarker, result, root } = runInstall( + mode, + "0.0.109", + {}, + { + lookupSignal: signal, + lookupSignalBeforePid: beforePid, + }, + ); + + const pid = Number(fs.readFileSync(lookupPid, "utf8")); + try { + expect(result.status).toBe(status); + expect(fs.existsSync(payloadMarker)).toBe(false); + expect( + fs.readdirSync(root).filter((name) => name.startsWith("nemoclaw-bootstrap-lookup.")), + ).toEqual([]); + expect( + fs + .readdirSync(root, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name), + ).toEqual(["bin"]); + const processState = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { + encoding: "utf8", + }); + expect(processState.status === 1 || processState.stdout.trim().startsWith("Z")).toBe(true); + } finally { + try { + process.kill(pid, "SIGKILL"); + } catch (error) { + expect((error as NodeJS.ErrnoException).code).toBe("ESRCH"); + } + } + }, + ); + + it.each([ + ["INT", 130], + ["TERM", 143], + ] as const)( + "finishes timeout cleanup when it receives SIG%s during termination", + (signal, status) => { + const { lookupPid, payloadMarker, result, root } = runInstall( + "cancel-during-cleanup", + "0.0.109", + {}, + { lookupTimeoutSeconds: 1, timeoutCleanupSignal: signal }, + ); + const pid = Number(fs.readFileSync(lookupPid, "utf8")); + + try { + expect(fs.existsSync(`${lookupPid}.cancel`)).toBe(true); + expect(result.status).toBe(status); + expect(fs.existsSync(payloadMarker)).toBe(false); + const processState = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { + encoding: "utf8", + }); + expect(processState.status === 1 || processState.stdout.trim().startsWith("Z")).toBe(true); + expect( + fs.readdirSync(root).filter((name) => name.startsWith("nemoclaw-bootstrap-lookup.")), + ).toEqual([]); + } finally { + try { + process.kill(pid, "SIGKILL"); + } catch (error) { + expect((error as NodeJS.ErrnoException).code).toBe("ESRCH"); + } + } + }, + 15_000, + ); + + it("kills a lookup descendant after its process-group leader exits", () => { + const { lookupPid, payloadMarker, result } = runInstall("descendant-ignore-term", "0.0.109"); + + expect(result.status).toBe(1); + expect(`${result.stdout}${result.stderr}`).toContain( + "Timed out during installed NemoClaw version lookup", + ); + expect(fs.existsSync(payloadMarker)).toBe(false); + const pid = Number(fs.readFileSync(lookupPid, "utf8")); + const processState = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { + encoding: "utf8", + }); + expect(processState.status === 1 || processState.stdout.trim().startsWith("Z")).toBe(true); + }, 15_000); +}); + +describe("versioned installer payload ref selection", () => { + it("passes the public bootstrap commit through the real payload to the managed clone", () => { + const { result, payloadMarker } = runInstall( + "0.0.108", + "0.0.109", + { + NEMOCLAW_INSTALL_REF: "lkg", + NEMOCLAW_INSTALL_TAG: "v0.0.108", + }, + { useRealPayload: true }, + ); + + expect(result.status).toBe(73); + expect(fs.readFileSync(payloadMarker, "utf8")).toBe( + "+target-commit:refs/nemoclaw-install/target", + ); + }); +});