diff --git a/ci/platform-matrix.json b/ci/platform-matrix.json index f903e2ffc8f..484c9449c9a 100644 --- a/ci/platform-matrix.json +++ b/ci/platform-matrix.json @@ -1,7 +1,7 @@ { "$comment": "Single source of truth for NemoClaw launch claims and platform support. Covers platforms, inference providers, supported agents, messaging integrations, and deployment paths. Scripts read this to generate README and docs tables. QA/CI update platform/provider rows; the engineering owner reviews other rows. Docs are derived.", "version": "1.1", - "updated": "2026-07-12", + "updated": "2026-07-15", "project_status": { "stage": "alpha", @@ -39,7 +39,7 @@ "status": "caveated", "prd_priority": "P0", "ci_tested": true, - "notes": "Start the container runtime (Colima or Docker Desktop) before running the installer. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight." + "notes": "Start the container runtime (Colima or Docker Desktop) before running the installer. OpenShell is installed through Homebrew and the gateway should appear in `brew services list` as `openshell`. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight." }, { "name": "DGX Spark", @@ -229,7 +229,7 @@ { "name": "Intel Mac (macOS x86_64)", "status": "unsupported", - "notes": "OpenShell does not publish macOS x86_64 standalone gateway assets. Install hard-fails on x86_64 macOS (`scripts/install-openshell.sh:663`). See issue #954 (closed)." + "notes": "The supported macOS OpenShell Homebrew gateway service path is Apple Silicon only. Install hard-fails on x86_64 macOS. See issue #954 (closed)." }, { "name": "Non-Ubuntu/Debian Linux distros", diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index 49b3c98cbe2..c418b1151d2 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -138,7 +138,7 @@ }, { "file": "test/e2e/support/e2e-expected-state.test.ts", - "test": "compiles host-preservation probes for every post-reboot recovery target", + "test": "compiles gateway-health and host-preservation probes for every post-reboot recovery target", "category": "security" }, { diff --git a/docs/get-started/prerequisites.mdx b/docs/get-started/prerequisites.mdx index b8b28670bde..678c11f7a55 100644 --- a/docs/get-started/prerequisites.mdx +++ b/docs/get-started/prerequisites.mdx @@ -92,7 +92,7 @@ The table comes from [`ci/platform-matrix.json`](https://github.com/NVIDIA/NemoC | OS | Container runtime | Status | Notes | |----|-------------------|--------|-------| | Linux | Docker | Tested | Primary tested path. Ubuntu 24.04 has host-level onboarding validation. A digest-pinned Ubuntu 26.04 userspace lane builds the CLI and runs preflight, installer, and platform contracts on eligible main pushes; Docker-host, AppArmor, Landlock, and live onboarding validation on 26.04 remain pending. Other distros (Ubuntu 22.04, Fedora, Rocky, Alma, NixOS, Arch) may work but are not validated. | -| macOS (Apple Silicon) | Colima, Docker Desktop | Tested with limitations | Start the container runtime (Colima or Docker Desktop) before running the installer. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight. | +| macOS (Apple Silicon) | Colima, Docker Desktop | Tested with limitations | Start the container runtime (Colima or Docker Desktop) before running the installer. OpenShell is installed through Homebrew and the gateway should appear in `brew services list` as `openshell`. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight. | | DGX Spark | Docker | Tested | Use the standard installer and `$$nemoclaw onboard`. For an end-to-end walkthrough with local inference, see the [NVIDIA Spark playbook](https://build.nvidia.com/spark/nemoclaw). | | Windows WSL2 | Docker Desktop (WSL backend) | Tested with limitations | Requires WSL2 with Docker Desktop backend. | {/* platform-matrix:end */} diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index 69354ff4d6d..844b4217f51 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -20,7 +20,7 @@ $$nemoclaw uninstall | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt. | -| `--keep-openshell` | Leave OpenShell binaries installed. | +| `--keep-openshell` | Leave OpenShell binaries, gateway service daemons, and gateway service configuration in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `$XDG_CONFIG_HOME/systemd/user/openshell-gateway.service` unit, or `~/.config/systemd/user/openshell-gateway.service` when `XDG_CONFIG_HOME` is unset, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models. | | `--destroy-user-data` | Also remove preserved user data in `rebuild-backups/`, `backups/`, and `sandboxes.json`. | | `--gateway ` | Override the gateway name to remove. The default is `nemoclaw`. | diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 1401afd46b9..d1207e37f5a 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -81,11 +81,19 @@ graph LR The logical diagram above shows how components relate. This section shows what actually runs where on the host. NemoClaw's default Docker-driver topology does not place the sandbox in an embedded k3s cluster. -On Linux, NemoClaw configures and restarts the package-managed OpenShell gateway user service when it is installed, then creates the sandbox as a Docker container. -NemoClaw treats that service as authoritative only when `systemctl --user show openshell-gateway` reports a package/vendor unit path and an `openshell-gateway` `ExecStart`. -Per-user units, partial units, and user-manager or bus outages do not take over gateway ownership; NemoClaw falls back to the standalone gateway process used by earlier installs. -That compatibility fallback remains until supported upgrade paths no longer include pre-service OpenShell installs and the package-managed handoff has direct nightly coverage. -On Apple Silicon macOS, NemoClaw starts the OpenShell Docker-driver gateway and creates the sandbox as a Docker container. +On Linux, NemoClaw configures, enables, restarts, and checks a trusted OpenShell gateway user service, then creates the sandbox as a Docker container. +NemoClaw prefers the upstream package-managed `openshell-gateway.service` when `systemctl --user show openshell-gateway` reports a package/vendor unit path and an `openshell-gateway` `ExecStart`. +For tarball-installed OpenShell binaries, the installer and onboarding stage a marked user-level `openshell-gateway.service` that follows OpenShell's systemd service model, so the gateway can restart after reboot or at the next user session. +The marker identifies the unit as NemoClaw-owned before NemoClaw reconciles or removes it. +The marked unit generates the local OpenShell mTLS bundle before daemon startup; its `openshell/gateway.env` file overrides the gateway port, Docker-driver configuration, and NemoClaw gateway state. +The marked unit and environment file use `$XDG_CONFIG_HOME` when it is set to an absolute path, otherwise they use `~/.config`. +Arbitrary per-user units, partial units, and user-manager or bus outages do not take over gateway ownership; NemoClaw falls back to the standalone gateway process when no trusted service path is available. +If NemoClaw cannot write or remove its marked user unit, it reports the filesystem failure and keeps the standalone fallback available. +That compatibility fallback remains until supported upgrade paths no longer include pre-service OpenShell installs and the service-backed handoff has direct nightly coverage. +On Apple Silicon macOS, the upstream OpenShell daemon model is the Homebrew service. +The installer installs OpenShell through the upstream Homebrew formula, and onboard restarts the `openshell` Homebrew service before checking gateway health. +If the Homebrew formula or service is unavailable, NemoClaw can still use the standalone Docker-driver gateway process as a compatibility fallback. +In either case, NemoClaw creates the sandbox as a Docker container. In both Docker-driver modes, the sandbox is a Docker container, not a Kubernetes pod. Entrypoint supervisors create the in-container `/tmp/nemoclaw-gateway-local` marker only when they actually launch an in-container gateway, and they normally keep it present while that supervisor is active. On normal exits, handled `SIGTERM`/`SIGINT`, startup failures, and shell `errexit` termination through the `EXIT` trap, the supervisor removes the marker on a best-effort basis so the Docker health check does not keep trusting a stale gateway PID. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index f77b64a90ea..a207ce4998d 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3035,7 +3035,7 @@ On Linux, uninstall removes `~/.local/state/nemoclaw`, which contains Docker-dri | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt | -| `--keep-openshell` | Leave OpenShell binaries installed | +| `--keep-openshell` | Leave OpenShell binaries, gateway service daemons, and gateway service configuration in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `$XDG_CONFIG_HOME/systemd/user/openshell-gateway.service` unit, or `~/.config/systemd/user/openshell-gateway.service` when `XDG_CONFIG_HOME` is unset, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models | | `--destroy-user-data` | Also remove preserved user data (`rebuild-backups/`, `backups/`, `sandboxes.json`) | | `--gateway ` | Override the gateway name to remove (default: `$$nemoclaw`) | @@ -3429,8 +3429,8 @@ Set them before running `$$nemoclaw onboard`. | `NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD` | unset or `auto` (default); `1`, `true`, `yes`, or `on` to enable; `0`, `false`, `no`, or `off` to disable | Controls whether base-image resolution may build a compatible image locally. The default allows builds during normal CLI runs and disables them when `NODE_ENV=test` or `VITEST=true`. When source inputs or a missing/incompatible release-version base require a fresh build, disabling local builds makes resolution fail instead of using an unproven image. | | `NEMOCLAW_DOCKER_GPU_PATCH` | unset, `auto`, `fallback`, `1`, or `0`; other legacy nonzero values remain accepted through `v0.0.x` and will be removed in `v0.1.0` | Selects Linux Docker-driver GPU routing. Unset, `auto`, or `0` uses native OpenShell GPU injection on ordinary native Linux. `fallback` explicitly opts into one native attempt followed by one bounded compatibility retry when trusted host evidence identifies a GPU-routing failure. `1` and legacy nonzero values select the compatibility patch from the outset. Docker Desktop WSL and Jetson/Tegra use the compatibility path by default; Docker Desktop WSL ignores `0`, while Jetson/Tegra accepts `0` only as a troubleshooting override that bypasses device-group propagation. | | `NEMOCLAW_OPENSHELL_GATEWAY_CONTAINER_PATCH` | `1` to enable; disabled by default | This setting explicitly opts into the Linux gateway compatibility container for an older host ABI or a diagnostic run; use it only on a trusted local host because it uses host networking and mounts the Docker socket read-only even though the socket still exposes the privileged Docker API; prefer OpenShell 0.0.72's directly supported glibc 2.28+ path; see the [OpenShell 0.0.72 compatibility review](/user-guide/openclaw/security/openshell-0.0.72-compatibility-review#source-of-truth-boundaries) for details. | -| `NEMOCLAW_OPENSHELL_GATEWAY_BIN` | path | Advanced override for the `openshell-gateway` binary used by the Linux Docker-driver standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | -| `NEMOCLAW_OPENSHELL_SANDBOX_BIN` | path | Advanced override for the `openshell-sandbox` binary used by the Linux Docker-driver standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | +| `NEMOCLAW_OPENSHELL_GATEWAY_BIN` | path | Advanced override for the `openshell-gateway` binary used by Docker-driver gateway startup when NemoClaw stages its Linux marked user service or uses the standalone fallback. The marked user service accepts only NemoClaw's trusted install paths (`~/.local/bin/openshell-gateway`, `/usr/local/bin/openshell-gateway`, or `/usr/bin/openshell-gateway`); other absolute paths use the standalone fallback. The macOS Homebrew service uses the Homebrew formula's gateway binary. Defaults to the binary next to `openshell`, then common install paths. | +| `NEMOCLAW_OPENSHELL_SANDBOX_BIN` | path | Advanced override for the `openshell-sandbox` binary used by Linux Docker-driver gateway startup, including the marked user service environment and standalone fallback. The macOS Homebrew service uses the Homebrew formula's driver layout. Defaults to the binary next to `openshell`, then common install paths. | | `NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR` | path | Advanced override for the Linux Docker-driver gateway SQLite state directory and standalone-fallback PID file. Defaults to `~/.local/state/nemoclaw/openshell-docker-gateway`. | | `NEMOCLAW_AUTO_FIX_FIREWALL` | `1` to enable | Opts in to automatic UFW remediation when Linux Docker-driver sandbox containers cannot reach the host gateway after a proven TCP failure. NemoClaw runs `sudo -n` only, validates the narrow Docker bridge subnet → gateway IP:port rule before invoking UFW, re-probes after applying it, and otherwise falls back to the printed manual command. | diff --git a/docs/reference/platform-support.mdx b/docs/reference/platform-support.mdx index e02d2cab64b..12ba49c6ea2 100644 --- a/docs/reference/platform-support.mdx +++ b/docs/reference/platform-support.mdx @@ -79,7 +79,7 @@ For the onboarding-time supported set without deferred rows, refer to [Prerequis | OS | Container runtime | Status | PRD priority | CI | Notes | |----|-------------------|--------|--------------|----|-------| | Linux | Docker | Tested | P0 | Yes | Primary tested path. Ubuntu 24.04 has host-level onboarding validation. A digest-pinned Ubuntu 26.04 userspace lane builds the CLI and runs preflight, installer, and platform contracts on eligible main pushes; Docker-host, AppArmor, Landlock, and live onboarding validation on 26.04 remain pending. Other distros (Ubuntu 22.04, Fedora, Rocky, Alma, NixOS, Arch) may work but are not validated. | -| macOS (Apple Silicon) | Colima, Docker Desktop | Tested with limitations | P0 | Yes | Start the container runtime (Colima or Docker Desktop) before running the installer. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight. | +| macOS (Apple Silicon) | Colima, Docker Desktop | Tested with limitations | P0 | Yes | Start the container runtime (Colima or Docker Desktop) before running the installer. OpenShell is installed through Homebrew and the gateway should appear in `brew services list` as `openshell`. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight. | | DGX Spark | Docker | Tested | P1 | Yes | Use the standard installer and `$$nemoclaw onboard`. For an end-to-end walkthrough with local inference, see the [NVIDIA Spark playbook](https://build.nvidia.com/spark/nemoclaw). | | Windows WSL2 | Docker Desktop (WSL backend) | Tested with limitations | P1 | No | Requires WSL2 with Docker Desktop backend. | | DGX Station | Docker | Deferred | P1 | No | The PRD marks this platform as P1. Workstation form-factor with NVIDIA GPUs and the same Docker + NVIDIA Container Toolkit + CDI requirements as DGX Spark. Onboard path not yet validated end-to-end on the hardware; vLLM defaults to `deepseek-ai/DeepSeek-V4-Flash` for this host class and will move out of `deferred` once the hardware run is signed off. | @@ -162,7 +162,7 @@ They are listed here so launch material, sales conversations, and support triage | Item | Status | Why | |------|--------|-----| | Podman / other container runtimes | Unsupported | Onboard surfaces an explicit unsupported-runtime error for Podman (`src/lib/onboard/fatal-runtime-preflight.ts` prints the rejection; `src/lib/onboard/preflight.ts` flags the unsupported runtime upstream). Only Docker Engine, Docker Desktop, and Colima are supported. See issue #420 (closed). | -| Intel Mac (macOS x86_64) | Unsupported | OpenShell does not publish macOS x86_64 standalone gateway assets. Install hard-fails on x86_64 macOS (`scripts/install-openshell.sh:663`). See issue #954 (closed). | +| Intel Mac (macOS x86_64) | Unsupported | The supported macOS OpenShell Homebrew gateway service path is Apple Silicon only. Install hard-fails on x86_64 macOS. See issue #954 (closed). | | Non-Ubuntu/Debian Linux distros | Unsupported | Installer assumes `apt-get`. Fedora/Rocky/Alma/Arch/NixOS are not validated and the installer's package-manager probes do not cover them. See open issue #899 (Fedora hang). | | Native Kubernetes or OpenShift deployments | Unsupported | NemoClaw runs the sandbox as a Docker container, not a Kubernetes pod. The default Docker-driver topology does not embed k3s. Operator-managed K8s/OpenShift deployments are out of scope; see issue #407 (community OpenShift through agent-sandbox CRD). | | Air-gapped / offline installs | Unsupported | Onboard assumes network reachability for package fetches, container pulls, and provider validation. See open issues #4872 and #2218 (production-deployment epic covering air-gapped support, China network guidance, multi-host topology). | diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 9c7387d47ca..920f61c1b2b 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -848,17 +848,45 @@ Follow these steps to reconnect. - **Linux:** start Docker if it is not already running (`sudo systemctl start docker`) - **macOS:** open Docker Desktop or start Colima (`colima start`) +1. Check the managed OpenShell gateway service. + + On Apple Silicon macOS, OpenShell is installed through Homebrew and the gateway is a Homebrew service: + + ```bash + brew services list + brew services restart openshell + ``` + + On Linux tarball installs, NemoClaw installs a marked user `openshell-gateway.service`. + The unit is written under `$XDG_CONFIG_HOME/systemd/user` when `XDG_CONFIG_HOME` is absolute, otherwise under `~/.config/systemd/user`. + The service generates the local OpenShell mTLS bundle before starting and then reads NemoClaw's `openshell/gateway.env` overrides. + The systemd user manager starts it after reboot, or at the next user session when lingering is not enabled. + If `systemctl --user` is available, check and restart it first: + + ```bash + systemctl --user status openshell-gateway + systemctl --user restart openshell-gateway + ``` + + On non-systemd Linux hosts or hosts where the user service cannot be reached, continue with the NemoClaw recovery step below. + 1. Check sandbox state. ```bash openshell sandbox list ``` - If the sandbox shows `Ready`, skip to step 4. + If the sandbox shows `Ready`, skip to step 5. 1. Recover the managed gateway (if needed). - If the sandbox is not listed or the command fails, let NemoClaw recover the managed gateway and sandbox registration: + If the sandbox is not listed after the service restart, or `systemctl --user` is unavailable, first ask NemoClaw to reconnect through the recorded sandbox: + + ```bash + $$nemoclaw status + ``` + + If that cannot restore the gateway registration, resume onboarding to recreate the managed gateway metadata: ```bash $$nemoclaw onboard --resume diff --git a/scripts/check-installer-hash.sh b/scripts/check-installer-hash.sh index c26cf106fab..fab5adc7169 100755 --- a/scripts/check-installer-hash.sh +++ b/scripts/check-installer-hash.sh @@ -6,7 +6,7 @@ # still match the immutable upstream checksum manifests. # # Checked artifacts: -# 1. OpenShell archives — scripts/install-openshell.sh release-asset table +# 1. OpenShell archives/formula — scripts/install-openshell.sh release-asset tables # 2. Brev OpenShell CLI — scripts/brev-launchable-ci-cpu.sh release-asset table # # Usage: @@ -85,7 +85,7 @@ sha256_file() { check_openshell_release_assets() { local installer="${REPO_ROOT}/scripts/install-openshell.sh" local brev_installer="${REPO_ROOT}/scripts/brev-launchable-ci-cpu.sh" - local release_base workspace manifests spec manifest expected actual source asset pinned upstream + local release_base workspace manifests spec manifest expected actual source asset pinned upstream formula_asset local matches required_manifest required_matches local pin_records parser_error parser_errors parsed_version release_version="" record_extra local allowlist_entry allowlist_version allowlist_extra @@ -144,8 +144,8 @@ check_openshell_release_assets() { esac done <<<"$pin_records" - if [[ "$count" -ne 8 ]]; then - echo " STALE: expected 8 pinned OpenShell v${release_version:-unknown} assets, found ${count}." + if [[ "$count" -ne 9 ]]; then + echo " STALE: expected 9 pinned OpenShell v${release_version:-unknown} assets, found ${count}." failures=$((failures + 1)) fi if [[ "$brev_count" -ne 2 ]]; then @@ -221,6 +221,29 @@ check_openshell_release_assets() { done while IFS=$'\t' read -r parsed_version source asset pinned record_extra; do + if [[ "$asset" == "openshell.rb" ]]; then + formula_asset="${workspace}/${asset}" + if ! fetch_file "${release_base}/${asset}" "$formula_asset"; then + echo " STALE: unable to download ${source} ${asset}." + failures=$((failures + 1)) + continue + fi + if ! actual=$(sha256_file "$formula_asset"); then + echo " STALE: unable to hash ${source} ${asset}." + failures=$((failures + 1)) + continue + fi + if [[ "$actual" == "$pinned" ]]; then + published_count=$((published_count + 1)) + echo " OK: ${source} ${asset} (${pinned})" + else + echo " STALE: ${source} ${asset} digest does not match the pinned v${release_version} release asset." + echo " pinned: ${pinned}" + echo " upstream: ${actual}" + failures=$((failures + 1)) + fi + continue + fi matches=$(awk -v asset="$asset" '$2 == asset { count++ } END { print count + 0 }' "$manifests") upstream=$(awk -v asset="$asset" '$2 == asset { print $1; exit }' "$manifests") if [[ "$matches" -eq 1 && "$pinned" == "$upstream" ]]; then @@ -235,8 +258,8 @@ check_openshell_release_assets() { fi done <<<"$pin_records" - if [[ "$published_count" -ne 10 ]]; then - echo " STALE: expected all 10 pinned asset references in the v${release_version} checksum manifests, matched ${published_count}." + if [[ "$published_count" -ne 11 ]]; then + echo " STALE: expected all 11 pinned asset references for v${release_version}, matched ${published_count}." failures=$((failures + 1)) fi return "$failures" diff --git a/scripts/checks/extract-installer-pins.mts b/scripts/checks/extract-installer-pins.mts index 2e897b4bca4..cd1e31742e6 100644 --- a/scripts/checks/extract-installer-pins.mts +++ b/scripts/checks/extract-installer-pins.mts @@ -48,7 +48,7 @@ const MAX_INSTALLER_INPUT_BYTES = 1024 * 1024; // release; the later pin PR may then change release data without authorizing // any operational installer change. A mismatch reports the candidate hash. const TRUSTED_INSTALLER_TEMPLATE_SHA256 = - "a101f002bd8e02aa7b38960ddcb76c9fca419bc3766f6870446f6a7e99e14d78"; + "7db8198d4888ed32ee3be8e15e9e215a11cb368f13c19b536496e96cd762c3e1"; const TRUSTED_BREV_TEMPLATE_SHA256 = "c0a4ddf25a02a9fe02b2df53a60942ea887610f04d4ce16a121b6e79a5aeff1a"; const EXPECTED_INSTALLER_ASSETS = [ @@ -61,6 +61,7 @@ const EXPECTED_INSTALLER_ASSETS = [ "openshell-sandbox-x86_64-unknown-linux-gnu.tar.gz", "openshell-sandbox-aarch64-unknown-linux-gnu.tar.gz", ] as const; +const EXPECTED_INSTALLER_FORMULA_ASSETS = ["openshell.rb"] as const; const EXPECTED_BREV_ASSETS = [ "openshell-x86_64-unknown-linux-musl.tar.gz", "openshell-aarch64-unknown-linux-musl.tar.gz", @@ -927,13 +928,22 @@ function runCli(): void { functionName: "openshell_pinned_sha256", sourceLabel: "installer", }); + const installerFormulaPins = extractInstallerPins(installerSource, { + functionName: "openshell_formula_pinned_sha256", + sourceLabel: "installer", + }); const brevPins = extractInstallerPins(brevInstallerSource, { functionName: "openshell_cli_pinned_sha256", sourceLabel: "Brev launchable", }); assertExactAssetSet(installerPins, EXPECTED_INSTALLER_ASSETS, "installer pin table"); + assertExactAssetSet( + installerFormulaPins, + EXPECTED_INSTALLER_FORMULA_ASSETS, + "installer formula pin table", + ); assertExactAssetSet(brevPins, EXPECTED_BREV_ASSETS, "Brev pin table"); - const pins = [...installerPins, ...brevPins]; + const pins = [...installerPins, ...installerFormulaPins, ...brevPins]; const releaseVersions = [...new Set(pins.map((pin) => pin.releaseVersion))].sort(); if (releaseVersions.length !== 1) { fail( @@ -949,7 +959,11 @@ function runCli(): void { } assertTrustedTemplate( installerSource, - ["openshell_pinned_sha256", "pinned_sandbox_build_version"], + [ + "openshell_pinned_sha256", + "openshell_formula_pinned_sha256", + "pinned_sandbox_build_version", + ], [ /^MIN_VERSION="([0-9]+\.[0-9]+\.[0-9]+)"$/gm, /^MAX_VERSION="([0-9]+\.[0-9]+\.[0-9]+)"$/gm, diff --git a/scripts/install-openshell.sh b/scripts/install-openshell.sh index 0c0bf559eb6..0fce4de05a9 100755 --- a/scripts/install-openshell.sh +++ b/scripts/install-openshell.sh @@ -82,6 +82,9 @@ if [ "$RESOLVED_CHANNEL" = "dev" ]; then warn "Dev channel install skips SHA-256 verification. Use only in trusted environments." fi +HOMEBREW_TAP="nvidia/openshell" +HOMEBREW_FORMULA_NAME="openshell" + # Honour the TS installer's blueprint-derived env overrides only on the stable # channel — the dev channel installs from the `dev` tag and uses DEV_MIN_VERSION # instead, so a malformed override should not abort a dev install (#3446 review). @@ -175,6 +178,18 @@ openshell_checksum_line() { awk -v asset="$asset" '$2 == asset { print; found=1; exit } END { if (!found) exit 1 }' "$checksum_file" } +openshell_formula_pinned_sha256() { + local release_tag="$1" asset="$2" + case "${release_tag}:${asset}" in + v0.0.72:openshell.rb) + printf '%s\n' "4b75a7e3a7630eb8954d73ca828b394d5e0646adbaa4b087b2435329d53b61b3" + ;; + *) + return 1 + ;; + esac +} + # A pinned digest authenticates bytes, but it does not make extraction safe. # Every consumed OpenShell archive must contain exactly the one regular binary # selected by its asset name. This rejects absolute/parent paths, extra or @@ -603,6 +618,107 @@ repair_existing_macos_vm_driver() { return 1 } +macos_homebrew_formula_installed() { + [ "$OS" = "Darwin" ] || return 1 + command -v brew >/dev/null 2>&1 || return 1 + brew list --formula "$HOMEBREW_FORMULA_NAME" >/dev/null 2>&1 +} + +restart_macos_homebrew_gateway_service() { + [ "$OS" = "Darwin" ] || return 0 + command -v brew >/dev/null 2>&1 || return 1 + info "restarting OpenShell Homebrew service..." + if brew services restart "$HOMEBREW_FORMULA_NAME"; then + return 0 + fi + warn "could not restart the OpenShell Homebrew service" + info "restart it later with: brew services restart ${HOMEBREW_FORMULA_NAME}" + info "then register it with: openshell gateway add https://127.0.0.1:17670 --local --name openshell" + return 0 +} + +download_openshell_formula() { + local release_tag="$1" output="$2" output_dir + output_dir="$(dirname "$output")" + if command -v gh >/dev/null 2>&1; then + if GH_PROMPT_DISABLED=1 GH_TOKEN="${GH_TOKEN:-${GITHUB_TOKEN:-}}" gh release download "$release_tag" --repo NVIDIA/OpenShell \ + --pattern "openshell.rb" --dir "$output_dir" --clobber 2>/dev/null; then + [ -f "$output" ] && return 0 + fi + warn "gh CLI formula download failed (auth may not be configured) — falling back to curl" + rm -f "$output" + fi + curl -fL -sS "https://github.com/NVIDIA/OpenShell/releases/download/${release_tag}/openshell.rb" \ + -o "$output" +} + +homebrew_formula_path() { + local tap="$1" formula="$2" tap_dir formula_dir + if ! brew tap-info "$tap" >/dev/null 2>&1; then + info "creating local Homebrew tap ${tap}..." >&2 + brew tap-new --no-git "$tap" >/dev/null + fi + + tap_dir="$(brew --repository "$tap" 2>/dev/null || true)" + [ -n "$tap_dir" ] || fail "could not locate Homebrew tap ${tap}" + + formula_dir="${tap_dir}/Formula" + mkdir -p "$formula_dir" + printf '%s/%s.rb\n' "$formula_dir" "$formula" +} + +install_macos_homebrew_formula() { + local tmpdir formula_file tap_formula_file formula_ref expected_sha actual_sha brew_prefix openshell_bin + [ "$OS" = "Darwin" ] || return 1 + [ "$ARCH_LABEL" = "aarch64" ] || fail "OpenShell ${PIN_VERSION} supports the Homebrew gateway service only on Apple Silicon macOS." + command -v brew >/dev/null 2>&1 || fail "Homebrew is required to install the OpenShell macOS gateway service. Install Homebrew and retry." + + tmpdir="$(mktemp -d)" + OPENSHELL_HOMEBREW_FORMULA_TMPDIR="$tmpdir" + trap 'rm -rf "${OPENSHELL_HOMEBREW_FORMULA_TMPDIR:-}"' EXIT + formula_file="${tmpdir}/openshell.rb" + + info "Downloading OpenShell Homebrew formula..." + download_openshell_formula "$RELEASE_TAG" "$formula_file" \ + || fail "failed to download OpenShell Homebrew formula for ${RELEASE_TAG}" + chmod 0644 "$formula_file" + + if [ "$RELEASE_TAG" != "dev" ]; then + expected_sha="$(openshell_formula_pinned_sha256 "$RELEASE_TAG" "openshell.rb")" \ + || fail "No NemoClaw-pinned SHA-256 for OpenShell $RELEASE_TAG Homebrew formula" + actual_sha="$(file_sha256 "$formula_file")" \ + || fail "No SHA-256 tool available (sha256sum/shasum)" + [ "$actual_sha" = "$expected_sha" ] \ + || fail "OpenShell Homebrew formula checksum does not match NemoClaw-pinned $RELEASE_TAG digest" + fi + + tap_formula_file="$(homebrew_formula_path "$HOMEBREW_TAP" "$HOMEBREW_FORMULA_NAME")" + info "staging Homebrew formula in tap ${HOMEBREW_TAP}..." + cp "$formula_file" "$tap_formula_file" + chmod 0644 "$tap_formula_file" + + formula_ref="${HOMEBREW_TAP}/${HOMEBREW_FORMULA_NAME}" + if brew list --formula "$HOMEBREW_FORMULA_NAME" >/dev/null 2>&1; then + info "reinstalling OpenShell with Homebrew..." + brew reinstall --formula "$formula_ref" + else + info "installing OpenShell with Homebrew..." + brew install --formula "$formula_ref" + fi + + restart_macos_homebrew_gateway_service || true + + brew_prefix="$(brew --prefix 2>/dev/null || true)" + openshell_bin="${brew_prefix}/bin/openshell" + [ -n "$brew_prefix" ] && [ -x "$openshell_bin" ] \ + || openshell_bin="$(command -v openshell 2>/dev/null || true)" + [ -n "$openshell_bin" ] && [ -x "$openshell_bin" ] \ + || fail "Homebrew completed but the openshell binary was not found on PATH." + require_openshell_messaging_features "$openshell_bin" + info "$("$openshell_bin" --version 2>&1 || echo openshell) installed" + exit 0 +} + validate_explicit_component_override gateway "${NEMOCLAW_OPENSHELL_GATEWAY_BIN:-}" validate_explicit_component_override sandbox "${NEMOCLAW_OPENSHELL_SANDBOX_BIN:-}" @@ -617,8 +733,15 @@ if command -v openshell >/dev/null 2>&1; then && printf '%s\n' "$INSTALLED_VERSION_OUTPUT" | grep -qi 'dev'; then if required_driver_bins_present "$ACTIVE_OPENSHELL_BIN" && openshell_has_required_messaging_features "$ACTIVE_OPENSHELL_BIN"; then if [ "$FORCE_INSTALL" != "1" ]; then - info "openshell already installed: $INSTALLED_VERSION_OUTPUT (dev channel)" - exit 0 + if [ "$OS" = "Darwin" ] && ! macos_homebrew_formula_installed; then + warn "openshell $INSTALLED_VERSION_OUTPUT is installed without the Homebrew gateway service — installing OpenShell with Homebrew..." + else + if [ "$OS" = "Darwin" ]; then + restart_macos_homebrew_gateway_service || true + fi + info "openshell already installed: $INSTALLED_VERSION_OUTPUT (dev channel)" + exit 0 + fi fi warn "Current OpenShell dev build requested — refreshing the moving dev release instead of reusing the installed binary." else @@ -639,7 +762,12 @@ if command -v openshell >/dev/null 2>&1; then warn "openshell $INSTALLED_VERSION is missing Docker-driver binaries — reinstalling pinned OpenShell ${PIN_VERSION}..." elif ! openshell_has_required_messaging_features "$ACTIVE_OPENSHELL_BIN"; then fail "${OPENSHELL_FEATURE_CHECK_ERROR:-openshell $INSTALLED_VERSION is missing required messaging credential rewrite and MCP L7 policy support. Install an OpenShell build that includes provider aliases, WebSocket text rewrite, request-body credential rewrite, and MCP/JSON-RPC L7 policy enforcement.}" + elif [ "$OS" = "Darwin" ] && ! macos_homebrew_formula_installed; then + warn "openshell $INSTALLED_VERSION is installed without the Homebrew gateway service — reinstalling pinned OpenShell ${PIN_VERSION} with Homebrew..." else + if [ "$OS" = "Darwin" ]; then + restart_macos_homebrew_gateway_service || true + fi info "openshell already installed: $INSTALLED_VERSION (>= $MIN_VERSION, <= $MAX_VERSION, messaging rewrite, MCP L7, and policy --base capable)" exit 0 fi @@ -651,6 +779,10 @@ fi info "Installing OpenShell from release '$RELEASE_TAG'..." +if [ "$OS" = "Darwin" ]; then + install_macos_homebrew_formula +fi + case "$OS" in Darwin) case "$ARCH_LABEL" in @@ -676,7 +808,7 @@ case "$OS" in CHECKSUM_FILES+=("openshell-gateway-checksums-sha256.txt") ;; x86_64) - fail "OpenShell ${PIN_VERSION} does not publish macOS x86_64 standalone gateway assets." + fail "OpenShell ${PIN_VERSION} supports the macOS Homebrew gateway service only on Apple Silicon." ;; esac ;; diff --git a/scripts/install.sh b/scripts/install.sh index f487398830e..e7a5fc06ae5 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1119,6 +1119,134 @@ prefer_user_local_openshell() { fi } +NEMOCLAW_GATEWAY_SERVICE_MARKER="NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1" +NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE="# ${NEMOCLAW_GATEWAY_SERVICE_MARKER}" + +upstream_openshell_gateway_user_service_installed() { + [[ "$(uname -s)" == "Linux" ]] || return 1 + [[ -f /usr/local/lib/systemd/user/openshell-gateway.service ]] \ + || [[ -f /usr/lib/systemd/user/openshell-gateway.service ]] \ + || [[ -f /lib/systemd/user/openshell-gateway.service ]] +} + +macos_openshell_homebrew_gateway_service_installed() { + [[ "$(uname -s)" == "Darwin" ]] || return 1 + command -v brew >/dev/null 2>&1 || return 1 + brew list --formula openshell >/dev/null 2>&1 +} + +resolve_openshell_gateway_bin_for_service() { + local gateway_bin="${NEMOCLAW_OPENSHELL_GATEWAY_BIN:-}" + if [[ -n "$gateway_bin" && -x "$gateway_bin" ]]; then + printf "%s\n" "$gateway_bin" + return 0 + fi + + gateway_bin="$(command -v openshell-gateway 2>/dev/null || true)" + [[ -n "$gateway_bin" && -x "$gateway_bin" ]] || return 1 + printf "%s\n" "$gateway_bin" +} + +trusted_openshell_gateway_bin_for_service() { + local gateway_bin="${1:-}" + case "$gateway_bin" in + "${HOME}/.local/bin/openshell-gateway" | /usr/local/bin/openshell-gateway | /usr/bin/openshell-gateway) + return 0 + ;; + *) + return 1 + ;; + esac +} + +is_nemoclaw_openshell_gateway_user_service() { + local service_path="${1:-}" + [[ -f "$service_path" ]] || return 1 + grep -Fxq "$NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE" "$service_path" +} + +openshell_user_config_home() { + if [[ -n "${XDG_CONFIG_HOME:-}" && "$XDG_CONFIG_HOME" == /* ]]; then + printf '%s\n' "$XDG_CONFIG_HOME" + else + printf '%s\n' "${HOME}/.config" + fi +} + +install_nemoclaw_openshell_gateway_user_service() { + [[ "$(uname -s)" == "Linux" ]] || return 0 + + local service_dir + service_dir="$(openshell_user_config_home)/systemd/user" + local service_path="${service_dir}/openshell-gateway.service" + + if upstream_openshell_gateway_user_service_installed; then + if is_nemoclaw_openshell_gateway_user_service "$service_path"; then + rm -f "$service_path" + info "Removed NemoClaw OpenShell gateway user service override: $service_path" + fi + return 0 + fi + + local gateway_bin + gateway_bin="$(resolve_openshell_gateway_bin_for_service)" || return 0 + + case "$gateway_bin" in + *[[:space:]]*) + warn "Skipping OpenShell gateway user service because the binary path contains whitespace: $gateway_bin" + return 0 + ;; + /*) ;; + *) + warn "Skipping OpenShell gateway user service because the binary path is not absolute: $gateway_bin" + return 0 + ;; + esac + if ! trusted_openshell_gateway_bin_for_service "$gateway_bin"; then + warn "Skipping OpenShell gateway user service because the binary path is not a trusted install path: $gateway_bin" + return 0 + fi + + if [[ -f "$service_path" ]] && ! is_nemoclaw_openshell_gateway_user_service "$service_path"; then + warn "Leaving non-NemoClaw OpenShell gateway user service in place: $service_path" + return 0 + fi + + if ! { + mkdir -p "$service_dir" \ + && chmod 700 "$service_dir" \ + && cat >"$service_path" < { + it("keeps OpenShell service and host gateway process when OpenShell is kept", () => { + const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const tmpHome = path.join(tmpRoot, "home"); + const xdgConfigHome = path.join(tmpRoot, "xdg-config"); + fs.mkdirSync(tmpHome, { recursive: true }); + const env = homeEnv(tmpHome, xdgConfigHome); + const servicePath = writeManagedService(tmpHome, env); + const envPath = writeGatewayEnv(tmpHome, env); + const run = vi.fn((_command: string, _args: string[]) => ok()); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: () => true, + env, + existsSync: (target) => String(target).startsWith(tmpRoot) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: fs.rmSync, + run, + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(0); + expect(fs.existsSync(servicePath)).toBe(true); + expect(fs.existsSync(envPath)).toBe(true); + expect(run.mock.calls.map(([command, args]) => [command, ...args].join("\0"))).not.toContain( + ["pgrep", "-f", HOST_GATEWAY_PGREP_PATTERN].join("\0"), + ); + expect(run.mock.calls.some(([command]) => command === "pgrep")).toBe(false); + } finally { + fs.rmSync(tmpRoot, { recursive: true, force: true }); + } + }); + + it("removes the NemoClaw-managed Linux user service on full uninstall", () => { + const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const tmpHome = path.join(tmpRoot, "home"); + const xdgConfigHome = path.join(tmpRoot, "xdg-config"); + fs.mkdirSync(tmpHome, { recursive: true }); + const env = homeEnv(tmpHome, xdgConfigHome); + const servicePath = writeManagedService(tmpHome, env); + const envPath = writeGatewayEnv(tmpHome, env); + const runCalls: string[][] = []; + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: (command) => command === "systemctl", + env, + existsSync: (target) => String(target).startsWith(tmpRoot) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: fs.rmSync, + run: vi.fn((command: string, args: string[]) => { + runCalls.push([command, ...args]); + return ok(); + }), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(0); + expect(fs.existsSync(servicePath)).toBe(false); + expect(fs.existsSync(envPath)).toBe(false); + expect(runCalls).toContainEqual([ + "systemctl", + "--user", + "disable", + "--now", + OPENSHELL_GATEWAY_USER_SERVICE, + ]); + } finally { + fs.rmSync(tmpRoot, { recursive: true, force: true }); + } + }); + + it("reports incomplete uninstall when disabling the service fails", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const servicePath = writeManagedService(tmpHome); + const errors: string[] = []; + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: (command) => command === "systemctl", + env: homeEnv(tmpHome), + error: (line) => errors.push(line), + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: fs.rmSync, + run: vi.fn((command: string, args: string[]) => + command === "systemctl" && args.includes("disable") + ? { status: 1, stdout: "", stderr: "failed\n" } + : ok(), + ), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(1); + expect(fs.existsSync(servicePath)).toBe(false); + expect(errors).toContain( + "Uninstall completed with errors. Some state may remain on disk; see warnings above.", + ); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + + it("reports incomplete uninstall when the managed service cannot be read", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const servicePath = writeManagedService(tmpHome); + const errors: string[] = []; + const originalReadFileSync = fs.readFileSync; + const readSpy = vi.spyOn(fs, "readFileSync").mockImplementation((( + target: fs.PathOrFileDescriptor, + options?: Parameters[1], + ) => { + return String(target) === servicePath + ? (() => { + throw new Error("permission denied"); + })() + : (originalReadFileSync(target, options as never) as ReturnType); + }) as typeof fs.readFileSync); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: () => true, + env: homeEnv(tmpHome), + error: (line) => errors.push(line), + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: fs.rmSync, + run: vi.fn(() => ok()), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(1); + expect(fs.existsSync(servicePath)).toBe(true); + expect(errors).toContain( + `Failed to read ${servicePath}; leaving gateway user service in place.`, + ); + expect(errors).toContain( + "Uninstall completed with errors. Some state may remain on disk; see warnings above.", + ); + } finally { + readSpy.mockRestore(); + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + + it("reports incomplete uninstall when the managed service file cannot be removed", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const servicePath = writeManagedService(tmpHome); + const errors: string[] = []; + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: (command) => command === "systemctl", + env: homeEnv(tmpHome), + error: (line) => errors.push(line), + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: vi.fn((target: fs.PathLike) => + String(target) === servicePath + ? (() => { + throw new Error("permission denied"); + })() + : fs.rmSync(target, { recursive: true, force: true }), + ) as typeof fs.rmSync, + run: vi.fn(() => ok()), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(1); + expect(fs.existsSync(servicePath)).toBe(true); + expect(errors).toContain(`Failed to remove ${servicePath}: permission denied`); + expect(errors).toContain( + "Uninstall completed with errors. Some state may remain on disk; see warnings above.", + ); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + + it("reports incomplete uninstall when user systemd reload fails after removal", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const servicePath = writeManagedService(tmpHome); + const errors: string[] = []; + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: (command) => command === "systemctl", + env: homeEnv(tmpHome), + error: (line) => errors.push(line), + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: fs.rmSync, + run: vi.fn((command: string, args: string[]) => + command === "systemctl" && args.includes("daemon-reload") + ? { status: 1, stdout: "", stderr: "failed\n" } + : ok(), + ), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(1); + expect(fs.existsSync(servicePath)).toBe(false); + expect(errors).toContain("Failed to reload the user systemd manager."); + expect(errors).toContain( + "Uninstall completed with errors. Some state may remain on disk; see warnings above.", + ); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + + it("does not remove Linux user service units on macOS", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-macos-service-")); + const servicePath = writeManagedService(tmpHome); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: () => true, + env: homeEnv(tmpHome), + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "darwin", + rmSync: fs.rmSync, + run: vi.fn(() => ok()), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(0); + expect(fs.existsSync(servicePath)).toBe(true); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); +}); diff --git a/src/lib/actions/uninstall/run-plan.test.ts b/src/lib/actions/uninstall/run-plan.test.ts index bc9885e7dc2..c6eb57cca95 100644 --- a/src/lib/actions/uninstall/run-plan.test.ts +++ b/src/lib/actions/uninstall/run-plan.test.ts @@ -1398,12 +1398,12 @@ describe("uninstall run plan", () => { }); }); - it("kills host openshell-gateway process during uninstall (#3516)", () => { + it("kills host openshell-gateway process during full uninstall (#3516)", () => { const logs: string[] = []; const killed: number[] = []; const exited = new Set(); const result = runUninstallPlan( - { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: () => true, env: { HOME: "/tmp/nemoclaw-uninstall-test-3516" } as NodeJS.ProcessEnv, diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 282b60394a3..4a4c0ac0531 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -10,19 +10,25 @@ import { dockerSpawnSync } from "../../adapters/docker/exec"; import { type AgentBranding, getAgentBranding } from "../../cli/branding"; import { isStdinTty, readLineFromStdin } from "../../core/stdin"; import { sleepMs } from "../../core/wait"; -import { - defaultUninstallPaths, - NEMOCLAW_OLLAMA_MODELS, - NEMOCLAW_PROVIDERS, - type UninstallPaths, -} from "../../domain/uninstall/paths"; import { gatewayDestroySkipMessage, OPENSHELL_SANDBOXES_DELETE_SKIP_MESSAGE, preservedRegistryUnrecoverableWarnings, providerDeleteSkipMessage, } from "../../domain/uninstall/messaging"; +import { + defaultUninstallPaths, + NEMOCLAW_OLLAMA_MODELS, + NEMOCLAW_PROVIDERS, + type UninstallPaths, +} from "../../domain/uninstall/paths"; import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; +import { + getOpenShellUserConfigHome, + getNemoclawOpenShellGatewayUserServicePath, + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE, + OPENSHELL_GATEWAY_USER_SERVICE, +} from "../../onboard/docker-driver-gateway-service"; import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; import { isModelRouterCommandLineForPort } from "../../onboard/model-router-process"; import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; @@ -52,6 +58,7 @@ export interface UninstallRunDeps { isTty?: boolean; kill?: (pid: number, signal?: NodeJS.Signals | number) => boolean; log?: (message: string) => void; + platform?: NodeJS.Platform; readLine?: () => string | null; rmSync?: typeof fs.rmSync; run?: (command: string, args: string[], options?: SpawnSyncOptions) => RunResult; @@ -233,6 +240,7 @@ interface UninstallRuntime { isTty: boolean; kill: (pid: number, signal?: NodeJS.Signals | number) => boolean; log: (message: string) => void; + platform: NodeJS.Platform; readLine: () => string | null; rmSync: typeof fs.rmSync; run: (command: string, args: string[], options?: SpawnSyncOptions) => RunResult; @@ -261,6 +269,7 @@ function buildRuntime(deps: UninstallRunDeps): UninstallRuntime { } }), log: deps.log ?? ((message) => console.log(message)), + platform: deps.platform ?? process.platform, readLine: deps.readLine ?? readLineFromStdin, rmSync: deps.rmSync ?? fs.rmSync, run: deps.run ?? defaultRun, @@ -603,6 +612,72 @@ function stopOrphanedOpenShell(runtime: UninstallRuntime): void { } } +function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): boolean { + if (runtime.platform !== "linux") return true; + const servicePath = getNemoclawOpenShellGatewayUserServicePath( + runtime.env.HOME || os.homedir(), + runtime.env, + ); + if (!runtime.existsSync(servicePath)) return true; + + let unit = ""; + try { + unit = fs.readFileSync(servicePath, "utf-8"); + } catch { + runtime.warn(`Failed to read ${servicePath}; leaving gateway user service in place.`); + return false; + } + if ( + !unit + .split(/\r?\n/) + .some((line) => line.trimEnd() === NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE) + ) { + runtime.warn(`Leaving ${servicePath} in place because it is not NemoClaw-managed.`); + return true; + } + + let disabled = true; + if (runtime.commandExists("systemctl")) { + const disable = runtime.run( + "systemctl", + ["--user", "disable", "--now", OPENSHELL_GATEWAY_USER_SERVICE], + { env: runtime.env, stdio: "ignore" }, + ); + if (disable.status === 0) { + runtime.log(`Disabled ${OPENSHELL_GATEWAY_USER_SERVICE}.service`); + } else { + runtime.warn(`Failed to disable ${OPENSHELL_GATEWAY_USER_SERVICE}.service`); + disabled = false; + } + } else { + runtime.warn("systemctl not found; removing NemoClaw gateway user service file only."); + } + + let removed = false; + try { + runtime.rmSync(servicePath, { force: true }); + removed = true; + } catch (error) { + runtime.warn( + `Failed to remove ${servicePath}: ${error instanceof Error ? error.message : String(error)}`, + ); + disabled = false; + } + if (removed) runtime.log(`Removed ${servicePath}`); + + if (runtime.commandExists("systemctl")) { + const reload = runtime.run("systemctl", ["--user", "daemon-reload"], { + env: runtime.env, + stdio: "ignore", + }); + if (reload.status !== 0) { + runtime.warn("Failed to reload the user systemd manager."); + disabled = false; + } + } + return disabled; +} + function removeOpenShellResources(options: UninstallRunOptions, runtime: UninstallRuntime): void { if (!runtime.commandExists("openshell")) { runtime.warn("openshell not found; skipping gateway/provider/sandbox cleanup."); @@ -895,31 +970,34 @@ function executePlan( if (step.name === "Stopping services") { stopHelperServices(paths, runtime); removeGlob(paths.helperServiceGlob, runtime); - stopMatchingPids( - `openshell.*forward.*${runtime.env.NEMOCLAW_DASHBOARD_PORT || "18789"}`, - runtime, - "local OpenShell forward processes", - ); - stopStaleDashboardListeners({ - run: runtime.run, - kill: runtime.kill, - env: runtime.env, - log: runtime.log, - warn: runtime.warn, - commandExists: runtime.commandExists, - }); - stopOrphanedOpenShell(runtime); - stopHostGatewayProcesses( - { + if (!options.keepOpenShell) { + if (!removeNemoclawOpenShellGatewayUserService(runtime)) ok = false; + stopMatchingPids( + `openshell.*forward.*${runtime.env.NEMOCLAW_DASHBOARD_PORT || "18789"}`, + runtime, + "local OpenShell forward processes", + ); + stopStaleDashboardListeners({ run: runtime.run, kill: runtime.kill, env: runtime.env, log: runtime.log, warn: runtime.warn, commandExists: runtime.commandExists, - }, - { logNoProcesses: true }, - ); + }); + stopOrphanedOpenShell(runtime); + stopHostGatewayProcesses( + { + run: runtime.run, + kill: runtime.kill, + env: runtime.env, + log: runtime.log, + warn: runtime.warn, + commandExists: runtime.commandExists, + }, + { logNoProcesses: true }, + ); + } stopOllamaAuthProxy(paths, runtime); stopOpenRouterRuntimeAdapter(paths, runtime); stopModelRouter(paths, runtime); @@ -945,7 +1023,9 @@ function executePlan( removeFileWithOptionalSudo(target, runtime); if (!removePathExcept(paths.nemoclawStateDir, preserveUnderStateDir, runtime)) ok = false; removePath(paths.gatewayLocalStateDir, runtime); - removePath(paths.openshellConfigDir, runtime); + if (options.keepOpenShell) + runtime.log("Keeping OpenShell gateway configuration as requested."); + else removePath(paths.openshellConfigDir, runtime); removePath(paths.nemoclawConfigDir, runtime); } } @@ -958,12 +1038,15 @@ export function buildRunPlan( ): { paths: UninstallPaths; plan: UninstallPlan } { const env = { ...process.env, ...(deps.env ?? {}) }; const home = env.HOME || os.homedir(); - const paths = defaultUninstallPaths({ - home, - repoRoot: path.resolve(__dirname, "..", "..", ".."), - tmpDir: env.TMPDIR, - xdgBinHome: env.XDG_BIN_HOME, - }); + const paths = { + ...defaultUninstallPaths({ + home, + repoRoot: path.resolve(__dirname, "..", "..", ".."), + tmpDir: env.TMPDIR, + xdgBinHome: env.XDG_BIN_HOME, + }), + openshellConfigDir: path.join(getOpenShellUserConfigHome(home, env), "openshell"), + }; const plan = buildUninstallPlan(paths, { deleteModels: options.deleteModels, gatewayName: options.gatewayName, diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index df6934a4fdb..230e7ce1597 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -1989,9 +1989,11 @@ async function startDockerDriverGateway({ await dockerDriverGatewayEnv.startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles, exitOnFailure, + gatewayBin, gatewayEnv: driftGatewayEnv, gatewayName: GATEWAY_NAME, - isDockerDriverGatewayReady: () => isDockerDriverGatewayHttpReady(), + isDockerDriverGatewayReady: () => + isDockerDriverGatewayHttpReady(undefined, undefined, driftGatewayEnv), registerDockerDriverGatewayEndpoint, runCaptureOpenshell, skipSandboxBridgeReachability, @@ -2003,15 +2005,12 @@ async function startDockerDriverGateway({ }) ) return; - const gatewayStatus = runCaptureOpenshell(["status"], { ignoreError: true }); const gwInfo = runCaptureOpenshell(["gateway", "info", "-g", GATEWAY_NAME], { ignoreError: true, }); const activeGatewayInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); - // Port availability and listener enumeration are not atomic. The cutover - // rechecks health before adoption, reaps every observed duplicate, and - // requires a fresh strict bind proof after reaping before launch. + // Cutover rechecks health, reaps duplicates, and requires strict bind proof before launch. const portListenerScan = getDockerDriverGatewayPortListenerScan( await checkGatewayPortAvailable(), { gatewayBin: identityGatewayBin }, @@ -2039,7 +2038,8 @@ async function startDockerDriverGateway({ getDockerDriverGatewayRuntimeDrift, logDockerDriverGatewayRestart, registerDockerDriverGatewayEndpoint, - isDockerDriverGatewayHttpReady, + isDockerDriverGatewayHttpReady: () => + isDockerDriverGatewayHttpReady(undefined, undefined, driftGatewayEnv), verifySandboxBridgeGatewayReachableOrExit: (fail, options) => verifySandboxBridgeGatewayReachableOrExit(fail, { ...options, diff --git a/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts b/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts index 5b9d79b6a01..245f8f80abc 100644 --- a/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts @@ -12,6 +12,10 @@ import { writeDockerGatewayDebEnvOverride, } from "./docker-driver-gateway-env"; +function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { + return { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; +} + describe("buildDockerGatewayDebEnvFile", () => { it("replaces all managed gateway env keys and preserves unrelated values", () => { const next = buildDockerGatewayDebEnvFile( @@ -20,6 +24,7 @@ describe("buildDockerGatewayDebEnvFile", () => { "OPENSHELL_BIND_ADDRESS=127.0.0.1", "OPENSHELL_SERVER_PORT=8080", "OPENSHELL_DOCKER_SUPERVISOR_IMAGE=old", + "DOCKER_HOST=unix:///tmp/old-docker.sock", ].join("\n"), { OPENSHELL_DRIVERS: "docker", @@ -35,6 +40,7 @@ describe("buildDockerGatewayDebEnvFile", () => { OPENSHELL_DOCKER_SUPERVISOR_IMAGE: "new", OPENSHELL_GATEWAY_CONFIG: "/tmp/openshell-gateway.toml", OPENSHELL_VM_DRIVER_STATE_DIR: "/tmp/old-vm-driver", + DOCKER_HOST: "unix:///tmp/new-docker.sock", }, ); @@ -44,8 +50,10 @@ describe("buildDockerGatewayDebEnvFile", () => { expect(next).toContain("OPENSHELL_DOCKER_SUPERVISOR_IMAGE=new\n"); expect(next).toContain("OPENSHELL_GATEWAY_CONFIG=/tmp/openshell-gateway.toml\n"); expect(next).toContain("OPENSHELL_VM_DRIVER_STATE_DIR=/tmp/old-vm-driver\n"); + expect(next).toContain("DOCKER_HOST='unix:///tmp/new-docker.sock'\n"); expect(next).not.toContain("OPENSHELL_BIND_ADDRESS=127.0.0.1"); expect(next).not.toContain("OPENSHELL_DOCKER_SUPERVISOR_IMAGE=old"); + expect(next).not.toContain("DOCKER_HOST=unix:///tmp/old-docker.sock"); }); it("removes stale VM driver env keys when writing a Docker-driver env file", () => { @@ -63,6 +71,22 @@ describe("buildDockerGatewayDebEnvFile", () => { expect(next).toBe("OPENSHELL_DRIVERS=docker\n"); }); + it("removes a stale Docker endpoint when the current runtime uses the default socket", () => { + const next = buildDockerGatewayDebEnvFile("DOCKER_HOST=unix:///tmp/old-docker.sock\n", { + OPENSHELL_DRIVERS: "docker", + }); + + expect(next).toBe("OPENSHELL_DRIVERS=docker\n"); + }); + + it("quotes Docker socket paths for both service env readers", () => { + const dockerHost = "unix:///Users/José Doe/.colima/$(literal)/docker.sock"; + + expect(buildDockerGatewayDebEnvFile("", { DOCKER_HOST: dockerHost })).toBe( + `DOCKER_HOST='${dockerHost}'\n`, + ); + }); + it("removes stale auth-disable env so OpenShell 0.0.72 TOML auth policy stays authoritative", () => { const next = buildDockerGatewayDebEnvFile( [ @@ -114,7 +138,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { () => ({ OPENSHELL_BIND_ADDRESS: "127.0.0.1", }), - { platform: "linux" }, + { env: homeEnv(tempHome), platform: "linux" }, ); const envFileContent = fs.readFileSync(envFile, "utf-8"); @@ -142,7 +166,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { () => ({ OPENSHELL_BIND_ADDRESS: "127.0.0.1", }), - { platform: "linux" }, + { env: homeEnv(tempHome), platform: "linux" }, ); expect(wrote).toBe(false); diff --git a/src/lib/onboard/docker-driver-gateway-env-service.test.ts b/src/lib/onboard/docker-driver-gateway-env-service.test.ts index 3c9f1861a7e..179ba32d9a4 100644 --- a/src/lib/onboard/docker-driver-gateway-env-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env-service.test.ts @@ -6,29 +6,42 @@ import os from "node:os"; import path from "node:path"; import { describe, expect, it, vi } from "vitest"; - -import { startPackageManagedDockerDriverGatewayWithEnvOverride } from "./docker-driver-gateway-env"; import { writeSafeGatewayAuthConfig } from "../../../test/support/docker-driver-gateway-env-test-support"; +import { startPackageManagedDockerDriverGatewayWithEnvOverride } from "./docker-driver-gateway-env"; + +function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { + return { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; +} describe("package-managed Docker-driver gateway env service", () => { it("writes the service env only when package-managed startup prepares the service", async () => { const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); + const dockerHost = `unix://${path.join(tempHome, ".colima", "default", "docker.sock")}`; + const env = { ...homeEnv(tempHome), DOCKER_HOST: dockerHost }; + const gatewayBin = path.join(tempHome, ".local", "bin", "openshell-gateway"); + const servicePath = path.join( + tempHome, + ".config", + "systemd", + "user", + "openshell-gateway.service", + ); const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); - const existsSpy = vi - .spyOn(fs, "existsSync") - .mockImplementation( - (candidate) => candidate === "/usr/lib/systemd/user/openshell-gateway.service", - ); + const existsSpy = vi.spyOn(fs, "existsSync").mockReturnValue(false); const homedirSpy = vi.spyOn(os, "homedir").mockReturnValue(tempHome); + const platformSpy = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); try { await expect( startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env, exitOnFailure: false, + gatewayBin, gatewayEnv: { OPENSHELL_BIND_ADDRESS: "127.0.0.1", OPENSHELL_GATEWAY_CONFIG: writeSafeGatewayAuthConfig(tempHome), + OPENSHELL_SERVER_PORT: "18080", }, gatewayName: "nemoclaw", hasOpenShellGatewayUserService: () => true, @@ -37,7 +50,7 @@ describe("package-managed Docker-driver gateway env service", () => { runCaptureOpenshell: (args) => args[0] === "status" ? "Gateway: nemoclaw\nConnected" - : "Gateway: nemoclaw\nGateway endpoint: https://127.0.0.1:8080/", + : "Gateway: nemoclaw\nGateway endpoint: https://127.0.0.1:18080/", skipSandboxBridgeReachability: false, startOpenShellGatewayUserService: (opts) => { opts?.prepareServiceEnv?.(); @@ -47,10 +60,135 @@ describe("package-managed Docker-driver gateway env service", () => { }), ).resolves.toBe(true); + expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_BIND_ADDRESS=127.0.0.1\n"); + expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_SERVER_PORT=18080\n"); + expect(fs.readFileSync(envFile, "utf-8")).toContain(`DOCKER_HOST='${dockerHost}'\n`); + } finally { + existsSpy.mockRestore(); + homedirSpy.mockRestore(); + platformSpy.mockRestore(); + fs.rmSync(tempHome, { recursive: true, force: true }); + } + }); + + it.each([ + "tcp://attacker.example:2375", + "ssh://docker.example", + "unix://relative/docker.sock", + "unix:///tmp/docker's.sock", + ])("rejects unsafe package-service Docker endpoint %s", async (dockerHost) => { + const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); + const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); + const startService = vi.fn((opts?: { prepareServiceEnv?: () => void }) => { + opts?.prepareServiceEnv?.(); + return { attempted: true, fallbackAllowed: false, started: true }; + }); + + try { + await expect( + startPackageManagedDockerDriverGatewayWithEnvOverride({ + clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env: { ...homeEnv(tempHome), DOCKER_HOST: dockerHost }, + exitOnFailure: false, + gatewayEnv: { + OPENSHELL_BIND_ADDRESS: "127.0.0.1", + OPENSHELL_GATEWAY_CONFIG: writeSafeGatewayAuthConfig(tempHome), + }, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => true, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: () => "", + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: startService, + verifySandboxBridgeGatewayReachableOrExit: async () => undefined, + }), + ).rejects.toThrow(/only safely serializable absolute unix:\/\/ Docker sockets are supported/); + + expect(startService).toHaveBeenCalledOnce(); + expect(fs.existsSync(envFile)).toBe(false); + } finally { + fs.rmSync(tempHome, { recursive: true, force: true }); + } + }); + + it("leaves remote Docker endpoints to standalone fallback when no package service exists", async () => { + const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); + const startService = vi.fn(); + + try { + await expect( + startPackageManagedDockerDriverGatewayWithEnvOverride({ + clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env: { ...homeEnv(tempHome), DOCKER_HOST: "ssh://docker.example" }, + exitOnFailure: false, + gatewayEnv: { + OPENSHELL_BIND_ADDRESS: "127.0.0.1", + OPENSHELL_GATEWAY_CONFIG: writeSafeGatewayAuthConfig(tempHome), + }, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => false, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: () => "", + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: startService, + verifySandboxBridgeGatewayReachableOrExit: async () => undefined, + }), + ).resolves.toBe(false); + + expect(startService).not.toHaveBeenCalled(); + } finally { + fs.rmSync(tempHome, { recursive: true, force: true }); + } + }); + + it("uses one XDG config root for the service unit and gateway env", async () => { + const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); + const configHome = path.join(tempHome, "xdg-config"); + const env = homeEnv(tempHome, configHome); + const gatewayBin = path.join(tempHome, ".local", "bin", "openshell-gateway"); + const servicePath = path.join(configHome, "systemd", "user", "openshell-gateway.service"); + const envFile = path.join(configHome, "openshell", "gateway.env"); + const existsSpy = vi.spyOn(fs, "existsSync").mockReturnValue(false); + const homedirSpy = vi.spyOn(os, "homedir").mockReturnValue(tempHome); + const platformSpy = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + + try { + await expect( + startPackageManagedDockerDriverGatewayWithEnvOverride({ + clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env, + exitOnFailure: false, + gatewayBin, + gatewayEnv: { + OPENSHELL_BIND_ADDRESS: "127.0.0.1", + OPENSHELL_GATEWAY_CONFIG: writeSafeGatewayAuthConfig(tempHome), + OPENSHELL_SERVER_PORT: "18080", + }, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => true, + isDockerDriverGatewayReady: async () => true, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: (args) => + args[0] === "status" + ? "Gateway: nemoclaw\nConnected" + : "Gateway: nemoclaw\nGateway endpoint: https://127.0.0.1:18080/", + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: (opts) => { + opts?.prepareServiceEnv?.(); + return { attempted: true, fallbackAllowed: false, started: true }; + }, + verifySandboxBridgeGatewayReachableOrExit: async () => undefined, + }), + ).resolves.toBe(true); + + expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); + expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_SERVER_PORT=18080\n"); + expect(fs.existsSync(path.join(tempHome, ".config", "openshell", "gateway.env"))).toBe(false); } finally { existsSpy.mockRestore(); homedirSpy.mockRestore(); + platformSpy.mockRestore(); fs.rmSync(tempHome, { recursive: true, force: true }); } }); @@ -78,6 +216,7 @@ describe("package-managed Docker-driver gateway env service", () => { const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); const startService = vi.fn(); + const env = homeEnv(tempHome); const homedirSpy = vi.spyOn(os, "homedir").mockReturnValue(tempHome); try { for (const key of [ @@ -96,6 +235,7 @@ describe("package-managed Docker-driver gateway env service", () => { expect(() => startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env, exitOnFailure: false, gatewayEnv: { OPENSHELL_BIND_ADDRESS: "127.0.0.1", diff --git a/src/lib/onboard/docker-driver-gateway-env.test.ts b/src/lib/onboard/docker-driver-gateway-env.test.ts index c264c530c2c..02ecccf2f89 100644 --- a/src/lib/onboard/docker-driver-gateway-env.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env.test.ts @@ -14,6 +14,10 @@ import { writeDockerGatewayDebEnvOverride, } from "./docker-driver-gateway-env"; +function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { + return { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; +} + describe("buildDockerDriverGatewayEnv", () => { it("sets Docker-driver gateway networking from NemoClaw configuration", () => { const env = buildDockerDriverGatewayEnv({ @@ -147,7 +151,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { () => ({ OPENSHELL_BIND_ADDRESS: "127.0.0.1", }), - { platform: "linux" }, + { env: homeEnv(tempHome), platform: "linux" }, ); const envFileContent = fs.readFileSync(envFile, "utf-8"); @@ -175,7 +179,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { () => ({ OPENSHELL_BIND_ADDRESS: "127.0.0.1", }), - { platform: "linux" }, + { env: homeEnv(tempHome), platform: "linux" }, ); expect(wrote).toBe(false); @@ -187,6 +191,31 @@ describe("writeDockerGatewayDebEnvOverride", () => { } }); + it("uses the provided HOME as the config root fallback when XDG_CONFIG_HOME is unset", () => { + const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-home-")); + const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); + const existsSpy = vi + .spyOn(fs, "existsSync") + .mockImplementation( + (candidate) => candidate === "/usr/lib/systemd/user/openshell-gateway.service", + ); + + try { + const wrote = writeDockerGatewayDebEnvOverride( + () => ({ + OPENSHELL_BIND_ADDRESS: "127.0.0.1", + }), + { env: homeEnv(tempHome), platform: "linux" }, + ); + + expect(wrote).toBe(true); + expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_BIND_ADDRESS=127.0.0.1\n"); + } finally { + existsSpy.mockRestore(); + fs.rmSync(tempHome, { recursive: true, force: true }); + } + }); + it("writes the service env only when package-managed startup prepares the service", async () => { const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); @@ -207,6 +236,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { await expect( startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env: homeEnv(tempHome), exitOnFailure: false, gatewayEnv, gatewayName: "nemoclaw", diff --git a/src/lib/onboard/docker-driver-gateway-env.ts b/src/lib/onboard/docker-driver-gateway-env.ts index 69d71f4d863..19d9b43263a 100644 --- a/src/lib/onboard/docker-driver-gateway-env.ts +++ b/src/lib/onboard/docker-driver-gateway-env.ts @@ -18,7 +18,9 @@ import { } from "./docker-driver-gateway-config"; import { buildDockerDriverGatewayLocalTlsEnv } from "./docker-driver-gateway-local-tls"; import { + getOpenShellUserConfigHome, hasOpenShellGatewayUserService, + installAndReportNemoclawOpenShellGatewayUserService, type PackageManagedDockerDriverGatewayOptions, startPackageManagedDockerDriverGateway, } from "./docker-driver-gateway-service"; @@ -26,6 +28,7 @@ import { export { getGatewayHttpsEndpoint, startPackageManagedDockerDriverGateway }; export const DOCKER_DRIVER_GATEWAY_RUNTIME_ENV_KEYS = [ + "DOCKER_HOST", "OPENSHELL_DRIVERS", "OPENSHELL_BIND_ADDRESS", "OPENSHELL_SERVER_PORT", @@ -57,7 +60,10 @@ export type PackageManagedDockerDriverGatewayWithEnvOverrideOptions = Omit< PackageManagedDockerDriverGatewayOptions, "prepareOpenShellGatewayUserServiceEnv" > & { + env?: NodeJS.ProcessEnv; + gatewayBin?: string | null; gatewayEnv: Record; + home?: string; }; export function getGatewayPortCheckOptions(): { host: string } { @@ -240,9 +246,27 @@ function formatEnvironmentFileAssignment(key: string, value: string): string { if (/[\0\r\n]/.test(value)) { throw new Error(`Invalid OpenShell gateway env value for ${key}: contains a line break`); } + if (key === "DOCKER_HOST") { + const dockerHost = normalizePackageServiceDockerHost(value); + if (!dockerHost) throw new Error("Invalid empty DOCKER_HOST for the OpenShell gateway service"); + return `${key}='${dockerHost}'`; + } return `${key}=${value}`; } +function normalizePackageServiceDockerHost(value: string | undefined): string | undefined { + const candidate = String(value || "").trim(); + if (!candidate) return undefined; + const prefix = "unix://"; + const socketPath = candidate.startsWith(prefix) ? candidate.slice(prefix.length) : ""; + if (path.isAbsolute(socketPath) && !/[\0\r\n']/.test(socketPath)) { + return candidate; + } + throw new Error( + "Invalid DOCKER_HOST for the OpenShell gateway service; only safely serializable absolute unix:// Docker sockets are supported.", + ); +} + function readTextFileIfPresent(filePath: string): string { try { return fs.readFileSync(filePath, "utf-8"); @@ -258,9 +282,14 @@ function readTextFileIfPresent(filePath: string): string { } } -function writeDockerGatewayDebEnvOverrideFile(getOverride: () => Record): void { +function writeDockerGatewayDebEnvOverrideFile( + getOverride: () => Record, + opts: { env?: NodeJS.ProcessEnv; home?: string } = {}, +): void { const override = getOverride(); - const envDir = path.join(os.homedir(), ".config", "openshell"); + const env = opts.env ?? process.env; + const home = opts.home ?? opts.env?.HOME ?? os.homedir(); + const envDir = path.join(getOpenShellUserConfigHome(home, env), "openshell"); const envFile = path.join(envDir, "gateway.env"); fs.mkdirSync(envDir, { recursive: true, mode: 0o700 }); fs.chmodSync(envDir, 0o700); @@ -277,7 +306,7 @@ export function writeDockerGatewayDebEnvOverride( opts: Parameters[0] = {}, ): boolean { if (!hasOpenShellGatewayUserService(opts)) return false; - writeDockerGatewayDebEnvOverrideFile(getOverride); + writeDockerGatewayDebEnvOverrideFile(getOverride, opts); return true; } @@ -290,14 +319,34 @@ export function writeDockerGatewayDebEnvOverrideOrThrow( } } -export function startPackageManagedDockerDriverGatewayWithEnvOverride({ - gatewayEnv, - ...options -}: PackageManagedDockerDriverGatewayWithEnvOverrideOptions): Promise { +export function startPackageManagedDockerDriverGatewayWithEnvOverride( + optionsWithEnv: PackageManagedDockerDriverGatewayWithEnvOverrideOptions, +): Promise { + const { env: _env, gatewayBin, gatewayEnv, home, ...options } = optionsWithEnv; + const env = optionsWithEnv.env ?? process.env; assertDockerDriverGatewayAuthConfigSafe(gatewayEnv); + const effectiveHome = home ?? optionsWithEnv.env?.HOME ?? os.homedir(); + if (gatewayBin !== undefined) { + installAndReportNemoclawOpenShellGatewayUserService({ + env, + gatewayBin, + home: effectiveHome, + }); + } return startPackageManagedDockerDriverGateway({ ...options, - prepareOpenShellGatewayUserServiceEnv: () => - writeDockerGatewayDebEnvOverrideFile(() => gatewayEnv), + hasOpenShellGatewayUserService: + options.hasOpenShellGatewayUserService ?? + (() => hasOpenShellGatewayUserService({ env, home: effectiveHome })), + prepareOpenShellGatewayUserServiceEnv: () => { + const serviceGatewayEnv = { ...gatewayEnv }; + delete serviceGatewayEnv.DOCKER_HOST; + const dockerHost = normalizePackageServiceDockerHost(env.DOCKER_HOST); + if (dockerHost) serviceGatewayEnv.DOCKER_HOST = dockerHost; + writeDockerGatewayDebEnvOverrideFile(() => serviceGatewayEnv, { + env, + home: effectiveHome, + }); + }, }); } diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index f50515d0cfa..107d0f55af7 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -1,13 +1,22 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import path from "node:path"; + import { describe, expect, it, vi } from "vitest"; import { createVirtualClock } from "./__test-helpers__/virtual-clock"; import { + buildNemoclawOpenShellGatewayUserService, + getNemoclawOpenShellGatewayUserServicePath, getOpenShellGatewayUserServiceBinaryPaths, getOpenShellGatewayUserServicePaths, + getOpenShellUserConfigHome, + hasNemoclawOpenShellGatewayUserService, hasOpenShellGatewayUserService, + installAndReportNemoclawOpenShellGatewayUserService, + installNemoclawOpenShellGatewayUserService, + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, type SpawnSyncLikeResult, startOpenShellGatewayUserService, startPackageManagedDockerDriverGateway, @@ -47,13 +56,62 @@ function spawnResult(status = 0, stderr = "", stdout = ""): SpawnSyncLikeResult }; } +function homebrewServiceStatusResult({ + exitCode = 0, + running = true, + status = "started", +}: { + exitCode?: number | null; + running?: boolean; + status?: string; +} = {}): SpawnSyncLikeResult { + return spawnResult( + 0, + "", + JSON.stringify([ + { + exit_code: exitCode, + loaded: true, + name: "openshell", + running, + status, + }, + ]), + ); +} + +function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { + return { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; +} + describe("docker-driver-gateway-service", () => { - it("detects the upstream OpenShell user service only on Linux", () => { + it("detects the platform OpenShell gateway service", () => { const existsSync = (candidate: string) => candidate === "/usr/lib/systemd/user/openshell-gateway.service"; + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => + args.join(" ") === "list --formula openshell" ? spawnResult() : spawnResult(1, "unexpected"), + ); expect(hasOpenShellGatewayUserService({ existsSync, platform: "linux" })).toBe(true); - expect(hasOpenShellGatewayUserService({ existsSync, platform: "darwin" })).toBe(false); + expect( + hasOpenShellGatewayUserService({ + commandExists: () => false, + existsSync, + platform: "darwin", + }), + ).toBe(false); + expect( + hasOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + platform: "darwin", + spawnSyncImpl, + }), + ).toBe(true); + expect(spawnSyncImpl).toHaveBeenCalledWith( + "brew", + ["list", "--formula", "openshell"], + expect.objectContaining({ encoding: "utf-8" }), + ); expect(getOpenShellGatewayUserServicePaths()).toEqual([ "/usr/local/lib/systemd/user/openshell-gateway.service", "/usr/lib/systemd/user/openshell-gateway.service", @@ -65,22 +123,184 @@ describe("docker-driver-gateway-service", () => { ]); }); + it("resolves the service unit under the effective XDG config home", () => { + expect( + getNemoclawOpenShellGatewayUserServicePath("/home/nvidia", { + XDG_CONFIG_HOME: "/tmp/nemoclaw-config", + }), + ).toBe("/tmp/nemoclaw-config/systemd/user/openshell-gateway.service"); + expect( + getNemoclawOpenShellGatewayUserServicePath("/home/nvidia", { + XDG_CONFIG_HOME: "relative-config", + }), + ).toBe("/home/nvidia/.config/systemd/user/openshell-gateway.service"); + expect(getOpenShellUserConfigHome("/home/nvidia", { XDG_CONFIG_HOME: "/tmp/config" })).toBe( + "/tmp/config", + ); + }); + it("ignores stale per-user service units so standalone fallback remains available", () => { - const existsSync = vi.fn( - (candidate: string) => - candidate === "/home/nvidia/.config/systemd/user/openshell-gateway.service", + const home = "/home/nvidia"; + const env = homeEnv(home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); + const existsSync = vi.fn((candidate: string) => candidate === servicePath); + + expect( + hasOpenShellGatewayUserService({ + existsSync, + env, + home, + platform: "linux", + readFileSync: () => `# not ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + }), + ).toBe(false); + }); + + it("detects and installs a NemoClaw-managed user service on Linux only", () => { + const home = "/home/nvidia"; + const env = homeEnv(home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); + const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; + const chmodSync = vi.fn(); + const mkdirSync = vi.fn(); + const writeFileSync = vi.fn(); + + expect( + installNemoclawOpenShellGatewayUserService({ + chmodSync, + env, + existsSync: () => false, + gatewayBin, + home, + mkdirSync: mkdirSync as never, + platform: "linux", + writeFileSync: writeFileSync as never, + }), + ).toEqual({ installed: true, path: servicePath }); + expect(mkdirSync).toHaveBeenCalledWith(path.dirname(servicePath), { + recursive: true, + mode: 0o700, + }); + expect(chmodSync).toHaveBeenCalledWith(path.dirname(servicePath), 0o700); + expect(chmodSync).toHaveBeenCalledWith(servicePath, 0o600); + expect(String(writeFileSync.mock.calls[0]?.[1])).toContain(`ExecStart=${gatewayBin}`); + expect(String(writeFileSync.mock.calls[0]?.[1])).toContain("After=default.target"); + expect(String(writeFileSync.mock.calls[0]?.[1])).toContain( + "Environment=OPENSHELL_LOCAL_TLS_DIR=%h/.local/state/openshell/tls", + ); + expect(String(writeFileSync.mock.calls[0]?.[1])).toContain( + `ExecStartPre=${gatewayBin} generate-certs --output-dir \${OPENSHELL_LOCAL_TLS_DIR} --server-san host.openshell.internal --server-san localhost --server-san 127.0.0.1`, + ); + expect( + hasNemoclawOpenShellGatewayUserService({ + existsSync: (candidate) => candidate === servicePath, + env, + home, + platform: "linux", + readFileSync: () => buildNemoclawOpenShellGatewayUserService(gatewayBin), + }), + ).toBe(true); + expect( + installNemoclawOpenShellGatewayUserService({ + gatewayBin: "/opt/homebrew/bin/openshell-gateway", + platform: "darwin", + writeFileSync: vi.fn() as never, + }), + ).toEqual({ installed: false, reason: "not a Linux host" }); + }); + + it("warns when Linux service installation cannot find a gateway binary", () => { + const warn = vi.fn(); + + expect( + installAndReportNemoclawOpenShellGatewayUserService({ + existsSync: () => false, + gatewayBin: null, + platform: "linux", + warn, + }), + ).toEqual({ installed: false, reason: "OpenShell gateway binary not found" }); + expect(warn).toHaveBeenCalledWith( + " OpenShell gateway user service not installed: OpenShell gateway binary not found.", ); + }); + + it("removes a NemoClaw user override when an upstream service exists", () => { + const home = "/home/nvidia"; + const env = homeEnv(home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); + const rmSync = vi.fn(); + + expect( + installNemoclawOpenShellGatewayUserService({ + existsSync: (candidate) => + candidate === "/usr/lib/systemd/user/openshell-gateway.service" || + candidate === servicePath, + env, + gatewayBin: null, + home, + platform: "linux", + readFileSync: () => + buildNemoclawOpenShellGatewayUserService("/home/nvidia/.local/bin/openshell-gateway"), + rmSync: rmSync as never, + }), + ).toMatchObject({ installed: false, removed: true }); + expect(rmSync).toHaveBeenCalledWith(servicePath, { force: true }); + }); + + it("rejects unsafe NemoClaw service ExecStart paths", () => { + expect( + installNemoclawOpenShellGatewayUserService({ + existsSync: () => false, + gatewayBin: "./openshell-gateway", + platform: "linux", + }).reason, + ).toMatch(/absolute path/); + expect( + installNemoclawOpenShellGatewayUserService({ + existsSync: () => false, + gatewayBin: "/home/nvidia/bad path/openshell-gateway", + platform: "linux", + }).reason, + ).toMatch(/cannot contain whitespace/); + expect( + installNemoclawOpenShellGatewayUserService({ + existsSync: () => false, + gatewayBin: "/opt/openshell/bin/openshell-gateway", + home: "/home/nvidia", + platform: "linux", + }).reason, + ).toMatch(/not in a trusted install path/); + }); - expect(hasOpenShellGatewayUserService({ existsSync, platform: "linux" })).toBe(false); - expect(existsSync.mock.calls.flat()).not.toContain( - "/home/nvidia/.config/systemd/user/openshell-gateway.service", + it("restarts the NemoClaw-managed user service after validating its identity", () => { + const home = "/home/nvidia"; + const env = homeEnv(home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); + const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => + args.includes("show") + ? spawnResult(0, "", trustedShowOutput(servicePath, gatewayBin)) + : spawnResult(), ); + + expect( + startOpenShellGatewayUserService({ + commandExists: (command) => command === "systemctl", + env, + existsSync: (candidate) => candidate === servicePath, + home, + platform: "linux", + readFileSync: () => buildNemoclawOpenShellGatewayUserService(gatewayBin), + spawnSyncImpl, + }), + ).toMatchObject({ attempted: true, fallbackAllowed: false, started: true }); }); it("restarts the upstream user service with systemctl --user after validating identity", () => { const events: string[] = []; const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { - events.push(args[1] ?? args[0] ?? ""); + events.push(args[0] === "is-active" ? "is-active" : (args[1] ?? args[0] ?? "")); return args.includes("show") ? spawnResult(0, "", trustedShowOutput()) : spawnResult(); }); @@ -93,8 +313,15 @@ describe("docker-driver-gateway-service", () => { spawnSyncImpl, }); - expect(result).toEqual({ attempted: true, fallbackAllowed: false, started: true }); - expect(events).toEqual(["daemon-reload", "show", "prepare-env", "enable", "restart"]); + expect(result).toMatchObject({ attempted: true, fallbackAllowed: false, started: true }); + expect(events).toEqual([ + "daemon-reload", + "show", + "prepare-env", + "enable", + "restart", + "is-active", + ]); expect(spawnSyncImpl.mock.calls.map(([command, args]) => [command, args])).toEqual([ ["systemctl", ["--user", "daemon-reload"]], [ @@ -103,9 +330,180 @@ describe("docker-driver-gateway-service", () => { ], ["systemctl", ["--user", "enable", "openshell-gateway"]], ["systemctl", ["--user", "restart", "openshell-gateway"]], + ["systemctl", ["--user", "is-active", "--quiet", "openshell-gateway"]], + ]); + }); + + it("restarts the macOS Homebrew gateway service", () => { + const events: string[] = []; + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { + const command = args.join(" "); + events.push(command); + return command === "services info --json openshell" + ? homebrewServiceStatusResult() + : spawnResult(); + }); + + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + env: {}, + platform: "darwin", + prepareServiceEnv: () => events.push("prepare-env"), + spawnSyncImpl, + }); + + expect(result).toEqual({ + attempted: true, + fallbackAllowed: false, + manager: "homebrew", + serviceName: "openshell", + started: true, + statusCommand: "brew services info openshell", + }); + expect(events).toEqual([ + "list --formula openshell", + "prepare-env", + "services restart openshell", + "services info --json openshell", ]); }); + it("waits briefly for a restarted macOS Homebrew service to begin running", () => { + let statusChecks = 0; + const sleepSeconds = vi.fn(); + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { + const isStatusCheck = args.join(" ") === "services info --json openshell"; + const result = isStatusCheck + ? homebrewServiceStatusResult({ + exitCode: statusChecks === 0 ? null : 0, + running: statusChecks > 0, + }) + : spawnResult(); + statusChecks += Number(isStatusCheck); + return result; + }); + + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + env: {}, + platform: "darwin", + sleepSeconds, + spawnSyncImpl, + }); + + expect(result).toMatchObject({ manager: "homebrew", started: true }); + expect(statusChecks).toBe(2); + expect(sleepSeconds).toHaveBeenCalledOnce(); + expect(sleepSeconds).toHaveBeenCalledWith(0.25); + }); + + it("rejects a macOS Homebrew service that exits after a successful restart", () => { + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { + return args.join(" ") === "services info --json openshell" + ? homebrewServiceStatusResult({ exitCode: 1, running: false, status: "error" }) + : spawnResult(); + }); + + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + env: {}, + platform: "darwin", + sleepSeconds: vi.fn(), + spawnSyncImpl, + }); + + expect(result).toMatchObject({ + attempted: true, + fallbackAllowed: false, + manager: "homebrew", + serviceName: "openshell", + started: false, + }); + expect(result.reason).toMatch(/not running.*status=error.*exit_code=1/); + }); + + it("rechecks Homebrew service liveness before the sandbox bridge probe", async () => { + const verifySandboxBridgeGatewayReachableOrExit = vi.fn(); + + await expect( + startPackageManagedDockerDriverGateway({ + clearDockerDriverGatewayRuntimeFiles: vi.fn(), + exitOnFailure: false, + gatewayName: "nemoclaw", + getHomebrewServiceRunningState: () => ({ + ok: false, + reason: "brew services info --json openshell reports exit_code=1", + }), + hasOpenShellGatewayUserService: () => true, + healthPollCount: 1, + healthPollInterval: 0, + isDockerDriverGatewayReady: async () => true, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: (args) => (args[0] === "status" ? STATUS_CONNECTED : GATEWAY_INFO), + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: () => ({ + attempted: true, + fallbackAllowed: false, + manager: "homebrew", + started: true, + statusCommand: "brew services info openshell", + }), + verifySandboxBridgeGatewayReachableOrExit, + }), + ).rejects.toThrow(/service stopped after startup.*exit_code=1/); + + expect(verifySandboxBridgeGatewayReachableOrExit).not.toHaveBeenCalled(); + }); + + it.each([ + "not json", + "[]", + ])("fails closed when Homebrew service status is unusable: %s", (stdout) => { + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + env: {}, + platform: "darwin", + sleepSeconds: vi.fn(), + spawnSyncImpl: vi.fn((_command: string, args: string[]) => + args.join(" ") === "services info --json openshell" + ? spawnResult(0, "", stdout) + : spawnResult(), + ), + }); + + expect(result).toMatchObject({ + attempted: true, + fallbackAllowed: false, + manager: "homebrew", + serviceName: "openshell", + started: false, + }); + expect(result.reason).toContain("brew services info --json openshell"); + }); + + it("does not fall back when the macOS Homebrew service restart fails", () => { + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + env: {}, + platform: "darwin", + spawnSyncImpl: vi.fn((_command: string, args: string[]) => + args.join(" ") === "services restart openshell" + ? spawnResult(1, "launchctl failed") + : spawnResult(), + ), + }); + + expect(result).toMatchObject({ + attempted: true, + fallbackAllowed: false, + manager: "homebrew", + serviceName: "openshell", + started: false, + statusCommand: "brew services info openshell", + }); + expect(result.reason).toContain("launchctl failed"); + }); + it("allows standalone fallback when the user systemd manager is unavailable", () => { const result = startOpenShellGatewayUserService({ commandExists: () => true, @@ -188,6 +586,29 @@ describe("docker-driver-gateway-service", () => { expect(result.reason).toContain("No such file or directory"); }); + it("does not report service startup success when the restarted service is inactive", () => { + const result = startOpenShellGatewayUserService({ + commandExists: () => true, + env: {}, + existsSync: () => true, + platform: "linux", + spawnSyncImpl: vi.fn((_command: string, args: string[]) => + args.includes("show") + ? spawnResult(0, "", trustedShowOutput()) + : args.includes("is-active") + ? spawnResult(3, "inactive") + : spawnResult(), + ), + }); + + expect(result).toMatchObject({ + attempted: true, + fallbackAllowed: false, + started: false, + }); + expect(result.reason).toContain("is-active --quiet openshell-gateway failed"); + }); + it("falls back instead of trusting an unverified service identity", () => { const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { if (args.includes("show")) { @@ -213,7 +634,7 @@ describe("docker-driver-gateway-service", () => { fallbackAllowed: true, started: false, }); - expect(result.reason).toContain("not the package-managed OpenShell gateway"); + expect(result.reason).toContain("not a trusted OpenShell gateway"); expect(spawnSyncImpl.mock.calls.map(([, args]) => args.join(" "))).not.toContain( "--user restart openshell-gateway", ); @@ -247,7 +668,7 @@ describe("docker-driver-gateway-service", () => { fallbackAllowed: true, started: false, }); - expect(result.reason).toContain("not the package-managed OpenShell gateway"); + expect(result.reason).toContain("not a trusted OpenShell gateway"); expect(spawnSyncImpl.mock.calls.map(([, args]) => args.join(" "))).not.toContain( "--user restart openshell-gateway", ); @@ -297,6 +718,60 @@ describe("docker-driver-gateway-service", () => { expect(events).toEqual(["register", "sleep", "register", "ready", "clear", "verify"]); }); + it("accepts package-managed service health when CLI metadata is healthy and direct gRPC probe is unavailable", async () => { + const clearDockerDriverGatewayRuntimeFiles = vi.fn(); + + await expect( + startPackageManagedDockerDriverGateway({ + clearDockerDriverGatewayRuntimeFiles, + exitOnFailure: false, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => true, + healthPollCount: 1, + healthPollInterval: 0, + isDockerDriverGatewayReady: async () => false, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: (args) => (args[0] === "status" ? STATUS_CONNECTED : GATEWAY_INFO), + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: () => ({ + attempted: true, + fallbackAllowed: false, + started: true, + }), + verifySandboxBridgeGatewayReachableOrExit: vi.fn(), + }), + ).resolves.toBe(true); + + expect(clearDockerDriverGatewayRuntimeFiles).toHaveBeenCalledOnce(); + }); + + it("accepts package-managed service health when direct gRPC probe is healthy and CLI status is unavailable", async () => { + const clearDockerDriverGatewayRuntimeFiles = vi.fn(); + + await expect( + startPackageManagedDockerDriverGateway({ + clearDockerDriverGatewayRuntimeFiles, + exitOnFailure: false, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => true, + healthPollCount: 1, + healthPollInterval: 0, + isDockerDriverGatewayReady: async () => true, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: (args) => (args[0] === "gateway" ? GATEWAY_INFO : ""), + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: () => ({ + attempted: true, + fallbackAllowed: false, + started: true, + }), + verifySandboxBridgeGatewayReachableOrExit: vi.fn(), + }), + ).resolves.toBe(true); + + expect(clearDockerDriverGatewayRuntimeFiles).toHaveBeenCalledOnce(); + }); + it("preserves bounded immediate package-service probes when the interval is zero", async () => { const clock = createVirtualClock(); let registerCount = 0; @@ -373,7 +848,7 @@ describe("docker-driver-gateway-service", () => { isDockerDriverGatewayReady: async () => false, now: clock.now, registerDockerDriverGatewayEndpoint: () => true, - runCaptureOpenshell: (args) => (args[0] === "status" ? STATUS_CONNECTED : GATEWAY_INFO), + runCaptureOpenshell: (args) => (args[0] === "status" ? "Error: Connection refused" : ""), sleepSeconds: clock.advance, skipSandboxBridgeReachability: false, startOpenShellGatewayUserService: () => ({ diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index dcdc0db52a0..2291eb7437f 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -3,9 +3,10 @@ import { type SpawnSyncOptions, spawnSync } from "node:child_process"; import fs from "node:fs"; +import os from "node:os"; import path from "node:path"; -import { sleepSeconds, waitUntilAsync } from "../core/wait"; +import { sleepSeconds, waitUntil, waitUntilAsync } from "../core/wait"; import { isGatewayHealthy } from "../state/gateway"; import { envInt } from "./env"; import { @@ -15,23 +16,60 @@ import { import { isDockerDriverGatewayHttpReady } from "./gateway-http-readiness"; export const OPENSHELL_GATEWAY_USER_SERVICE = "openshell-gateway"; +export const OPENSHELL_GATEWAY_HOMEBREW_SERVICE = "openshell"; +export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER = + "NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"; +export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE = `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`; +const HOMEBREW_SERVICE_STATUS_POLL_ATTEMPTS = 5; +const HOMEBREW_SERVICE_STATUS_POLL_INTERVAL_SECONDS = 0.25; export interface OpenShellGatewayUserServiceOptions { commandExists?: (command: string) => boolean; env?: NodeJS.ProcessEnv; existsSync?: (filePath: string) => boolean; + home?: string; platform?: NodeJS.Platform; prepareServiceEnv?: () => void; + readFileSync?: (filePath: string, encoding: BufferEncoding) => string; + sleepSeconds?: (seconds: number) => void; spawnSyncImpl?: SpawnSyncLike; } export interface OpenShellGatewayUserServiceStartResult { attempted: boolean; fallbackAllowed: boolean; + manager?: "homebrew" | "systemd"; reason?: string; + serviceName?: string; + statusCommand?: string; started: boolean; } +export interface InstallNemoclawOpenShellGatewayUserServiceOptions + extends Pick< + OpenShellGatewayUserServiceOptions, + "env" | "existsSync" | "home" | "platform" | "readFileSync" + > { + chmodSync?: (filePath: string, mode: number) => void; + gatewayBin: string | null; + mkdirSync?: typeof fs.mkdirSync; + rmSync?: typeof fs.rmSync; + writeFileSync?: typeof fs.writeFileSync; +} + +export interface InstallNemoclawOpenShellGatewayUserServiceResult { + installed: boolean; + path?: string; + reason?: string; + removed?: boolean; +} + +export interface InstallAndReportNemoclawOpenShellGatewayUserServiceOptions + extends InstallNemoclawOpenShellGatewayUserServiceOptions { + log?: (message: string) => void; + warn?: (message: string) => void; +} + export interface SpawnSyncLikeResult { error?: Error; status: number | null; @@ -49,6 +87,7 @@ export interface PackageManagedDockerDriverGatewayOptions { clearDockerDriverGatewayRuntimeFiles: () => void; exitOnFailure: boolean; gatewayName: string; + getHomebrewServiceRunningState?: () => { ok: boolean; reason?: string }; hasOpenShellGatewayUserService?: () => boolean; healthPollCount?: number; healthPollInterval?: number; @@ -73,6 +112,14 @@ interface OpenShellGatewayUserServiceIdentity { fragmentPath: string; } +interface OpenShellGatewayUserServiceTarget { + manager: "homebrew" | "systemd"; + serviceName: string; + statusCommand: string; + trustedBinaryPaths: string[]; + trustedUnitPaths: string[]; +} + export function getOpenShellGatewayUserServicePaths(): string[] { return [ "/usr/local/lib/systemd/user/openshell-gateway.service", @@ -85,7 +132,65 @@ export function getOpenShellGatewayUserServiceBinaryPaths(): string[] { return ["/usr/local/bin/openshell-gateway", "/usr/bin/openshell-gateway"]; } -export function hasOpenShellGatewayUserService( +function effectiveHome(home: string | undefined, env: NodeJS.ProcessEnv | undefined): string { + return home ?? env?.HOME ?? os.homedir(); +} + +export function getOpenShellUserConfigHome(home = os.homedir(), env?: NodeJS.ProcessEnv): string { + const configured = env?.XDG_CONFIG_HOME?.trim(); + if (configured && path.isAbsolute(configured)) return path.normalize(configured); + return path.join(home, ".config"); +} + +export function getNemoclawOpenShellGatewayUserServicePath( + home = os.homedir(), + env?: NodeJS.ProcessEnv, +): string { + return path.join( + getOpenShellUserConfigHome(home, env), + "systemd", + "user", + "openshell-gateway.service", + ); +} + +export function getNemoclawOpenShellGatewayUserServiceBinaryPaths(home = os.homedir()): string[] { + return [ + path.join(home, ".local", "bin", "openshell-gateway"), + ...getOpenShellGatewayUserServiceBinaryPaths(), + ]; +} + +function formatError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function readTextFileIfPresent( + filePath: string, + opts: Pick = {}, +): string { + const readFileSync = opts.readFileSync ?? fs.readFileSync; + try { + return readFileSync(filePath, "utf-8"); + } catch { + return ""; + } +} + +function hasNemoclawOpenShellGatewayUserServiceMarker(unit: string): boolean { + return unit + .split(/\r?\n/) + .some((line) => line.trimEnd() === NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE); +} + +function isNemoclawManagedOpenShellGatewayUserServiceUnit( + filePath: string, + opts: Pick = {}, +): boolean { + return hasNemoclawOpenShellGatewayUserServiceMarker(readTextFileIfPresent(filePath, opts)); +} + +function hasUpstreamOpenShellGatewayUserService( opts: Pick = {}, ): boolean { if ((opts.platform ?? process.platform) !== "linux") return false; @@ -93,6 +198,95 @@ export function hasOpenShellGatewayUserService( return getOpenShellGatewayUserServicePaths().some((candidate) => existsSync(candidate)); } +function hasHomebrewOpenShellGatewayService( + opts: Pick< + OpenShellGatewayUserServiceOptions, + "commandExists" | "env" | "platform" | "spawnSyncImpl" + > = {}, +): boolean { + const platform = opts.platform ?? process.platform; + if (platform !== "darwin") return false; + const env = opts.env ?? process.env; + const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); + if (!commandExists("brew")) return false; + const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; + const result = runBrew(["list", "--formula", OPENSHELL_GATEWAY_HOMEBREW_SERVICE], { + env, + spawnSyncImpl, + }); + return result.ok; +} + +export function hasNemoclawOpenShellGatewayUserService( + opts: Pick< + OpenShellGatewayUserServiceOptions, + "env" | "existsSync" | "home" | "platform" | "readFileSync" + > = {}, +): boolean { + if ((opts.platform ?? process.platform) !== "linux") return false; + const env = opts.env ?? process.env; + const existsSync = opts.existsSync ?? fs.existsSync; + const home = effectiveHome(opts.home, opts.env); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); + return ( + existsSync(servicePath) && + isNemoclawManagedOpenShellGatewayUserServiceUnit(servicePath, { + readFileSync: opts.readFileSync, + }) + ); +} + +function resolveOpenShellGatewayUserService( + opts: Pick< + OpenShellGatewayUserServiceOptions, + "commandExists" | "env" | "existsSync" | "home" | "platform" | "readFileSync" | "spawnSyncImpl" + > = {}, +): OpenShellGatewayUserServiceTarget | null { + const platform = opts.platform ?? process.platform; + if (platform === "darwin") { + if (!hasHomebrewOpenShellGatewayService(opts)) return null; + return { + manager: "homebrew", + serviceName: OPENSHELL_GATEWAY_HOMEBREW_SERVICE, + statusCommand: `brew services info ${OPENSHELL_GATEWAY_HOMEBREW_SERVICE}`, + trustedBinaryPaths: [], + trustedUnitPaths: [], + }; + } + if (platform !== "linux") return null; + if (hasUpstreamOpenShellGatewayUserService(opts)) { + return { + manager: "systemd", + serviceName: OPENSHELL_GATEWAY_USER_SERVICE, + statusCommand: `systemctl --user status ${OPENSHELL_GATEWAY_USER_SERVICE}`, + trustedBinaryPaths: getOpenShellGatewayUserServiceBinaryPaths(), + trustedUnitPaths: getOpenShellGatewayUserServicePaths(), + }; + } + if (hasNemoclawOpenShellGatewayUserService(opts)) { + const env = opts.env ?? process.env; + const home = effectiveHome(opts.home, opts.env); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); + return { + manager: "systemd", + serviceName: OPENSHELL_GATEWAY_USER_SERVICE, + statusCommand: `systemctl --user status ${OPENSHELL_GATEWAY_USER_SERVICE}`, + trustedBinaryPaths: getNemoclawOpenShellGatewayUserServiceBinaryPaths(home), + trustedUnitPaths: [servicePath], + }; + } + return null; +} + +export function hasOpenShellGatewayUserService( + opts: Pick< + OpenShellGatewayUserServiceOptions, + "commandExists" | "env" | "existsSync" | "home" | "platform" | "readFileSync" | "spawnSyncImpl" + > = {}, +): boolean { + return resolveOpenShellGatewayUserService(opts) !== null; +} + function defaultCommandExists(command: string, env: NodeJS.ProcessEnv): boolean { return ( spawnSync("sh", ["-c", 'command -v "$1" >/dev/null 2>&1', "sh", command], { @@ -134,6 +328,95 @@ function runSystemctlUser( return { ok: true, stdout: text(result.stdout) }; } +function runBrew( + args: string[], + opts: Required>, +): { ok: boolean; reason?: string; stdout?: string } { + const result = opts.spawnSyncImpl("brew", args, { + encoding: "utf-8", + env: opts.env, + stdio: ["ignore", "pipe", "pipe"], + } satisfies SpawnSyncOptions); + if (result.error) { + return { ok: false, reason: result.error.message }; + } + if (result.status !== 0) { + const detail = + text(result.stderr).trim() || text(result.stdout).trim() || `exit ${String(result.status)}`; + return { ok: false, reason: detail }; + } + return { ok: true, stdout: text(result.stdout) }; +} + +function parseHomebrewServiceRunningState( + output: string, + serviceName: string, +): { ok: boolean; reason?: string } { + let parsed: unknown; + try { + parsed = JSON.parse(output); + } catch { + return { ok: false, reason: "returned invalid JSON" }; + } + if (!Array.isArray(parsed)) return { ok: false, reason: "returned a non-array response" }; + const service = parsed.find( + (entry): entry is Record => + typeof entry === "object" && entry !== null && entry.name === serviceName, + ); + if (!service) return { ok: false, reason: `did not report service ${serviceName}` }; + if (service.loaded === true && service.running === true) return { ok: true }; + return { + ok: false, + reason: `${serviceName} is not running (loaded=${String(service.loaded ?? "")}, running=${String(service.running ?? "")}, status=${String(service.status ?? "")}, exit_code=${String(service.exit_code ?? "")})`, + }; +} + +function readHomebrewServiceRunningState( + opts: Pick & { + serviceName?: string; + } = {}, +): { ok: boolean; reason?: string } { + const env = opts.env ?? process.env; + const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; + const serviceName = opts.serviceName ?? OPENSHELL_GATEWAY_HOMEBREW_SERVICE; + const statusArgs = ["services", "info", "--json", serviceName]; + const status = runBrew(statusArgs, { env, spawnSyncImpl }); + if (!status.ok) { + return { ok: false, reason: `brew ${statusArgs.join(" ")} failed: ${status.reason}` }; + } + const running = parseHomebrewServiceRunningState(status.stdout ?? "", serviceName); + if (!running.ok) { + return { ok: false, reason: `brew ${statusArgs.join(" ")} ${running.reason}` }; + } + return { ok: true }; +} + +function waitForHomebrewServiceRunning( + opts: Pick & { + serviceName?: string; + } = {}, +): { ok: boolean; reason?: string } { + const sleepSecondsImpl = opts.sleepSeconds ?? sleepSeconds; + let latest: { ok: boolean; reason?: string } = { + ok: false, + reason: "Homebrew service status was not checked", + }; + const running = waitUntil( + () => { + latest = readHomebrewServiceRunningState(opts); + return latest.ok; + }, + { + backoffFactor: 1, + initialIntervalMs: HOMEBREW_SERVICE_STATUS_POLL_INTERVAL_SECONDS * 1000, + maxAttempts: HOMEBREW_SERVICE_STATUS_POLL_ATTEMPTS, + maxIntervalMs: HOMEBREW_SERVICE_STATUS_POLL_INTERVAL_SECONDS * 1000, + sleep: (ms) => sleepSecondsImpl(ms / 1000), + }, + ); + return running ? { ok: true } : latest; +} + function parseSystemctlShowProperties(output: string): Record { const properties: Record = {}; for (const line of output.split(/\r?\n/)) { @@ -145,17 +428,18 @@ function parseSystemctlShowProperties(output: string): Record { } function isTrustedOpenShellGatewayUserServiceIdentity( + service: OpenShellGatewayUserServiceTarget, identity: OpenShellGatewayUserServiceIdentity, ): boolean { const fragmentPath = path.normalize(identity.fragmentPath.trim()); - const trustedUnit = getOpenShellGatewayUserServicePaths().some( + const trustedUnit = service.trustedUnitPaths.some( (candidate) => path.normalize(candidate) === fragmentPath, ); if (!trustedUnit) return false; const execStartPath = extractSystemdExecStartPath(identity.execStart); if (!execStartPath) return false; const normalizedExecStartPath = path.normalize(execStartPath); - return getOpenShellGatewayUserServiceBinaryPaths().some( + return service.trustedBinaryPaths.some( (candidate) => path.normalize(candidate) === normalizedExecStartPath, ); } @@ -168,17 +452,18 @@ function extractSystemdExecStartPath(execStart: string): string | null { } function readTrustedOpenShellGatewayUserServiceIdentity( + service: OpenShellGatewayUserServiceTarget, opts: Required>, ): { fallbackAllowed: boolean; ok: boolean; reason?: string } { const result = runSystemctlUser( - ["show", OPENSHELL_GATEWAY_USER_SERVICE, "--property=FragmentPath", "--property=ExecStart"], + ["show", service.serviceName, "--property=FragmentPath", "--property=ExecStart"], opts, ); if (!result.ok) { return { fallbackAllowed: userManagerLooksUnavailable(result.reason ?? ""), ok: false, - reason: `systemctl --user show ${OPENSHELL_GATEWAY_USER_SERVICE} failed: ${result.reason}`, + reason: `systemctl --user show ${service.serviceName} failed: ${result.reason}`, }; } @@ -194,25 +479,196 @@ function readTrustedOpenShellGatewayUserServiceIdentity( reason: "service identity is incomplete", }; } - if (!isTrustedOpenShellGatewayUserServiceIdentity(identity)) { + if (!isTrustedOpenShellGatewayUserServiceIdentity(service, identity)) { return { fallbackAllowed: true, ok: false, - reason: `service identity is not the package-managed OpenShell gateway (${identity.fragmentPath})`, + reason: `service identity is not a trusted OpenShell gateway (${identity.fragmentPath})`, }; } return { fallbackAllowed: false, ok: true }; } +function assertSafeSystemdExecPath(filePath: string): void { + if (!path.isAbsolute(filePath)) { + throw new Error("OpenShell gateway service ExecStart must be an absolute path"); + } + if (/[\0\r\n\t ]/.test(filePath)) { + throw new Error("OpenShell gateway service ExecStart path cannot contain whitespace"); + } +} + +function isTrustedNemoclawGatewayServiceBinaryPath(filePath: string, home: string): boolean { + const normalizedPath = path.normalize(filePath); + return getNemoclawOpenShellGatewayUserServiceBinaryPaths(home).some( + (candidate) => path.normalize(candidate) === normalizedPath, + ); +} + +export function buildNemoclawOpenShellGatewayUserService(gatewayBin: string): string { + assertSafeSystemdExecPath(gatewayBin); + return [ + "# NemoClaw-managed OpenShell gateway user service", + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE, + "[Unit]", + "Description=OpenShell Gateway", + "Documentation=https://github.com/NVIDIA/OpenShell", + "After=default.target", + "", + "[Service]", + "Type=simple", + "StateDirectory=openshell/gateway", + "Environment=OPENSHELL_LOCAL_TLS_DIR=%h/.local/state/openshell/tls", + "EnvironmentFile=-%E/openshell/gateway.env", + `ExecStartPre=${gatewayBin} generate-certs --output-dir \${OPENSHELL_LOCAL_TLS_DIR} --server-san host.openshell.internal --server-san localhost --server-san 127.0.0.1`, + `ExecStart=${gatewayBin}`, + "Restart=on-failure", + "RestartSec=5s", + "PrivateTmp=true", + "UMask=0077", + "", + "[Install]", + "WantedBy=default.target", + "", + ].join("\n"); +} + +export function installNemoclawOpenShellGatewayUserService( + opts: InstallNemoclawOpenShellGatewayUserServiceOptions, +): InstallNemoclawOpenShellGatewayUserServiceResult { + const platform = opts.platform ?? process.platform; + if (platform !== "linux") return { installed: false, reason: "not a Linux host" }; + const home = effectiveHome(opts.home, opts.env); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, opts.env); + const existsSync = opts.existsSync ?? fs.existsSync; + if (hasUpstreamOpenShellGatewayUserService(opts)) { + if ( + existsSync(servicePath) && + isNemoclawManagedOpenShellGatewayUserServiceUnit(servicePath, { + readFileSync: opts.readFileSync, + }) + ) { + const rmSync = opts.rmSync ?? fs.rmSync; + try { + rmSync(servicePath, { force: true }); + } catch (error) { + return { + installed: false, + path: servicePath, + reason: `failed to remove NemoClaw gateway user service override: ${formatError(error)}`, + }; + } + return { + installed: false, + path: servicePath, + reason: "upstream OpenShell gateway service is installed", + removed: true, + }; + } + return { installed: false, reason: "upstream OpenShell gateway service is installed" }; + } + if (!opts.gatewayBin) return { installed: false, reason: "OpenShell gateway binary not found" }; + + const alreadyExists = existsSync(servicePath); + if ( + alreadyExists && + !isNemoclawManagedOpenShellGatewayUserServiceUnit(servicePath, { + readFileSync: opts.readFileSync, + }) + ) { + return { + installed: false, + path: servicePath, + reason: "refusing to overwrite a non-NemoClaw gateway user service", + }; + } + + let unit: string; + try { + unit = buildNemoclawOpenShellGatewayUserService(opts.gatewayBin); + } catch (error) { + return { + installed: false, + path: servicePath, + reason: error instanceof Error ? error.message : String(error), + }; + } + if (!isTrustedNemoclawGatewayServiceBinaryPath(opts.gatewayBin, home)) { + return { + installed: false, + path: servicePath, + reason: "OpenShell gateway service ExecStart path is not in a trusted install path", + }; + } + + const serviceDir = path.dirname(servicePath); + const mkdirSync = opts.mkdirSync ?? fs.mkdirSync; + const chmodSync = opts.chmodSync ?? fs.chmodSync; + const writeFileSync = opts.writeFileSync ?? fs.writeFileSync; + try { + mkdirSync(serviceDir, { recursive: true, mode: 0o700 }); + chmodSync(serviceDir, 0o700); + writeFileSync(servicePath, unit, { encoding: "utf-8", mode: 0o600 }); + chmodSync(servicePath, 0o600); + } catch (error) { + return { + installed: false, + path: servicePath, + reason: `failed to write OpenShell gateway user service: ${formatError(error)}`, + }; + } + return { installed: true, path: servicePath }; +} + +function isBenignGatewayUserServiceInstallSkip(reason: string | undefined): boolean { + return ( + reason === "not a Linux host" || reason === "upstream OpenShell gateway service is installed" + ); +} + +export function installAndReportNemoclawOpenShellGatewayUserService( + opts: InstallAndReportNemoclawOpenShellGatewayUserServiceOptions, +): InstallNemoclawOpenShellGatewayUserServiceResult { + const result = installNemoclawOpenShellGatewayUserService(opts); + const log = opts.log ?? console.log; + const warn = opts.warn ?? console.warn; + if (result.installed && result.path) { + log(` Installed OpenShell gateway user service: ${result.path}`); + } else if (result.removed && result.path) { + log(` Removed NemoClaw OpenShell gateway user service override: ${result.path}`); + } else if (result.reason && !isBenignGatewayUserServiceInstallSkip(result.reason)) { + warn(` OpenShell gateway user service not installed: ${result.reason}.`); + } + return result; +} + export function startOpenShellGatewayUserService( opts: OpenShellGatewayUserServiceOptions = {}, ): OpenShellGatewayUserServiceStartResult { const platform = opts.platform ?? process.platform; - if (platform !== "linux") { - return { attempted: false, fallbackAllowed: true, started: false, reason: "not a Linux host" }; + if (platform !== "linux" && platform !== "darwin") { + return { + attempted: false, + fallbackAllowed: true, + started: false, + reason: "unsupported service platform", + }; } + const env = opts.env ?? process.env; + const home = effectiveHome(opts.home, opts.env); const existsSync = opts.existsSync ?? fs.existsSync; - if (!hasOpenShellGatewayUserService({ existsSync, platform })) { + const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); + const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; + const service = resolveOpenShellGatewayUserService({ + commandExists, + env, + existsSync, + home, + platform, + readFileSync: opts.readFileSync, + spawnSyncImpl, + }); + if (!service) { return { attempted: false, fallbackAllowed: true, @@ -221,18 +677,87 @@ export function startOpenShellGatewayUserService( }; } - const env = opts.env ?? process.env; - const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); + if (service.manager === "homebrew") { + if (!commandExists("brew")) { + return { + attempted: true, + fallbackAllowed: true, + manager: service.manager, + reason: "brew is not available", + serviceName: service.serviceName, + started: false, + statusCommand: service.statusCommand, + }; + } + + try { + opts.prepareServiceEnv?.(); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + return { + attempted: true, + fallbackAllowed: false, + manager: service.manager, + reason: `failed to prepare OpenShell gateway service environment: ${detail}`, + serviceName: service.serviceName, + started: false, + statusCommand: service.statusCommand, + }; + } + + const result = runBrew(["services", "restart", service.serviceName], { env, spawnSyncImpl }); + if (!result.ok) { + return { + attempted: true, + fallbackAllowed: false, + manager: service.manager, + reason: `brew services restart ${service.serviceName} failed: ${result.reason}`, + serviceName: service.serviceName, + started: false, + statusCommand: service.statusCommand, + }; + } + + const running = waitForHomebrewServiceRunning({ + env, + serviceName: service.serviceName, + sleepSeconds: opts.sleepSeconds, + spawnSyncImpl, + }); + if (!running.ok) { + return { + attempted: true, + fallbackAllowed: false, + manager: service.manager, + reason: running.reason, + serviceName: service.serviceName, + started: false, + statusCommand: service.statusCommand, + }; + } + + return { + attempted: true, + fallbackAllowed: false, + manager: service.manager, + serviceName: service.serviceName, + started: true, + statusCommand: service.statusCommand, + }; + } + if (!commandExists("systemctl")) { return { attempted: true, fallbackAllowed: true, + manager: service.manager, started: false, reason: "systemctl is not available", + serviceName: service.serviceName, + statusCommand: service.statusCommand, }; } - const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; for (const args of [["daemon-reload"]]) { const result = runSystemctlUser(args, { env, spawnSyncImpl }); if (!result.ok) { @@ -240,19 +765,25 @@ export function startOpenShellGatewayUserService( return { attempted: true, fallbackAllowed: userManagerLooksUnavailable(result.reason ?? ""), + manager: service.manager, reason, + serviceName: service.serviceName, started: false, + statusCommand: service.statusCommand, }; } } - const identity = readTrustedOpenShellGatewayUserServiceIdentity({ env, spawnSyncImpl }); + const identity = readTrustedOpenShellGatewayUserServiceIdentity(service, { env, spawnSyncImpl }); if (!identity.ok) { return { attempted: true, fallbackAllowed: identity.fallbackAllowed, + manager: service.manager, reason: identity.reason, + serviceName: service.serviceName, started: false, + statusCommand: service.statusCommand, }; } @@ -263,14 +794,17 @@ export function startOpenShellGatewayUserService( return { attempted: true, fallbackAllowed: false, + manager: service.manager, reason: `failed to prepare OpenShell gateway service environment: ${detail}`, + serviceName: service.serviceName, started: false, + statusCommand: service.statusCommand, }; } for (const args of [ - ["enable", OPENSHELL_GATEWAY_USER_SERVICE], - ["restart", OPENSHELL_GATEWAY_USER_SERVICE], + ["enable", service.serviceName], + ["restart", service.serviceName], ]) { const result = runSystemctlUser(args, { env, spawnSyncImpl }); if (!result.ok) { @@ -278,19 +812,48 @@ export function startOpenShellGatewayUserService( return { attempted: true, fallbackAllowed: userManagerLooksUnavailable(result.reason ?? ""), + manager: service.manager, reason, + serviceName: service.serviceName, started: false, + statusCommand: service.statusCommand, }; } } - return { attempted: true, fallbackAllowed: false, started: true }; + const active = runSystemctlUser(["is-active", "--quiet", service.serviceName], { + env, + spawnSyncImpl, + }); + if (!active.ok) { + const reason = `systemctl --user is-active --quiet ${service.serviceName} failed: ${active.reason}`; + return { + attempted: true, + fallbackAllowed: userManagerLooksUnavailable(active.reason ?? ""), + manager: service.manager, + reason, + serviceName: service.serviceName, + started: false, + statusCommand: service.statusCommand, + }; + } + + return { + attempted: true, + fallbackAllowed: false, + manager: service.manager, + serviceName: service.serviceName, + started: true, + statusCommand: service.statusCommand, + }; } export async function startPackageManagedDockerDriverGateway({ clearDockerDriverGatewayRuntimeFiles, exitOnFailure, gatewayName, + getHomebrewServiceRunningState: + getHomebrewServiceRunningStateImpl = readHomebrewServiceRunningState, hasOpenShellGatewayUserService: hasOpenShellGatewayUserServiceImpl = hasOpenShellGatewayUserService, healthPollCount, @@ -308,7 +871,7 @@ export async function startPackageManagedDockerDriverGateway({ }: PackageManagedDockerDriverGatewayOptions): Promise { if (!hasOpenShellGatewayUserServiceImpl()) return false; - console.log(" Starting OpenShell Docker-driver gateway via upstream user service..."); + console.log(" Starting OpenShell Docker-driver gateway via package-managed service..."); const serviceStart = startOpenShellGatewayUserServiceImpl({ prepareServiceEnv: prepareOpenShellGatewayUserServiceEnv, }); @@ -316,13 +879,18 @@ export async function startPackageManagedDockerDriverGateway({ const detail = serviceStart.reason ? ` (${serviceStart.reason})` : ""; if (serviceStart.fallbackAllowed) { console.warn( - ` OpenShell gateway user service is unavailable${detail}; using standalone fallback.`, + ` OpenShell gateway package-managed service is unavailable${detail}; using standalone fallback.`, ); return false; } - const message = `OpenShell gateway user service failed to start${detail}.`; + const message = `OpenShell gateway service failed to start${detail}.`; console.error(` ${message}`); - console.error(" Check: systemctl --user status openshell-gateway"); + console.error( + ` Check: ${ + serviceStart.statusCommand ?? + `systemctl --user status ${serviceStart.serviceName ?? OPENSHELL_GATEWAY_USER_SERVICE}` + }`, + ); if (exitOnFailure) process.exit(1); throw new Error(message); } @@ -332,34 +900,63 @@ export async function startPackageManagedDockerDriverGateway({ const waitOptions = createGatewayHealthWaitOptions(pollCount, pollInterval, now, (ms) => sleepSecondsImpl(ms / 1000), ); + let lastReadiness = { + cliHealthy: false, + grpcHealthy: false, + registered: false, + }; const healthy = waitOptions !== null && (await waitUntilAsync(async () => { - if (!registerDockerDriverGatewayEndpoint()) return false; + const registered = registerDockerDriverGatewayEndpoint(); + if (!registered) { + lastReadiness = { cliHealthy: false, grpcHealthy: false, registered }; + return false; + } const status = runCaptureOpenshell(["status"], { ignoreError: true }); const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { ignoreError: true, }); const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); - return ( - isGatewayHealthy(status, namedInfo, currentInfo) && (await isDockerDriverGatewayReady()) - ); + const cliHealthy = isGatewayHealthy(status, namedInfo, currentInfo); + const grpcHealthy = await isDockerDriverGatewayReady(); + lastReadiness = { cliHealthy, grpcHealthy, registered }; + return cliHealthy || grpcHealthy; }, waitOptions)); if (healthy) { + if (serviceStart.manager === "homebrew") { + const running = getHomebrewServiceRunningStateImpl(); + if (!running.ok) { + const detail = running.reason ? ` (${running.reason})` : ""; + const message = `OpenShell gateway service stopped after startup${detail}.`; + console.error(` ${message}`); + console.error(` Check: ${serviceStart.statusCommand}`); + if (exitOnFailure) process.exit(1); + throw new Error(message); + } + } clearDockerDriverGatewayRuntimeFiles(); await verifySandboxBridgeGatewayReachableOrExit(exitOnFailure, { skip: skipSandboxBridgeReachability, }); - console.log(" ✓ OpenShell gateway user service is healthy"); + console.log(" ✓ OpenShell gateway package-managed service is healthy"); return true; } - const message = `OpenShell gateway user service started but did not become healthy within the configured ${formatGatewayHealthWaitLimit( + const message = `OpenShell gateway service started but did not become healthy within the configured ${formatGatewayHealthWaitLimit( pollCount, pollInterval, )}.`; console.error(` ${message}`); - console.error(" Check: systemctl --user status openshell-gateway"); + console.error( + ` Last readiness check: endpoint registered=${lastReadiness.registered ? "yes" : "no"}, OpenShell CLI health=${lastReadiness.cliHealthy ? "yes" : "no"}, direct gRPC health=${lastReadiness.grpcHealthy ? "yes" : "no"}.`, + ); + console.error( + ` Check: ${ + serviceStart.statusCommand ?? + `systemctl --user status ${serviceStart.serviceName ?? OPENSHELL_GATEWAY_USER_SERVICE}` + }`, + ); if (exitOnFailure) process.exit(1); throw new Error(message); } diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index b2ec0797d7a..ad7094d037e 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -60,6 +60,7 @@ describe("dynamic gateway runtime helpers", () => { expect(probeDockerDriverGatewayHttpReady).toHaveBeenLastCalledWith( undefined, "http://127.0.0.1:8080/openshell.v1.OpenShell/Health", + undefined, ); expect(probeGatewayTcpReady).toHaveBeenLastCalledWith(8080, 250); expect(getGatewayClusterImageDrift).toHaveBeenLastCalledWith({ gatewayName: "nemoclaw" }); @@ -78,6 +79,14 @@ describe("dynamic gateway runtime helpers", () => { expect(getGatewayClusterImageDrift).toHaveBeenLastCalledWith({ gatewayName: "nemoclaw-8081", }); + + const env = { OPENSHELL_LOCAL_TLS_DIR: "/tmp/nemoclaw-test-tls" }; + await helpers.isDockerDriverGatewayHttpReady(25, undefined, env); + expect(probeDockerDriverGatewayHttpReady).toHaveBeenLastCalledWith( + 25, + "http://127.0.0.1:8081/openshell.v1.OpenShell/Health", + env, + ); }); it("preserves explicit probe URLs and injects the bound default wait probe", async () => { diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index f387a47dee9..de3a43ace7d 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -256,11 +256,16 @@ export function createDynamicGatewayRuntimeHelpers(deps: DynamicGatewayRuntimeDe const targetUrl = url ?? `${deps.getDockerDriverGatewayEndpoint(deps.getGatewayPort())}/`; return deps.probeGatewayHttpReady(timeoutMs, targetUrl, method, signal); }; - const isDockerDriverGatewayHttpReady = (timeoutMs?: number, url?: string) => + const isDockerDriverGatewayHttpReady = ( + timeoutMs?: number, + url?: string, + env?: NodeJS.ProcessEnv, + ) => deps.probeDockerDriverGatewayHttpReady( timeoutMs, url ?? `${deps.getDockerDriverGatewayEndpoint(deps.getGatewayPort())}/openshell.v1.OpenShell/Health`, + env, ); const waitForGatewayHttpReady = ( opts: import("./gateway-http-readiness").WaitForGatewayHttpReadyOpts = {}, diff --git a/src/lib/onboard/gateway-http-readiness.test.ts b/src/lib/onboard/gateway-http-readiness.test.ts index cd94c943834..72ef284ecb0 100644 --- a/src/lib/onboard/gateway-http-readiness.test.ts +++ b/src/lib/onboard/gateway-http-readiness.test.ts @@ -2,11 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import http from "node:http"; +import fs from "node:fs"; import type { AddressInfo } from "node:net"; +import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; -import { isGatewayHttpReady } from "./gateway-http-readiness"; +import { isDockerDriverGatewayHttpReady, isGatewayHttpReady } from "./gateway-http-readiness"; const servers: http.Server[] = []; @@ -84,3 +86,27 @@ describe("isGatewayHttpReady abort handling", () => { await expect(probe).resolves.toBe(false); }); }); + +describe("isDockerDriverGatewayHttpReady TLS env", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("uses the supplied gateway env when loading Docker-driver mTLS client files", async () => { + const tlsDir = path.join("/tmp", "nemoclaw-probe-tls"); + const readPaths: string[] = []; + const readFileSync = vi.spyOn(fs, "readFileSync").mockImplementation((filePath) => { + readPaths.push(String(filePath)); + throw new Error("missing test TLS material"); + }); + + await expect( + isDockerDriverGatewayHttpReady(1, "https://127.0.0.1:1/openshell.v1.OpenShell/Health", { + OPENSHELL_LOCAL_TLS_DIR: tlsDir, + }), + ).resolves.toBe(false); + + expect(readFileSync).toHaveBeenCalled(); + expect(readPaths[0]).toBe(path.join(tlsDir, "ca.crt")); + }); +}); diff --git a/src/lib/onboard/gateway-http-readiness.ts b/src/lib/onboard/gateway-http-readiness.ts index edf27a001f6..3d3ea9a0fa7 100644 --- a/src/lib/onboard/gateway-http-readiness.ts +++ b/src/lib/onboard/gateway-http-readiness.ts @@ -124,17 +124,19 @@ function isGatewayHttpReadyImpl( export function isDockerDriverGatewayHttpReady( timeoutMs = ISGATEWAY_HTTP_READY_DEFAULT_TIMEOUT_MS, url = `${getGatewayHttpsEndpoint(GATEWAY_PORT)}/openshell.v1.OpenShell/Health`, + env: NodeJS.ProcessEnv = process.env, ): Promise { return withTraceSpan( "nemoclaw.gateway.docker_driver_http_probe", { timeout_ms: timeoutMs, url }, - () => isDockerDriverGatewayHttpReadyImpl(timeoutMs, url), + () => isDockerDriverGatewayHttpReadyImpl(timeoutMs, url, env), ); } function isDockerDriverGatewayHttpReadyImpl( timeoutMs = ISGATEWAY_HTTP_READY_DEFAULT_TIMEOUT_MS, url = `${getGatewayHttpsEndpoint(GATEWAY_PORT)}/openshell.v1.OpenShell/Health`, + env: NodeJS.ProcessEnv = process.env, ): Promise { const effectiveTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0 @@ -187,7 +189,7 @@ function isDockerDriverGatewayHttpReadyImpl( try { const origin = `${parsed.protocol}//${parsed.host}`; - const connectOptions = dockerDriverGatewayHttp2ConnectOptions(parsed); + const connectOptions = dockerDriverGatewayHttp2ConnectOptions(parsed, env); if (parsed.protocol === "https:" && !connectOptions) return settle(false); client = http2.connect(origin, connectOptions); client.on("error", () => settle(false)); @@ -224,9 +226,10 @@ function isDockerDriverGatewayHttpReadyImpl( function dockerDriverGatewayHttp2ConnectOptions( parsed: URL, + env: NodeJS.ProcessEnv = process.env, ): http2.SecureClientSessionOptions | undefined { if (parsed.protocol !== "https:") return undefined; - const localTlsDir = process.env.OPENSHELL_LOCAL_TLS_DIR; + const localTlsDir = env.OPENSHELL_LOCAL_TLS_DIR; if (!localTlsDir) return undefined; try { return { diff --git a/src/lib/onboard/openshell-install.ts b/src/lib/onboard/openshell-install.ts index 4c13d70ff6a..27e873aee49 100644 --- a/src/lib/onboard/openshell-install.ts +++ b/src/lib/onboard/openshell-install.ts @@ -200,7 +200,7 @@ export function ensureOpenshellForOnboard(deps: OpenShellInstallDeps): OpenShell } else if (needsDockerDriverBinaries) { const required = platform === "linux" ? "gateway and sandbox" : "gateway"; deps.log( - ` OpenShell standalone gateway onboarding requires the ${required} binaries. Reinstalling...`, + ` OpenShell Docker-driver gateway onboarding requires the ${required} binaries. Reinstalling...`, ); } else if (needsMessagingFeatures) { deps.log( diff --git a/test/e2e/fixtures/phases/lifecycle.ts b/test/e2e/fixtures/phases/lifecycle.ts index 021bd074b07..2575bc1b230 100644 --- a/test/e2e/fixtures/phases/lifecycle.ts +++ b/test/e2e/fixtures/phases/lifecycle.ts @@ -35,6 +35,10 @@ const STATUS_TIMEOUT_MS = 5 * 60_000; const REBUILD_TIMEOUT_MS = 20 * 60_000; const SANDBOX_READY_ATTEMPTS = 30; const SANDBOX_READY_DELAY_MS = 5_000; +const USER_SERVICE_UNAVAILABLE_EXIT = 75; +const OPENSHELL_GATEWAY_USER_SERVICE = "openshell-gateway"; +const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE = + "# NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"; export type LifecycleProfile = "post-reboot-recovery" | "dcode-rebuild-invalid-credential"; @@ -179,25 +183,26 @@ export class LifecyclePhaseFixture { } /** - * Reproduce the host-side conditions of a DGX Spark / Linux Docker-driver - * reboot AND drive the user-visible action that exposes the bug: + * Reproduce the host-side conditions of a Linux Docker-driver reboot and + * drive the user-visible action that exposes reboot recovery bugs: * * 1. Locate the OpenShell-labeled Docker container for the * target's sandbox name and either stop it (default) or * stop+rename it to a `*-nemoclaw-gpu-backup-*` sibling. - * The gateway runtime is left HEALTHY — attempting to stop - * and restart it from the OpenShell CLI is unreliable on - * `ubuntu-latest` (no `gateway start` subcommand) and the - * remaining bug class for #4423 specifically requires a - * `healthy_named` gateway when status runs (otherwise - * #4578's mitigation takes over and masks the signal). + * The gateway runtime is stopped and restarted through the + * OpenShell user service when the host exposes one, which + * mirrors a reboot or user-manager restart. Hosts without a + * visible user service fall back to the existing first-session + * status/start path. * * 2. Invoke `nemoclaw status` — the user-visible action * that documented the regression in #4423. On unfixed `main` * the destructive `missing` branch in `status.ts` wipes the * registry entry. On the PR-A fix branch the new Docker-driver * recovery helper restarts the labeled container before - * stale-removal can fire. + * stale-removal can fire. The preceding gateway restart must + * make `openshell status` report the named gateway connected + * without running `nemoclaw onboard --resume`. * * We deliberately do NOT assert on the status exit code here * because the bug is precisely that status "succeeds" at @@ -265,6 +270,18 @@ export class LifecyclePhaseFixture { }); } + const previousRuntime = await this.restartGatewayRuntime({ + delayMs: 0, + requireUserService: true, + sandboxName: instance.sandboxName, + }); + steps.push({ + id: `gateway-restart:${previousRuntime?.kind ?? "user-service"}`, + results: [], + }); + await this.waitForGatewayConnected(); + steps.push({ id: "gateway-connected:nemoclaw", results: [] }); + // Final step: drive the user-visible action that exposed #4423. // We invoke status through the host CLI client so artifacts are // captured and the command goes through the same @@ -346,14 +363,22 @@ export class LifecyclePhaseFixture { async startGatewayRuntime( previousRuntime: HostGatewayRuntime | null, - options: { sandboxName?: string } = {}, + options: { requireUserService?: boolean; sandboxName?: string } = {}, ): Promise { + const userServiceStart = await this.startOpenShellGatewayUserService({ + requireAvailable: options.requireUserService, + }); + if (userServiceStart) return userServiceStart; + if (options.sandboxName) { + return await this.host.nemoclaw([options.sandboxName, "status"], { + artifactName: `lifecycle-gateway-recover-through-nemoclaw-status-${options.sandboxName}`, + env: buildAvailabilityProbeEnv(), + timeoutMs: 120_000, + }); + } if (previousRuntime?.kind === "pid") { - const args = options.sandboxName ? [options.sandboxName, "status"] : ["status"]; - return await this.host.nemoclaw(args, { - artifactName: options.sandboxName - ? `lifecycle-gateway-recover-through-nemoclaw-status-${options.sandboxName}` - : "lifecycle-gateway-recover-through-nemoclaw-status", + return await this.host.nemoclaw(["status"], { + artifactName: "lifecycle-gateway-recover-through-nemoclaw-status", env: buildAvailabilityProbeEnv(), timeoutMs: 120_000, }); @@ -365,8 +390,47 @@ export class LifecyclePhaseFixture { }); } + private async startOpenShellGatewayUserService(options: { + requireAvailable?: boolean; + }): Promise { + const result = await this.host.command( + "sh", + [ + "-lc", + [ + "set -eu", + `unit="$HOME/.config/systemd/user/${OPENSHELL_GATEWAY_USER_SERVICE}.service"`, + `if ! command -v systemctl >/dev/null 2>&1; then exit ${USER_SERVICE_UNAVAILABLE_EXIT}; fi`, + `if [ ! -f "$unit" ]; then exit ${USER_SERVICE_UNAVAILABLE_EXIT}; fi`, + `grep -Fxq '${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE}' "$unit" || exit ${USER_SERVICE_UNAVAILABLE_EXIT}`, + `systemctl --user is-enabled ${OPENSHELL_GATEWAY_USER_SERVICE} >/dev/null`, + "systemctl --user daemon-reload", + `systemctl --user restart ${OPENSHELL_GATEWAY_USER_SERVICE}`, + ].join("\n"), + ], + { + artifactName: "lifecycle-gateway-user-service-restart", + env: buildAvailabilityProbeEnv(), + timeoutMs: 120_000, + }, + ); + if (result.exitCode === 0) return result; + if (result.exitCode === USER_SERVICE_UNAVAILABLE_EXIT && !options.requireAvailable) { + return null; + } + if (result.exitCode === USER_SERVICE_UNAVAILABLE_EXIT) { + throw new Error( + `OpenShell gateway user service is not available for reboot lifecycle recovery.`, + ); + } + throw new Error( + `OpenShell gateway user service restart failed during reboot lifecycle: ` + + `${result.stderr || result.stdout || `exit ${String(result.exitCode)}`}`, + ); + } + async restartGatewayRuntime( - options: { delayMs?: number; sandboxName?: string } = {}, + options: { delayMs?: number; requireUserService?: boolean; sandboxName?: string } = {}, ): Promise { const previousRuntime = await this.stopGatewayRuntime(); if (this.gateway) { @@ -379,6 +443,7 @@ export class LifecyclePhaseFixture { await new Promise((resolve) => setTimeout(resolve, delayMs)); } await this.startGatewayRuntime(previousRuntime, { + requireUserService: options.requireUserService, sandboxName: options.sandboxName, }); return previousRuntime; diff --git a/test/e2e/registry/definitions/baseline.ts b/test/e2e/registry/definitions/baseline.ts index b9a1647f91d..366d804ccd4 100644 --- a/test/e2e/registry/definitions/baseline.ts +++ b/test/e2e/registry/definitions/baseline.ts @@ -158,32 +158,19 @@ const canonicalTargetInputs: CanonicalTargetInput[] = [ requiredSecrets: ["NVIDIA_API_KEY"], }, { - // Failing-test-first regression scaffold for #4423. After - // onboarding, the lifecycle phase exercises the host-side - // conditions a Linux Docker-driver host can reach from - // `ubuntu-latest`: - // 1. `docker stop` the labeled sandbox container (gateway is - // left HEALTHY — the OpenShell CLI on `ubuntu-latest` has - // no `gateway start` subcommand and #4578's mitigation - // would otherwise mask the regression target). - // 2. Run `nemoclaw status` so any destructive - // registry/container path runs against host-observable - // state. - // The state-validation phase then asserts the host-side - // invariants declared by the `post-reboot-recovery-ready` - // expected-state: cli installed, local registry entry - // preserved, labeled Docker container present (running, - // stopped, or `*-nemoclaw-gpu-backup-*` sibling). - // - // The full DGX Spark post-reboot bug class — healthy_named - // gateway returning literal `NotFound` while Docker still has - // the labeled container — cannot be reproduced from CI without - // a real reboot. This target therefore locks in #4578's - // mitigation and the host-side preservation invariants any - // recovery path must respect; PR-A's Docker-driver recovery - // helper (parts 2 & 3 of ericksoa's plan) extends this scaffold, - // and a follow-up target on a controlled runner can layer in - // gateway/sandbox runtime probes once that helper lands. + // Reboot-style Docker-driver recovery without a physical reboot: + // 1. `docker stop` the labeled sandbox container. + // 2. Stop the OpenShell gateway runtime, then restart it through + // `openshell-gateway.service` when the host exposes the user + // service. Hosts without a visible user service use the + // documented first-session fallback path. + // 3. Run `nemoclaw status` so any destructive + // registry/container path runs against host-observable state. + // The state-validation phase then asserts the typed + // `post-reboot-recovery-ready` contract: cli installed, named + // gateway healthy, local registry entry preserved, and labeled + // Docker container present (running, stopped, or a + // `*-nemoclaw-gpu-backup-*` sibling). id: "ubuntu-repo-docker-post-reboot-recovery", manifestName: "openclaw-nvidia-post-reboot-recovery", environment: ubuntuRepoDockerLifecycle("cloud-openclaw", "post-reboot-recovery"), @@ -191,8 +178,8 @@ const canonicalTargetInputs: CanonicalTargetInput[] = [ suiteIds: ["smoke"], requiredSecrets: ["NVIDIA_INFERENCE_API_KEY"], description: - "Failing-test-first guard for #4423: post-reboot recovery must preserve " + - "the local registry entry and restart the labeled Docker container.", + "Post-reboot recovery guard: the gateway must recover through the user service " + + "or first-session fallback while preserving the local sandbox registry and container.", }, { id: "ubuntu-repo-openai-compatible-openclaw", diff --git a/test/e2e/registry/expected-states.ts b/test/e2e/registry/expected-states.ts index a1f3c552f01..9edb6cfddc9 100644 --- a/test/e2e/registry/expected-states.ts +++ b/test/e2e/registry/expected-states.ts @@ -88,9 +88,9 @@ const onboardingFailurePolicyPresetsRequired: ExpectedState = { cli: { installed: true }, }; -// Post-reboot recovery contract for #4423. After the lifecycle phase -// stops the labeled sandbox container, the host-side invariants this -// target locks down are: +// Post-reboot recovery contract. After the lifecycle phase restarts +// the OpenShell gateway through the user service when available, then +// runs `nemoclaw status`, this target locks down: // // * `cli` still installed. // * `localRegistry` entry preserved: this is the user-visible @@ -102,16 +102,14 @@ const onboardingFailurePolicyPresetsRequired: ExpectedState = { // not delete the labeled container or its `*-nemoclaw-gpu-backup-*` // sibling as a side effect. // -// Gateway/sandbox runtime state are intentionally OMITTED from this -// expected state. The user-visible bug is host-side state -// destruction; gateway/sandbox liveness on a `ubuntu-latest` runner -// after `docker stop` is environmental and varies independently of -// the regression target. Once PR-A lands its Docker-driver recovery -// helper, a follow-up target can extend the expected state with -// runtime invariants on a more controlled runner. +// * `gateway` healthy: the user-service path must restore the +// named OpenShell gateway without `nemoclaw onboard --resume` +// when persistence is available, with the documented first- +// session fallback used only when a user service is not exposed. const postRebootRecoveryReady: ExpectedState = { id: "post-reboot-recovery-ready", cli: { installed: true }, + gateway: { expected: "present", health: "healthy" }, localRegistry: { expected: "present" }, dockerSandboxContainer: { expected: "present" }, }; diff --git a/test/e2e/support/e2e-expected-state.test.ts b/test/e2e/support/e2e-expected-state.test.ts index edd95b0361f..87a07bcfce9 100644 --- a/test/e2e/support/e2e-expected-state.test.ts +++ b/test/e2e/support/e2e-expected-state.test.ts @@ -200,8 +200,8 @@ describe("target expected-state references", () => { } }); - // source-shape-contract: security -- Post-reboot targets must retain host registry and container preservation probes - it("compiles host-preservation probes for every post-reboot recovery target", () => { + // source-shape-contract: security -- Post-reboot targets must retain host preservation and gateway recovery probes + it("compiles gateway-health and host-preservation probes for every post-reboot recovery target", () => { const recoveryTargets = listTargets().filter( (target) => target.environment?.lifecycle === "post-reboot-recovery", ); @@ -211,6 +211,7 @@ describe("target expected-state references", () => { const probes = probesForState(requireExpectedState(target.expectedStateId!)); expect(probes, target.id).toEqual( expect.arrayContaining([ + "gateway-healthy", "local-registry-entry-present", "docker-sandbox-container-present", ]), diff --git a/test/e2e/support/e2e-phase-lifecycle.test.ts b/test/e2e/support/e2e-phase-lifecycle.test.ts index ead03683b27..24175ecbdaa 100644 --- a/test/e2e/support/e2e-phase-lifecycle.test.ts +++ b/test/e2e/support/e2e-phase-lifecycle.test.ts @@ -114,10 +114,16 @@ function restoreEnv(name: string, value: string | undefined): void { } describe("LifecyclePhaseFixture.simulate post-reboot-recovery (stop-original)", () => { - it("stops the labeled container then runs `nemoclaw status`", async () => { + it("stops the labeled container, restarts the gateway service, then runs status", async () => { const runner = new FakeRunner(); runner.enqueue(shellResult(0, "openshell-cluster-e2e-ubuntu-repo-cloud-openclaw\n")); // discover runner.enqueue(shellResult(0)); // docker stop + runner.enqueue(shellResult(0)); // forward stop + runner.enqueue(shellResult(0)); // gateway stop + runner.enqueue(shellResult(0)); // pid stop + runner.enqueue(shellResult(0)); // container stop + runner.enqueue(shellResult(0)); // user service restart + runner.enqueue(shellResult(0, "Connected to nemoclaw\n")); // openshell status runner.enqueue(shellResult(1, "Removed stale local registry entry.\n")); // status (non-zero on unfixed) const cleanup = new FakeCleanup(); @@ -126,28 +132,20 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (stop-original)", expect(result.profile).toBe("post-reboot-recovery"); expect(result.steps.map((step) => step.id)).toEqual([ "docker-stop:openshell-cluster-e2e-ubuntu-repo-cloud-openclaw", + "gateway-restart:user-service", + "gateway-connected:nemoclaw", "nemoclaw-status:e2e-ubuntu-repo-cloud-openclaw", ]); - expect(runner.calls.map((call) => ({ command: call.command, args: call.args }))).toEqual([ - { - command: "docker", - args: [ - "ps", - "-a", - "--filter", - "label=openshell.ai/sandbox-name=e2e-ubuntu-repo-cloud-openclaw", - "--format", - "{{.Names}}", - ], - }, - { - command: "docker", - args: ["stop", "openshell-cluster-e2e-ubuntu-repo-cloud-openclaw"], - }, - { - command: "nemoclaw", - args: ["e2e-ubuntu-repo-cloud-openclaw", "status"], - }, + expect(runner.calls.map((call) => `${call.command} ${call.args.join(" ")}`)).toEqual([ + "docker ps -a --filter label=openshell.ai/sandbox-name=e2e-ubuntu-repo-cloud-openclaw --format {{.Names}}", + "docker stop openshell-cluster-e2e-ubuntu-repo-cloud-openclaw", + "sh -lc command -v openshell >/dev/null 2>&1 && openshell forward stop 18789 || true", + "sh -lc command -v openshell >/dev/null 2>&1 && openshell gateway stop -g nemoclaw || true", + expect.stringContaining("sh -lc pid_file="), + expect.stringContaining("sh -lc cid="), + expect.stringContaining("systemctl --user is-enabled openshell-gateway"), + "openshell status", + "nemoclaw e2e-ubuntu-repo-cloud-openclaw status", ]); expect(cleanup.calls.map((call) => call.name)).toEqual([ "lifecycle.docker-start:openshell-cluster-e2e-ubuntu-repo-cloud-openclaw", @@ -158,6 +156,12 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (stop-original)", const runner = new FakeRunner(); runner.enqueue(shellResult(0, "container-1\n")); // discover runner.enqueue(shellResult(0)); // docker stop + runner.enqueue(shellResult(0)); // forward stop + runner.enqueue(shellResult(0)); // gateway stop + runner.enqueue(shellResult(0)); // pid stop + runner.enqueue(shellResult(0)); // container stop + runner.enqueue(shellResult(0)); // user service restart + runner.enqueue(shellResult(0, "Connected to nemoclaw\n")); // openshell status runner.enqueue(shellResult(1, "Removed stale local registry entry.\n")); // status non-zero const cleanup = new FakeCleanup(); @@ -187,6 +191,28 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (stop-original)", fixture(runner, cleanup).simulate("post-reboot-recovery", instance()), ).rejects.toThrow(/could not query Docker for label/); }); + + it("fails when the managed OpenShell gateway user service is unavailable", async () => { + const runner = new FakeRunner(); + runner.enqueue(shellResult(0, "container-1\n")); // discover + runner.enqueue(shellResult(0)); // docker stop + runner.enqueue(shellResult(0)); // forward stop + runner.enqueue(shellResult(0)); // gateway stop + runner.enqueue(shellResult(0)); // pid stop + runner.enqueue(shellResult(0)); // container stop + runner.enqueue(shellResult(75, "")); // no managed user service available + const cleanup = new FakeCleanup(); + + await expect( + fixture(runner, cleanup).simulate("post-reboot-recovery", instance()), + ).rejects.toThrow(/OpenShell gateway user service is not available/); + + expect(runner.calls.map((call) => `${call.command} ${call.args.join(" ")}`)).toEqual( + expect.arrayContaining([ + expect.stringContaining("systemctl --user is-enabled openshell-gateway"), + ]), + ); + }); }); describe("LifecyclePhaseFixture.simulate post-reboot-recovery (rename-to-gpu-backup)", () => { @@ -195,6 +221,12 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (rename-to-gpu-bac runner.enqueue(shellResult(0, "openshell-cluster-e2e-x\n")); // discover runner.enqueue(shellResult(0)); // docker stop runner.enqueue(shellResult(0)); // docker rename + runner.enqueue(shellResult(0)); // forward stop + runner.enqueue(shellResult(0)); // gateway stop + runner.enqueue(shellResult(0)); // pid stop + runner.enqueue(shellResult(0)); // container stop + runner.enqueue(shellResult(0)); // user service restart + runner.enqueue(shellResult(0, "Connected to nemoclaw\n")); // openshell status runner.enqueue(shellResult(1, "Removed stale local registry entry.\n")); // status const cleanup = new FakeCleanup(); @@ -267,6 +299,7 @@ describe("LifecyclePhaseFixture gateway runtime restart helpers", () => { runner.enqueue(shellResult(1, "")); // expectHostRuntimeStopped pid probe runner.enqueue(shellResult(0, "")); // expectHostRuntimeStopped container probe runner.enqueue(shellResult(0)); // lifecycle-gateway-stopped true artifact + runner.enqueue(shellResult(75, "")); // no user service available runner.enqueue(shellResult(0, "status recovered\n")); // start through nemoclaw status runner.enqueue(shellResult(0, "Connected to nemoclaw\n")); // waitForGatewayConnected const cleanup = new FakeCleanup(); @@ -289,6 +322,7 @@ describe("LifecyclePhaseFixture gateway runtime restart helpers", () => { expect.stringContaining("sh -lc pid_file="), "docker ps -qf name=openshell-cluster-nemoclaw", "true ", + expect.stringContaining("sh -lc set -eu"), "nemoclaw status", "openshell status", ]); @@ -296,6 +330,7 @@ describe("LifecyclePhaseFixture gateway runtime restart helpers", () => { it("can recover a PID runtime through sandbox-specific status", async () => { const runner = new FakeRunner(); + runner.enqueue(shellResult(75, "")); // no user service available runner.enqueue(shellResult(0, "status recovered\n")); const cleanup = new FakeCleanup(); @@ -309,6 +344,7 @@ describe("LifecyclePhaseFixture gateway runtime restart helpers", () => { ).resolves.toMatchObject({ exitCode: 0 }); expect(runner.calls.map((call) => `${call.command} ${call.args.join(" ")}`)).toEqual([ + expect.stringContaining("sh -lc set -eu"), "nemoclaw e2e-survival status", ]); }); diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts new file mode 100644 index 00000000000..f2650777a8e --- /dev/null +++ b/test/install-openshell-gateway-service.test.ts @@ -0,0 +1,251 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import { TEST_SYSTEM_PATH, writeExecutable } from "./helpers/installer-sourced-env"; + +const INSTALLER = path.join(import.meta.dirname, "..", "install.sh"); + +function runInstallHelper(tmp: string, body: string, env: NodeJS.ProcessEnv = {}) { + return spawnSync( + "bash", + ["-c", ["set -euo pipefail", `source ${JSON.stringify(INSTALLER)}`, body].join("\n")], + { + cwd: tmp, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmp, + PATH: TEST_SYSTEM_PATH, + XDG_CONFIG_HOME: "", + NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), + ...env, + }, + }, + ); +} + +describe("install.sh OpenShell gateway service", () => { + it("stages a Linux OpenShell gateway user service from the installer wrapper", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const gatewayBin = path.join(tmp, ".local", "bin", "openshell-gateway"); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + + try { + const result = runInstallHelper( + tmp, + [ + "upstream_openshell_gateway_user_service_installed() { return 1; }", + `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + ); + + const unit = fs.readFileSync(servicePath, "utf-8"); + expect(result.status).toBe(0); + expect(unit).toContain("# NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"); + expect(unit).toContain("After=default.target"); + expect(unit).toContain("Environment=OPENSHELL_LOCAL_TLS_DIR=%h/.local/state/openshell/tls"); + expect(unit).toContain( + `ExecStartPre=${gatewayBin} generate-certs --output-dir \${OPENSHELL_LOCAL_TLS_DIR} --server-san host.openshell.internal --server-san localhost --server-san 127.0.0.1`, + ); + expect(unit).toContain(`ExecStart=${gatewayBin}`); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("reconciles the service when OpenShell already exists in if-missing mode", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const gatewayBin = path.join(tmp, ".local", "bin", "openshell-gateway"); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + const eventsPath = path.join(tmp, "events.log"); + fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + + try { + const result = runInstallHelper( + tmp, + [ + 'command_exists() { [[ "$1" == openshell ]]; }', + `spin() { printf 'spin\\n' >>${JSON.stringify(eventsPath)}; return 1; }`, + `prefer_user_local_openshell() { printf 'prefer\\n' >>${JSON.stringify(eventsPath)}; }`, + "upstream_openshell_gateway_user_service_installed() { return 1; }", + `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, + "maybe_install_openshell_during_install if-missing", + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); + expect(fs.readFileSync(eventsPath, "utf-8")).toBe("prefer\n"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("skips OpenShell reinstall on macOS when the Homebrew service is present", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const eventsPath = path.join(tmp, "events.log"); + + try { + const result = runInstallHelper( + tmp, + [ + 'uname() { [[ "${1:-}" == "-s" ]] && printf "Darwin\\n" || printf "arm64\\n"; }', + 'command_exists() { [[ "$1" == openshell ]]; }', + 'brew() { [[ "$*" == "list --formula openshell" ]]; }', + `spin() { printf 'spin\\n' >>${JSON.stringify(eventsPath)}; return 1; }`, + `prefer_user_local_openshell() { printf 'prefer\\n' >>${JSON.stringify(eventsPath)}; }`, + `install_nemoclaw_openshell_gateway_user_service() { printf 'service\\n' >>${JSON.stringify(eventsPath)}; }`, + "maybe_install_openshell_during_install if-missing", + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(eventsPath, "utf-8")).toBe("prefer\nservice\n"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("installs OpenShell on macOS when only the CLI exists and the Homebrew service is missing", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const eventsPath = path.join(tmp, "events.log"); + + try { + const result = runInstallHelper( + tmp, + [ + 'uname() { [[ "${1:-}" == "-s" ]] && printf "Darwin\\n" || printf "arm64\\n"; }', + 'command_exists() { [[ "$1" == openshell ]]; }', + 'brew() { [[ "$*" == "list --formula openshell" ]] && return 1; return 0; }', + `spin() { printf 'spin:%s\\n' "$*" >>${JSON.stringify(eventsPath)}; return 0; }`, + `prefer_user_local_openshell() { printf 'prefer\\n' >>${JSON.stringify(eventsPath)}; }`, + `install_nemoclaw_openshell_gateway_user_service() { printf 'service\\n' >>${JSON.stringify(eventsPath)}; }`, + "maybe_install_openshell_during_install if-missing", + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(result.stdout).toContain( + "OpenShell CLI exists but the macOS Homebrew gateway service is missing.", + ); + const events = fs.readFileSync(eventsPath, "utf-8"); + expect(events).toContain("spin:Installing OpenShell CLI bash "); + expect(events).toContain("/scripts/install-openshell.sh\n"); + expect(events).toContain("prefer\nservice\n"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("uses absolute XDG_CONFIG_HOME for the Linux user service path", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const configHome = path.join(tmp, "xdg-config"); + const gatewayBin = path.join(tmp, ".local", "bin", "openshell-gateway"); + const servicePath = path.join(configHome, "systemd", "user", "openshell-gateway.service"); + fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + + try { + const result = runInstallHelper( + tmp, + [ + "upstream_openshell_gateway_user_service_installed() { return 1; }", + `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + { XDG_CONFIG_HOME: configHome }, + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); + expect(fs.existsSync(path.join(tmp, ".config", "systemd", "user"))).toBe(false); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("skips service staging for relative gateway binary paths", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + writeExecutable(path.join(tmp, "openshell-gateway"), "#!/usr/bin/env bash\nexit 0\n"); + + try { + const result = runInstallHelper( + tmp, + [ + "upstream_openshell_gateway_user_service_installed() { return 1; }", + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + { NEMOCLAW_OPENSHELL_GATEWAY_BIN: "./openshell-gateway" }, + ); + + expect(result.status).toBe(0); + expect(fs.existsSync(servicePath)).toBe(false); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("removes a marked user override before resolving a gateway binary", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + fs.writeFileSync( + servicePath, + "# NemoClaw-managed OpenShell gateway user service\n# NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1\n", + ); + + try { + const result = runInstallHelper( + tmp, + [ + "upstream_openshell_gateway_user_service_installed() { return 0; }", + "resolve_openshell_gateway_bin_for_service() { return 1; }", + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(fs.existsSync(servicePath)).toBe(false); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("does not overwrite a foreign user service containing the marker text", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const gatewayBin = path.join(tmp, ".local", "bin", "openshell-gateway"); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + const originalUnit = "# foreign unit\n# not NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1\n"; + fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + fs.writeFileSync(servicePath, originalUnit); + + try { + const result = runInstallHelper( + tmp, + [ + "upstream_openshell_gateway_user_service_installed() { return 1; }", + `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(servicePath, "utf-8")).toBe(originalUnit); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); +}); diff --git a/test/install-openshell-version-check.test.ts b/test/install-openshell-version-check.test.ts index a4c4fb2651e..4a47bb5acb3 100644 --- a/test/install-openshell-version-check.test.ts +++ b/test/install-openshell-version-check.test.ts @@ -13,6 +13,7 @@ import { buildRebuildHermesChildEnv } from "./e2e/live/rebuild-hermes-env.ts"; const SCRIPT = path.join(import.meta.dirname, "..", "scripts", "install-openshell.sh"); const PINNED_OPEN_SHELL_SHA256 = { cliDarwinArm64: "117b5354cc42d80bc4d5e070ea5ac4e341208ff6d3c29b516d8a9c80e2310f8d", + formula: "4b75a7e3a7630eb8954d73ca828b394d5e0646adbaa4b087b2435329d53b61b3", cliLinuxArm64: "a5ff01a3240d73c72ec1700eda6cc6c752a86cf50c5dd1b5bdc459f544d03045", cliLinuxX64: "37836c3b50383e03249c5e16512c1806e591fba8451408a84fb2f628ddb318c4", gatewayDarwinArm64: "8c07362107393eb5f4ae4b9ee9f4257fd53862c51ad8dd96f2fe31bb6d8d7ffb", @@ -55,6 +56,7 @@ function runWithInstalledVersion( sandboxBinaryDigest?: string; driverVersionExit?: number; driverReadable?: boolean; + homebrewFormula?: boolean; os?: string; arch?: string; } = {}, @@ -166,6 +168,7 @@ exit 1`, ); if ((options.os ?? "Linux") === "Darwin") { + const homebrewFormula = options.homebrewFormula ?? true; writeExecutable( path.join(fakeBin, "codesign"), `#!/usr/bin/env bash @@ -182,6 +185,23 @@ fi if [ -n "$state" ]; then : > "$state" fi +exit 0`, + ); + writeExecutable( + path.join(fakeBin, "brew"), + `#!/usr/bin/env bash +case "$*" in + "list --formula openshell") + exit ${homebrewFormula ? "0" : "1"} + ;; + "services restart openshell") + exit 0 + ;; + "--prefix") + printf '%s\\n' ${JSON.stringify(tmp)} + exit 0 + ;; +esac exit 0`, ); } @@ -422,23 +442,12 @@ describe("install-openshell.sh version check", { timeout: 15_000 }, () => { ); }); - it.each([ - { archiveShape: "safe", status: 0, unsafe: false }, - { archiveShape: "absolute", status: 1, unsafe: true }, - { archiveShape: "traversal", status: 1, unsafe: true }, - { archiveShape: "duplicate", status: 1, unsafe: true }, - { archiveShape: "extra", status: 1, unsafe: true }, - { archiveShape: "symlink", status: 1, unsafe: true }, - { archiveShape: "hardlink", status: 1, unsafe: true }, - { archiveShape: "device", status: 1, unsafe: true }, - { archiveShape: "late-traversal", status: 1, unsafe: true }, - ] as const)("$archiveShape macOS arm64 archives are checked before extraction", (expected) => { - const { archiveShape } = expected; - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-macos-assets-")); + it("fails closed when the macOS Homebrew formula does not match the pinned digest", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-macos-formula-")); try { const fakeBin = path.join(tmp, "bin"); const downloadLog = path.join(tmp, "downloads.log"); - const tarLog = path.join(tmp, "tar.log"); + const brewLog = path.join(tmp, "brew.log"); fs.mkdirSync(fakeBin); writeExecutable( @@ -452,106 +461,147 @@ if [ "\${1:-}" = "-m" ]; then echo "arm64"; else echo "Darwin"; fi`, if [ "\${1:-}" = "--version" ]; then echo "openshell 0.0.36"; exit 0; fi exit 99`, ); - writeExecutable( - path.join(fakeBin, "gh"), - `#!/usr/bin/env bash -exit 1`, - ); + writeExecutable(path.join(fakeBin, "gh"), "#!/usr/bin/env bash\nexit 1\n"); writeExecutable( path.join(fakeBin, "curl"), `#!/usr/bin/env bash echo "$@" >> ${JSON.stringify(downloadLog)} out="" while [ "$#" -gt 0 ]; do - if [ "$1" = "-o" ]; then - shift - out="$1" - fi + if [ "$1" = "-o" ]; then shift; out="$1"; fi shift || true done -if [ -n "$out" ]; then - case "$(basename "$out")" in - openshell-checksums-sha256.txt) - printf '%s\n' \ - '${PINNED_OPEN_SHELL_SHA256.cliDarwinArm64} openshell-aarch64-apple-darwin.tar.gz' > "$out" - ;; - openshell-gateway-checksums-sha256.txt) - printf '%s\n' \ - '${PINNED_OPEN_SHELL_SHA256.gatewayDarwinArm64} openshell-gateway-aarch64-apple-darwin.tar.gz' > "$out" - ;; - *) - : > "$out" - ;; - esac -fi +[ -n "$out" ] || exit 1 +printf '%s\\n' 'class Openshell < Formula' > "$out" exit 0`, ); writeExecutable( path.join(fakeBin, "sha256sum"), `#!/usr/bin/env bash -cat >/dev/null -echo "checksum OK" +printf '%s %s\\n' '${ZERO_SHA256}' "$1"`, + ); + writeExecutable( + path.join(fakeBin, "brew"), + `#!/usr/bin/env bash +printf '%s\\n' "$*" >> ${JSON.stringify(brewLog)} exit 0`, ); + + const result = spawnSync("bash", [SCRIPT], { + env: { + ...process.env, + HOME: tmp, + NEMOCLAW_OPENSHELL_CHANNEL: "stable", + PATH: `${fakeBin}:/usr/bin:/bin`, + }, + encoding: "utf8", + }); + + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(1); + expect(result.stderr).toContain( + "OpenShell Homebrew formula checksum does not match NemoClaw-pinned v0.0.72 digest", + ); + expect(fs.readFileSync(downloadLog, "utf-8")).toContain("openshell.rb"); + expect(fs.existsSync(brewLog) ? fs.readFileSync(brewLog, "utf-8") : "").toBe(""); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("installs macOS OpenShell through the Homebrew formula and restarts the service", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-macos-formula-")); + try { + const fakeBin = path.join(tmp, "bin"); + const homebrewPrefix = path.join(tmp, "homebrew"); + const tapRepo = path.join(tmp, "tap"); + const downloadLog = path.join(tmp, "downloads.log"); + const brewLog = path.join(tmp, "brew.log"); + fs.mkdirSync(fakeBin); + fs.mkdirSync(path.join(homebrewPrefix, "bin"), { recursive: true }); + writeExecutable( - path.join(fakeBin, "tar"), + path.join(fakeBin, "uname"), `#!/usr/bin/env bash -printf '%s\\n' "$*" >> ${JSON.stringify(tarLog)} -case "$*" in -*openshell-gateway*) name="openshell-gateway" ;; -*) name="openshell" ;; -esac -case "\${1:-}" in --tzf) - case ${JSON.stringify(archiveShape)} in - absolute) printf '/tmp/%s\\n' "$name" ;; - traversal) printf '../%s\\n' "$name" ;; - duplicate) printf '%s\\n%s\\n' "$name" "$name" ;; - extra) printf '%s\\nunexpected\\n' "$name" ;; - late-traversal) - if [ "$name" = "openshell-gateway" ]; then printf '../%s\\n' "$name"; else printf '%s\\n' "$name"; fi - ;; - *) printf '%s\\n' "$name" ;; - esac - exit 0 - ;; --tvzf) - case ${JSON.stringify(archiveShape)} in - symlink) printf 'lrwxrwxrwx 0/0 0 2026-01-01 00:00 %s -> target\\n' "$name" ;; - hardlink) printf 'hrwxr-xr-x 0/0 0 2026-01-01 00:00 %s link to target\\n' "$name" ;; - device) printf 'crw-rw-rw- 0/0 1,3 2026-01-01 00:00 %s\\n' "$name" ;; - *) printf '%s\\n' "-rwxr-xr-x 0/0 1 2026-01-01 00:00 $name" ;; - esac - exit 0 - ;; -esac -outdir="" -prev="" -for arg in "$@"; do - if [ "$prev" = "-C" ]; then - outdir="$arg" - break +if [ "\${1:-}" = "-m" ]; then echo "arm64"; else echo "Darwin"; fi`, + ); + writeExecutable( + path.join(fakeBin, "openshell"), + `#!/usr/bin/env bash +if [ "\${1:-}" = "--version" ]; then echo "openshell 0.0.36"; exit 0; fi +exit 99`, + ); + writeExecutable(path.join(fakeBin, "gh"), "#!/usr/bin/env bash\nexit 1\n"); + writeExecutable( + path.join(fakeBin, "curl"), + `#!/usr/bin/env bash +echo "$@" >> ${JSON.stringify(downloadLog)} +out="" +while [ "$#" -gt 0 ]; do + if [ "$1" = "-o" ]; then + shift; out="$1" fi - prev="$arg" + shift || true done -[ -n "$outdir" ] || exit 1 -printf '#!/usr/bin/env bash\nexit 0\n' > "$outdir/$name" -chmod 755 "$outdir/$name" +[ -n "$out" ] || exit 1 +cat > "$out" <<'EOF' +class Openshell < Formula + def post_install + entitlements.write <<~XML + + XML + end +end +EOF exit 0`, ); writeExecutable( - path.join(fakeBin, "install"), + path.join(fakeBin, "sha256sum"), `#!/usr/bin/env bash -dest="\${@: -1}" -mkdir -p "$(dirname "$dest")" - cat > "$dest" <<'EOF' +printf '%s %s\\n' '${PINNED_OPEN_SHELL_SHA256.formula}' "$1"`, + ); + writeExecutable( + path.join(fakeBin, "brew"), + `#!/usr/bin/env bash +printf '%s\\n' "$*" >> ${JSON.stringify(brewLog)} +case "$*" in + "tap-info nvidia/openshell") + exit 1 + ;; + "tap-new --no-git nvidia/openshell") + mkdir -p ${JSON.stringify(path.join(tapRepo, "Formula"))} + exit 0 + ;; + "--repository nvidia/openshell") + printf '%s\\n' ${JSON.stringify(tapRepo)} + exit 0 + ;; + "list --formula openshell") + exit 1 + ;; + "install --formula nvidia/openshell/openshell") + cat > ${JSON.stringify(path.join(homebrewPrefix, "bin", "openshell"))} <<'EOF' #!/usr/bin/env bash if [ "\${1:-}" = "--version" ]; then echo "openshell ${REQUIRED_OPENSHELL_VERSION}"; exit 0; fi # ${OPENSHELL_FEATURE_MARKERS} exit 0 EOF -chmod +x "$dest" -exit 0`, + cat > ${JSON.stringify(path.join(homebrewPrefix, "bin", "openshell-gateway"))} <<'EOF' +#!/usr/bin/env bash +if [ "\${1:-}" = "--version" ]; then echo "openshell-gateway ${REQUIRED_OPENSHELL_VERSION}"; exit 0; fi +exit 0 +EOF + chmod 755 ${JSON.stringify(path.join(homebrewPrefix, "bin", "openshell"))} ${JSON.stringify(path.join(homebrewPrefix, "bin", "openshell-gateway"))} + exit 0 + ;; + "services restart openshell") + exit 0 + ;; + "--prefix") + printf '%s\\n' ${JSON.stringify(homebrewPrefix)} + exit 0 + ;; +esac +exit 1`, ); const result = spawnSync("bash", [SCRIPT], { @@ -565,20 +615,22 @@ exit 0`, encoding: "utf8", }); - expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(expected.status); - expect(result.stderr.includes("Unsafe OpenShell archive")).toBe(expected.unsafe); - const installedVersion = spawnSync(path.join(fakeBin, "openshell"), ["--version"], { - encoding: "utf8", - }).stdout.trim(); - expect(installedVersion).toBe( - expected.unsafe ? "openshell 0.0.36" : `openshell ${REQUIRED_OPENSHELL_VERSION}`, - ); - expect(/^xzf /m.test(fs.readFileSync(tarLog, "utf8"))).toBe(!expected.unsafe); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); const downloads = fs.readFileSync(downloadLog, "utf-8"); - expect(downloads).toContain("openshell-aarch64-apple-darwin.tar.gz"); - expect(downloads).toContain("openshell-gateway-aarch64-apple-darwin.tar.gz"); - expect(downloads).not.toContain("openshell-driver-vm-aarch64-apple-darwin.tar.gz"); - expect(downloads).toContain("openshell-gateway-checksums-sha256.txt"); + expect(downloads).toContain("openshell.rb"); + expect(downloads).not.toContain("openshell-aarch64-apple-darwin.tar.gz"); + const brewEvents = fs.readFileSync(brewLog, "utf-8").trim().split("\n"); + expect(brewEvents).toEqual([ + "tap-info nvidia/openshell", + "tap-new --no-git nvidia/openshell", + "--repository nvidia/openshell", + "list --formula openshell", + "install --formula nvidia/openshell/openshell", + "services restart openshell", + "--prefix", + ]); + const stagedFormula = fs.readFileSync(path.join(tapRepo, "Formula", "openshell.rb"), "utf-8"); + expect(stagedFormula).toContain("entitlements.write <<~XML"); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } @@ -1049,7 +1101,7 @@ exit 0`, expect(result.stdout).toContain("Installing OpenShell from release 'dev'"); }); - it("reuses a macOS dev build with its required standalone gateway", () => { + it("reuses a macOS dev build with its required Homebrew gateway service", () => { const result = runWithInstalledVersion( "0.0.72-dev.8+g7bce1223d", { diff --git a/test/installer-hash-check.test.ts b/test/installer-hash-check.test.ts index dc9394088df..ebdc1b1a490 100644 --- a/test/installer-hash-check.test.ts +++ b/test/installer-hash-check.test.ts @@ -54,6 +54,8 @@ const ASSET_DIGESTS = new Map([ ], ]); const ASSETS = [...ASSET_DIGESTS.keys()]; +const FORMULA_ASSET = "openshell.rb"; +const FORMULA_DIGEST = "4b75a7e3a7630eb8954d73ca828b394d5e0646adbaa4b087b2435329d53b61b3"; const UNPUBLISHED_ASSET = "openshell-sandbox-aarch64-unknown-linux-gnu-unpublished.tar.gz"; const OFFICIAL_UNEXPECTED_INSTALLER_ASSET = "openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz"; const OFFICIAL_UNEXPECTED_INSTALLER_DIGEST = @@ -432,6 +434,7 @@ function renderPinFunction( assets: string[], openshellVersion: string, formatting: PinFormatting, + digestMap: ReadonlyMap = ASSET_DIGESTS, ): string { const functionOpening = formatting === "mixed-whitespace" ? `${functionName}\t( )\t{` : `${functionName}() {`; @@ -447,7 +450,7 @@ function renderPinFunction( : ' case "${release_tag}:${asset}" in'; const cases = assets .map((asset) => { - const digest = ASSET_DIGESTS.get(asset) ?? "missing"; + const digest = digestMap.get(asset) ?? "missing"; const pattern = formatting === "quote-styles" ? ` 'v${openshellVersion}:${asset}')` @@ -477,17 +480,21 @@ function renderPinFunction( function replacePinFunction( source: string, functionName: string, - nextFunctionName: string, + nextMarker: string, replacement: string, ): string { const start = source.indexOf(`${functionName}() {`); - const next = source.indexOf(`\n${nextFunctionName}() {`, start); + const next = source.indexOf(`\n${nextMarker}`, start); expect(start, `${functionName} template start`).not.toBe(-1); expect(next, `${functionName} template end`).not.toBe(-1); return `${source.slice(0, start)}${replacement}${source.slice(next)}`; } -function renderInstallerTemplate(openshellVersion: string, pinFunction: string): string { +function renderInstallerTemplate( + openshellVersion: string, + pinFunction: string, + formulaPinFunction: string, +): string { const selected = INSTALLER_TEMPLATE.replace( /^MIN_VERSION="[0-9]+\.[0-9]+\.[0-9]+"$/m, `MIN_VERSION="${openshellVersion}"`, @@ -497,12 +504,18 @@ function renderInstallerTemplate(openshellVersion: string, pinFunction: string): /^DEV_MIN_VERSION="[0-9]+\.[0-9]+\.[0-9]+"$/m, `DEV_MIN_VERSION="${openshellVersion}"`, ); - const withPinFunction = replacePinFunction( + const withArchivePinFunction = replacePinFunction( selected, "openshell_pinned_sha256", - "openshell_checksum_line", + "openshell_checksum_line() {", pinFunction, ); + const withPinFunction = replacePinFunction( + withArchivePinFunction, + "openshell_formula_pinned_sha256", + "# A pinned digest authenticates bytes", + formulaPinFunction, + ); const sandboxFunctionStart = withPinFunction.indexOf("pinned_sandbox_build_version() {"); const sandboxFunctionEnd = withPinFunction.indexOf( "\ncomponent_build_version() {", @@ -524,7 +537,7 @@ function renderBrevTemplate(openshellVersion: string, pinFunction: string): stri return replacePinFunction( selected, "openshell_cli_pinned_sha256", - "openshell_checksum_line", + "openshell_checksum_line() {", pinFunction, ); } @@ -562,6 +575,13 @@ function createFixture( renderInstallerTemplate( openshellVersion, renderPinFunction("openshell_pinned_sha256", ASSETS, openshellVersion, formatting), + renderPinFunction( + "openshell_formula_pinned_sha256", + [FORMULA_ASSET], + openshellVersion, + formatting, + new Map([[FORMULA_ASSET, FORMULA_DIGEST]]), + ), ), ); fs.writeFileSync( @@ -610,16 +630,37 @@ case "$url" in *) printf '%s' '${CHECKSUM_MANIFESTS.get("openshell-gateway-checksums-sha256.txt")}' >"$output" ;; esac ;; - openshell-sandbox-checksums-sha256.txt) - printf '%s' '${CHECKSUM_MANIFESTS.get("openshell-sandbox-checksums-sha256.txt")}' >"$output" - ;; + openshell-sandbox-checksums-sha256.txt) + printf '%s' '${CHECKSUM_MANIFESTS.get("openshell-sandbox-checksums-sha256.txt")}' >"$output" + ;; + openshell.rb) + printf '%s\n' 'class Openshell < Formula; end' >"$output" + ;; + esac + ;; + *) exit 22 ;; + esac + `, + ); + fs.chmodSync(path.join(binDir, "curl"), 0o755); + fs.writeFileSync( + path.join(binDir, "sha256sum"), + `#!/usr/bin/env bash +set -euo pipefail +case "\${1:-}" in + */openshell.rb) + printf '%s %s\\n' '${FORMULA_DIGEST}' "$1" + ;; + *) + case "$(uname -s)" in + Darwin) /usr/bin/shasum -a 256 "$@" ;; + *) /usr/bin/sha256sum "$@" ;; esac ;; - *) exit 22 ;; esac `, ); - fs.chmodSync(path.join(binDir, "curl"), 0o755); + fs.chmodSync(path.join(binDir, "sha256sum"), 0o755); return fixtureRoot; } @@ -983,7 +1024,7 @@ describe("installer hash verification", () => { expect(result.status).not.toBe(0); expect(result.stdout).toContain("Checking OpenShell v0.0.72 release assets"); - expect(result.stdout).toContain("14 OpenShell release-asset check(s) failed"); + expect(result.stdout).toContain("15 OpenShell release-asset check(s) failed"); expect(result.stdout).not.toContain("All installer hashes are current"); }); @@ -992,7 +1033,7 @@ describe("installer hash verification", () => { expect(result.status).toBe(1); expect(result.stdout).toContain("digest does not match the pinned v0.0.72 release asset"); - expect(result.stdout).toContain("expected all 10 pinned asset references"); + expect(result.stdout).toContain("expected all 11 pinned asset references"); expect(result.stdout).not.toContain("All installer hashes are current"); }); diff --git a/test/reboot-recovery-docs.test.ts b/test/reboot-recovery-docs.test.ts new file mode 100644 index 00000000000..620379aa069 --- /dev/null +++ b/test/reboot-recovery-docs.test.ts @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +const repoRoot = path.resolve(import.meta.dirname, ".."); +const troubleshooting = readFileSync( + path.join(repoRoot, "docs/reference/troubleshooting.mdx"), + "utf8", +); + +function section(markdown: string, heading: string): string { + const start = markdown.indexOf(heading); + expect(start).toBeGreaterThanOrEqual(0); + const next = markdown.indexOf("\n### ", start + heading.length); + return markdown.slice(start, next === -1 ? undefined : next); +} + +describe("reboot recovery documentation", () => { + it("routes macOS and Linux through managed OpenShell services before onboard resume", () => { + const reboot = section(troubleshooting, "### Reconnect after a host reboot"); + + expect(reboot).toContain("brew services restart openshell"); + expect(reboot).toContain("openshell-gateway.service"); + expect(reboot).toContain("systemctl --user restart openshell-gateway"); + expect(reboot).toContain("non-systemd Linux hosts"); + expect(reboot.indexOf("systemctl --user restart openshell-gateway")).toBeLessThan( + reboot.indexOf("$$nemoclaw onboard --resume"), + ); + }); +});