diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index f17434b9d74..0adbb2219c4 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -4620,6 +4620,17 @@ jobs: run: >- npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/managed-image-multiarch-startup.test.ts + - name: Remove owned Docker Engine 27 receipt daemon + if: always() + shell: bash + run: | + set -euo pipefail + node --import tsx scripts/checks/docker-engine-27-receipt-transfer-e2e.ts \ + --cleanup-only \ + --run-id "$GITHUB_RUN_ID" \ + --run-attempt "$GITHUB_RUN_ATTEMPT" \ + --platform "$NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM" + - name: Validate OpenClaw managed-image security boundary shell: bash run: >- diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 0f97b92ffb9..f0b0137907d 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -108,6 +108,19 @@ The global `$$nemoclaw doctor` command remains available without a sandbox name. The hosted installer accepts options after `bash -s --`. These options control installation and the onboarding run that follows it. +### `--force-fresh-install` + +On Apple silicon macOS, remove every NemoClaw- and OpenShell-managed sandbox, gateway, credential, configuration file, and recovery record before reinstalling and starting fresh onboarding. This destructive reset keeps downloaded model caches, but the removed state cannot be recovered without an external backup. Unlike `--fresh`, it removes the existing managed installation instead of only requesting fresh onboarding state. + +Use the hosted installer so the selected candidate is staged outside the state it removes: + +```bash +curl -fsSL https://www.nvidia.com/nemoclaw.sh | \ + bash -s -- --force-fresh-install +``` + +The equivalent environment variable is `NEMOCLAW_FORCE_FRESH_INSTALL=1`. The installer rejects this option outside Apple silicon macOS and stops without deleting remaining state if the authoritative whole-host uninstall cannot complete. + ### `--local-model-runtime=vllm` Enable the fixed vLLM local model profile. The flag accepts only `vllm`. It makes the remaining onboarding non-interactive and disables Express profile selection. diff --git a/install.sh b/install.sh index 4b469a1a435..e5f29a9f640 100755 --- a/install.sh +++ b/install.sh @@ -313,6 +313,7 @@ bootstrap_usage() { printf " Use only with NEMOCLAW_AGENT=hermes, no registered sandboxes, no local model profile,\n" printf " and the build, cloud, or routed NVIDIA hosted provider\n" printf " --fresh Discard any failed/interrupted onboarding session and start over\n" + printf " --force-fresh-install Destroy all NemoClaw and OpenShell state, then reinstall (Apple silicon macOS only)\n" printf " --force-station-install Validate an unrecognized Station GB300 release profile without onboarding\n" printf " --version, -v Print installer version and exit\n" printf " --help, -h Show this help message and exit\n\n" @@ -326,6 +327,7 @@ bootstrap_usage() { printf " Use only with NEMOCLAW_AGENT=hermes, no registered sandboxes, no local model profile,\n" printf " and the build, cloud, or routed NVIDIA hosted provider\n" printf " NEMOCLAW_FRESH=1 Same as --fresh\n" + printf " NEMOCLAW_FORCE_FRESH_INSTALL=1 Same as --force-fresh-install (Apple silicon macOS only)\n" printf " NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE=1 Same as --yes-i-accept-third-party-software\n" printf " NEMOCLAW_NO_EXPRESS=1 Skip express install prompt on supported platforms\n" printf " NEMOCLAW_SANDBOX_NAME Sandbox name to create/use\n" diff --git a/scripts/checks/docker-engine-27-receipt-transfer-e2e.ts b/scripts/checks/docker-engine-27-receipt-transfer-e2e.ts new file mode 100644 index 00000000000..b2579f77234 --- /dev/null +++ b/scripts/checks/docker-engine-27-receipt-transfer-e2e.ts @@ -0,0 +1,489 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { + dockerDaemonReceiptMount, + transferDockerReceiptToDaemon, +} from "../../src/lib/onboard/managed-startup/docker-receipt-transfer.ts"; + +const DIND_IMAGE = + "docker.io/library/docker:27.5.1-dind@sha256:aa3df78ecf320f5fafdce71c659f1629e96e9de0968305fe1de670e0ca9176ce"; +const RECEIPT_IMAGE = + "docker.io/library/alpine:3.20@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc"; +const RECEIPT_VOLUME_DIRECTORY = "/run/nemoclaw/managed-startup-receipt-transfer"; +const DAEMON_OWNER_LABEL = "io.nvidia.nemoclaw.e2e.docker27-receipt"; +export const DOCKER_ENGINE_27_OPERATION_TIMEOUT_MS = 30_000; +export const DOCKER_ENGINE_27_PULL_TIMEOUT_MS = 120_000; +export const DOCKER_ENGINE_27_CLEANUP_TIMEOUT_MS = 15_000; +export const DOCKER_ENGINE_27_READINESS_ATTEMPTS = 45; +export const DOCKER_ENGINE_27_READINESS_COMMAND_TIMEOUT_MS = 5_000; +export const DOCKER_ENGINE_27_READINESS_INTERVAL_MS = 1_000; +export const DOCKER_ENGINE_27_MAX_OPERATION_COUNT = 28; +export const DOCKER_ENGINE_27_PULL_COUNT = 2; +export const DOCKER_ENGINE_27_CLEANUP_OPERATION_COUNT = 3; +export const DOCKER_ENGINE_27_PROCESS_ALLOWANCE_MS = 60_000; +export const DOCKER_ENGINE_27_MINIMUM_PROBE_TIMEOUT_MS = + DOCKER_ENGINE_27_READINESS_ATTEMPTS * + (DOCKER_ENGINE_27_READINESS_COMMAND_TIMEOUT_MS + DOCKER_ENGINE_27_READINESS_INTERVAL_MS) + + DOCKER_ENGINE_27_MAX_OPERATION_COUNT * DOCKER_ENGINE_27_OPERATION_TIMEOUT_MS + + DOCKER_ENGINE_27_PULL_COUNT * DOCKER_ENGINE_27_PULL_TIMEOUT_MS + + DOCKER_ENGINE_27_CLEANUP_OPERATION_COUNT * DOCKER_ENGINE_27_CLEANUP_TIMEOUT_MS + + DOCKER_ENGINE_27_PROCESS_ALLOWANCE_MS; +export const DOCKER_ENGINE_27_MINIMUM_CLEANUP_PROCESS_TIMEOUT_MS = + DOCKER_ENGINE_27_CLEANUP_OPERATION_COUNT * DOCKER_ENGINE_27_CLEANUP_TIMEOUT_MS + + DOCKER_ENGINE_27_PROCESS_ALLOWANCE_MS / 2; + +export type DockerEngine27Platform = "linux/amd64" | "linux/arm64"; + +export function dockerEngine27ReceiptDaemonName( + runId: number | string, + runAttempt: number | string, + platform: DockerEngine27Platform, +): string { + const run = String(runId); + const attempt = String(runAttempt); + requireCondition(/^[1-9][0-9]{0,15}$/u.test(run), "Docker Engine 27 run ID is invalid"); + requireCondition(/^[1-9][0-9]{0,5}$/u.test(attempt), "Docker Engine 27 run attempt is invalid"); + requireCondition( + platform === "linux/amd64" || platform === "linux/arm64", + "Docker Engine 27 platform is invalid", + ); + return `nemoclaw-receipt-engine27-${run}-${attempt}-${platform.replace("/", "-")}`; +} + +export function dockerEngine27ReceiptIdentityArguments( + runId: number | string, + runAttempt: number | string, + platform: DockerEngine27Platform, +): string[] { + dockerEngine27ReceiptDaemonName(runId, runAttempt, platform); + return ["--run-id", String(runId), "--run-attempt", String(runAttempt), "--platform", platform]; +} + +export type CommandResult = { + readonly error?: Error; + readonly status: number | null; + readonly stderr: string; + readonly stdout: string; +}; + +type DockerCommandProfile = "cleanup" | "operation" | "pull" | "readiness"; + +function runDocker( + args: readonly string[], + profile: DockerCommandProfile = "operation", +): CommandResult { + const result = spawnSync("docker", [...args], { + encoding: "utf8", + killSignal: "SIGKILL", + maxBuffer: profile === "operation" || profile === "pull" ? 8 * 1024 * 1024 : 1024 * 1024, + timeout: + profile === "pull" + ? DOCKER_ENGINE_27_PULL_TIMEOUT_MS + : profile === "readiness" + ? DOCKER_ENGINE_27_READINESS_COMMAND_TIMEOUT_MS + : profile === "cleanup" + ? DOCKER_ENGINE_27_CLEANUP_TIMEOUT_MS + : DOCKER_ENGINE_27_OPERATION_TIMEOUT_MS, + }); + return { + ...(result.error ? { error: result.error } : {}), + status: result.status, + stderr: result.stderr ?? "", + stdout: result.stdout ?? "", + }; +} + +function commandDetail(result: CommandResult): string { + return `${result.stderr} ${result.stdout} ${result.error?.message ?? ""}`.trim().slice(-1_600); +} + +function requireSuccess(result: CommandResult, operation: string): string { + if (result.status !== 0) { + throw new Error(`${operation} failed: ${commandDetail(result)}`); + } + return result.stdout.trim(); +} + +function requireCondition(condition: unknown, detail: string): asserts condition { + if (!condition) throw new Error(detail); +} + +async function waitForDocker27(daemonName: string): Promise { + for (let attempt = 0; attempt < DOCKER_ENGINE_27_READINESS_ATTEMPTS; attempt += 1) { + if (runDocker(["exec", daemonName, "docker", "info"], "readiness").status === 0) return; + await new Promise((resolve) => + setTimeout(resolve, DOCKER_ENGINE_27_READINESS_INTERVAL_MS), + ); + } + throw new Error("Docker Engine 27 daemon did not become ready"); +} + +function seedName(args: readonly string[]): string { + const nameIndex = args.indexOf("--name"); + requireCondition(nameIndex >= 0 && args[nameIndex + 1], "receipt seed command omitted --name"); + return args[nameIndex + 1]; +} + +function assertSeedIsolation( + innerDocker: (args: readonly string[]) => CommandResult, + name: string, +): void { + const inspected = JSON.parse( + requireSuccess(innerDocker(["inspect", name]), "inspect receipt seed"), + ); + requireCondition( + Array.isArray(inspected) && inspected.length === 1, + "receipt seed inspect changed shape", + ); + validateDockerEngine27SeedIsolation(inspected[0]); +} + +export function validateDockerEngine27SeedIsolation(value: unknown): void { + requireCondition(typeof value === "object" && value !== null, "receipt seed inspect is invalid"); + const seed = value as { + Config?: { User?: unknown }; + HostConfig?: { + CapDrop?: unknown; + Mounts?: unknown; + NetworkMode?: unknown; + Privileged?: unknown; + ReadonlyRootfs?: unknown; + SecurityOpt?: unknown; + }; + }; + requireCondition(seed.Config?.User === "0", "receipt seed did not use numeric root"); + requireCondition(seed.HostConfig?.NetworkMode === "none", "receipt seed retained networking"); + requireCondition(seed.HostConfig?.Privileged === false, "receipt seed was privileged"); + requireCondition(seed.HostConfig?.ReadonlyRootfs === true, "receipt seed root was writable"); + requireCondition( + Array.isArray(seed.HostConfig?.SecurityOpt) && + seed.HostConfig.SecurityOpt.includes("no-new-privileges"), + "receipt seed omitted no-new-privileges", + ); + requireCondition( + Array.isArray(seed.HostConfig?.CapDrop) && seed.HostConfig.CapDrop.includes("ALL"), + "receipt seed retained capabilities", + ); + requireCondition( + Array.isArray(seed.HostConfig?.Mounts) && + seed.HostConfig.Mounts.some( + (mount) => + typeof mount === "object" && + mount !== null && + Reflect.get(mount, "Type") === "volume" && + Reflect.get(mount, "Target") === RECEIPT_VOLUME_DIRECTORY, + ), + "receipt seed omitted the daemon volume", + ); +} + +export function requireDockerResourceAbsent(result: CommandResult, resource: string): void { + const detail = commandDetail(result); + requireCondition( + result.status !== 0 && /\bno such (?:container|object|volume)\b/iu.test(detail), + `${resource} absence was not proven after receipt-transfer cleanup: ${detail}`, + ); +} + +export function cleanupDockerEngine27ReceiptDaemon(daemonName: string): void { + const inspected = runDocker( + [ + "container", + "inspect", + "--format", + `{{ index .Config.Labels "${DAEMON_OWNER_LABEL}" }}`, + daemonName, + ], + "cleanup", + ); + if (inspected.status !== 0) { + requireCondition( + /No such (?:container|object)/iu.test(commandDetail(inspected)), + `could not inspect Docker Engine 27 daemon during cleanup: ${commandDetail(inspected)}`, + ); + return; + } + requireCondition( + inspected.stdout.trim() === daemonName, + "refusing to remove a Docker Engine 27 daemon with mismatched ownership", + ); + requireSuccess(runDocker(["rm", "-f", daemonName], "cleanup"), "remove Docker Engine 27 daemon"); + requireDockerResourceAbsent( + runDocker(["container", "inspect", daemonName], "cleanup"), + "Docker Engine 27 daemon", + ); +} + +function errorDetail(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +export function finalizeDockerEngine27ReceiptProbe( + primaryError: unknown | null, + cleanupDaemon: () => void, + cleanupFixture: () => void, +): void { + const cleanupErrors: unknown[] = []; + try { + cleanupDaemon(); + } catch (error) { + cleanupErrors.push(error); + } + try { + cleanupFixture(); + } catch (error) { + cleanupErrors.push(error); + } + if (primaryError !== null) { + if (cleanupErrors.length === 0) throw primaryError; + throw new AggregateError( + [primaryError, ...cleanupErrors], + `Docker Engine 27 receipt probe failed: ${errorDetail(primaryError)}; cleanup also failed: ${cleanupErrors.map(errorDetail).join("; ")}`, + ); + } + if (cleanupErrors.length > 0) { + throw new AggregateError( + cleanupErrors, + `Docker Engine 27 receipt probe cleanup failed: ${cleanupErrors.map(errorDetail).join("; ")}`, + ); + } +} + +async function verifyDockerEngine27ReceiptTransfer(daemonName: string): Promise { + const suffix = randomUUID().replaceAll("-", ""); + const legacySeed = `nemoclaw-receipt-legacy-seed-${suffix}`; + const legacyVolume = `nemoclaw-receipt-legacy-volume-${suffix}`; + const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-receipt-engine27-")); + const fixtureReceipt = path.join(fixtureRoot, "receipt"); + const daemonReceipt = `/nemoclaw-receipt-${suffix}`; + let primaryError: unknown | null = null; + let successfulVolume: string | null = null; + + fs.mkdirSync(fixtureReceipt, { mode: 0o700 }); + fs.writeFileSync(path.join(fixtureReceipt, "receipt.json"), "verified\n", { mode: 0o400 }); + + const innerDocker = (args: readonly string[]): CommandResult => + runDocker(["exec", daemonName, "docker", ...args]); + + try { + requireSuccess( + runDocker(["pull", DIND_IMAGE], "pull"), + "pull digest-pinned Docker Engine 27 image", + ); + requireSuccess( + runDocker([ + "run", + "--pull", + "never", + "--privileged", + "--detach", + "--name", + daemonName, + "--label", + `${DAEMON_OWNER_LABEL}=${daemonName}`, + "--env", + "DOCKER_TLS_CERTDIR=", + DIND_IMAGE, + "--host=unix:///var/run/docker.sock", + ]), + "start isolated Docker Engine 27 daemon", + ); + await waitForDocker27(daemonName); + const engineVersion = requireSuccess( + innerDocker(["version", "--format", "{{.Server.Version}}"]), + "read isolated Docker version", + ); + requireCondition( + engineVersion === "27.5.1", + `unexpected Docker Engine version ${engineVersion}`, + ); + + requireSuccess( + runDocker(["exec", daemonName, "docker", "pull", RECEIPT_IMAGE], "pull"), + "pull digest-pinned receipt image", + ); + requireSuccess( + runDocker(["cp", fixtureReceipt, `${daemonName}:${daemonReceipt}`]), + "stage protected receipt in Docker Engine 27 client", + ); + + requireSuccess(innerDocker(["volume", "create", legacyVolume]), "create legacy probe volume"); + requireSuccess( + innerDocker([ + "create", + "--name", + legacySeed, + "--pull", + "never", + "--network", + "none", + "--read-only", + "--user", + "0:0", + "--security-opt", + "no-new-privileges", + "--cap-drop", + "ALL", + "--mount", + `type=volume,src=${legacyVolume},dst=${RECEIPT_VOLUME_DIRECTORY}`, + RECEIPT_IMAGE, + ]), + "create legacy receipt seed", + ); + const legacyCopy = innerDocker([ + "cp", + "-a", + daemonReceipt, + `${legacySeed}:${RECEIPT_VOLUME_DIRECTORY}/receipt`, + ]); + requireCondition(legacyCopy.status !== 0, "Docker Engine 27 unexpectedly accepted --user 0:0"); + requireCondition( + /unable to find entry "0:0" in passwd(?: database)?/u.test(commandDetail(legacyCopy)), + `Docker Engine 27 returned an unexpected legacy failure: ${commandDetail(legacyCopy)}`, + ); + requireSuccess(innerDocker(["rm", "-f", legacySeed]), "remove legacy receipt seed"); + requireSuccess(innerDocker(["volume", "rm", legacyVolume]), "remove legacy receipt volume"); + + let successfulSeed = ""; + const dockerRun = (args: readonly string[]): CommandResult => { + const result = innerDocker(args); + if (args[0] === "create" && result.status === 0) { + successfulSeed = seedName(args); + assertSeedIsolation(innerDocker, successfulSeed); + } + return result; + }; + const receipt = transferDockerReceiptToDaemon({ + image: RECEIPT_IMAGE, + receiptPath: daemonReceipt, + destinations: ["/run/nemoclaw/receipt"], + dockerOptions: {}, + dockerRun, + }); + successfulVolume = receipt.volumeName; + requireCondition(successfulSeed.length > 0, "receipt transfer did not create a seed"); + requireDockerResourceAbsent( + innerDocker(["container", "inspect", successfulSeed]), + "successful receipt seed", + ); + requireSuccess( + innerDocker([ + "run", + "--rm", + "--network", + "none", + "--read-only", + "--user", + "0", + "--security-opt", + "no-new-privileges", + "--cap-drop", + "ALL", + "--mount", + dockerDaemonReceiptMount(receipt, "/run/nemoclaw/receipt"), + RECEIPT_IMAGE, + "sh", + "-ceu", + [ + 'test "$(cat /run/nemoclaw/receipt/receipt.json)" = verified', + 'test "$(stat -c %u:%g:%a /run/nemoclaw/receipt)" = 0:0:700', + 'test "$(stat -c %u:%g:%a /run/nemoclaw/receipt/receipt.json)" = 0:0:400', + "! touch /run/nemoclaw/receipt/write-denied", + ].join(" && "), + ]), + "verify Docker Engine 27 receipt volume", + ); + requireSuccess(innerDocker(["volume", "rm", receipt.volumeName]), "remove receipt volume"); + successfulVolume = null; + + let failedSeed = ""; + let failedVolume = ""; + const failingDockerRun = (args: readonly string[]): CommandResult => { + if (args[0] === "volume" && args[1] === "create") failedVolume = String(args.at(-1) ?? ""); + if (args[0] === "create") failedSeed = seedName(args); + return innerDocker(args); + }; + const missingReceipt = `/nemoclaw-missing-receipt-${suffix}`; + let transferFailure: unknown; + try { + transferDockerReceiptToDaemon({ + image: RECEIPT_IMAGE, + receiptPath: missingReceipt, + destinations: ["/run/nemoclaw/receipt"], + dockerOptions: {}, + dockerRun: failingDockerRun, + }); + } catch (error) { + transferFailure = error; + } + requireCondition(transferFailure instanceof Error, "missing receipt transfer did not fail"); + requireCondition( + transferFailure.message.includes(`host receipt ${missingReceipt}`), + "receipt failure omitted the retained host receipt", + ); + requireCondition( + failedSeed.length > 0 && failedVolume.length > 0, + "failed transfer omitted resources", + ); + requireDockerResourceAbsent( + innerDocker(["container", "inspect", failedSeed]), + "failed receipt seed", + ); + requireDockerResourceAbsent( + innerDocker(["volume", "inspect", failedVolume]), + "failed receipt volume", + ); + } catch (error) { + primaryError = error; + } + finalizeDockerEngine27ReceiptProbe( + primaryError, + () => { + innerDocker(["rm", "-f", legacySeed]); + innerDocker(["volume", "rm", legacyVolume]); + if (successfulVolume) innerDocker(["volume", "rm", successfulVolume]); + cleanupDockerEngine27ReceiptDaemon(daemonName); + }, + () => fs.rmSync(fixtureRoot, { force: true, recursive: true }), + ); +} + +function requiredArgument(args: readonly string[], name: string): string { + const index = args.indexOf(name); + const value = index < 0 ? "" : String(args[index + 1] ?? ""); + requireCondition(value.length > 0, `Docker Engine 27 probe requires ${name}`); + return value; +} + +function daemonNameFromArguments(args: readonly string[]): string { + const platform = requiredArgument(args, "--platform"); + requireCondition( + platform === "linux/amd64" || platform === "linux/arm64", + "Docker Engine 27 platform is invalid", + ); + return dockerEngine27ReceiptDaemonName( + requiredArgument(args, "--run-id"), + requiredArgument(args, "--run-attempt"), + platform, + ); +} + +if (path.resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) { + const args = process.argv.slice(2); + const daemonName = daemonNameFromArguments(args); + const operation = args.includes("--cleanup-only") + ? Promise.resolve().then(() => cleanupDockerEngine27ReceiptDaemon(daemonName)) + : verifyDockerEngine27ReceiptTransfer(daemonName); + void operation.catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + }); +} diff --git a/scripts/install.sh b/scripts/install.sh index e9af688d079..4d42204c6ac 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1087,6 +1087,7 @@ usage() { printf " Use only with NEMOCLAW_AGENT=hermes, no registered sandboxes, no local model profile,\n" printf " and the build, cloud, or routed NVIDIA hosted provider\n" printf " --fresh Discard any failed/interrupted onboarding session and start over\n" + printf " --force-fresh-install Destroy all NemoClaw and OpenShell state, then reinstall (Apple silicon macOS only)\n" printf " --station-deepseek Use DeepSeek V4 Flash for DGX Station express install (interactive terminal required)\n" printf " --force-station-install Validate an unrecognized Station GB300 release profile without onboarding\n" printf " --version, -v Print installer version and exit\n" @@ -1100,6 +1101,7 @@ usage() { printf " and the build, cloud, or routed NVIDIA hosted provider\n" printf " NEMOCLAW_NON_INTERACTIVE_SUDO_MODE=prompt Allow sudo prompts during non-interactive onboarding\n" printf " NEMOCLAW_FRESH=1 Same as --fresh\n" + printf " NEMOCLAW_FORCE_FRESH_INSTALL=1 Same as --force-fresh-install (Apple silicon macOS only)\n" printf " NEMOCLAW_NO_EXPRESS=1 Skip the Express prompt on detected platforms\n" printf " NEMOCLAW_SANDBOX_NAME Sandbox name to create/use\n" printf " HF_TOKEN Optional Hugging Face read token for managed-vLLM downloads\n" @@ -1383,6 +1385,85 @@ spin() { return $status } +FORCE_FRESH_PREPARE_TIMEOUT_SECONDS=900 +FORCE_FRESH_UNINSTALL_TIMEOUT_SECONDS=900 + +installer_command_group_is_alive() { + local command_pid="$1" + kill -0 -- "-$command_pid" 2>/dev/null || kill -0 "$command_pid" 2>/dev/null +} + +terminate_installer_command_group() { + local command_pid="$1" grace_ticks + installer_command_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 + installer_command_group_is_alive "$command_pid" || break + sleep 0.1 + done + if installer_command_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 +} + +run_bounded_installer_command() ( + local label="$1" timeout_seconds="$2" log command_pid="" status=0 ticks=0 pending_signal=0 + shift 2 + [[ "$timeout_seconds" =~ ^[1-9][0-9]*$ ]] \ + || error "Installer command timeout must be a positive integer." + log="$(mktemp)" + # Invoked indirectly by the signal and exit traps below. + # shellcheck disable=SC2329 + cleanup_bounded_installer_command() { + local cleanup_status="$1" + trap 'cleanup_status=130' INT + trap 'cleanup_status=143' TERM + trap - EXIT + [[ -z "$command_pid" ]] || terminate_installer_command_group "$command_pid" + rm -f "$log" + exit "$cleanup_status" + } + trap 'pending_signal=130' INT + trap 'pending_signal=143' TERM + trap 'cleanup_bounded_installer_command "$?"' EXIT + info "$label" + set -m + "$@" >"$log" 2>&1 & + command_pid=$! + set +m + trap 'cleanup_bounded_installer_command 130' INT + trap 'cleanup_bounded_installer_command 143' TERM + ((pending_signal == 0)) || cleanup_bounded_installer_command "$pending_signal" + while installer_command_group_is_alive "$command_pid"; do + if ((ticks >= timeout_seconds * 10)); then + if [[ "${NEMOCLAW_FORCE_FRESH_CLEANUP_ACTIVE:-}" == "1" ]]; then + printf '[ERROR] Timed out during %s after %s seconds. Force-fresh cleanup is incomplete; remaining state was preserved for retry and OpenShell package removal did not start.\n' "$label" "$timeout_seconds" >&2 + else + printf '[ERROR] Timed out during %s after %s seconds. Existing state was preserved; force-fresh cleanup did not start. Retry when package installation is healthy.\n' "$label" "$timeout_seconds" >&2 + fi + return 124 + fi + sleep 0.1 + ticks=$((ticks + 1)) + done + if wait "$command_pid"; then + status=0 + else + status=$? + fi + command_pid="" + if ((status != 0)); then + cat "$log" >&2 + fi + rm -f "$log" + trap - EXIT + return "$status" +) + command_exists() { command -v "$1" &>/dev/null; } # Apply the gateway's Unix-socket constraints before Node or CLI modules are available. @@ -1400,7 +1481,7 @@ installer_docker_host_has_supported_shape() { # Admit a usable socket and the default context before Docker or recovery effects. # Persisted JSON inspection can wait only for its missing Node.js prerequisite. validate_installer_docker_target_before_host_changes() { - local raw="${DOCKER_HOST-}" candidate active_context="" + local raw="${DOCKER_HOST-}" candidate active_context="" context_host="" installer_docker_host_has_supported_shape \ || error "DOCKER_HOST is not a supported absolute local Unix socket endpoint. Unset DOCKER_HOST or set it to an absolute local Unix socket URL, such as unix:///var/run/docker.sock. Then rerun the installer." candidate="${raw#"${raw%%[![:space:]]*}"}" @@ -1417,8 +1498,21 @@ validate_installer_docker_target_before_host_changes() { fi active_context="$(docker_active_context)" fi - [[ "$active_context" == default ]] \ - || error "The Docker context does not select the local default target. Unset DOCKER_CONTEXT or set it to default, and run 'docker context use default' if a non-default context is persisted. Then rerun the installer." + if [[ "$active_context" != default ]]; then + context_host="$(docker context inspect "$active_context" --format '{{.Endpoints.docker.Host}}' 2>/dev/null || true)" + [[ -n "$context_host" ]] \ + || error "The Docker context does not select a supported local Unix socket. Select a local Docker or Colima context, then rerun the installer." + DOCKER_HOST="$context_host" + installer_docker_host_has_supported_shape \ + || error "The Docker context does not select a supported local Unix socket. Select a local Docker or Colima context, then rerun the installer." + export DOCKER_HOST + unset DOCKER_CONTEXT + elif [[ -n "$candidate" ]]; then + unset DOCKER_CONTEXT + fi + # DOCKER_CONTEXT takes precedence over DOCKER_HOST in Docker clients. Once + # admission resolves a local socket, keep that socket authoritative through + # host preflight and automatic onboarding. } # Re-read persisted context after Node installation instead of trusting the temporary default. @@ -1427,7 +1521,6 @@ complete_deferred_installer_docker_context_validation() { _INSTALLER_DOCKER_CONTEXT_VALIDATION_DEFERRED="" unset DOCKER_CONTEXT validate_installer_docker_target_before_host_changes - export DOCKER_CONTEXT=default } MIN_NODE_VERSION="22.19.0" @@ -2286,6 +2379,45 @@ NODE # over their own openshell version) # Both modes defer when NEMOCLAW_DEFER_OPENSHELL_INSTALL=1 so the pre-upgrade # backup flow can run before any version bump. +record_managed_user_local_openshell_install() { + local user_bin manifest temp_manifest binary binary_path digest + local -a sha256_command + user_bin="${XDG_BIN_HOME:-${HOME}/.local/bin}" + manifest="${user_bin}/.nemoclaw-openshell-managed-v1" + if command_exists sha256sum; then + sha256_command=(sha256sum) + elif command_exists shasum; then + sha256_command=(shasum -a 256) + else + error "Could not record managed OpenShell ownership because no SHA-256 command is available." + fi + temp_manifest="$(mktemp "${manifest}.tmp.XXXXXX")" \ + || error "Could not create the managed OpenShell install manifest." + _cleanup_files+=("$temp_manifest") + chmod 600 "$temp_manifest" \ + || error "Could not secure the managed OpenShell install manifest." + for binary in openshell openshell-gateway openshell-sandbox openshell-driver-vm; do + binary_path="${user_bin}/${binary}" + if [[ ! -e "$binary_path" ]]; then + case "$binary" in + openshell | openshell-gateway) + error "The verified standalone OpenShell install did not provide ${binary_path}." + ;; + *) continue ;; + esac + fi + [[ -f "$binary_path" && ! -L "$binary_path" && -x "$binary_path" ]] \ + || error "The verified standalone OpenShell install did not provide ${binary_path}." + digest="$("${sha256_command[@]}" "$binary_path" | awk '{print $1}')" \ + || error "Could not hash the installed ${binary} binary." + [[ "$digest" =~ ^[a-f0-9]{64}$ ]] \ + || error "The installed ${binary} binary returned an invalid SHA-256 digest." + printf '%s %s\n' "$digest" "$binary" >>"$temp_manifest" + done + mv -f -- "$temp_manifest" "$manifest" \ + || error "Could not publish the managed OpenShell install manifest." +} + maybe_install_openshell_during_install() { local mode="${1:-force}" local explicit_openshell_bin="${NEMOCLAW_OPENSHELL_BIN:-}" @@ -2318,7 +2450,14 @@ maybe_install_openshell_during_install() { fi if ! _NEMOCLAW_OPENSHELL_INSTALL_METHOD="$macos_install_method" \ spin "Installing OpenShell CLI" bash "${NEMOCLAW_SOURCE_ROOT}/scripts/install-openshell.sh"; then - return 1 + if [[ "$platform" == "Darwin" && "$macos_install_method" == "homebrew" ]] \ + && truthy_env "${FORCE_FRESH_INSTALL:-}" \ + && _NEMOCLAW_OPENSHELL_INSTALL_METHOD="$macos_install_method" \ + spin "Verifying the installed OpenShell CLI" bash "${NEMOCLAW_SOURCE_ROOT}/scripts/install-openshell.sh"; then + warn "Homebrew reported an install failure after placing OpenShell; the pinned OpenShell verifier passed, so force-fresh installation will continue." + else + return 1 + fi fi if [[ "$platform" == "Darwin" ]]; then observed_install_method="$(observed_macos_openshell_install_method)" || return 1 @@ -2334,6 +2473,7 @@ maybe_install_openshell_during_install() { standalone) prefer_user_local_openshell verified-install \ || error "The verified standalone OpenShell installation did not provide trusted executable user-local CLI and gateway binaries. The installer stopped before gateway recovery." + record_managed_user_local_openshell_install warn "Homebrew is not installed; using the verified standalone OpenShell gateway without reboot persistence." ;; *) @@ -2465,6 +2605,11 @@ preflight_nemoclaw_acp_shim() { fi is_installer_managed_cli_shim "$shim_path" "nemoclaw-acp" "$cli_path" && return 0 is_npm_managed_nemoclaw_acp_link "$shim_path" "$cli_path" && return 0 + if truthy_env "${FORCE_FRESH_INSTALL:-}" && [[ "$cli_path" != "$shim_path" ]]; then + _NEMOCLAW_FORCE_FRESH_SKIP_ACP_SHIM=true + warn "Leaving unrelated $shim_path unchanged; the force-fresh install will not publish a nemoclaw-acp shim there." + return 0 + fi error "Installation stopped because $shim_path already exists and is not a NemoClaw-managed shim. NemoClaw left it unchanged. Move or remove that path, then rerun the installer." } @@ -2555,6 +2700,11 @@ ensure_cli_shim() { npm_bin="$(resolve_npm_bin)" || true shim_path="${NEMOCLAW_SHIM_DIR}/${cli_bin}" + if [[ "$cli_bin" == "nemoclaw-acp" ]] \ + && [[ "${_NEMOCLAW_FORCE_FRESH_SKIP_ACP_SHIM:-false}" == true ]]; then + return 0 + fi + if [[ -z "$npm_bin" || ! -x "$npm_bin/$cli_bin" ]]; then return 1 fi @@ -3494,6 +3644,213 @@ run_preupgrade_backup() { NEMOCLAW_REQUIRE_ALL_SANDBOX_BACKUPS=1 "$current_cli_runner" backup-all 2>&1 } +force_fresh_install_has_existing_state() { + local container_id container_image container_inventory container_label_inventory container_name + local receipt_volume_inventory user_bin volume_name volume_suffix + local existing_state=0 + _FORCE_FRESH_UNVERIFIED_DOCKER_CONTAINER="" + _FORCE_FRESH_UNVERIFIED_RECEIPT_VOLUME="" + user_bin="${XDG_BIN_HOME:-${HOME}/.local/bin}" + if [[ -e "$(nemoclaw_state_root)" ]] \ + || [[ -e "${HOME}/.config/nemoclaw" ]] \ + || [[ -e "${HOME}/.config/openshell" ]] \ + || [[ -e "${HOME}/.local/state/nemoclaw" ]] \ + || [[ -e "${user_bin}/nemoclaw" ]] \ + || [[ -e "${user_bin}/openshell" ]] \ + || [[ -e "${user_bin}/openshell-gateway" ]] \ + || [[ -e "${user_bin}/openshell-sandbox" ]] \ + || [[ -e "${user_bin}/openshell-driver-vm" ]] \ + || command_exists nemoclaw \ + || command_exists openshell; then + existing_state=1 + fi + if command_exists brew \ + && brew list --formula nvidia/openshell/openshell >/dev/null 2>&1; then + existing_state=1 + fi + if command_exists docker; then + docker info >/dev/null 2>&1 || return 2 + container_label_inventory="$( + docker ps -aq --filter label=io.nvidia.nemoclaw.managed-image.contract=1 2>/dev/null + )" || return 2 + _FORCE_FRESH_UNVERIFIED_DOCKER_CONTAINER="$(printf '%s\n' "$container_label_inventory" | sed -n '1p')" + container_inventory="$( + docker ps -a --format '{{.ID}} {{.Image}} {{.Names}}' 2>/dev/null + )" || return 2 + while read -r container_id container_image container_name; do + [[ -n "$container_id" ]] || continue + case "$container_name" in + openshell-* | nemoclaw-*) _FORCE_FRESH_UNVERIFIED_DOCKER_CONTAINER="$container_id" ;; + esac + case "$container_image" in + nemoclaw-* | openshell/* | ghcr.io/nvidia/nemoclaw | ghcr.io/nvidia/nemoclaw:* | ghcr.io/nvidia/nemoclaw@* | ghcr.io/nvidia/nemoclaw/* | ghcr.io/nvidia/nemoclaw-*) + _FORCE_FRESH_UNVERIFIED_DOCKER_CONTAINER="$container_id" + ;; + esac + [[ -z "$_FORCE_FRESH_UNVERIFIED_DOCKER_CONTAINER" ]] || break + done <<<"$container_inventory" + receipt_volume_inventory="$( + docker volume ls --format '{{.Name}}' 2>/dev/null + )" || return 2 + while IFS= read -r volume_name; do + case "$volume_name" in + nemoclaw-managed-startup-receipt-volume-*) ;; + *) continue ;; + esac + volume_suffix="${volume_name#nemoclaw-managed-startup-receipt-volume-}" + [[ "${#volume_suffix}" -eq 32 && "$volume_suffix" =~ ^[0-9a-f]+$ ]] || continue + _FORCE_FRESH_UNVERIFIED_RECEIPT_VOLUME="$volume_name" + return 3 + done <<<"$receipt_volume_inventory" + fi + if ((existing_state == 0)) && [[ -n "$_FORCE_FRESH_UNVERIFIED_DOCKER_CONTAINER" ]]; then + return 4 + fi + ((existing_state == 0)) || return 0 + return 1 +} + +force_fresh_install_source_root() { + local source_root state_root state_parent + source_root="$(cd "${NEMOCLAW_SOURCE_ROOT}" && pwd -P)" \ + || error "Could not resolve the staged source for the force-fresh install." + state_root="$(nemoclaw_state_root)" \ + || error "Could not resolve the NemoClaw state root for the force-fresh install." + if [[ -d "$state_root" ]]; then + state_root="$(cd "$state_root" && pwd -P)" \ + || error "Could not resolve the existing NemoClaw state root." + else + state_parent="$(dirname "$state_root")" + state_root="$(cd "$state_parent" && pwd -P)/$(basename "$state_root")" \ + || error "Could not resolve the NemoClaw state parent directory." + fi + case "$source_root" in + "$state_root" | "$state_root"/*) + error "The force-fresh installer must run from the versioned bootstrap checkout outside ${state_root}. Use the public curl installer with --force-fresh-install." + ;; + esac + [[ -d "${source_root}/.git" && ! -L "${source_root}/.git" ]] \ + || error "The force-fresh installer requires a staged NemoClaw Git checkout." + printf '%s' "$source_root" +} + +prepare_force_fresh_uninstaller() { + local source_root="$1" prepare_status=0 + if [[ -z "${NEMOCLAW_AGENT:-}" || "${NEMOCLAW_AGENT}" == "openclaw" ]]; then + run_bounded_installer_command "Preparing OpenClaw package for force-fresh cleanup" "$FORCE_FRESH_PREPARE_TIMEOUT_SECONDS" bash -c "$(declare -f info warn resolve_openclaw_version pre_extract_openclaw); pre_extract_openclaw \"\$1\"" _ "$source_root" \ + || warn "Pre-extraction failed — npm install may fail if the OpenClaw tarball is broken" + fi + run_bounded_installer_command "Preparing the force-fresh uninstaller" "$FORCE_FRESH_PREPARE_TIMEOUT_SECONDS" bash -c \ + "cd \"$source_root\" && node scripts/lib/openshell-sdk-install.mts prepare && npm install --ignore-scripts --prefer-offline --include=optional --@nvidia:registry=https://npm.pkg.github.com && node scripts/lib/openshell-sdk-install.mts check && npm run --if-present build:cli" \ + || prepare_status=$? + if ((prepare_status == 124)); then + error "Force-fresh uninstaller preparation timed out before cleanup. Existing state was preserved; rerun when package installation is healthy." + elif ((prepare_status != 0)); then + error "The staged force-fresh uninstaller could not be prepared. Existing state was preserved; cleanup did not start." + fi + [[ -s "${source_root}/dist/lib/actions/uninstall/run-plan.js" ]] \ + || error "The staged force-fresh uninstaller did not build." +} + +run_force_fresh_uninstaller() { + local source_root="$1" node_bin preflight_status=0 cleanup_status=0 + node_bin="$(command -v node 2>/dev/null || true)" + [[ -n "$node_bin" && -x "$node_bin" ]] \ + || error "Node.js is required for the force-fresh uninstaller." + run_bounded_installer_command \ + "Validating force-fresh OpenShell ownership" \ + "$FORCE_FRESH_UNINSTALL_TIMEOUT_SECONDS" \ + "$node_bin" "${source_root}/bin/nemoclaw.js" internal uninstall run-plan \ + --force-fresh-ownership-preflight \ + || preflight_status=$? + if ((preflight_status == 124)); then + error "The staged canonical ownership preflight timed out. No cleanup started; retry when local process execution is healthy." + elif ((preflight_status != 0)); then + error "Force-fresh cleanup stopped because the staged canonical ownership preflight rejected a user-local OpenShell executable. Reconcile the reported binary, then rerun. No cleanup started." + fi + NEMOCLAW_FORCE_FRESH_CLEANUP_ACTIVE=1 run_bounded_installer_command \ + "Running authoritative force-fresh cleanup" \ + "$FORCE_FRESH_UNINSTALL_TIMEOUT_SECONDS" \ + env NEMOCLAW_UNINSTALL_DESTROY_USER_DATA=1 "$node_bin" \ + "${source_root}/bin/nemoclaw.js" internal uninstall run-plan \ + --yes --destroy-user-data --force-fresh-reset --all-gateway-ports \ + || cleanup_status=$? + if ((cleanup_status == 124)); then + error "Authoritative force-fresh cleanup timed out and is incomplete. Inspect the remaining state, then rerun; OpenShell package removal did not start." + elif ((cleanup_status != 0)); then + return "$cleanup_status" + fi +} + +preflight_macos_openshell_for_force_fresh_install() { + local formula="nvidia/openshell/openshell" binary="" binary_path="" + local user_bin="${XDG_BIN_HOME:-${HOME}/.local/bin}" homebrew_bin="" + if command_exists brew \ + && brew list --formula "$formula" >/dev/null 2>&1; then + homebrew_bin="$(brew --prefix 2>/dev/null)/bin" \ + || error "Homebrew could not report its installation prefix before force-fresh cleanup. No cleanup started." + [[ "$homebrew_bin" != "/bin" ]] \ + || error "Homebrew returned an empty installation prefix before force-fresh cleanup. No cleanup started." + fi + for binary in openshell openshell-gateway openshell-sandbox openshell-driver-vm; do + binary_path="${user_bin}/${binary}" + if [[ -e "$binary_path" ]]; then + [[ -f "$binary_path" && ! -L "$binary_path" && -x "$binary_path" && -O "$binary_path" ]] \ + || error "The force-fresh installer found an unsafe OpenShell executable at ${binary_path}. Remove or reconcile it explicitly, then rerun. No cleanup started." + fi + binary_path="$(command -v "$binary" 2>/dev/null || true)" + [[ -z "$binary_path" || "$binary_path" == "${user_bin}/${binary}" ]] && continue + [[ -n "$homebrew_bin" && "$binary_path" == "${homebrew_bin}/${binary}" ]] && continue + error "The force-fresh installer found an unverified OpenShell executable at ${binary_path}. Remove or reconcile it explicitly, then rerun. No cleanup started." + done +} + +remove_macos_openshell_for_force_fresh_install() { + local formula="nvidia/openshell/openshell" binary="" openshell_path="" + if command_exists brew && brew list --formula "$formula" >/dev/null 2>&1; then + brew services stop "$formula" >/dev/null 2>&1 || true + brew uninstall --force "$formula" \ + || error "Homebrew could not remove OpenShell during the force-fresh install. Rerun the same command after Homebrew is healthy." + fi + hash -r 2>/dev/null || true + for binary in openshell openshell-gateway openshell-sandbox openshell-driver-vm; do + openshell_path="$(command -v "$binary" 2>/dev/null || true)" + [[ -z "$openshell_path" ]] \ + || error "The force-fresh installer found a remaining OpenShell executable at ${openshell_path}. Remove or reconcile that installation explicitly, then rerun." + done +} + +run_force_fresh_install_reset() { + local source_root existing_state_status=0 + warn "Force-fresh install selected. NemoClaw will destroy all NemoClaw/OpenShell sandboxes, gateways, credentials, configuration, and recovery state on this host. Model caches are kept." + preflight_macos_openshell_for_force_fresh_install + force_fresh_install_has_existing_state || existing_state_status=$? + case "$existing_state_status" in + 0) + source_root="$(force_fresh_install_source_root)" + prepare_force_fresh_uninstaller "$source_root" + run_force_fresh_uninstaller "$source_root" \ + || error "Force-fresh cleanup stopped because the authoritative whole-host uninstall did not complete. The installer preserved remaining state for a safe retry." + ;; + 1) info "No existing NemoClaw or OpenShell installation was found; continuing with a clean install." ;; + 2) error "Docker is installed but unavailable. Start the selected local Docker or Colima daemon, then rerun --force-fresh-install. No cleanup started." ;; + 3) error "Force-fresh cleanup found unverified receipt volume ${_FORCE_FRESH_UNVERIFIED_RECEIPT_VOLUME}. Docker names and mutable labels are not ownership proof. Inspect it, remove it only after confirming it belongs to the interrupted NemoClaw install, then rerun. No cleanup started." ;; + 4) error "Force-fresh cleanup found unverified Docker container ${_FORCE_FRESH_UNVERIFIED_DOCKER_CONTAINER}. NemoClaw cannot prove this Docker-only resource belongs to the current installation. Inspect and reconcile it explicitly, then rerun. No cleanup started." ;; + *) error "Could not inspect existing NemoClaw or OpenShell state. No cleanup started." ;; + esac + remove_macos_openshell_for_force_fresh_install + FRESH=1 + export NEMOCLAW_FRESH=1 + export NEMOCLAW_REINSTALL_CLI=1 + _PREEXISTING_SANDBOX_COUNT=0 +} + +validate_force_fresh_install_platform() { + truthy_env "${FORCE_FRESH_INSTALL:-}" || return 0 + [[ "$(uname -s)" == "Darwin" && "$(uname -m)" == "arm64" ]] \ + || error "--force-fresh-install currently supports Apple silicon macOS only." +} + # Return nonzero when OpenShell is absent or its version command fails. installed_openshell_version() { command_exists openshell || return 1 @@ -7063,6 +7420,9 @@ install_nemoclaw_before_onboarding() { bash "${SCRIPT_DIR}/setup-jetson.sh" prepare_installer_node_runtime + if truthy_env "${FORCE_FRESH_INSTALL:-}"; then + run_force_fresh_install_reset + fi ensure_station_express_pair step 2 "${_CLI_DISPLAY} CLI" @@ -7071,7 +7431,9 @@ install_nemoclaw_before_onboarding() { # install.sh stays focused on dependency setup. fix_npm_permissions preflight_nemoclaw_acp_shim - preinstall_backup_and_retire_legacy_gateway + if ! truthy_env "${FORCE_FRESH_INSTALL:-}"; then + preinstall_backup_and_retire_legacy_gateway + fi install_nemoclaw verify_nemoclaw require_reportable_openshell_version @@ -7097,6 +7459,7 @@ main() { ACCEPT_THIRD_PARTY_SOFTWARE="" DEFER_ONBOARDING="" FRESH="" + FORCE_FRESH_INSTALL="" STATION_DEEPSEEK="" FORCE_STATION_INSTALL="" LOCAL_MODEL_RUNTIME="" @@ -7116,6 +7479,7 @@ main() { --yes-i-accept-third-party-software) ACCEPT_THIRD_PARTY_SOFTWARE=1 ;; --defer-onboarding) DEFER_ONBOARDING=1 ;; --fresh) FRESH=1 ;; + --force-fresh-install) FORCE_FRESH_INSTALL=1 ;; --station-deepseek) STATION_DEEPSEEK=1 ;; --force-station-install) FORCE_STATION_INSTALL=1 ;; --local-model-runtime=*) @@ -7160,6 +7524,12 @@ main() { ACCEPT_THIRD_PARTY_SOFTWARE="${ACCEPT_THIRD_PARTY_SOFTWARE:-${NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE:-}}" DEFER_ONBOARDING="${DEFER_ONBOARDING:-${NEMOCLAW_DEFER_ONBOARDING:-}}" FRESH="${FRESH:-${NEMOCLAW_FRESH:-}}" + FORCE_FRESH_INSTALL="${FORCE_FRESH_INSTALL:-${NEMOCLAW_FORCE_FRESH_INSTALL:-}}" + if truthy_env "${FORCE_FRESH_INSTALL:-}"; then + validate_force_fresh_install_platform + FRESH=1 + export FORCE_FRESH_INSTALL NEMOCLAW_FORCE_FRESH_INSTALL=1 + fi if [ -n "${LOCAL_MODEL_RUNTIME:-}" ]; then export NEMOCLAW_ENABLE_LOCAL_MODEL_PROFILE=1 export NEMOCLAW_LOCAL_MODEL_RUNTIME="$LOCAL_MODEL_RUNTIME" diff --git a/src/commands/internal/uninstall/run-plan.test.ts b/src/commands/internal/uninstall/run-plan.test.ts index 1eec8cf174e..e732d34f9f4 100644 --- a/src/commands/internal/uninstall/run-plan.test.ts +++ b/src/commands/internal/uninstall/run-plan.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import type { Config } from "@oclif/core"; const mocks = vi.hoisted(() => ({ + preflightForceFreshUserLocalOpenShellOwnership: vi.fn(), runUninstallPlan: vi.fn(), runUninstallPlanProduction: vi.fn(), })); @@ -19,6 +20,27 @@ vi.mock("../../../lib/actions/uninstall/all-gateway-ports", () => ({ import InternalUninstallRunPlanCommand from "./run-plan"; describe("internal uninstall command", () => { + it("runs the hidden force-fresh ownership preflight without starting uninstall", async () => { + const previousExitCode = process.exitCode; + process.exitCode = undefined; + mocks.preflightForceFreshUserLocalOpenShellOwnership.mockReturnValue(false); + const instance = new InternalUninstallRunPlanCommand([], {} as Config); + Object.defineProperty(instance, "parse", { + value: vi.fn().mockResolvedValue({ + flags: { "force-fresh-ownership-preflight": true }, + }), + }); + + try { + await instance.run(); + expect(mocks.preflightForceFreshUserLocalOpenShellOwnership).toHaveBeenCalledOnce(); + expect(mocks.runUninstallPlanProduction).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + } finally { + process.exitCode = previousExitCode; + } + }); + it("awaits the production uninstall transaction before applying its exit result", async () => { const previousExitCode = process.exitCode; let complete!: (value: { exitCode: number }) => void; @@ -37,7 +59,9 @@ describe("internal uninstall command", () => { process.exitCode = undefined; const instance = new InternalUninstallRunPlanCommand([], {} as Config); Object.defineProperty(instance, "parse", { - value: vi.fn().mockResolvedValue({ flags: { yes: true, "keep-openshell": true } }), + value: vi.fn().mockResolvedValue({ + flags: { yes: true, "force-fresh-reset": true, "keep-openshell": true }, + }), }); const command = instance.run().then(() => { finished = true; @@ -45,7 +69,7 @@ describe("internal uninstall command", () => { try { await Promise.race([started, command]); expect(mocks.runUninstallPlanProduction).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ assumeYes: true, keepOpenShell: true }), + expect.objectContaining({ assumeYes: true, forceFreshReset: true, keepOpenShell: true }), expect.objectContaining({ backupAllBeforeUninstall: expect.any(Function), withSandboxMutationLock: expect.any(Function), diff --git a/src/commands/internal/uninstall/run-plan.ts b/src/commands/internal/uninstall/run-plan.ts index e74af1470f5..9e4a4fb6041 100644 --- a/src/commands/internal/uninstall/run-plan.ts +++ b/src/commands/internal/uninstall/run-plan.ts @@ -7,7 +7,10 @@ import { runUninstallAllGatewayPorts, } from "../../../lib/actions/uninstall/all-gateway-ports"; import { backupAllUnderPortableHostFence } from "../../../lib/actions/maintenance"; -import { runUninstallPlanProduction } from "../../../lib/actions/uninstall/run-plan"; +import { + preflightForceFreshUserLocalOpenShellOwnership, + runUninstallPlanProduction, +} from "../../../lib/actions/uninstall/run-plan"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../../lib/cli/branding"; import { NemoClawCommand } from "../../../lib/cli/nemoclaw-oclif-command"; import { GATEWAY_PORT } from "../../../lib/core/ports"; @@ -30,6 +33,8 @@ export default class InternalUninstallRunPlanCommand extends NemoClawCommand { "Uninstall every gateway port on this host, not only the port NEMOCLAW_GATEWAY_PORT selects", }), "all-gateway-ports-child": Flags.boolean({ hidden: true }), + "force-fresh-ownership-preflight": Flags.boolean({ hidden: true }), + "force-fresh-reset": Flags.boolean({ hidden: true }), "keep-openshell": Flags.boolean({ description: "Leave the openshell binary installed" }), "delete-models": Flags.boolean({ description: @@ -47,10 +52,17 @@ export default class InternalUninstallRunPlanCommand extends NemoClawCommand { public async run(): Promise { const { flags } = await this.parse(InternalUninstallRunPlanCommand); + if (flags["force-fresh-ownership-preflight"]) { + this.applyExitResult({ + exitCode: preflightForceFreshUserLocalOpenShellOwnership() ? 0 : 1, + }); + return; + } const options = { assumeYes: flags.yes ?? false, deleteModels: flags["delete-models"] ?? false, destroyUserData: flags["destroy-user-data"] ?? false, + forceFreshReset: flags["force-fresh-reset"] ?? false, gatewayName: flags.gateway, keepOpenShell: flags["keep-openshell"] ?? false, }; diff --git a/src/lib/actions/uninstall/all-gateway-ports.test.ts b/src/lib/actions/uninstall/all-gateway-ports.test.ts index c6cb52f7921..229aaf7a869 100644 --- a/src/lib/actions/uninstall/all-gateway-ports.test.ts +++ b/src/lib/actions/uninstall/all-gateway-ports.test.ts @@ -352,7 +352,12 @@ describe("uninstall across every gateway port (#7791)", () => { ], [ "every passthrough flag", - { deleteModels: true, destroyUserData: true, keepOpenShell: true }, + { + deleteModels: true, + destroyUserData: true, + forceFreshReset: true, + keepOpenShell: true, + }, [ "internal", "uninstall", @@ -361,6 +366,7 @@ describe("uninstall across every gateway port (#7791)", () => { "--all-gateway-ports-child", "--delete-models", "--destroy-user-data", + "--force-fresh-reset", "--keep-openshell", ], ], diff --git a/src/lib/actions/uninstall/all-gateway-ports.ts b/src/lib/actions/uninstall/all-gateway-ports.ts index 62e4bd96ea2..3fe3cf3e28d 100644 --- a/src/lib/actions/uninstall/all-gateway-ports.ts +++ b/src/lib/actions/uninstall/all-gateway-ports.ts @@ -68,6 +68,7 @@ export function uninstallChildArgs(options: UninstallRunOptions): string[] { const args = ["internal", "uninstall", "run-plan", "--yes", "--all-gateway-ports-child"]; if (options.deleteModels) args.push("--delete-models"); if (options.destroyUserData) args.push("--destroy-user-data"); + if (options.forceFreshReset) args.push("--force-fresh-reset"); if (options.keepOpenShell) args.push("--keep-openshell"); return args; } diff --git a/src/lib/actions/uninstall/run-plan-docker-scope.test.ts b/src/lib/actions/uninstall/run-plan-docker-scope.test.ts index c8aa8d3260d..68fd04ec773 100644 --- a/src/lib/actions/uninstall/run-plan-docker-scope.test.ts +++ b/src/lib/actions/uninstall/run-plan-docker-scope.test.ts @@ -151,4 +151,172 @@ describe("uninstall Docker resource scope", () => { expect(calls).toContainEqual(["rmi", "-f", "i-openshell"]); }); + + it.each([ + { + kind: "labelled", + volume: `nemoclaw-managed-startup-receipt-volume-${"a".repeat(32)}`, + }, + { + kind: "unlabelled", + volume: `nemoclaw-managed-startup-receipt-volume-${"b".repeat(32)}`, + }, + ])("preserves an $kind receipt-volume match during force-fresh cleanup", async ({ volume }) => { + const calls: string[][] = []; + const routes: Record RunResult> = { + info: () => ok(), + "ps -a --format {{.ID}} {{.Image}} {{.Names}}": () => ok(), + "volume ls --format {{.Name}}": () => ok(volume), + "volume inspect openshell-cluster-nemoclaw": () => ({ + status: 1, + stdout: "", + stderr: "Error response from daemon: get openshell-cluster-nemoclaw: no such volume", + }), + }; + const runDocker = vi.fn((args: string[]) => { + calls.push(args); + const command = args.join(" "); + return (routes[command] ?? (() => ok()))(); + }); + + const result = await runUninstallPlan( + { + assumeYes: true, + deleteModels: false, + destroyUserData: true, + forceFreshReset: true, + keepOpenShell: true, + }, + { + commandExists: () => true, + env: { HOME: "/tmp/nemoclaw-force-fresh-receipts" } as NodeJS.ProcessEnv, + existsSync: () => false, + hasPortableRuntimeCleanup: () => false, + isTty: false, + kill: () => true, + log: () => undefined, + rmSync: vi.fn(), + run: (command, args) => + command === "openshell" && args.join(" ") === "gateway list -o json" + ? ok(JSON.stringify([{ name: "nemoclaw" }])) + : ok(), + runDocker, + }, + ); + + expect(result.exitCode).toBe(1); + expect(calls).toContainEqual(["volume", "ls", "--format", "{{.Name}}"]); + expect(calls).not.toContainEqual(["volume", "rm", "-f", volume]); + }); + + it.each([ + { + failureCommand: ["volume", "rm", "-f", "openshell-cluster-nemoclaw"], + plannedVolumeInspection: ok(), + scenario: "planned-volume removal fails", + }, + { + failureCommand: ["volume", "inspect", "openshell-cluster-nemoclaw"], + plannedVolumeInspection: { status: 1, stdout: "", stderr: "permission denied" }, + scenario: "planned-volume inspection is inconclusive", + }, + ] as const)( + "fails force-fresh cleanup when $scenario", + async ({ failureCommand, plannedVolumeInspection }) => { + const routes: Record = { + info: ok(), + "ps -a --format {{.ID}} {{.Image}} {{.Names}}": ok(), + "volume inspect openshell-cluster-nemoclaw": plannedVolumeInspection, + "volume rm -f openshell-cluster-nemoclaw": { + status: 1, + stdout: "", + stderr: "busy", + }, + }; + const runDocker = vi.fn((args: string[]): RunResult => { + return routes[args.join(" ")] ?? ok(); + }); + + const result = await runUninstallPlan( + { + assumeYes: true, + deleteModels: false, + destroyUserData: true, + forceFreshReset: true, + keepOpenShell: true, + }, + { + commandExists: () => true, + env: { HOME: "/tmp/nemoclaw-force-fresh-docker-failure" } as NodeJS.ProcessEnv, + existsSync: () => false, + hasPortableRuntimeCleanup: () => false, + isTty: false, + kill: () => true, + log: () => undefined, + rmSync: vi.fn(), + run: (command, args) => + command === "openshell" && args.join(" ") === "gateway list -o json" + ? ok(JSON.stringify([{ name: "nemoclaw" }])) + : ok(), + runDocker, + }, + ); + + expect(result.exitCode).toBe(1); + expect(runDocker).toHaveBeenCalledWith(failureCommand, expect.any(Object)); + expect(runDocker).toHaveBeenCalledWith( + ["volume", "inspect", "openshell-cluster-nemoclaw"], + expect.objectContaining({ stdio: ["ignore", "pipe", "pipe"] }), + ); + }, + ); + + it("preserves a convention-matching container and images during force-fresh cleanup", async () => { + const calls: string[][] = []; + const routes: Record = { + info: ok(), + "ps -a --format {{.ID}} {{.Image}} {{.Names}}": ok( + "foreign-id registry.example.com/unrelated:latest openshell-foreign", + ), + "volume inspect openshell-cluster-nemoclaw": { + status: 1, + stdout: "", + stderr: "Error response from daemon: get openshell-cluster-nemoclaw: no such volume", + }, + }; + const runDocker = vi.fn((args: string[]): RunResult => { + calls.push(args); + return routes[args.join(" ")] ?? ok(); + }); + + const result = await runUninstallPlan( + { + assumeYes: true, + deleteModels: false, + destroyUserData: true, + forceFreshReset: true, + keepOpenShell: true, + }, + { + commandExists: () => true, + env: { HOME: "/tmp/nemoclaw-force-fresh-foreign-container" } as NodeJS.ProcessEnv, + existsSync: () => false, + hasPortableRuntimeCleanup: () => false, + isTty: false, + kill: () => true, + log: () => undefined, + rmSync: vi.fn(), + run: (command, args) => + command === "openshell" && args.join(" ") === "gateway list -o json" + ? ok(JSON.stringify([{ name: "nemoclaw" }])) + : ok(), + runDocker, + }, + ); + + expect(result.exitCode).toBe(1); + expect(calls).toContainEqual(["ps", "-a", "--format", "{{.ID}} {{.Image}} {{.Names}}"]); + expect(calls).not.toContainEqual(["rm", "-f", "foreign-id"]); + expect(calls.some((args) => args[0] === "rmi")).toBe(false); + }); }); diff --git a/src/lib/actions/uninstall/run-plan-homebrew-openshell.test.ts b/src/lib/actions/uninstall/run-plan-homebrew-openshell.test.ts index 40aa566beea..6a859dd4e30 100644 --- a/src/lib/actions/uninstall/run-plan-homebrew-openshell.test.ts +++ b/src/lib/actions/uninstall/run-plan-homebrew-openshell.test.ts @@ -1,9 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { expect, it, vi } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { expect, it, onTestFinished, vi } from "vitest"; import { + preflightForceFreshUserLocalOpenShellOwnership, type RunResult, runUninstallPlan as runUninstallPlanBase, type UninstallRunDeps, @@ -21,9 +25,45 @@ function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } -async function runUninstallPlan(deps: UninstallRunDeps) { +it("rejects an unverified user-local OpenShell binary before cleanup", () => { + const home = "/tmp/nemoclaw-force-fresh-ownership-preflight"; + const target = `${home}/.local/bin/openshell`; + const errors: string[] = []; + + expect( + preflightForceFreshUserLocalOpenShellOwnership({ + env: { HOME: home } as NodeJS.ProcessEnv, + error: (message) => errors.push(message), + existsSync: (candidate) => candidate === target, + isManagedOpenShellBinary: () => false, + }), + ).toBe(false); + expect(errors).toEqual([ + `Force-fresh ownership preflight rejected ${target}: its managed OpenShell install manifest is absent or does not match. No cleanup started.`, + ]); +}); + +it("rejects a malformed managed-install manifest through the canonical parser", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ownership-preflight-")); + onTestFinished(() => fs.rmSync(home, { force: true, recursive: true })); + const userBin = path.join(home, "bin"); + fs.mkdirSync(userBin); + fs.writeFileSync(path.join(userBin, "openshell"), "#!/bin/sh\n", { mode: 0o755 }); + fs.writeFileSync(path.join(userBin, ".nemoclaw-openshell-managed-v1"), "malformed\n", { + mode: 0o600, + }); + + expect( + preflightForceFreshUserLocalOpenShellOwnership({ + env: { HOME: home, XDG_BIN_HOME: userBin } as NodeJS.ProcessEnv, + error: () => undefined, + }), + ).toBe(false); +}); + +async function runUninstallPlan(deps: UninstallRunDeps, forceFreshReset = false) { return await runUninstallPlanBase( - { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { assumeYes: true, deleteModels: false, forceFreshReset, keepOpenShell: false }, { resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ gatewayName, @@ -43,6 +83,8 @@ async function runUninstallPlan(deps: UninstallRunDeps) { async function uninstallOpenShell(options: { brewAvailable: boolean; brewStatus: number | null; + forceFreshReset?: boolean; + managedUserLocal?: boolean; platform?: NodeJS.Platform; }) { const home = "/tmp/nemoclaw-uninstall-test"; @@ -56,28 +98,32 @@ async function uninstallOpenShell(options: { removed.push(target); return ok(); }; - const result = await runUninstallPlan({ - commandExists: (command) => - command === "openshell" || (command === "brew" && options.brewAvailable), - env: { HOME: home } as NodeJS.ProcessEnv, - existsSync: (target) => existing.has(String(target)), - hasPortableRuntimeCleanup: () => false, - isTty: true, - log: (line) => logs.push(line), - platform: options.platform ?? "darwin", - rmSync: vi.fn((target) => remove(String(target))), - run: vi.fn((command, args) => { - calls.push([command, ...args]); - return command === "sudo" && args[0] === "rm" && args[1] === "-f" - ? remove(args[2]) - : command === "openshell" && args[0] === "gateway" && args[1] === "list" - ? ok(JSON.stringify([{ name: "nemoclaw" }])) - : command === "brew" && args[0] === "list" - ? { status: options.brewStatus, stdout: "", stderr: "" } - : ok(); - }), - runDocker: () => ok(), - }); + const result = await runUninstallPlan( + { + commandExists: (command) => + command === "openshell" || (command === "brew" && options.brewAvailable), + env: { HOME: home } as NodeJS.ProcessEnv, + existsSync: (target) => existing.has(String(target)), + hasPortableRuntimeCleanup: () => false, + isManagedOpenShellBinary: () => options.managedUserLocal ?? false, + isTty: true, + log: (line) => logs.push(line), + platform: options.platform ?? "darwin", + rmSync: vi.fn((target) => remove(String(target))), + run: vi.fn((command, args) => { + calls.push([command, ...args]); + return command === "sudo" && args[0] === "rm" && args[1] === "-f" + ? remove(args[2]) + : command === "openshell" && args[0] === "gateway" && args[1] === "list" + ? ok(JSON.stringify([{ name: "nemoclaw" }])) + : command === "brew" && args[0] === "list" + ? { status: options.brewStatus, stdout: "", stderr: "" } + : ok(); + }), + runDocker: () => ok(), + }, + options.forceFreshReset, + ); return { calls, executablePaths, logs, remaining: [...existing], removed, result }; } @@ -98,6 +144,34 @@ it("retains a Homebrew-managed OpenShell and reports its removal command (#8882) ); }); +it("lets force-fresh remove only managed user-local OpenShell binaries", async () => { + const { executablePaths, remaining, removed, result } = await uninstallOpenShell({ + brewAvailable: true, + brewStatus: 0, + forceFreshReset: true, + managedUserLocal: true, + }); + const userLocal = executablePaths.filter((target) => target.includes("/.local/bin/")); + const system = executablePaths.filter((target) => target.startsWith("/usr/local/bin/")); + + expect(result.exitCode).toBe(0); + expect(new Set(removed)).toEqual(new Set(userLocal)); + expect(new Set(remaining)).toEqual(new Set(system)); +}); + +it("retains unverified user-local OpenShell binaries during force-fresh cleanup", async () => { + const { executablePaths, remaining, removed, result } = await uninstallOpenShell({ + brewAvailable: true, + brewStatus: 0, + forceFreshReset: true, + managedUserLocal: false, + }); + + expect(result.exitCode).toBe(0); + expect(removed).toEqual([]); + expect(new Set(remaining)).toEqual(new Set(executablePaths)); +}); + it.each([ { label: "Homebrew is unavailable", diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 961976ba567..918edc7b193 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { SpawnSyncOptions } from "node:child_process"; -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -129,6 +129,7 @@ import { isModelRouterPid, isOllamaAuthProxyPid, pidExists, + removeForceFreshReceiptVolumes, } from "./runtime-commands"; import { buildUninstallPlan, @@ -157,6 +158,7 @@ export interface UninstallRunOptions { assumeYes: boolean; deleteModels: boolean; destroyUserData?: boolean; + forceFreshReset?: boolean; gatewayName?: string; keepOpenShell: boolean; } @@ -172,6 +174,7 @@ export interface UninstallRunDeps { fs?: FileSystemDeps; getTrustedActiveOpenShellGatewayUserServiceIdentity?: typeof getTrustedActiveOpenShellGatewayUserServiceIdentity; isPortFree?: (port: number) => boolean; + isManagedOpenShellBinary?: (target: string, userBin: string) => boolean; isTty?: boolean; kill?: (pid: number, signal?: NodeJS.Signals | number) => boolean; log?: (message: string) => void; @@ -534,6 +537,7 @@ interface UninstallRuntime { existsSync: (target: string) => boolean; getTrustedActiveOpenShellGatewayUserServiceIdentity: typeof getTrustedActiveOpenShellGatewayUserServiceIdentity; isPortFree: ((port: number) => boolean) | undefined; + isManagedOpenShellBinary: (target: string, userBin: string) => boolean; isTty: boolean; kill: (pid: number, signal?: NodeJS.Signals | number) => boolean; log: (message: string) => void; @@ -586,6 +590,8 @@ function buildRuntime(deps: UninstallRunDeps): UninstallRuntime { deps.getTrustedActiveOpenShellGatewayUserServiceIdentity ?? getTrustedActiveOpenShellGatewayUserServiceIdentity, isPortFree: deps.isPortFree, + isManagedOpenShellBinary: + deps.isManagedOpenShellBinary ?? defaultManagedOpenShellBinaryOwnership, // Side-effect-free TTY check + EAGAIN-tolerant reader; the // process.stdin/non-blocking-fd hazard is documented in core/stdin.ts. isTty: deps.isTty ?? isStdinTty(), @@ -854,6 +860,121 @@ function reportRetainedMacOsOpenShell(runtime: UninstallRuntime): void { ); } +const MANAGED_OPENSHELL_INSTALL_MANIFEST = ".nemoclaw-openshell-managed-v1"; +const MANAGED_OPENSHELL_BINARY_NAMES = new Set([ + "openshell", + "openshell-gateway", + "openshell-sandbox", + "openshell-driver-vm", +]); + +function managedOpenShellManifest(userBin: string): ReadonlyMap | null { + let opened: OpenRegularFile | null = null; + try { + opened = openRegularFileNoFollow(path.join(userBin, MANAGED_OPENSHELL_INSTALL_MANIFEST)); + const owner = process.getuid?.(); + const stat = opened.stat(); + if (owner === undefined || stat.uid !== owner || (stat.mode & 0o022) !== 0) return null; + const entries = new Map(); + for (const line of opened.readBytes(2_048).toString("utf8").trim().split(/\r?\n/u)) { + const match = /^([a-f0-9]{64}) (openshell(?:-gateway|-sandbox|-driver-vm)?)$/u.exec(line); + const digest = match?.[1]; + const binary = match?.[2]; + if (!digest || !binary || entries.has(binary)) return null; + entries.set(binary, digest); + } + return entries.size > 0 ? entries : null; + } catch { + return null; + } finally { + opened?.close(); + } +} + +function regularFileSha256(target: string): { digest: string; uid: number } | null { + let opened: OpenRegularFile | null = null; + try { + opened = openRegularFileNoFollow(target); + const stat = opened.stat(); + return { + digest: createHash("sha256") + .update(opened.readBytes(256 * 1024 * 1024)) + .digest("hex"), + uid: stat.uid, + }; + } catch { + return null; + } finally { + opened?.close(); + } +} + +function defaultManagedOpenShellBinaryOwnership(target: string, userBin: string): boolean { + const binary = path.basename(target); + if ( + path.dirname(path.resolve(target)) !== path.resolve(userBin) || + !MANAGED_OPENSHELL_BINARY_NAMES.has(binary) + ) { + return false; + } + const expected = managedOpenShellManifest(userBin)?.get(binary); + const actual = regularFileSha256(target); + const owner = process.getuid?.(); + return Boolean( + expected && actual && owner !== undefined && actual.uid === owner && actual.digest === expected, + ); +} + +export function preflightForceFreshUserLocalOpenShellOwnership( + deps: UninstallRunDeps = {}, +): boolean { + const runtime = buildRuntime(deps); + const userBin = path.resolve( + runtime.env.XDG_BIN_HOME || path.join(runtime.env.HOME || os.homedir(), ".local", "bin"), + ); + let accepted = true; + for (const binary of MANAGED_OPENSHELL_BINARY_NAMES) { + const target = path.join(userBin, binary); + if (!runtime.existsSync(target) || runtime.isManagedOpenShellBinary(target, userBin)) continue; + runtime.error( + `Force-fresh ownership preflight rejected ${target}: its managed OpenShell install manifest is absent or does not match. No cleanup started.`, + ); + accepted = false; + } + return accepted; +} + +function removeForceFreshUserLocalOpenShell( + paths: UninstallPaths, + runtime: UninstallRuntime, +): boolean { + const userBin = path.resolve( + runtime.env.XDG_BIN_HOME || path.join(runtime.env.HOME || os.homedir(), ".local", "bin"), + ); + let removed = 0; + let retained = false; + try { + for (const target of paths.openshellInstallPaths) { + if (path.dirname(path.resolve(target)) !== userBin || !runtime.existsSync(target)) continue; + if (!runtime.isManagedOpenShellBinary(target, userBin)) { + retained = true; + runtime.warn( + `Leaving ${target} in place because its managed OpenShell install manifest is absent or does not match.`, + ); + continue; + } + if (removePath(target, runtime)) removed += 1; + } + if (removed > 0 && !retained) { + removePath(path.join(userBin, MANAGED_OPENSHELL_INSTALL_MANIFEST), runtime); + } + return true; + } catch (error) { + runtime.error(`Could not remove managed user-local OpenShell binaries: ${formatError(error)}`); + return false; + } +} + async function deletePortableOpenShellSandbox( runtime: UninstallRuntime, sandboxName: string, @@ -2258,10 +2379,18 @@ function stopBedrockRuntimeAdapterForUninstall( throw new IncompleteBedrockRuntimeAdapterCleanupError(); } -function removeDockerContainers(runtime: UninstallRuntime, gatewayName?: string): void { +function removeDockerContainers( + runtime: UninstallRuntime, + gatewayName?: string, + allowConventionRemoval = true, +): boolean { const result = runtime.runDocker(["ps", "-a", "--format", "{{.ID}} {{.Image}} {{.Names}}"], { env: runtime.env, }); + if (result.status !== 0) { + runtime.warn("Failed to inventory Docker containers"); + return false; + } const ids = splitNonEmptyLines(result.stdout) .filter((line) => { const fields = dockerInventoryFields(line, 3); @@ -2292,19 +2421,34 @@ function removeDockerContainers(runtime: UninstallRuntime, gatewayName?: string) .map((line) => line.split(/\s+/)[0]); if (ids.length === 0) { runtime.log(`No ${runtimeBranding(runtime).display}/OpenShell Docker containers found`); - return; + return true; + } + if (!allowConventionRemoval) { + runtime.warn( + `Force-fresh cleanup preserved convention-matching Docker container ${ids[0]} because no trusted host state binds that container ID to this installation.`, + ); + return false; } + let removedAll = true; for (const id of [...new Set(ids)]) { if (runtime.runDocker(["rm", "-f", id], { env: runtime.env, stdio: "ignore" }).status === 0) runtime.log(`Removed Docker container ${id}`); - else runtime.warn(`Failed to remove Docker container ${id}`); + else { + runtime.warn(`Failed to remove Docker container ${id}`); + removedAll = false; + } } + return removedAll; } -function removeDockerImages(runtime: UninstallRuntime): void { +function removeDockerImages(runtime: UninstallRuntime): boolean { const result = runtime.runDocker(["images", "--format", "{{.ID}} {{.Repository}}:{{.Tag}}"], { env: runtime.env, }); + if (result.status !== 0) { + runtime.warn("Failed to inventory Docker images"); + return false; + } const ids = splitNonEmptyLines(result.stdout) // `openclaw` is deliberately absent: NemoClaw builds no image under that // name, so the term only ever selected the separate OpenClaw project's @@ -2314,13 +2458,18 @@ function removeDockerImages(runtime: UninstallRuntime): void { .map((line) => line.split(/\s+/)[0]); if (ids.length === 0) { runtime.log(`No ${runtimeBranding(runtime).display}/OpenShell Docker images found`); - return; + return true; } + let removedAll = true; for (const id of [...new Set(ids)]) { if (runtime.runDocker(["rmi", "-f", id], { env: runtime.env, stdio: "ignore" }).status === 0) runtime.log(`Removed Docker image ${id}`); - else runtime.warn(`Failed to remove Docker image ${id}`); + else { + runtime.warn(`Failed to remove Docker image ${id}`); + removedAll = false; + } } + return removedAll; } function dockerInventoryFields(line: string, expectedFields: number): string[] { @@ -2348,18 +2497,97 @@ function isOwnedDockerImageRepository(imageRef: string): boolean { ); } -function removeDockerVolume(name: string, runtime: UninstallRuntime): void { - if ( - runtime.runDocker(["volume", "inspect", name], { env: runtime.env, stdio: "ignore" }).status !== - 0 - ) - return; +function dockerVolumeInspectionProvesAbsence(name: string, result: RunResult): boolean { + if (result.status !== 1 || result.error || result.signal) return false; + const escapedName = name.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); + const detail = `${result.stderr} ${result.stdout}`.trim(); + return [ + new RegExp( + `^(?:(?:Error response from daemon|Error):\\s*)?(?:No such volume|No such object):?\\s*${escapedName}$`, + "iu", + ), + new RegExp( + `^(?:Error response from daemon:\\s*)?get\\s+${escapedName}:\\s*no such volume$`, + "iu", + ), + ].some((pattern) => pattern.test(detail)); +} + +function removeDockerVolume(name: string, runtime: UninstallRuntime): boolean { + const inspection = runtime.runDocker(["volume", "inspect", name], { + env: runtime.env, + stdio: ["ignore", "pipe", "pipe"], + }); + if (inspection.status !== 0) { + if (dockerVolumeInspectionProvesAbsence(name, inspection)) return true; + runtime.warn(`Failed to inspect Docker volume ${name}`); + return false; + } if ( runtime.runDocker(["volume", "rm", "-f", name], { env: runtime.env, stdio: "ignore" }) .status === 0 ) runtime.log(`Removed Docker volume ${name}`); - else runtime.warn(`Failed to remove Docker volume ${name}`); + else { + runtime.warn(`Failed to remove Docker volume ${name}`); + return false; + } + return true; +} + +function executeDockerResourceStep( + options: UninstallRunOptions, + runtime: UninstallRuntime, + scopedToSelectedGateway: boolean, + externallySupervised: boolean, + volumeNames: readonly string[], +): boolean { + if (externallySupervised) { + runtime.log( + "Kept Docker containers, images, and volumes used by the externally supervised gateway.", + ); + return true; + } + if (!dockerIsAvailable(runtime)) { + if (!options.forceFreshReset || !runtime.commandExists("docker")) return true; + runtime.error( + "Docker is installed but unavailable; force-fresh cleanup cannot prove that receipt volumes are absent.", + ); + return false; + } + const removedContainers = removeDockerContainers( + runtime, + scopedToSelectedGateway ? options.gatewayName || resolveGatewayName(GATEWAY_PORT) : undefined, + !options.forceFreshReset, + ); + if (options.forceFreshReset && !removedContainers) { + runtime.error("Force-fresh cleanup found a Docker container without verified ownership."); + return false; + } + let removedImages = true; + if (scopedToSelectedGateway) { + runtime.log("Sibling gateways remain; kept shared Docker images."); + } else if (options.forceFreshReset) { + runtime.log("Kept Docker images because repository naming is not force-fresh ownership proof."); + } else { + removedImages = removeDockerImages(runtime); + } + let removedVolumes = true; + for (const volumeName of volumeNames) { + if (!removeDockerVolume(volumeName, runtime)) removedVolumes = false; + } + if (!options.forceFreshReset) return true; + if (!removedContainers || !removedImages || !removedVolumes) { + runtime.error("Force-fresh cleanup could not remove every required Docker resource."); + return false; + } + if (scopedToSelectedGateway) { + runtime.error( + "Force-fresh cleanup preserved receipt volumes because another gateway environment remains.", + ); + return false; + } + return removeForceFreshReceiptVolumes(runtime); } function parseOllamaModelInventory(output: string): string[] { @@ -4098,25 +4326,18 @@ async function executePreparedPlan( otherGatewayPorts, ); } else if (step.name === "Docker resources") { - if (externallySupervised) { - runtime.log( - "Kept Docker containers, images, and volumes used by the externally supervised gateway.", - ); - } else if (dockerIsAvailable(runtime)) { - removeDockerContainers( + if ( + !executeDockerResourceStep( + options, runtime, - scopedToSelectedGateway - ? options.gatewayName || resolveGatewayName(GATEWAY_PORT) - : undefined, - ); - if (scopedToSelectedGateway) { - runtime.log("Sibling gateways remain; kept shared Docker images."); - } else { - removeDockerImages(runtime); - } - step.actions.forEach((action) => { - if (action.kind === "delete-docker-volume") removeDockerVolume(action.name, runtime); - }); + scopedToSelectedGateway, + externallySupervised, + step.actions.flatMap((action) => + action.kind === "delete-docker-volume" ? [action.name] : [], + ), + ) + ) { + return { ok: false, scopedToSelectedGateway }; } } else if (step.name === "Model stores") { if ( @@ -4136,9 +4357,12 @@ async function executePreparedPlan( for (const pattern of paths.runtimeTempGlobs) removeGlob(pattern, runtime); if (preserveSharedOpenShell) { runtime.log(binaryKeepMessage); - } else if (GATEWAY_PORT !== DEFAULT_GATEWAY_PORT) { + } else if (GATEWAY_PORT !== DEFAULT_GATEWAY_PORT && !options.forceFreshReset) { runtime.log("Keeping OpenShell binaries used by the default gateway service."); } else if (runtime.platform === "darwin") { + if (options.forceFreshReset && !removeForceFreshUserLocalOpenShell(paths, runtime)) { + return { ok: false, scopedToSelectedGateway }; + } reportRetainedMacOsOpenShell(runtime); } else { paths.openshellInstallPaths.forEach((target) => diff --git a/src/lib/actions/uninstall/runtime-commands.ts b/src/lib/actions/uninstall/runtime-commands.ts index a0d3dc97b36..81846e679a6 100644 --- a/src/lib/actions/uninstall/runtime-commands.ts +++ b/src/lib/actions/uninstall/runtime-commands.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { SpawnSyncOptions } from "node:child_process"; + import { createUninstallSandboxLifecycle, createUninstallSandboxObserver, @@ -12,6 +14,7 @@ import { } from "../../domain/uninstall/messaging"; import { isOllamaAuthProxyCommandLine } from "../../inference/ollama/process"; import { isModelRouterCommandLineForPort } from "../../onboard/model-router-process"; +import { MANAGED_STARTUP_RECEIPT_VOLUME_PREFIX } from "../../onboard/managed-startup/docker-receipt-transfer"; interface UninstallRuntimeCommands { env: NodeJS.ProcessEnv; @@ -21,6 +24,53 @@ interface UninstallRuntimeCommands { warn(message: string): void; } +interface ForceFreshDockerCleanupRuntime { + env: NodeJS.ProcessEnv; + error(message: string): void; + log(message: string): void; + runDocker(args: string[], options?: SpawnSyncOptions): RunResult; +} + +const MANAGED_STARTUP_RECEIPT_VOLUME_PATTERN = new RegExp( + `^${MANAGED_STARTUP_RECEIPT_VOLUME_PREFIX}-[0-9a-f]{32}$`, + "u", +); + +function nonEmptyLines(output: string): string[] { + return output + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter(Boolean); +} + +function forceFreshReceiptVolumeMatches(runtime: ForceFreshDockerCleanupRuntime): string[] | null { + const inventory = runtime.runDocker(["volume", "ls", "--format", "{{.Name}}"], { + env: runtime.env, + }); + if (inventory.status !== 0) { + runtime.error( + "Could not inventory managed-startup receipt volumes during force-fresh cleanup.", + ); + return null; + } + return nonEmptyLines(inventory.stdout).filter((name) => + MANAGED_STARTUP_RECEIPT_VOLUME_PATTERN.test(name), + ); +} + +export function removeForceFreshReceiptVolumes(runtime: ForceFreshDockerCleanupRuntime): boolean { + const volumes = forceFreshReceiptVolumeMatches(runtime); + if (volumes === null) return false; + const [unverified] = volumes; + if (unverified) { + runtime.error( + `Preserved managed-startup receipt volume '${unverified}' because its Docker name and mutable label are not trusted ownership proof.`, + ); + return false; + } + return true; +} + export async function deleteSelectedGatewaySandbox( runtime: UninstallRuntimeCommands, gatewayName: string, diff --git a/src/lib/onboard/managed-bootstrap/docker-shared-state-rollback-authority.test.ts b/src/lib/onboard/managed-bootstrap/docker-shared-state-rollback-authority.test.ts index 9b9069d6b0d..a4ac6454c33 100644 --- a/src/lib/onboard/managed-bootstrap/docker-shared-state-rollback-authority.test.ts +++ b/src/lib/onboard/managed-bootstrap/docker-shared-state-rollback-authority.test.ts @@ -279,7 +279,7 @@ describe("Docker managed-bootstrap shared-state rollback authority", () => { expect(volumeCreates).toHaveLength(1); expect(rollbackMount).toMatch( new RegExp( - `^type=volume,src=${String(volumeCreates[0]?.[2])},dst=${path.posix.dirname(MANAGED_STARTUP_SHARED_ROLLBACK_RECEIPT_DIRECTORY)},readonly$`, + `^type=volume,src=${String(volumeCreates[0]?.at(-1))},dst=${path.posix.dirname(MANAGED_STARTUP_SHARED_ROLLBACK_RECEIPT_DIRECTORY)},readonly$`, "u", ), ); diff --git a/src/lib/onboard/managed-startup/docker-receipt-transfer.test.ts b/src/lib/onboard/managed-startup/docker-receipt-transfer.test.ts index ede6497cd79..7ca4dd5c468 100644 --- a/src/lib/onboard/managed-startup/docker-receipt-transfer.test.ts +++ b/src/lib/onboard/managed-startup/docker-receipt-transfer.test.ts @@ -10,6 +10,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { cleanupDockerDaemonReceiptBestEffort, dockerDaemonReceiptMount, + MANAGED_STARTUP_RECEIPT_VOLUME_LABEL, transferDockerReceiptToDaemon, } from "./docker-receipt-transfer"; @@ -51,19 +52,25 @@ describe("Docker daemon receipt transfer", () => { }); expect(calls.map((args) => args[0])).toEqual(["volume", "create", "cp", "rm"]); - expect(calls[1]).toEqual( + const volumeArgs = calls[0] ?? []; + const labelIndex = volumeArgs.indexOf("--label"); + expect(labelIndex).toBeGreaterThanOrEqual(0); + expect(volumeArgs[labelIndex + 1]).toBe(`${MANAGED_STARTUP_RECEIPT_VOLUME_LABEL}=1`); + const seedArgs = calls[1] ?? []; + expect(seedArgs).toEqual( expect.arrayContaining([ "--network", "none", "--read-only", "--user", - "0:0", "--security-opt", "no-new-privileges", "--cap-drop", "ALL", ]), ); + expect(seedArgs.at(seedArgs.indexOf("--user") + 1)).toBe("0"); + expect(seedArgs).not.toContain("0:0"); expect(calls[2]).toEqual( expect.arrayContaining([ "-a", diff --git a/src/lib/onboard/managed-startup/docker-receipt-transfer.ts b/src/lib/onboard/managed-startup/docker-receipt-transfer.ts index addca58147d..907d6dac0e3 100644 --- a/src/lib/onboard/managed-startup/docker-receipt-transfer.ts +++ b/src/lib/onboard/managed-startup/docker-receipt-transfer.ts @@ -10,7 +10,8 @@ import { cleanupTempDir } from "../temp-files"; const RECEIPT_VOLUME_DIRECTORY = "/run/nemoclaw/managed-startup-receipt-transfer"; const RECEIPT_SEED_PREFIX = "nemoclaw-managed-startup-receipt-seed"; -const RECEIPT_VOLUME_PREFIX = "nemoclaw-managed-startup-receipt-volume"; +export const MANAGED_STARTUP_RECEIPT_VOLUME_PREFIX = "nemoclaw-managed-startup-receipt-volume"; +export const MANAGED_STARTUP_RECEIPT_VOLUME_LABEL = "io.nvidia.nemoclaw.managed-startup.receipt"; export type DockerDaemonReceipt = { readonly hostPath: string; @@ -100,12 +101,15 @@ export function transferDockerReceiptToDaemon( options: DockerReceiptTransferOptions, ): DockerDaemonReceipt { const dockerRun = options.dockerRun; - const volumeName = receiptName(RECEIPT_VOLUME_PREFIX); + const volumeName = receiptName(MANAGED_STARTUP_RECEIPT_VOLUME_PREFIX); const seedName = receiptName(RECEIPT_SEED_PREFIX); let volumeCreated = false; let seedCreated = false; try { - const volume = dockerRun(["volume", "create", volumeName], options.dockerOptions); + const volume = dockerRun( + ["volume", "create", "--label", `${MANAGED_STARTUP_RECEIPT_VOLUME_LABEL}=1`, volumeName], + options.dockerOptions, + ); if (!hasZeroDockerExitStatus(volume)) { throw new Error(`Could not create managed-startup receipt volume: ${commandDetail(volume)}`); } @@ -121,7 +125,7 @@ export function transferDockerReceiptToDaemon( "none", "--read-only", "--user", - "0:0", + "0", "--security-opt", "no-new-privileges", "--cap-drop", diff --git a/test/e2e/live/managed-image-multiarch-startup.test.ts b/test/e2e/live/managed-image-multiarch-startup.test.ts index 3d52f079e8d..b6db4e77544 100644 --- a/test/e2e/live/managed-image-multiarch-startup.test.ts +++ b/test/e2e/live/managed-image-multiarch-startup.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; import path from "node:path"; @@ -10,11 +11,16 @@ import { parseProtectedManagedImageContracts, parseProtectedManagedImageEvidence, } from "../../../scripts/checks/protected-managed-image-contract.ts"; +import { + dockerEngine27ReceiptDaemonName, + dockerEngine27ReceiptIdentityArguments, +} from "../../../scripts/checks/docker-engine-27-receipt-transfer-e2e.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import { protectedManagedImageDispatchEnvironment, readRegularArtifact, } from "./managed-image-multiarch-startup-helpers.ts"; +import { trustedShellCommand } from "../fixtures/shell-probe.ts"; test( "binds protected all-agent direct startup to the exact multiarch dispatch (#7744)", @@ -24,10 +30,11 @@ test( "validate protected activation and dispatch identity", "validate exact all-agent managed-image contracts", "validate direct-start evidence binding", + "verify Docker Engine 27 receipt transfer", ], }, }, - ({ progress }) => { + async ({ cleanup, progress, shellProbe }) => { progress.phase("validate protected activation and dispatch identity"); const dispatch = protectedManagedImageDispatchEnvironment(); @@ -56,9 +63,62 @@ test( }, ); + progress.phase("verify Docker Engine 27 receipt transfer"); + const docker27DaemonName = dockerEngine27ReceiptDaemonName( + dispatch.runId, + dispatch.runAttempt, + dispatch.platform, + ); + const docker27IdentityArgs = dockerEngine27ReceiptIdentityArguments( + dispatch.runId, + dispatch.runAttempt, + dispatch.platform, + ); + cleanup.trackDisposable(`remove owned Docker Engine 27 daemon ${docker27DaemonName}`, () => { + execFileSync( + process.execPath, + [ + "--import", + "tsx", + "scripts/checks/docker-engine-27-receipt-transfer-e2e.ts", + "--cleanup-only", + ...docker27IdentityArgs, + ], + { + cwd: dispatch.workspace, + killSignal: "SIGKILL", + stdio: "ignore", + timeout: 90_000, + }, + ); + }); + const docker27Result = await shellProbe.run( + trustedShellCommand({ + command: process.execPath, + args: [ + "--import", + "tsx", + "scripts/checks/docker-engine-27-receipt-transfer-e2e.ts", + ...docker27IdentityArgs, + ], + reason: "verify the Docker Engine 27 receipt archive-copy boundary", + }), + { + artifactName: "docker-engine-27-receipt-transfer", + cwd: dispatch.workspace, + env: { + ...(process.env.DOCKER_CONFIG ? { DOCKER_CONFIG: process.env.DOCKER_CONFIG } : {}), + ...(process.env.HOME ? { HOME: process.env.HOME } : {}), + }, + timeoutMs: 30 * 60_000, + }, + ); + expect( - evidence.contractSha256 === - `sha256:${createHash("sha256").update(contractBytes).digest("hex")}` && + docker27Result.exitCode === 0 && + !docker27Result.timedOut && + evidence.contractSha256 === + `sha256:${createHash("sha256").update(contractBytes).digest("hex")}` && JSON.stringify(evidence.contracts) === JSON.stringify(contracts), ).toBe(true); }, diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 0aecb3f7a85..6ccb4fe503c 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -37,6 +37,7 @@ }, { "live": "test/e2e/live/managed-image-multiarch-startup.test.ts", + "liveSources": ["test/e2e/live/managed-image-multiarch-startup-helpers.ts"], "fast": [ "test/e2e/support/base-image-publication.test.ts", "test/e2e/support/managed-image-multiarch-startup-helpers.test.ts", diff --git a/test/e2e/support/managed-image-multiarch-startup-helpers.test.ts b/test/e2e/support/managed-image-multiarch-startup-helpers.test.ts index 76cf813d7e9..9b44d27e858 100644 --- a/test/e2e/support/managed-image-multiarch-startup-helpers.test.ts +++ b/test/e2e/support/managed-image-multiarch-startup-helpers.test.ts @@ -7,6 +7,15 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + DOCKER_ENGINE_27_MINIMUM_CLEANUP_PROCESS_TIMEOUT_MS, + DOCKER_ENGINE_27_MINIMUM_PROBE_TIMEOUT_MS, + dockerEngine27ReceiptDaemonName, + dockerEngine27ReceiptIdentityArguments, + finalizeDockerEngine27ReceiptProbe, + requireDockerResourceAbsent, + validateDockerEngine27SeedIsolation, +} from "../../../scripts/checks/docker-engine-27-receipt-transfer-e2e.ts"; import { protectedManagedImageDispatchEnvironment, readRegularArtifact, @@ -38,6 +47,113 @@ afterEach(() => { }); describe("protected managed-image startup helpers", () => { + it("preserves the probe failure and attempts fixture cleanup after daemon cleanup fails", () => { + const cleanupFixture = vi.fn(); + + expect(() => + finalizeDockerEngine27ReceiptProbe( + new Error("receipt transfer failed"), + () => { + throw new Error("daemon cleanup failed"); + }, + cleanupFixture, + ), + ).toThrow(/receipt transfer failed.*daemon cleanup failed/u); + expect(cleanupFixture).toHaveBeenCalledOnce(); + }); + + it("derives one Docker 27 identity for probe and cleanup on each matrix platform", () => { + const amd64 = dockerEngine27ReceiptDaemonName(123, 4, "linux/amd64"); + const arm64 = dockerEngine27ReceiptDaemonName(123, 4, "linux/arm64"); + const sharedIdentity = dockerEngine27ReceiptIdentityArguments(123, 4, "linux/amd64"); + const probeArgs = ["docker-engine-27-receipt-transfer-e2e.ts", ...sharedIdentity]; + const cleanupArgs = [ + "docker-engine-27-receipt-transfer-e2e.ts", + "--cleanup-only", + ...sharedIdentity, + ]; + + expect(amd64).toBe("nemoclaw-receipt-engine27-123-4-linux-amd64"); + expect(arm64).toBe("nemoclaw-receipt-engine27-123-4-linux-arm64"); + expect(amd64).not.toBe(arm64); + expect(cleanupArgs.filter((arg) => arg !== "--cleanup-only")).toEqual(probeArgs); + expect(sharedIdentity).toEqual([ + "--run-id", + "123", + "--run-attempt", + "4", + "--platform", + "linux/amd64", + ]); + }); + + it("bounds the complete Docker 27 probe and external cleanup", () => { + expect(30 * 60_000).toBeGreaterThanOrEqual(DOCKER_ENGINE_27_MINIMUM_PROBE_TIMEOUT_MS); + expect(90_000).toBeGreaterThanOrEqual(DOCKER_ENGINE_27_MINIMUM_CLEANUP_PROCESS_TIMEOUT_MS); + }); + + it("requires numeric root and every receipt seed isolation control", () => { + const secureSeed = { + Config: { User: "0" }, + HostConfig: { + CapDrop: ["ALL"], + Mounts: [ + { + Type: "volume", + Target: "/run/nemoclaw/managed-startup-receipt-transfer", + }, + ], + NetworkMode: "none", + Privileged: false, + ReadonlyRootfs: true, + SecurityOpt: ["no-new-privileges"], + }, + }; + + expect(() => validateDockerEngine27SeedIsolation(secureSeed)).not.toThrow(); + expect(() => + validateDockerEngine27SeedIsolation({ ...secureSeed, Config: { User: "0:0" } }), + ).toThrow("receipt seed did not use numeric root"); + expect(() => + validateDockerEngine27SeedIsolation({ + ...secureSeed, + HostConfig: { ...secureSeed.HostConfig, Privileged: true }, + }), + ).toThrow("receipt seed was privileged"); + expect(() => + validateDockerEngine27SeedIsolation({ + ...secureSeed, + HostConfig: { ...secureSeed.HostConfig, CapDrop: [] }, + }), + ).toThrow("receipt seed retained capabilities"); + }); + + it("proves cleanup only from Docker's explicit absence response", () => { + expect(() => + requireDockerResourceAbsent( + { status: 1, stderr: "Error: No such container: receipt-seed", stdout: "" }, + "receipt seed", + ), + ).not.toThrow(); + expect(() => + requireDockerResourceAbsent( + { + error: new Error("spawnSync docker ETIMEDOUT"), + status: null, + stderr: "", + stdout: "", + }, + "receipt seed", + ), + ).toThrow("receipt seed absence was not proven"); + expect(() => + requireDockerResourceAbsent( + { status: 1, stderr: "permission denied", stdout: "" }, + "receipt seed", + ), + ).toThrow("receipt seed absence was not proven"); + }); + it("parses exact protected dispatch identity", () => { expect(protectedManagedImageDispatchEnvironment()).toMatchObject({ baseSha: sha, diff --git a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts index c188bb6dbdc..9ad0ea04bf0 100644 --- a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts +++ b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts @@ -100,6 +100,16 @@ describe("protected managed-image runtime workflow", () => { expect(validateManagedImageProtectedRuntimeWorkflow(value)).toEqual([]); }); + it("requires cancellation cleanup for the derived Docker Engine 27 receipt daemon", () => { + const value = workflow(); + const cleanup = namedMultiarchStep(value, "Remove owned Docker Engine 27 receipt daemon"); + cleanup.if = "${{ !cancelled() }}"; + + expect(validateManagedImageMultiarchWorkflow(value)).toContain( + "managed-image-multiarch-startup Docker Engine 27 receipt daemon cleanup must always run", + ); + }); + // source-shape-contract: security -- The direct runner imports candidate shared modules and must not use stale build output it("builds the candidate shared boundary before direct managed-image contracts", () => { const value = workflow(); diff --git a/test/install/install-preexisting-sandbox-recovery.test.ts b/test/install/install-preexisting-sandbox-recovery.test.ts index d0625795551..ab49cddd18a 100644 --- a/test/install/install-preexisting-sandbox-recovery.test.ts +++ b/test/install/install-preexisting-sandbox-recovery.test.ts @@ -38,6 +38,7 @@ function runRecoveryBeforeOnboard( options: { detectedExpressPlatform?: string; dockerContext?: string; + dockerContextEndpoint?: string; dockerHost?: string; hostPreflightExitCode?: number; includeNodeOnPath?: boolean; @@ -185,6 +186,14 @@ exit 0 [[ "$*" == "info --format {{.Host.RemoteSocket.Path}}" ]] || return 99 printf '%s\n' "$PODMAN_SOCKET" } + docker() { + if [[ "\${1:-}" == "context" && "\${2:-}" == "inspect" ]]; then + [[ -n "$DOCKER_CONTEXT_ENDPOINT" ]] || return 1 + printf '%s\n' "$DOCKER_CONTEXT_ENDPOINT" + return 0 + fi + return 99 + } sleep() { printf 'sleep=%s\n' "$*" >> "${callLog}"; } step() { :; } install_nodejs() { @@ -221,6 +230,7 @@ exit 0 extraEnv: { DETECTED_EXPRESS_PLATFORM: options.detectedExpressPlatform ?? "", ...(options.dockerContext !== undefined ? { DOCKER_CONTEXT: options.dockerContext } : {}), + DOCKER_CONTEXT_ENDPOINT: options.dockerContextEndpoint ?? "", ...(dockerConfig === undefined ? {} : { DOCKER_CONFIG: dockerConfig }), ...(options.dockerHost !== undefined ? { DOCKER_HOST: options.dockerHost } : {}), NEMOCLAW_RESTORE_LATEST_BACKUP_ON_RECREATE: "1", @@ -277,6 +287,19 @@ describe("install.sh pre-existing sandbox recovery ordering (#6114)", () => { expect(result.output).toContain("Existing sandboxes recovered; skipping generic onboarding"); }); + it("resolves a persisted local Colima context to its Unix socket", () => { + const result = runRecoveryBeforeOnboard(2, 0, { + dockerContextEndpoint: "unix:///Users/test/.colima/default/docker.sock", + persistedDockerContext: "colima", + recordRuntimeTarget: true, + }); + + expect(result.status, result.output).toBe(0); + expect(result.calls).toContain( + "cli-target=host:unix:///Users/test/.colima/default/docker.sock,context:unset argv=upgrade-sandboxes --auto", + ); + }); + it("treats a whitespace-only Docker host as unset", () => { const result = runRecoveryBeforeOnboard(2, 0, { dockerHost: " \t ", @@ -312,6 +335,20 @@ describe("install.sh pre-existing sandbox recovery ordering (#6114)", () => { expect(result.output).not.toContain("Docker context does not select the local default target"); }); + it("keeps a deferred persisted Colima socket authoritative during recovery", () => { + const result = runRecoveryBeforeOnboard(2, 0, { + dockerContextEndpoint: "unix:///Users/test/.colima/default/docker.sock", + includeNodeOnPath: false, + persistedDockerContext: "colima", + recordRuntimeTarget: true, + }); + + expect(result.status, result.output).toBe(0); + expect(result.calls).toContain( + "cli-target=host:unix:///Users/test/.colima/default/docker.sock,context:unset argv=upgrade-sandboxes --auto", + ); + }); + it("rejects a deferred remote Docker context before recovery", () => { const result = runRecoveryBeforeOnboard(2, 0, { includeNodeOnPath: false, @@ -329,7 +366,7 @@ describe("install.sh pre-existing sandbox recovery ordering (#6114)", () => { expect(result.calls).not.toContain( 'restore=1 confirmed=["legacy-box"] argv=upgrade-sandboxes --auto', ); - expect(result.output).toContain("Docker context does not select the local default target"); + expect(result.output).toContain("Docker context does not select a supported local Unix socket"); }); it.each([ @@ -388,8 +425,7 @@ describe("install.sh pre-existing sandbox recovery ordering (#6114)", () => { expect(result.status).toBe(1); expect(result.calls).toEqual([]); - expect(result.output).toContain("Docker context does not select the local default target"); - expect(result.output).toContain("docker context use default"); + expect(result.output).toContain("Docker context does not select a supported local Unix socket"); }); it("rejects a non-local Podman socket before sandbox recovery", () => { diff --git a/test/installer-integration/install-downgrade-guard.test.ts b/test/installer-integration/install-downgrade-guard.test.ts index 805aa85a1fb..e7045b7947a 100644 --- a/test/installer-integration/install-downgrade-guard.test.ts +++ b/test/installer-integration/install-downgrade-guard.test.ts @@ -228,6 +228,18 @@ describe("public installer downgrade guard", () => { expect(fs.existsSync(payloadMarker)).toBe(false); }); + it("keeps the installed CLI when force-fresh would implicitly downgrade lkg", () => { + const { result, payloadMarker } = runInstall("0.0.118", "0.0.109", { + NEMOCLAW_FORCE_FRESH_INSTALL: "1", + }); + + 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([ ["Hermes", "hermes"], ["Deep Agents", "langchain-deepagents-code"], diff --git a/test/installer-integration/install-force-fresh.test.ts b/test/installer-integration/install-force-fresh.test.ts new file mode 100644 index 00000000000..dc4bfac85c5 --- /dev/null +++ b/test/installer-integration/install-force-fresh.test.ts @@ -0,0 +1,818 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { expect, it, onTestFinished } from "vitest"; + +import { createInstallerCheckout, runInstallerSourcedBody } from "../helpers/installer-run-fixture"; +import { + INSTALLER_PAYLOAD, + TEST_SYSTEM_PATH, + writeExecutable, +} from "../helpers/installer-sourced-env"; + +const INSTALLER = path.join(import.meta.dirname, "../..", "install.sh"); + +function installerCheckout(prefix: string) { + const checkout = createInstallerCheckout(prefix); + onTestFinished(() => checkout.remove()); + return checkout; +} + +function callPayloadFunction(command: string, env: Record = {}) { + return spawnSync("bash", ["-c", `source "${INSTALLER_PAYLOAD}" 2>/dev/null; ${command}`], { + cwd: path.join(import.meta.dirname, "../.."), + encoding: "utf-8", + env: { + HOME: os.tmpdir(), + PATH: TEST_SYSTEM_PATH, + ...env, + }, + }); +} + +function processExists(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +it.each([ + ["public bootstrap", INSTALLER], + ["versioned payload", INSTALLER_PAYLOAD], +])( + "documents the Apple silicon macOS-only destructive option in the %s help", + (_surface, installer) => { + const result = spawnSync("bash", [installer, "--help"], { + cwd: path.join(import.meta.dirname, "../.."), + encoding: "utf-8", + }); + + expect(result.status).toBe(0); + const output = `${result.stdout}${result.stderr}`; + expect(output).toMatch(/--force-fresh-install .*Apple silicon macOS only/u); + expect(output).toMatch(/NEMOCLAW_FORCE_FRESH_INSTALL=1 .*Apple silicon macOS only/u); + }, +); + +it("detects a Homebrew-only OpenShell installation", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout("nemoclaw-force-fresh-detect-"); + writeExecutable( + path.join(fakeBin, "brew"), + `#!/usr/bin/env bash +if [ "$*" = "list --formula nvidia/openshell/openshell" ]; then exit 0; fi +exit 1 +`, + ); + + const result = callPayloadFunction("force_fresh_install_has_existing_state && printf 'present'", { + HOME: tmp, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + }); + + expect(result.status).toBe(0); + expect(result.stdout).toBe("present"); +}); + +it("stops before cleanup for a label-only Docker container without trusted state", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout("nemoclaw-force-fresh-detect-docker-"); + const cleanupMarker = path.join(tmp, "cleanup-started"); + writeExecutable( + path.join(fakeBin, "docker"), + `#!/usr/bin/env bash +case "$*" in + info) exit 0 ;; + "ps -aq --filter label=io.nvidia.nemoclaw.managed-image.contract=1") printf '0123456789ab\n' ;; + "ps -a --format {{.ID}} {{.Image}} {{.Names}}") + printf '0123456789ab registry.example.com/unrelated:latest arbitrary-name\n' + ;; + "volume ls --format {{.Name}}") exit 0 ;; + *) exit 1 ;; +esac +`, + ); + + const result = callPayloadFunction( + ` + warn() { :; } + prepare_force_fresh_uninstaller() { touch "$CLEANUP_MARKER"; } + run_force_fresh_uninstaller() { touch "$CLEANUP_MARKER"; } + remove_macos_openshell_for_force_fresh_install() { touch "$CLEANUP_MARKER"; } + run_force_fresh_install_reset + `, + { + CLEANUP_MARKER: cleanupMarker, + HOME: tmp, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain("unverified Docker container 0123456789ab"); + expect(fs.existsSync(cleanupMarker)).toBe(false); +}); + +it("stops before cleanup for a convention-matching Docker-only container", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout("nemoclaw-force-fresh-ignore-docker-"); + const cleanupMarker = path.join(tmp, "cleanup-started"); + writeExecutable( + path.join(fakeBin, "docker"), + `#!/usr/bin/env bash +case "$*" in + info) exit 0 ;; + "ps -aq --filter label=io.nvidia.nemoclaw.managed-image.contract=1") exit 0 ;; + "ps -a --format {{.ID}} {{.Image}} {{.Names}}") + printf 'fedcba987654 redis:7 openshell-orphan\n' + ;; + "volume ls --format {{.Name}}") exit 0 ;; + *) exit 1 ;; +esac +`, + ); + + const result = callPayloadFunction( + ` + warn() { :; } + prepare_force_fresh_uninstaller() { touch "$CLEANUP_MARKER"; } + run_force_fresh_uninstaller() { touch "$CLEANUP_MARKER"; } + remove_macos_openshell_for_force_fresh_install() { touch "$CLEANUP_MARKER"; } + run_force_fresh_install_reset + `, + { + CLEANUP_MARKER: cleanupMarker, + HOME: tmp, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain("unverified Docker container fedcba987654"); + expect(fs.existsSync(cleanupMarker)).toBe(false); +}); + +it("stops before cleanup for a labelled receipt-volume-only state", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout("nemoclaw-force-fresh-receipt-detect-"); + const cleanupMarker = path.join(tmp, "cleanup-started"); + const receiptVolume = "nemoclaw-managed-startup-receipt-volume-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + writeExecutable( + path.join(fakeBin, "docker"), + `#!/usr/bin/env bash +case "$*" in + info) exit 0 ;; + "ps -aq --filter label=io.nvidia.nemoclaw.managed-image.contract=1") exit 0 ;; + "ps -a --format {{.ID}} {{.Image}} {{.Names}}") exit 0 ;; + "volume ls --format {{.Name}}") printf '%s\n' "$RECEIPT_VOLUME" ;; + *) exit 1 ;; +esac +`, + ); + + const result = callPayloadFunction( + ` + warn() { :; } + remove_macos_openshell_for_force_fresh_install() { touch "$CLEANUP_MARKER"; } + prepare_force_fresh_uninstaller() { touch "$CLEANUP_MARKER"; } + run_force_fresh_install_reset + `, + { + CLEANUP_MARKER: cleanupMarker, + HOME: tmp, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + RECEIPT_VOLUME: receiptVolume, + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `unverified receipt volume ${receiptVolume}`, + ); + expect(fs.existsSync(cleanupMarker)).toBe(false); +}); + +it("stops before cleanup for an unlabelled receipt-volume-only state", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout("nemoclaw-force-fresh-legacy-receipt-"); + const cleanupMarker = path.join(tmp, "cleanup-started"); + const legacyVolume = "nemoclaw-managed-startup-receipt-volume-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + writeExecutable( + path.join(fakeBin, "docker"), + `#!/usr/bin/env bash +case "$*" in + info) exit 0 ;; + "ps -aq --filter label=io.nvidia.nemoclaw.managed-image.contract=1") exit 0 ;; + "ps -a --format {{.ID}} {{.Image}} {{.Names}}") exit 0 ;; + "volume ls --format {{.Name}}") printf '%s\n' "$LEGACY_VOLUME" ;; + *) + if [[ "$1" == "volume" && "$2" == "inspect" ]]; then + printf '\n' + exit 0 + fi + exit 1 + ;; +esac +`, + ); + + const result = callPayloadFunction( + ` + warn() { :; } + remove_macos_openshell_for_force_fresh_install() { touch "$CLEANUP_MARKER"; } + prepare_force_fresh_uninstaller() { touch "$CLEANUP_MARKER"; } + run_force_fresh_install_reset + `, + { + CLEANUP_MARKER: cleanupMarker, + HOME: tmp, + LEGACY_VOLUME: legacyVolume, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain(`unverified receipt volume ${legacyVolume}`); + expect(fs.existsSync(cleanupMarker)).toBe(false); +}); + +it("stops before cleanup when local state exists but Docker is unavailable", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout( + "nemoclaw-force-fresh-docker-unavailable-", + ); + const cleanupMarker = path.join(tmp, "cleanup-started"); + fs.mkdirSync(path.join(tmp, ".config", "nemoclaw"), { recursive: true }); + writeExecutable(path.join(fakeBin, "docker"), "#!/usr/bin/env bash\nexit 1\n"); + + const result = callPayloadFunction( + ` + warn() { :; } + remove_macos_openshell_for_force_fresh_install() { touch "$CLEANUP_MARKER"; } + prepare_force_fresh_uninstaller() { touch "$CLEANUP_MARKER"; } + run_force_fresh_install_reset + `, + { + CLEANUP_MARKER: cleanupMarker, + HOME: tmp, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain("Docker is installed but unavailable"); + expect(fs.existsSync(cleanupMarker)).toBe(false); +}); + +it("runs destructive cleanup through the staged candidate CLI", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout("nemoclaw-force-fresh-cli-"); + const logPath = path.join(tmp, "node.log"); + const sourceRoot = path.join(tmp, "candidate"); + fs.mkdirSync(path.join(sourceRoot, "bin"), { recursive: true }); + fs.writeFileSync(path.join(sourceRoot, "bin", "nemoclaw.js"), "// staged candidate\n"); + writeExecutable( + path.join(fakeBin, "node"), + `#!/usr/bin/env bash +printf 'destroy=%s args=%s\n' "\${NEMOCLAW_UNINSTALL_DESTROY_USER_DATA:-}" "$*" >> "$FORCE_FRESH_LOG" +`, + ); + + const result = callPayloadFunction(`run_force_fresh_uninstaller ${JSON.stringify(sourceRoot)}`, { + FORCE_FRESH_LOG: logPath, + HOME: tmp, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + }); + + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(fs.readFileSync(logPath, "utf-8")).toBe( + `destroy= args=${path.join(sourceRoot, "bin", "nemoclaw.js")} internal uninstall run-plan --force-fresh-ownership-preflight\n` + + `destroy=1 args=${path.join(sourceRoot, "bin", "nemoclaw.js")} internal uninstall run-plan --yes --destroy-user-data --force-fresh-reset --all-gateway-ports\n`, + ); +}); + +it("records digest ownership after a verified managed user-local OpenShell install", () => { + const { root: tmp } = installerCheckout("nemoclaw-force-fresh-openshell-manifest-"); + const localBin = path.join(tmp, ".local", "bin"); + fs.mkdirSync(localBin, { recursive: true }); + const openshellSource = "#!/usr/bin/env bash\nprintf 'openshell 0.0.116\\n'\n"; + const gatewaySource = "#!/usr/bin/env bash\nexit 0\n"; + const sandboxSource = "#!/usr/bin/env bash\nprintf 'sandbox\\n'\n"; + const driverSource = "#!/usr/bin/env bash\nprintf 'driver\\n'\n"; + writeExecutable(path.join(localBin, "openshell"), openshellSource); + writeExecutable(path.join(localBin, "openshell-gateway"), gatewaySource); + writeExecutable(path.join(localBin, "openshell-sandbox"), sandboxSource); + writeExecutable(path.join(localBin, "openshell-driver-vm"), driverSource); + + const result = callPayloadFunction("record_managed_user_local_openshell_install", { + HOME: tmp, + XDG_BIN_HOME: localBin, + }); + const manifest = fs.readFileSync(path.join(localBin, ".nemoclaw-openshell-managed-v1"), "utf8"); + + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(manifest.trim().split("\n")).toEqual([ + `${createHash("sha256").update(openshellSource).digest("hex")} openshell`, + `${createHash("sha256").update(gatewaySource).digest("hex")} openshell-gateway`, + `${createHash("sha256").update(sandboxSource).digest("hex")} openshell-sandbox`, + `${createHash("sha256").update(driverSource).digest("hex")} openshell-driver-vm`, + ]); +}); + +it("stops when the staged candidate uninstaller fails", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout("nemoclaw-force-fresh-failure-"); + const sourceRoot = path.join(tmp, "candidate"); + fs.mkdirSync(path.join(sourceRoot, "bin"), { recursive: true }); + fs.writeFileSync(path.join(sourceRoot, "bin", "nemoclaw.js"), "// staged candidate\n"); + writeExecutable(path.join(fakeBin, "node"), "#!/usr/bin/env bash\nexit 9\n"); + + const result = callPayloadFunction(`run_force_fresh_uninstaller ${JSON.stringify(sourceRoot)}`, { + HOME: tmp, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + }); + + expect(result.status).not.toBe(0); +}); + +it("removes only Homebrew after the canonical uninstaller handles user-local binaries", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout("nemoclaw-force-fresh-brew-"); + const localBin = path.join(tmp, ".local", "bin"); + const logPath = path.join(tmp, "brew.log"); + fs.mkdirSync(localBin, { recursive: true }); + writeExecutable(path.join(localBin, "openshell"), "#!/usr/bin/env bash\nexit 0\n"); + writeExecutable(path.join(localBin, "openshell-gateway"), "#!/usr/bin/env bash\nexit 0\n"); + writeExecutable(path.join(localBin, "openshell-sandbox"), "#!/usr/bin/env bash\nexit 0\n"); + writeExecutable(path.join(localBin, "openshell-driver-vm"), "#!/usr/bin/env bash\nexit 0\n"); + writeExecutable( + path.join(fakeBin, "brew"), + `#!/usr/bin/env bash +printf '%s\n' "$*" >> "$FORCE_FRESH_LOG" +exit 0 +`, + ); + + const result = callPayloadFunction("remove_macos_openshell_for_force_fresh_install", { + FORCE_FRESH_LOG: logPath, + HOME: tmp, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + }); + + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(fs.readFileSync(logPath, "utf-8").trim().split("\n")).toEqual([ + "list --formula nvidia/openshell/openshell", + "services stop nvidia/openshell/openshell", + "uninstall --force nvidia/openshell/openshell", + ]); + expect(fs.existsSync(path.join(localBin, "openshell"))).toBe(true); + expect(fs.existsSync(path.join(localBin, "openshell-gateway"))).toBe(true); + expect(fs.existsSync(path.join(localBin, "openshell-sandbox"))).toBe(true); + expect(fs.existsSync(path.join(localBin, "openshell-driver-vm"))).toBe(true); +}, 30_000); + +it("stops when Homebrew cannot remove OpenShell", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout("nemoclaw-force-fresh-brew-fail-"); + writeExecutable( + path.join(fakeBin, "brew"), + `#!/usr/bin/env bash +if [ "$1" = "list" ]; then exit 0; fi +if [ "$1" = "services" ]; then exit 0; fi +exit 7 +`, + ); + + const result = callPayloadFunction("remove_macos_openshell_for_force_fresh_install", { + HOME: tmp, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + }); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain("Homebrew could not remove OpenShell"); +}); + +it.each(["openshell", "openshell-gateway", "openshell-sandbox", "openshell-driver-vm"])( + "rejects a remaining %s executable outside managed and Homebrew paths", + (binary) => { + const { root: tmp, binDir: fakeBin } = installerCheckout("nemoclaw-force-fresh-foreign-bin-"); + const foreignBin = path.join(tmp, "foreign", "bin"); + fs.mkdirSync(foreignBin, { recursive: true }); + writeExecutable(path.join(foreignBin, binary), "#!/usr/bin/env bash\nexit 0\n"); + + const result = callPayloadFunction("remove_macos_openshell_for_force_fresh_install", { + HOME: tmp, + PATH: `${foreignBin}:${fakeBin}:${TEST_SYSTEM_PATH}`, + }); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `remaining OpenShell executable at ${path.join(foreignBin, binary)}`, + ); + }, +); + +it("rejects a foreign OpenShell executable before staged cleanup begins", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout( + "nemoclaw-force-fresh-foreign-preflight-", + ); + const foreignBin = path.join(tmp, "foreign", "bin"); + const cleanupMarker = path.join(tmp, "cleanup-started"); + fs.mkdirSync(foreignBin, { recursive: true }); + writeExecutable(path.join(foreignBin, "openshell-sandbox"), "#!/usr/bin/env bash\nexit 0\n"); + + const result = callPayloadFunction( + ` + warn() { :; } + prepare_force_fresh_uninstaller() { touch "$CLEANUP_MARKER"; } + run_force_fresh_uninstaller() { touch "$CLEANUP_MARKER"; } + remove_macos_openshell_for_force_fresh_install() { touch "$CLEANUP_MARKER"; } + run_force_fresh_install_reset + `, + { + CLEANUP_MARKER: cleanupMarker, + HOME: tmp, + PATH: `${foreignBin}:${fakeBin}:${TEST_SYSTEM_PATH}`, + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `unverified OpenShell executable at ${path.join(foreignBin, "openshell-sandbox")}`, + ); + expect(fs.existsSync(cleanupMarker)).toBe(false); +}); + +it("runs cleanup before selecting fresh onboarding", () => { + const result = callPayloadFunction(` + warn() { :; } + info() { :; } + force_fresh_install_has_existing_state() { return 0; } + force_fresh_install_source_root() { printf '/tmp/staged-candidate'; } + prepare_force_fresh_uninstaller() { printf 'prepare:%s\\n' "$1"; } + run_force_fresh_uninstaller() { printf 'uninstall:%s\\n' "$1"; } + remove_macos_openshell_for_force_fresh_install() { printf 'openshell-reset\\n'; } + run_force_fresh_install_reset + printf 'fresh=%s env=%s reinstall=%s count=%s\\n' "$FRESH" "$NEMOCLAW_FRESH" "$NEMOCLAW_REINSTALL_CLI" "$_PREEXISTING_SANDBOX_COUNT" + `); + + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "prepare:/tmp/staged-candidate", + "uninstall:/tmp/staged-candidate", + "openshell-reset", + "fresh=1 env=1 reinstall=1 count=0", + ]); +}); + +it.each(["openshell-gateway", "openshell-sandbox", "openshell-driver-vm"])( + "routes a standalone %s helper through canonical cleanup", + (binary) => { + const { root: tmp } = installerCheckout("nemoclaw-force-fresh-helper-detect-"); + const localBin = path.join(tmp, ".local", "bin"); + fs.mkdirSync(localBin, { recursive: true }); + writeExecutable(path.join(localBin, binary), "#!/usr/bin/env bash\nexit 0\n"); + + const result = callPayloadFunction( + "force_fresh_install_has_existing_state && printf 'present'", + { HOME: tmp }, + ); + + expect(result.status).toBe(0); + expect(result.stdout).toBe("present"); + }, +); + +it("routes a managed helper from XDG_BIN_HOME through the staged uninstaller", () => { + const { root: tmp } = installerCheckout("nemoclaw-force-fresh-xdg-helper-detect-"); + const userBin = path.join(tmp, "xdg-bin"); + const helperSource = "#!/usr/bin/env bash\nprintf 'sandbox\\n'\n"; + fs.mkdirSync(userBin, { recursive: true }); + writeExecutable(path.join(userBin, "openshell-sandbox"), helperSource); + fs.writeFileSync( + path.join(userBin, ".nemoclaw-openshell-managed-v1"), + `${createHash("sha256").update(helperSource).digest("hex")} openshell-sandbox\n`, + { mode: 0o600 }, + ); + + const result = callPayloadFunction( + ` + warn() { :; } + force_fresh_install_source_root() { printf '/tmp/staged-candidate'; } + prepare_force_fresh_uninstaller() { printf 'prepare:%s\\n' "$1"; } + run_force_fresh_uninstaller() { printf 'uninstall:%s\\n' "$1"; } + remove_macos_openshell_for_force_fresh_install() { :; } + run_force_fresh_install_reset + `, + { HOME: tmp, XDG_BIN_HOME: userBin }, + ); + + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "prepare:/tmp/staged-candidate", + "uninstall:/tmp/staged-candidate", + ]); +}); + +it("lets the staged uninstaller reject a malformed ownership manifest before package removal", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout( + "nemoclaw-force-fresh-malformed-manifest-", + ); + const userBin = path.join(tmp, "xdg-bin"); + const packageMarker = path.join(tmp, "package-removal-started"); + const preflightLog = path.join(tmp, "preflight.log"); + const sourceRoot = path.join(tmp, "candidate"); + fs.mkdirSync(path.join(sourceRoot, "bin"), { recursive: true }); + fs.writeFileSync(path.join(sourceRoot, "bin", "nemoclaw.js"), "// staged candidate\n"); + fs.mkdirSync(userBin, { recursive: true }); + writeExecutable(path.join(userBin, "openshell"), "#!/usr/bin/env bash\nexit 0\n"); + fs.writeFileSync(path.join(userBin, ".nemoclaw-openshell-managed-v1"), "malformed\n", { + mode: 0o600, + }); + writeExecutable( + path.join(fakeBin, "node"), + `#!/usr/bin/env bash +printf '%s\n' "$*" > "$PREFLIGHT_LOG" +case "$*" in + *--force-fresh-ownership-preflight) exit 9 ;; + *) touch "$PACKAGE_MARKER"; exit 0 ;; +esac +`, + ); + + const result = callPayloadFunction( + ` + warn() { :; } + force_fresh_install_source_root() { printf '%s' "$SOURCE_ROOT"; } + prepare_force_fresh_uninstaller() { :; } + remove_macos_openshell_for_force_fresh_install() { touch "$PACKAGE_MARKER"; } + run_force_fresh_install_reset + `, + { + HOME: tmp, + PACKAGE_MARKER: packageMarker, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + PREFLIGHT_LOG: preflightLog, + SOURCE_ROOT: sourceRoot, + XDG_BIN_HOME: userBin, + }, + ); + + expect(result.status).not.toBe(0); + expect(fs.readFileSync(preflightLog, "utf8")).toContain( + "internal uninstall run-plan --force-fresh-ownership-preflight", + ); + expect(fs.existsSync(packageMarker)).toBe(false); +}); + +it("stops before package removal when managed uninstall rejects partial state", () => { + const result = callPayloadFunction(` + warn() { :; } + info() { :; } + force_fresh_install_has_existing_state() { return 0; } + force_fresh_install_source_root() { printf '/tmp/staged-candidate'; } + prepare_force_fresh_uninstaller() { :; } + run_force_fresh_uninstaller() { return 9; } + remove_macos_openshell_for_force_fresh_install() { printf 'openshell-reset\\n'; } + run_force_fresh_install_reset + `); + + expect(result.status).not.toBe(0); + expect(result.stdout).not.toContain("openshell-reset"); + expect(`${result.stdout}${result.stderr}`).toContain( + "authoritative whole-host uninstall did not complete", + ); +}); + +it("bounds staged uninstaller preparation before destructive cleanup", () => { + const { root: tmp } = installerCheckout("nemoclaw-force-fresh-timeout-"); + const cleanupMarker = path.join(tmp, "cleanup-started"); + const descendantPidFile = path.join(tmp, "descendant.pid"); + const startedAt = performance.now(); + const result = callPayloadFunction( + ` + NEMOCLAW_AGENT=hermes + FORCE_FRESH_PREPARE_TIMEOUT_SECONDS=1 + force_fresh_install_has_existing_state() { return 0; } + force_fresh_install_source_root() { printf '/tmp/staged-candidate'; } + bash() { + (trap '' TERM; while :; do sleep 1; done) & + child_pid=$! + printf '%s' "$child_pid" > "$DESCENDANT_PID_FILE" + trap '' TERM + wait "$child_pid" + } + run_force_fresh_uninstaller() { touch "$CLEANUP_MARKER"; } + remove_macos_openshell_for_force_fresh_install() { touch "$CLEANUP_MARKER"; } + run_force_fresh_install_reset + `, + { CLEANUP_MARKER: cleanupMarker, DESCENDANT_PID_FILE: descendantPidFile, HOME: tmp }, + ); + const elapsedMs = performance.now() - startedAt; + + expect(result.status).not.toBe(0); + expect(elapsedMs).toBeGreaterThanOrEqual(900); + expect(elapsedMs).toBeLessThan(10_000); + expect(`${result.stdout}${result.stderr}`).toContain( + "Force-fresh uninstaller preparation timed out before cleanup", + ); + expect(processExists(Number(fs.readFileSync(descendantPidFile, "utf8")))).toBe(false); + expect(fs.existsSync(cleanupMarker)).toBe(false); +}, 15_000); + +it("bounds and reaps timed-out authoritative cleanup before package removal", () => { + const { root: tmp, binDir: fakeBin } = installerCheckout( + "nemoclaw-force-fresh-uninstall-timeout-", + ); + const sourceRoot = path.join(tmp, "candidate"); + const descendantPidFile = path.join(tmp, "cleanup-descendant.pid"); + const packageMarker = path.join(tmp, "package-removal-started"); + fs.mkdirSync(path.join(sourceRoot, "bin"), { recursive: true }); + fs.writeFileSync(path.join(sourceRoot, "bin", "nemoclaw.js"), "// staged candidate\n"); + writeExecutable( + path.join(fakeBin, "node"), + `#!/usr/bin/env bash +case "$*" in + *--force-fresh-ownership-preflight) exit 0 ;; +esac +(trap '' TERM; while :; do sleep 1; done) & +child_pid=$! +printf '%s' "$child_pid" > "$DESCENDANT_PID_FILE" +trap '' TERM +wait "$child_pid" +`, + ); + + const result = callPayloadFunction( + ` + warn() { :; } + FORCE_FRESH_UNINSTALL_TIMEOUT_SECONDS=1 + force_fresh_install_has_existing_state() { return 0; } + force_fresh_install_source_root() { printf '%s' "$SOURCE_ROOT"; } + prepare_force_fresh_uninstaller() { :; } + remove_macos_openshell_for_force_fresh_install() { touch "$PACKAGE_MARKER"; } + run_force_fresh_install_reset + `, + { + DESCENDANT_PID_FILE: descendantPidFile, + HOME: tmp, + PACKAGE_MARKER: packageMarker, + PATH: `${fakeBin}:${TEST_SYSTEM_PATH}`, + SOURCE_ROOT: sourceRoot, + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + "Authoritative force-fresh cleanup timed out and is incomplete", + ); + expect(processExists(Number(fs.readFileSync(descendantPidFile, "utf8")))).toBe(false); + expect(fs.existsSync(packageMarker)).toBe(false); +}, 15_000); + +it.each([ + ["flag", "--force-fresh-install", {}], + ["environment variable", "", { NEMOCLAW_FORCE_FRESH_INSTALL: "1" }], +] as const)( + "routes the public force-fresh %s through reset before CLI installation", + (_source, forceFreshArg, extraEnv) => { + const run = runInstallerSourcedBody( + ` + set -e + order="" + record() { order="\${order}$1 "; } + apply_persisted_automatic_gateway_port() { :; } + validate_deferred_hermes_onboarding_request() { :; } + load_station_vllm_conflict_helpers() { :; } + consume_station_local_vllm_resume() { return 1; } + resolve_nemoclaw_gateway_port() { printf '8080'; } + preflight_explicit_express_flags() { :; } + validate_installer_docker_target_before_host_changes() { :; } + print_banner() { :; } + preflight_usage_notice_prompt() { :; } + prepare_installer_host() { :; } + bash() { :; } + prepare_installer_node_runtime() { :; } + run_force_fresh_install_reset() { record reset; } + ensure_station_express_pair() { :; } + step() { :; } + fix_npm_permissions() { :; } + preflight_nemoclaw_acp_shim() { :; } + preinstall_backup_and_retire_legacy_gateway() { record legacy-backup; } + install_nemoclaw() { record install; } + verify_nemoclaw() { _CLI_PATH=""; } + require_reportable_openshell_version() { :; } + command_exists() { return 1; } + warn() { :; } + finalize_install() { :; } + clear_station_resume_after_completed_onboarding() { :; } + uname() { [[ "$1" == "-m" ]] && printf 'arm64' || printf 'Darwin'; } + main ${forceFreshArg} --non-interactive --yes-i-accept-third-party-software + record "fresh:$FRESH:$NEMOCLAW_FORCE_FRESH_INSTALL" + printf '%s' "$order" + `, + { extraEnv: { ...extraEnv } }, + ); + onTestFinished(run.remove); + + expect(run.result.status, run.output).toBe(0); + expect(run.result.stdout.trim()).toBe("reset install fresh:1:1"); + expect(run.result.stdout).not.toContain("legacy-backup"); + }, +); + +it("continues force-fresh installation when Homebrew fails after the pinned runtime lands", () => { + const result = callPayloadFunction(` + warn() { printf 'warn:%s\n' "$*"; } + uname() { printf 'Darwin'; } + observed_macos_openshell_install_method() { printf 'homebrew\n'; } + spin_count=0 + spin() { + spin_count=$((spin_count + 1)) + printf 'spin:%s\n' "$1" + [ "$spin_count" -eq 2 ] + } + prefer_homebrew_openshell() { printf 'prefer:%s\n' "$1"; } + install_nemoclaw_openshell_gateway_user_service() { printf 'service\n'; } + FORCE_FRESH_INSTALL=1 + maybe_install_openshell_during_install force + `); + + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "spin:Installing OpenShell CLI", + "spin:Verifying the installed OpenShell CLI", + "warn:Homebrew reported an install failure after placing OpenShell; the pinned OpenShell verifier passed, so force-fresh installation will continue.", + "prefer:verified-install", + "service", + ]); +}); + +it("rejects force-fresh installation outside macOS", () => { + const result = callPayloadFunction(` + error() { printf '%s' "$*" >&2; return 1; } + uname() { printf 'Linux'; } + FORCE_FRESH_INSTALL=1 + validate_force_fresh_install_platform + `); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + "--force-fresh-install currently supports Apple silicon macOS only", + ); +}); + +it("rejects force-fresh installation on Intel macOS", () => { + const result = callPayloadFunction(` + error() { printf '%s' "$*" >&2; return 1; } + uname() { [[ "$1" == "-s" ]] && printf 'Darwin' || printf 'x86_64'; } + FORCE_FRESH_INSTALL=1 + validate_force_fresh_install_platform + `); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + "--force-fresh-install currently supports Apple silicon macOS only", + ); +}); + +it("rejects a staged source inside the state root", () => { + const { root: tmp } = installerCheckout("nemoclaw-force-fresh-source-"); + const sourceRoot = path.join(tmp, ".nemoclaw", "source"); + fs.mkdirSync(path.join(sourceRoot, ".git"), { recursive: true }); + + const result = callPayloadFunction( + `NEMOCLAW_SOURCE_ROOT=${JSON.stringify(sourceRoot)}; force_fresh_install_source_root`, + { HOME: tmp }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + "must run from the versioned bootstrap checkout", + ); +}, 30_000); + +it("keeps an unrelated ACP shim", () => { + const { root: tmp } = installerCheckout("nemoclaw-force-fresh-acp-"); + const shimDir = path.join(tmp, ".local", "bin"); + const npmBin = path.join(tmp, "npm", "bin"); + fs.mkdirSync(shimDir, { recursive: true }); + fs.mkdirSync(npmBin, { recursive: true }); + fs.writeFileSync(path.join(shimDir, "nemoclaw-acp"), "foreign executable\n"); + + const result = callPayloadFunction( + ` + warn() { :; } + resolve_npm_bin() { printf '${npmBin}'; } + preflight_nemoclaw_acp_shim + printf '%s' "$_NEMOCLAW_FORCE_FRESH_SKIP_ACP_SHIM" + `, + { + FORCE_FRESH_INSTALL: "1", + HOME: tmp, + NEMOCLAW_SHIM_DIR: shimDir, + }, + ); + + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(result.stdout).toBe("true"); + expect(fs.readFileSync(path.join(shimDir, "nemoclaw-acp"), "utf-8")).toBe("foreign executable\n"); +}, 30_000); diff --git a/test/mcp/mcp-tool-discovery-image-contract.test.ts b/test/mcp/mcp-tool-discovery-image-contract.test.ts index 76056046743..1dc6bcc07fe 100644 --- a/test/mcp/mcp-tool-discovery-image-contract.test.ts +++ b/test/mcp/mcp-tool-discovery-image-contract.test.ts @@ -13,10 +13,6 @@ import { expectManagedToolDiscoveryRuntimeImageContract } from "../support/manag const repoRoot = path.join(import.meta.dirname, "../.."); const runtimeRoot = "/usr/local/lib/nemoclaw/mcp-tool-discovery-runtime"; -const managedStartupRuntimeBundle = "managed-startup-image-runtime.bundle"; -const reviewedRuntimeHashOverrides: Readonly> = { - [managedStartupRuntimeBundle]: "b636367343f48e681eae468abaac40bab8890bfec96e8e4f566cff5e5a8a226c", -}; const dockerfiles = [ "Dockerfile", "agents/hermes/Dockerfile", @@ -218,7 +214,7 @@ describe("MCP tool discovery image contract", () => { // source-shape-contract: security -- Exact reviewed runtime digests reject substituted executable and license artifacts before managed image construction. it.each([ { - expectedHash: "0c07b731d2f32a9419605bae4f84329c8d7440528eed2ac6dbcd5835724961e9", + expectedHash: "b636367343f48e681eae468abaac40bab8890bfec96e8e4f566cff5e5a8a226c", relativePath: "managed-startup-image-runtime.bundle", }, { @@ -242,9 +238,7 @@ describe("MCP tool discovery image contract", () => { .createHash("sha256") .update(fs.readFileSync(path.join(bundleRoot, relativePath))) .digest("hex"); - expect(actualHash, relativePath).toBe( - reviewedRuntimeHashOverrides[relativePath] ?? expectedHash, - ); + expect(actualHash, relativePath).toBe(expectedHash); }); it("executes the reviewed MCP discovery runtime artifact", () => { diff --git a/tools/e2e/managed-image-multiarch-workflow-boundary.mts b/tools/e2e/managed-image-multiarch-workflow-boundary.mts index 0e6412504ad..27cafe5a71a 100644 --- a/tools/e2e/managed-image-multiarch-workflow-boundary.mts +++ b/tools/e2e/managed-image-multiarch-workflow-boundary.mts @@ -467,6 +467,21 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): "tools/e2e/live-vitest-invocation.mts run", `--test-path ${DIRECT_TEST_PATH}`, ]); + const receiptDaemonCleanup = requireStep( + errors, + steps, + "Remove owned Docker Engine 27 receipt daemon", + ); + if (receiptDaemonCleanup?.if !== "always()") { + errors.push(`${JOB_ID} Docker Engine 27 receipt daemon cleanup must always run`); + } + requireFragments(errors, receiptDaemonCleanup, [ + "scripts/checks/docker-engine-27-receipt-transfer-e2e.ts", + "--cleanup-only", + '--run-id "$GITHUB_RUN_ID"', + '--run-attempt "$GITHUB_RUN_ATTEMPT"', + '--platform "$NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM"', + ]); const cacheUpload = requireStep( errors, steps, @@ -530,6 +545,7 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): "Run every exact managed-image contract directly", "Remove isolated protected managed-image registry", "Validate protected managed-image evidence", + "Remove owned Docker Engine 27 receipt daemon", "Validate OpenClaw managed-image security boundary", "Validate managed-image glibc probe lifecycle", "Remove protected managed-image cohort resources",