diff --git a/.github/workflows/e2e-vitest-scenarios.yaml b/.github/workflows/e2e-vitest-scenarios.yaml index 2158a7fe4d2..abf0a61286e 100644 --- a/.github/workflows/e2e-vitest-scenarios.yaml +++ b/.github/workflows/e2e-vitest-scenarios.yaml @@ -1759,6 +1759,113 @@ jobs: if-no-files-found: ignore retention-days: 14 + upgrade-stale-sandbox-vitest: + needs: generate-matrix + if: ${{ (inputs.jobs == '' && inputs.scenarios == '') || contains(format(',{0},', inputs.jobs), ',upgrade-stale-sandbox-vitest,') || contains(format(',{0},', inputs.scenarios), ',upgrade-stale-sandbox,') }} + runs-on: ubuntu-latest + timeout-minutes: 55 + env: + FREE_STANDING_VITEST_JOB: "1" + FREE_STANDING_SCENARIO_ID: "upgrade-stale-sandbox" + E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/vitest/upgrade-stale-sandbox + NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js + NEMOCLAW_RUN_E2E_SCENARIOS: "1" + NEMOCLAW_NON_INTERACTIVE: "1" + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1" + NEMOCLAW_SANDBOX_NAME: "e2e-upgrade-stale" + OPENSHELL_GATEWAY: "nemoclaw" + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + + - name: Configure isolated Docker auth directory + run: echo "DOCKER_CONFIG=${RUNNER_TEMP}/docker-config-upgrade-stale-sandbox" >> "$GITHUB_ENV" + + - name: Authenticate to Docker Hub + env: + DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} + DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} + shell: bash + run: | + set -euo pipefail + if [[ -z "${DOCKERHUB_USERNAME}" || -z "${DOCKERHUB_TOKEN}" ]]; then + echo "::notice::Docker Hub credentials not configured; continuing with anonymous pulls." + exit 0 + fi + mkdir -p "${DOCKER_CONFIG}" + chmod 700 "${DOCKER_CONFIG}" + login_succeeded=0 + for attempt in 1 2 3; do + if echo "${DOCKERHUB_TOKEN}" | timeout 30s docker login docker.io --username "${DOCKERHUB_USERNAME}" --password-stdin; then + login_succeeded=1 + break + fi + if [[ "$attempt" -lt 3 ]]; then + echo "::warning::Docker Hub login attempt ${attempt} failed; retrying." + sleep 5 + fi + done + if [[ "$login_succeeded" -ne 1 ]]; then + echo "::warning::Docker Hub login failed after 3 attempts; continuing with anonymous pulls." + fi + + - name: Set up Node + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.0.0 + with: + node-version: 22 + cache: npm + + - name: Install root dependencies + run: npm ci --ignore-scripts + + - name: Build CLI + run: npm run build:cli + + - name: Install OpenShell CLI + run: | + set -euo pipefail + env -u DOCKER_CONFIG -u DOCKERHUB_USERNAME -u DOCKERHUB_TOKEN -u NVIDIA_INFERENCE_API_KEY -u NVIDIA_API_KEY -u GITHUB_TOKEN \ + bash scripts/install-openshell.sh + + - name: Run upgrade stale sandbox live Vitest test + env: + NVIDIA_INFERENCE_API_KEY: ${{ secrets.NVIDIA_INFERENCE_API_KEY }} + run: | + set -euo pipefail + export PATH="$HOME/.local/bin:$HOME/.npm-global/bin:$PATH" + if command -v openshell >/dev/null 2>&1; then + OPENSHELL_BIN="$(command -v openshell)" + elif [ -x "$HOME/.local/bin/openshell" ]; then + OPENSHELL_BIN="$HOME/.local/bin/openshell" + else + echo "::error::OpenShell CLI not found after install" + ls -la /usr/local/bin/openshell "$HOME/.local/bin/openshell" 2>&1 || true + exit 1 + fi + export OPENSHELL_BIN + "$OPENSHELL_BIN" --version + npx vitest run --project e2e-scenarios-live \ + test/e2e-scenario/live/upgrade-stale-sandbox.test.ts \ + --silent=false --reporter=default + + - name: Upload upgrade stale sandbox artifacts + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: e2e-vitest-scenarios-upgrade-stale-sandbox + path: e2e-artifacts/vitest/upgrade-stale-sandbox/ + include-hidden-files: false + if-no-files-found: ignore + retention-days: 14 + + - name: Clean up Docker auth + if: always() + run: | + set -euo pipefail + docker logout docker.io || true + rm -rf "${DOCKER_CONFIG}" + double-onboard-vitest: needs: generate-matrix if: ${{ (inputs.jobs == '' && inputs.scenarios == '') || contains(format(',{0},', inputs.jobs), ',double-onboard-vitest,') || contains(format(',{0},', inputs.scenarios), ',double-onboard,') }} @@ -3663,6 +3770,7 @@ jobs: rebuild-openclaw-vitest, sandbox-rebuild-vitest, state-backup-restore-vitest, + upgrade-stale-sandbox-vitest, token-rotation-vitest, messaging-compatible-endpoint-vitest, messaging-providers-vitest, diff --git a/test/e2e-scenario/live/upgrade-stale-sandbox-helpers.ts b/test/e2e-scenario/live/upgrade-stale-sandbox-helpers.ts new file mode 100644 index 00000000000..9e49e87e438 --- /dev/null +++ b/test/e2e-scenario/live/upgrade-stale-sandbox-helpers.ts @@ -0,0 +1,300 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; +import type { HostCliClient } from "../fixtures/clients/host.ts"; +import { resultText } from "../fixtures/clients/index.ts"; +import { type SandboxClient, validateSandboxName } from "../fixtures/clients/sandbox.ts"; +import { expect } from "../fixtures/e2e-test.ts"; +import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; +import { isTransientProviderValidationFailure } from "./network-policy-transient-provider.ts"; + +export const REPO_ROOT = path.resolve(import.meta.dirname, "../../.."); +const BLUEPRINT_RELPATH = path.join("nemoclaw-blueprint", "blueprint.yaml"); +const BLUEPRINT = path.join(REPO_ROOT, BLUEPRINT_RELPATH); +const TEST_SANDBOX_PREFIX = "e2e-upgrade-stale"; +export const SANDBOX_NAME = + process.env.NEMOCLAW_SANDBOX_NAME ?? + [TEST_SANDBOX_PREFIX, process.env.GITHUB_RUN_ID, process.env.GITHUB_RUN_ATTEMPT, process.pid] + .filter(Boolean) + .join("-"); +validateSandboxName(SANDBOX_NAME); +assertSafeSandboxName(); +export const OLD_OPENCLAW_VERSION = "2026.3.11"; +export const OLD_BASE_TAG = `nemoclaw-old-base:${SANDBOX_NAME.toLowerCase().replace(/[^a-z0-9_.-]+/g, "-")}`; +const REGISTRY_FILE = path.join(os.homedir(), ".nemoclaw", "sandboxes.json"); +const SESSION_FILE = path.join(os.homedir(), ".nemoclaw", "onboard-session.json"); +const INSTALL_ATTEMPTS = process.env.CI === "true" || process.env.GITHUB_ACTIONS === "true" ? 3 : 1; + +interface FileSnapshot { + exists: boolean; + content?: string; +} + +function assertSafeSandboxName(): void { + if (!SANDBOX_NAME.startsWith(TEST_SANDBOX_PREFIX)) { + throw new Error( + `upgrade-stale-sandbox live test is destructive and only accepts sandbox names with prefix ${TEST_SANDBOX_PREFIX}; got ${SANDBOX_NAME}`, + ); + } +} + +export function commandEnv(apiKey?: string): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { + ...buildAvailabilityProbeEnv(), + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1", + NEMOCLAW_NON_INTERACTIVE: "1", + NEMOCLAW_REBUILD_VERBOSE: "1", + NEMOCLAW_RECREATE_SANDBOX: "1", + NEMOCLAW_SANDBOX_NAME: SANDBOX_NAME, + OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY ?? "nemoclaw", + }; + apiKey && Object.assign(env, { NVIDIA_INFERENCE_API_KEY: apiKey, NVIDIA_API_KEY: apiKey }); + return env; +} + +export async function bestEffort(run: () => Promise): Promise { + try { + await run(); + } catch { + // Cleanup must not mask the primary assertion failure. + } +} + +function readJsonFile(file: string, fallback: T): T { + try { + return fs.existsSync(file) ? (JSON.parse(fs.readFileSync(file, "utf8")) as T) : fallback; + } catch { + return fallback; + } +} + +function writeJsonFile(file: string, value: unknown): void { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, "utf8"); +} + +function snapshotFile(file: string): FileSnapshot { + return fs.existsSync(file) + ? { exists: true, content: fs.readFileSync(file, "utf8") } + : { exists: false }; +} + +function restoreFile(file: string, snapshot: FileSnapshot): void { + snapshot.exists || fs.rmSync(file, { force: true }); + if (!snapshot.exists) return; + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, snapshot.content ?? "", "utf8"); +} + +function createOldBaseBuildContext(): string { + const buildContext = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-upgrade-stale-base-")); + fs.mkdirSync(path.join(buildContext, path.dirname(BLUEPRINT_RELPATH)), { recursive: true }); + const original = fs.readFileSync(BLUEPRINT, "utf8"); + const minOpenClawVersion = /^(\s*min_openclaw_version:\s*).*/m; + expect( + minOpenClawVersion.test(original), + "blueprint min_openclaw_version line was not found", + ).toBe(true); + fs.writeFileSync( + path.join(buildContext, BLUEPRINT_RELPATH), + original.replace(minOpenClawVersion, `$1"${OLD_OPENCLAW_VERSION}"`), + "utf8", + ); + return buildContext; +} + +export function writeStaleRegistryEntry(): void { + const session = readJsonFile>(SESSION_FILE, {}); + const envProvider = + process.env.NEMOCLAW_PROVIDER === "custom" + ? "compatible-endpoint" + : process.env.NEMOCLAW_PROVIDER; + const provider = + typeof session.provider === "string" && session.provider + ? session.provider + : envProvider || "compatible-endpoint"; + const model = + (typeof session.model === "string" && session.model) || + process.env.NEMOCLAW_MODEL || + process.env.NEMOCLAW_COMPAT_MODEL || + "nvidia/nvidia/nemotron-3-super-v3"; + const registry = readJsonFile<{ + sandboxes?: Record>; + defaultSandbox?: string; + }>(REGISTRY_FILE, {}); + registry.sandboxes = registry.sandboxes ?? {}; + registry.sandboxes[SANDBOX_NAME] = { + name: SANDBOX_NAME, + createdAt: new Date().toISOString(), + model, + provider, + gpuEnabled: false, + policies: [], + policyTier: null, + agent: null, + agentVersion: OLD_OPENCLAW_VERSION, + }; + registry.defaultSandbox = SANDBOX_NAME; + writeJsonFile(REGISTRY_FILE, registry); + writeJsonFile(SESSION_FILE, { ...session, sandboxName: SANDBOX_NAME, status: "complete" }); +} + +export function assertDockerAvailable( + result: ShellProbeResult, + skip: (note?: string) => never, +): void { + result.exitCode === 0 || process.env.GITHUB_ACTIONS === "true" + ? undefined + : skip(`Docker is required for stale sandbox upgrade E2E: ${resultText(result)}`); + result.exitCode === 0 || + process.env.GITHUB_ACTIONS !== "true" || + (() => { + throw new Error(`Docker is required for stale sandbox upgrade E2E: ${resultText(result)}`); + })(); +} + +export function registerStateRestore(cleanup: { + add(name: string, run: () => Promise | void): void; +}): void { + const registrySnapshot = snapshotFile(REGISTRY_FILE); + const sessionSnapshot = snapshotFile(SESSION_FILE); + cleanup.add(`restore NemoClaw state files for ${SANDBOX_NAME}`, () => { + restoreFile(REGISTRY_FILE, registrySnapshot); + restoreFile(SESSION_FILE, sessionSnapshot); + }); +} + +export async function cleanupStaleSandbox( + host: HostCliClient, + sandbox: SandboxClient, +): Promise { + await bestEffort(() => + host.nemoclaw([SANDBOX_NAME, "destroy", "--yes"], { + artifactName: "cleanup-nemoclaw-destroy-upgrade-stale", + env: commandEnv(), + timeoutMs: 120_000, + }), + ); + await bestEffort(() => + sandbox.openshell(["sandbox", "delete", SANDBOX_NAME], { + artifactName: "cleanup-openshell-delete-upgrade-stale", + env: commandEnv(), + timeoutMs: 60_000, + }), + ); +} + +export async function cleanupOldImage(host: HostCliClient): Promise { + await bestEffort(() => + host.command("docker", ["image", "rm", "-f", OLD_BASE_TAG], { + artifactName: "cleanup-docker-image-upgrade-stale", + env: buildAvailabilityProbeEnv(), + timeoutMs: 60_000, + }), + ); +} + +export async function installCurrentNemoclaw( + host: HostCliClient, + apiKey: string, +): Promise { + let install: ShellProbeResult | undefined; + for (let attempt = 1; attempt <= INSTALL_ATTEMPTS; attempt += 1) { + install = await host.command("bash", ["install.sh", "--non-interactive"], { + artifactName: + attempt === 1 + ? "phase-1-install-current-nemoclaw" + : `phase-1-install-current-nemoclaw-attempt-${attempt}`, + cwd: REPO_ROOT, + env: commandEnv(apiKey), + redactionValues: [apiKey], + timeoutMs: 20 * 60_000, + }); + const retry = + install.exitCode !== 0 && + isTransientProviderValidationFailure(install) && + attempt < INSTALL_ATTEMPTS; + install.exitCode === 0 && (attempt = INSTALL_ATTEMPTS + 1); + retry && (await new Promise((resolve) => setTimeout(resolve, 10_000 * attempt))); + !retry && install.exitCode !== 0 && (attempt = INSTALL_ATTEMPTS + 1); + } + if (!install) throw new Error("install command did not run"); + return install; +} + +export function assertDeleteInstalledSandboxAllowed(result: ShellProbeResult): void { + result.exitCode === 0 || expect(result.exitCode, resultText(result)).toBe(1); + result.exitCode === 0 || + expect(resultText(result)).toMatch(/not found|does not exist|no sandbox/i); +} + +export async function buildOldOpenClawBase(host: HostCliClient): Promise { + const oldBaseBuildContext = createOldBaseBuildContext(); + try { + return await host.command( + "docker", + [ + "build", + "--build-arg", + `OPENCLAW_VERSION=${OLD_OPENCLAW_VERSION}`, + "-f", + path.join(REPO_ROOT, "Dockerfile.base"), + "-t", + OLD_BASE_TAG, + oldBaseBuildContext, + ], + { + artifactName: "phase-2-build-old-openclaw-base", + env: buildAvailabilityProbeEnv(), + timeoutMs: 20 * 60_000, + }, + ); + } finally { + fs.rmSync(oldBaseBuildContext, { recursive: true, force: true }); + } +} + +export function createFixtureDockerfile(cleanup: { + add(name: string, run: () => Promise | void): void; +}): string { + const fixtureDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-old-openclaw-")); + cleanup.add("remove stale sandbox fixture Dockerfile", () => + fs.rmSync(fixtureDir, { recursive: true, force: true }), + ); + const fixtureDockerfile = path.join(fixtureDir, "Dockerfile"); + fs.writeFileSync( + fixtureDockerfile, + [ + `FROM ${OLD_BASE_TAG}`, + "USER sandbox", + "WORKDIR /sandbox", + "RUN mkdir -p /sandbox/.openclaw/workspace /sandbox/.openclaw && echo '{}' > /sandbox/.openclaw/openclaw.json", + 'CMD ["/bin/bash"]', + "", + ].join("\n"), + ); + return fixtureDockerfile; +} + +export async function waitSandboxReady( + host: HostCliClient, + artifactName: string, +): Promise { + return await host.command( + "bash", + [ + "-lc", + `for _i in $(seq 1 30); do openshell sandbox list 2>/dev/null | grep -q '${SANDBOX_NAME}.*Ready' && exit 0; sleep 5; done; openshell sandbox list >&2; exit 1`, + ], + { artifactName, env: commandEnv(), timeoutMs: 180_000 }, + ); +} + +export function registeredStaleSandboxJson(): string { + return fs.readFileSync(REGISTRY_FILE, "utf8"); +} diff --git a/test/e2e-scenario/live/upgrade-stale-sandbox.test.ts b/test/e2e-scenario/live/upgrade-stale-sandbox.test.ts new file mode 100644 index 00000000000..0b796fe38b8 --- /dev/null +++ b/test/e2e-scenario/live/upgrade-stale-sandbox.test.ts @@ -0,0 +1,158 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * Live Vitest replacement for test/e2e/test-upgrade-stale-sandbox.sh. + * + * Preserves the legacy #1904 contract with real Docker/OpenShell/NemoClaw + * boundaries: onboard current NemoClaw, create an old OpenClaw sandbox from a + * real image, register stale sandbox metadata, prove upgrade-sandboxes detects + * the stale sandbox, rebuild it, and prove the stale version is gone. + */ + +import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; +import { resultText } from "../fixtures/clients/index.ts"; +import { expect, test } from "../fixtures/e2e-test.ts"; +import { shouldRunLiveE2EScenarios } from "../fixtures/live-project-gate.ts"; +import { + assertDeleteInstalledSandboxAllowed, + assertDockerAvailable, + buildOldOpenClawBase, + cleanupOldImage, + cleanupStaleSandbox, + commandEnv, + createFixtureDockerfile, + installCurrentNemoclaw, + OLD_OPENCLAW_VERSION, + registeredStaleSandboxJson, + registerStateRestore, + SANDBOX_NAME, + waitSandboxReady, + writeStaleRegistryEntry, +} from "./upgrade-stale-sandbox-helpers.ts"; + +const LIVE_TIMEOUT_MS = 45 * 60_000; + +test.skipIf(!shouldRunLiveE2EScenarios())( + "upgrade-sandboxes detects and rebuilds stale OpenClaw sandboxes (#1904)", + { timeout: LIVE_TIMEOUT_MS }, + async ({ artifacts, cleanup, host, sandbox, secrets, skip }) => { + const apiKey = secrets.required("NVIDIA_INFERENCE_API_KEY"); + + await artifacts.writeJson("scenario.json", { + id: "upgrade-stale-sandbox", + runner: "vitest", + legacySource: "test/e2e/test-upgrade-stale-sandbox.sh", + boundary: "install.sh + Docker old base image + OpenShell sandbox create + NemoClaw rebuild", + sandboxName: SANDBOX_NAME, + oldOpenClawVersion: OLD_OPENCLAW_VERSION, + contracts: [ + "current NemoClaw install/onboard succeeds before stale fixture creation", + "an old OpenClaw base image can be created with the legacy version", + "a sandbox registered with old agentVersion is reported stale by upgrade-sandboxes --check", + "nemoclaw rebuild --yes upgrades the sandbox away from the old OpenClaw version", + "upgrade-sandboxes --check reports up-to-date after rebuild", + ], + }); + + const dockerInfo = await host.command("docker", ["info"], { + artifactName: "phase-0-docker-info", + env: buildAvailabilityProbeEnv(), + timeoutMs: 30_000, + }); + assertDockerAvailable(dockerInfo, skip); + + registerStateRestore(cleanup); + cleanup.add(`destroy stale sandbox ${SANDBOX_NAME}`, () => cleanupStaleSandbox(host, sandbox)); + cleanup.add("remove stale OpenClaw test image", () => cleanupOldImage(host)); + await cleanupStaleSandbox(host, sandbox); + + const install = await installCurrentNemoclaw(host, apiKey); + expect(install.exitCode, resultText(install)).toBe(0); + + const deleteInstalledSandbox = await sandbox.openshell(["sandbox", "delete", SANDBOX_NAME], { + artifactName: "phase-2-delete-installed-sandbox", + env: commandEnv(), + timeoutMs: 120_000, + }); + assertDeleteInstalledSandboxAllowed(deleteInstalledSandbox); + + const buildOldBase = await buildOldOpenClawBase(host); + expect(buildOldBase.exitCode, resultText(buildOldBase)).toBe(0); + + const fixtureDockerfile = createFixtureDockerfile(cleanup); + const createOldSandbox = await sandbox.openshell( + [ + "sandbox", + "create", + "--name", + SANDBOX_NAME, + "--from", + fixtureDockerfile, + "--gateway", + "nemoclaw", + "--no-tty", + "--", + "true", + ], + { + artifactName: "phase-3-create-old-openclaw-sandbox", + env: commandEnv(), + timeoutMs: 15 * 60_000, + }, + ); + expect(createOldSandbox.exitCode, resultText(createOldSandbox)).toBe(0); + + const waitReady = await waitSandboxReady(host, "phase-3-wait-old-sandbox-ready"); + expect(waitReady.exitCode, resultText(waitReady)).toBe(0); + + const oldVersion = await sandbox.exec(SANDBOX_NAME, ["openclaw", "--version"], { + artifactName: "phase-3-old-openclaw-version", + env: commandEnv(), + timeoutMs: 60_000, + }); + expect(oldVersion.exitCode, resultText(oldVersion)).toBe(0); + expect(resultText(oldVersion)).toContain(OLD_OPENCLAW_VERSION); + + writeStaleRegistryEntry(); + await artifacts.writeText("registered-stale-sandbox.json", registeredStaleSandboxJson()); + + const staleCheck = await host.nemoclaw(["upgrade-sandboxes", "--check"], { + artifactName: "phase-5-upgrade-sandboxes-check-stale", + env: commandEnv(apiKey), + redactionValues: [apiKey], + timeoutMs: 120_000, + }); + expect(staleCheck.exitCode, resultText(staleCheck)).toBe(0); + expect(resultText(staleCheck)).toMatch(/stale|need upgrading/i); + expect(resultText(staleCheck)).not.toMatch(/up to date/i); + + const rebuild = await host.nemoclaw([SANDBOX_NAME, "rebuild", "--yes"], { + artifactName: "phase-6-rebuild-stale-sandbox", + env: commandEnv(apiKey), + redactionValues: [apiKey], + timeoutMs: 25 * 60_000, + }); + expect(rebuild.exitCode, resultText(rebuild)).toBe(0); + + const waitRebuiltReady = await waitSandboxReady(host, "phase-6-wait-rebuilt-sandbox-ready"); + expect(waitRebuiltReady.exitCode, resultText(waitRebuiltReady)).toBe(0); + + const newVersion = await sandbox.exec(SANDBOX_NAME, ["openclaw", "--version"], { + artifactName: "phase-6-new-openclaw-version", + env: commandEnv(), + timeoutMs: 60_000, + }); + expect(newVersion.exitCode, resultText(newVersion)).toBe(0); + expect(resultText(newVersion)).not.toContain(OLD_OPENCLAW_VERSION); + + const cleanCheck = await host.nemoclaw(["upgrade-sandboxes", "--check"], { + artifactName: "phase-7-upgrade-sandboxes-check-clean", + env: commandEnv(apiKey), + redactionValues: [apiKey], + timeoutMs: 120_000, + }); + expect(cleanCheck.exitCode, resultText(cleanCheck)).toBe(0); + expect(resultText(cleanCheck)).toMatch(/up to date/i); + }, +); diff --git a/test/e2e-scenario/support-tests/e2e-scenarios-workflow.test.ts b/test/e2e-scenario/support-tests/e2e-scenarios-workflow.test.ts index 2e3e22e0a7c..2da7d41c134 100644 --- a/test/e2e-scenario/support-tests/e2e-scenarios-workflow.test.ts +++ b/test/e2e-scenario/support-tests/e2e-scenarios-workflow.test.ts @@ -8,14 +8,13 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; import YAML from "yaml"; - -import { testTimeoutOptions } from "../../helpers/timeouts"; import { evaluateE2eVitestWorkflowDispatchSelectors, readFreeStandingJobsInventory, validateE2eVitestScenariosWorkflowBoundary, validateFreeStandingWorkflowInventory, } from "../../../tools/e2e-scenarios/workflow-boundary.mts"; +import { testTimeoutOptions } from "../../helpers/timeouts"; function readWorkflow(): Record { return YAML.parse( @@ -396,6 +395,26 @@ describe("e2e-vitest-scenarios workflow boundary", () => { selectedFreeStandingJobs: ["state-backup-restore-vitest"], registryScenarios: [], }); + expect( + evaluateE2eVitestWorkflowDispatchSelectors({ + scenarios: "upgrade-stale-sandbox", + }), + ).toMatchObject({ + valid: true, + liveScenariosRuns: false, + selectedFreeStandingJobs: ["upgrade-stale-sandbox-vitest"], + registryScenarios: [], + }); + expect( + evaluateE2eVitestWorkflowDispatchSelectors({ + jobs: "upgrade-stale-sandbox-vitest", + }), + ).toMatchObject({ + valid: true, + liveScenariosRuns: false, + selectedFreeStandingJobs: ["upgrade-stale-sandbox-vitest"], + registryScenarios: [], + }); expect( evaluateE2eVitestWorkflowDispatchSelectors({ scenarios: "model-router-provider-routed-inference", @@ -565,14 +584,18 @@ describe("e2e-vitest-scenarios workflow boundary", () => { }, ); - it("derives the free-standing inventory from workflow job metadata", () => { + it("derives the free-standing inventory from workflow job metadata", { timeout: 60_000 }, () => { const inventory = readFreeStandingJobsInventory(); expect(validateFreeStandingWorkflowInventory()).toEqual([]); expect(inventory.allowedJobs).toContain("openshell-version-pin-vitest"); expect(inventory.allowedJobs).toContain("gateway-guard-recovery"); + expect(inventory.allowedJobs).toContain("upgrade-stale-sandbox-vitest"); expect(inventory.scenarioToJob.get("openshell-version-pin")).toBe( "openshell-version-pin-vitest", ); + expect(inventory.scenarioToJob.get("upgrade-stale-sandbox")).toBe( + "upgrade-stale-sandbox-vitest", + ); expect(inventory.scenarioToJob.get("credential-migration")).toBeUndefined(); expect( inventory.allowedJobs.every((job) => diff --git a/tools/e2e-scenarios/workflow-boundary.mts b/tools/e2e-scenarios/workflow-boundary.mts index c315b65ec56..8decf10480e 100644 --- a/tools/e2e-scenarios/workflow-boundary.mts +++ b/tools/e2e-scenarios/workflow-boundary.mts @@ -1497,6 +1497,172 @@ function validateStateBackupRestoreVitestJob(errors: string[], jobs: WorkflowRec } } +function validateUpgradeStaleSandboxVitestJob(errors: string[], jobs: WorkflowRecord): void { + const jobName = "upgrade-stale-sandbox-vitest"; + const scenarioName = "upgrade-stale-sandbox"; + const job = asRecord(jobs[jobName]); + if (Object.keys(job).length === 0) { + errors.push("workflow missing upgrade-stale-sandbox-vitest job"); + return; + } + + if (job["runs-on"] !== "ubuntu-latest") { + errors.push("upgrade-stale-sandbox-vitest job must run on ubuntu-latest"); + } + validateFreeStandingJobSelector(errors, jobs, jobName, scenarioName); + if (job["timeout-minutes"] !== 55) { + errors.push("upgrade-stale-sandbox-vitest job must keep the legacy 55 minute timeout"); + } + + const jobEnv = asRecord(job.env); + if (jobEnv.NEMOCLAW_RUN_E2E_SCENARIOS !== "1") { + errors.push("upgrade-stale-sandbox-vitest job must set NEMOCLAW_RUN_E2E_SCENARIOS=1"); + } + if ( + jobEnv.E2E_ARTIFACT_DIR !== "${{ github.workspace }}/e2e-artifacts/vitest/upgrade-stale-sandbox" + ) { + errors.push( + "upgrade-stale-sandbox-vitest job must write artifacts under e2e-artifacts/vitest/upgrade-stale-sandbox", + ); + } + if (jobEnv.NEMOCLAW_CLI_BIN !== "${{ github.workspace }}/bin/nemoclaw.js") { + errors.push("upgrade-stale-sandbox-vitest job must point NEMOCLAW_CLI_BIN at the repo CLI"); + } + if (jobEnv.OPENSHELL_GATEWAY !== "nemoclaw") { + errors.push("upgrade-stale-sandbox-vitest job must force OPENSHELL_GATEWAY=nemoclaw"); + } + if (jobEnv.NEMOCLAW_SANDBOX_NAME !== "e2e-upgrade-stale") { + errors.push( + "upgrade-stale-sandbox-vitest job must set NEMOCLAW_SANDBOX_NAME=e2e-upgrade-stale", + ); + } + if ("DOCKER_CONFIG" in jobEnv) { + errors.push("upgrade-stale-sandbox-vitest job must not set DOCKER_CONFIG at job level"); + } + for (const secret of ["NVIDIA_INFERENCE_API_KEY", ...COMMON_SECRET_ENV_NAMES]) { + requireEnvDoesNotExposeSecret(errors, "upgrade-stale-sandbox-vitest job", jobEnv, secret); + } + + const steps = asSteps(job.steps); + requireNoDispatchInputInterpolation(errors, steps); + for (const step of steps) { + const stepName = `upgrade-stale-sandbox-vitest step '${step.name ?? step.uses ?? ""}'`; + const stepEnv = asRecord(step.env); + if (step.name !== "Run upgrade stale sandbox live Vitest test") { + requireEnvDoesNotExposeSecret(errors, stepName, stepEnv, "NVIDIA_INFERENCE_API_KEY"); + requireEnvDoesNotExposeSecret(errors, stepName, stepEnv, "NVIDIA_API_KEY"); + } + if (step.name !== "Authenticate to Docker Hub") { + requireEnvDoesNotExposeSecret(errors, stepName, stepEnv, "DOCKERHUB_USERNAME"); + requireEnvDoesNotExposeSecret(errors, stepName, stepEnv, "DOCKERHUB_TOKEN"); + requireNoDockerHubAuthInRun(errors, stepName, stringValue(step.run)); + } + requireEnvDoesNotExposeSecret(errors, stepName, stepEnv, "GITHUB_TOKEN"); + } + + const checkout = steps.find((step) => stringValue(step.uses).startsWith("actions/checkout@")); + if (!checkout) errors.push("upgrade-stale-sandbox-vitest job missing checkout step"); + requireFullShaAction(errors, checkout, "upgrade-stale-sandbox-vitest checkout"); + if (asRecord(checkout?.with)["persist-credentials"] !== false) { + errors.push("upgrade-stale-sandbox-vitest checkout step must set persist-credentials=false"); + } + + const configureDockerAuth = requireJobStep( + errors, + jobName, + steps, + "Configure isolated Docker auth directory", + ); + requireRunContains( + errors, + configureDockerAuth, + 'echo "DOCKER_CONFIG=${RUNNER_TEMP}/docker-config-upgrade-stale-sandbox" >> "$GITHUB_ENV"', + ); + + const dockerHubAuth = requireJobStep(errors, jobName, steps, "Authenticate to Docker Hub"); + const dockerHubEnv = asRecord(dockerHubAuth?.env); + if (dockerHubEnv.DOCKERHUB_USERNAME !== "${{ secrets.DOCKERHUB_USERNAME }}") { + errors.push( + "upgrade-stale-sandbox-vitest Docker Hub auth must receive DOCKERHUB_USERNAME from secrets", + ); + } + if (dockerHubEnv.DOCKERHUB_TOKEN !== "${{ secrets.DOCKERHUB_TOKEN }}") { + errors.push( + "upgrade-stale-sandbox-vitest Docker Hub auth must receive DOCKERHUB_TOKEN from secrets", + ); + } + requireRunContains(errors, dockerHubAuth, 'mkdir -p "${DOCKER_CONFIG}"'); + requireRunContains(errors, dockerHubAuth, 'chmod 700 "${DOCKER_CONFIG}"'); + requireRunContains(errors, dockerHubAuth, "docker login docker.io"); + requireRunContains(errors, dockerHubAuth, "continuing with anonymous pulls"); + + const setupNode = namedStep(steps, "Set up Node"); + if (!setupNode) errors.push("upgrade-stale-sandbox-vitest job missing step: Set up Node"); + requireFullShaAction(errors, setupNode, "upgrade-stale-sandbox-vitest setup-node"); + + const installRootDependencies = requireJobStep( + errors, + jobName, + steps, + "Install root dependencies", + ); + requireRunContains(errors, installRootDependencies, "npm ci --ignore-scripts"); + + const buildCli = requireJobStep(errors, jobName, steps, "Build CLI"); + requireRunContains(errors, buildCli, "npm run build:cli"); + + const installOpenShell = requireJobStep(errors, jobName, steps, "Install OpenShell CLI"); + requireRunContains(errors, installOpenShell, "bash scripts/install-openshell.sh"); + requireRunContains(errors, installOpenShell, "env -u DOCKER_CONFIG"); + requireRunContains(errors, installOpenShell, "-u DOCKERHUB_USERNAME"); + requireRunContains(errors, installOpenShell, "-u DOCKERHUB_TOKEN"); + requireRunContains(errors, installOpenShell, "-u NVIDIA_INFERENCE_API_KEY"); + requireRunContains(errors, installOpenShell, "-u NVIDIA_API_KEY"); + requireRunContains(errors, installOpenShell, "-u GITHUB_TOKEN"); + + const runVitest = requireJobStep( + errors, + jobName, + steps, + "Run upgrade stale sandbox live Vitest test", + ); + const runVitestEnv = asRecord(runVitest?.env); + if (runVitestEnv.NVIDIA_INFERENCE_API_KEY !== "${{ secrets.NVIDIA_INFERENCE_API_KEY }}") { + errors.push( + "upgrade-stale-sandbox-vitest step must receive NVIDIA_INFERENCE_API_KEY from secrets", + ); + } + requireRunContains(errors, runVitest, "OPENSHELL_BIN"); + requireRunContains(errors, runVitest, "npx vitest run --project e2e-scenarios-live"); + requireRunContains(errors, runVitest, "test/e2e-scenario/live/upgrade-stale-sandbox.test.ts"); + + const upload = requireJobStep(errors, jobName, steps, "Upload upgrade stale sandbox artifacts"); + requireFullShaAction(errors, upload, "upgrade-stale-sandbox-vitest upload-artifact"); + const uploadWith = asRecord(upload?.with); + if (uploadWith.name !== "e2e-vitest-scenarios-upgrade-stale-sandbox") { + errors.push("upgrade-stale-sandbox-vitest artifact upload name must be stable"); + } + const uploadPath = stringValue(uploadWith.path); + requireUploadPathContains(errors, uploadPath, "e2e-artifacts/vitest/upgrade-stale-sandbox/"); + if (uploadWith["include-hidden-files"] !== false) { + errors.push( + "upgrade-stale-sandbox-vitest artifact upload must set include-hidden-files: false", + ); + } + if (uploadWith["if-no-files-found"] !== "ignore") { + errors.push( + "upgrade-stale-sandbox-vitest artifact upload must ignore missing fixture artifacts", + ); + } + if (uploadWith["retention-days"] !== 14) { + errors.push("upgrade-stale-sandbox-vitest artifact upload retention-days must be 14"); + } + + const cleanup = requireJobStep(errors, jobName, steps, "Clean up Docker auth"); + requireRunContains(errors, cleanup, "docker logout docker.io"); + requireRunContains(errors, cleanup, 'rm -rf "${DOCKER_CONFIG}"'); +} + function validateTokenRotationVitestJob(errors: string[], jobs: WorkflowRecord): void { const jobName = "token-rotation-vitest"; const job = asRecord(jobs[jobName]); @@ -3804,6 +3970,7 @@ export function validateE2eVitestScenariosWorkflowBoundary( validateRebuildOpenClawVitestJob(errors, jobs); validateSandboxRebuildVitestJob(errors, jobs); validateStateBackupRestoreVitestJob(errors, jobs); + validateUpgradeStaleSandboxVitestJob(errors, jobs); validateTokenRotationVitestJob(errors, jobs); validateMessagingCompatibleEndpointVitestJob(errors, jobs); validateFreeStandingJobSelector(