From f1a694506be33a7e07ebf014d49efefaad6976f3 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Fri, 12 Jun 2026 09:58:21 -0400 Subject: [PATCH 1/3] test(e2e): migrate test-sandbox-rebuild.sh to vitest --- .github/workflows/e2e-vitest-scenarios.yaml | 100 ++++++- .../e2e-scenario/fixtures/phases/lifecycle.ts | 80 ++++++ .../fixtures/phases/onboarding.ts | 22 +- .../fixtures/phases/state-validation.ts | 239 ++++++++++++++++ .../e2e-scenario/live/sandbox-rebuild.test.ts | 258 ++++++++++++++++++ .../e2e-phase-state-validation.test.ts | 114 ++++++++ .../e2e-scenarios-workflow.test.ts | 29 ++ tools/e2e-scenarios/workflow-boundary.mts | 117 ++++++++ 8 files changed, 948 insertions(+), 11 deletions(-) create mode 100644 test/e2e-scenario/live/sandbox-rebuild.test.ts diff --git a/.github/workflows/e2e-vitest-scenarios.yaml b/.github/workflows/e2e-vitest-scenarios.yaml index 174b24ae263..485487d60ec 100644 --- a/.github/workflows/e2e-vitest-scenarios.yaml +++ b/.github/workflows/e2e-vitest-scenarios.yaml @@ -40,7 +40,7 @@ jobs: SCENARIOS: ${{ inputs.scenarios }} run: | set -euo pipefail - allowed_jobs="openshell-version-pin-vitest,onboard-negative-paths-vitest,inference-routing-vitest,credential-migration-vitest,runtime-overrides-vitest,hermes-e2e-vitest,hermes-root-entrypoint-smoke-vitest,network-policy-vitest,rebuild-openclaw-vitest,token-rotation-vitest,launchable-smoke-vitest,openclaw-tui-chat-correlation-vitest,gateway-guard-recovery,double-onboard-vitest,issue-4434-tui-unreachable-inference-vitest,model-router-provider-routed-inference-vitest" + allowed_jobs="openshell-version-pin-vitest,onboard-negative-paths-vitest,inference-routing-vitest,credential-migration-vitest,runtime-overrides-vitest,hermes-e2e-vitest,hermes-root-entrypoint-smoke-vitest,network-policy-vitest,rebuild-openclaw-vitest,sandbox-rebuild-vitest,token-rotation-vitest,launchable-smoke-vitest,openclaw-tui-chat-correlation-vitest,gateway-guard-recovery,double-onboard-vitest,issue-4434-tui-unreachable-inference-vitest,model-router-provider-routed-inference-vitest" if [ -n "${JOBS}" ] && [ -n "${SCENARIOS}" ]; then echo "::error::Use either scenarios or jobs, not both." >&2 exit 1 @@ -93,12 +93,12 @@ jobs: SCENARIOS: ${{ inputs.scenarios }} run: | set -euo pipefail - allowed_jobs="openshell-version-pin-vitest,onboard-negative-paths-vitest,inference-routing-vitest,credential-migration-vitest,runtime-overrides-vitest,hermes-e2e-vitest,hermes-root-entrypoint-smoke-vitest,network-policy-vitest,rebuild-openclaw-vitest,token-rotation-vitest,launchable-smoke-vitest,openclaw-tui-chat-correlation-vitest,gateway-guard-recovery,double-onboard-vitest,issue-4434-tui-unreachable-inference-vitest,model-router-provider-routed-inference-vitest" + allowed_jobs="openshell-version-pin-vitest,onboard-negative-paths-vitest,inference-routing-vitest,credential-migration-vitest,runtime-overrides-vitest,hermes-e2e-vitest,hermes-root-entrypoint-smoke-vitest,network-policy-vitest,rebuild-openclaw-vitest,sandbox-rebuild-vitest,token-rotation-vitest,launchable-smoke-vitest,openclaw-tui-chat-correlation-vitest,gateway-guard-recovery,double-onboard-vitest,issue-4434-tui-unreachable-inference-vitest,model-router-provider-routed-inference-vitest" args=(--emit-live-matrix) matrix="" hermes_selected=false registry_scenarios=() - free_standing_scenarios=(openshell-version-pin onboard-negative-paths inference-routing runtime-overrides hermes-e2e hermes-root-entrypoint-smoke network-policy rebuild-openclaw token-rotation openclaw-tui-chat-correlation double-onboard issue-4434-tui-unreachable-inference model-router-provider-routed-inference) + free_standing_scenarios=(openshell-version-pin onboard-negative-paths inference-routing runtime-overrides hermes-e2e hermes-root-entrypoint-smoke network-policy rebuild-openclaw sandbox-rebuild token-rotation openclaw-tui-chat-correlation double-onboard issue-4434-tui-unreachable-inference model-router-provider-routed-inference) is_free_standing_scenario() { local id="$1" local known @@ -876,6 +876,99 @@ jobs: if-no-files-found: ignore retention-days: 14 + sandbox-rebuild-vitest: + needs: [validate-jobs, generate-matrix] + if: ${{ (inputs.jobs == '' && inputs.scenarios == '') || contains(format(',{0},', inputs.jobs), ',sandbox-rebuild-vitest,') || contains(format(',{0},', inputs.scenarios), ',sandbox-rebuild,') }} + runs-on: ubuntu-latest + timeout-minutes: 90 + env: + E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/vitest/sandbox-rebuild + NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js + NEMOCLAW_RUN_E2E_SCENARIOS: "1" + NEMOCLAW_NON_INTERACTIVE: "1" + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1" + OPENSHELL_GATEWAY: nemoclaw + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + + - 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 + 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 + env: + NEMOCLAW_NON_INTERACTIVE: "1" + run: | + set -euo pipefail + env -u DOCKER_CONFIG -u DOCKERHUB_USERNAME -u DOCKERHUB_TOKEN -u NVIDIA_API_KEY -u GITHUB_TOKEN bash scripts/install-openshell.sh + + - name: Run sandbox rebuild live test + env: + NVIDIA_API_KEY: ${{ secrets.NVIDIA_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/sandbox-rebuild.test.ts \ + --silent=false --reporter=default + + - name: Upload sandbox rebuild artifacts + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: e2e-vitest-scenarios-sandbox-rebuild + path: e2e-artifacts/vitest/sandbox-rebuild/ + include-hidden-files: false + if-no-files-found: ignore + retention-days: 14 + double-onboard-vitest: needs: validate-jobs if: ${{ (inputs.jobs == '' && inputs.scenarios == '') || contains(format(',{0},', inputs.jobs), ',double-onboard-vitest,') }} @@ -1397,6 +1490,7 @@ jobs: hermes-root-entrypoint-smoke-vitest, network-policy-vitest, rebuild-openclaw-vitest, + sandbox-rebuild-vitest, token-rotation-vitest, launchable-smoke-vitest, double-onboard-vitest, diff --git a/test/e2e-scenario/fixtures/phases/lifecycle.ts b/test/e2e-scenario/fixtures/phases/lifecycle.ts index 263f7c6f965..c457898e4e4 100644 --- a/test/e2e-scenario/fixtures/phases/lifecycle.ts +++ b/test/e2e-scenario/fixtures/phases/lifecycle.ts @@ -21,6 +21,9 @@ const DOCKER_PROBE_TIMEOUT_MS = 15_000; // the gateway recovery path retries. Keep the budget generous; the // bug is independent of latency. 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; export type LifecycleProfile = "post-reboot-recovery"; @@ -56,6 +59,36 @@ export interface LifecycleResult { steps: Array<{ id: string; results: ShellProbeResult[] }>; } +export interface RebuildSandboxOptions { + artifactName?: string; + env?: NodeJS.ProcessEnv; + redactionValues?: string[]; + timeoutMs?: number; + verbose?: boolean; +} + +export interface SandboxReadyAfterRebuildOptions { + attempts?: number; + delayMs?: number; + env?: NodeJS.ProcessEnv; + artifactNamePrefix?: string; + timeoutMs?: number; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function instanceName(instance: NemoClawInstance | string): string { + const name = typeof instance === "string" ? instance : instance.sandboxName; + return name; +} + +function outputContainsReadySandbox(result: ShellProbeResult, sandboxName: string): boolean { + const escaped = sandboxName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`${escaped}.*\\bReady\\b`, "i").test(`${result.stdout}\n${result.stderr}`); +} + export class LifecyclePhaseFixture { constructor( private readonly host: HostCliClient, @@ -63,6 +96,53 @@ export class LifecyclePhaseFixture { private readonly cleanup: LifecycleCleanup, ) {} + async rebuildSandbox( + instance: NemoClawInstance | string, + options: RebuildSandboxOptions = {}, + ): Promise { + const sandboxName = instanceName(instance); + const args = [sandboxName, "rebuild", "--yes"]; + if (options.verbose) args.push("--verbose"); + const result = await this.host.nemoclaw(args, { + artifactName: options.artifactName ?? `lifecycle-rebuild-${sandboxName}`, + env: { + ...buildAvailabilityProbeEnv(), + ...(options.env ?? {}), + }, + redactionValues: options.redactionValues, + timeoutMs: options.timeoutMs ?? REBUILD_TIMEOUT_MS, + }); + assertExitZero(result, `nemoclaw ${sandboxName} rebuild --yes`); + return result; + } + + async assertSandboxReadyAfterRebuild( + instance: NemoClawInstance | string, + options: SandboxReadyAfterRebuildOptions = {}, + ): Promise { + const sandboxName = instanceName(instance); + const attempts = options.attempts ?? SANDBOX_READY_ATTEMPTS; + const delayMs = options.delayMs ?? SANDBOX_READY_DELAY_MS; + const env = { ...buildAvailabilityProbeEnv(), ...(options.env ?? {}) }; + let last: ShellProbeResult | undefined; + for (let attempt = 1; attempt <= attempts; attempt += 1) { + const artifactPrefix = options.artifactNamePrefix ?? `lifecycle-rebuild-ready-${sandboxName}`; + last = await this.sandbox.list({ + artifactName: `${artifactPrefix}-${attempt}`, + env, + timeoutMs: options.timeoutMs ?? 30_000, + }); + if (last.exitCode === 0 && outputContainsReadySandbox(last, sandboxName)) { + return last; + } + if (attempt < attempts) await sleep(delayMs); + } + const detail = last ? `${last.stdout}\n${last.stderr}`.trim() : "no probe result"; + throw new Error( + `sandbox ${sandboxName} did not become Ready after rebuild within ${attempts} attempts: ${detail}`, + ); + } + async simulate( profile: LifecycleProfile, instance: NemoClawInstance, diff --git a/test/e2e-scenario/fixtures/phases/onboarding.ts b/test/e2e-scenario/fixtures/phases/onboarding.ts index 817ff311f2e..00cbd0f545d 100644 --- a/test/e2e-scenario/fixtures/phases/onboarding.ts +++ b/test/e2e-scenario/fixtures/phases/onboarding.ts @@ -247,17 +247,23 @@ export class OnboardingPhaseFixture { } } + async destroySandbox(sandboxName: string, artifactName?: string): Promise { + validateSandboxName(sandboxName); + const result = await this.host.nemoclaw([sandboxName, "destroy", "--yes"], { + artifactName: artifactName ?? `cleanup-destroy-${artifactLabel(sandboxName)}`, + env: buildAvailabilityProbeEnv(), + timeoutMs: DEFAULT_TIMEOUT_MS, + }); + if (result.exitCode !== 0 && !hasMissingSandboxDeleteSignature(result)) { + assertExitZero(result, `cleanup destroy sandbox ${sandboxName}`); + } + return result; + } + private registerSandboxCleanup(sandboxName: string): void { if (!this.cleanup) return; this.cleanup.add(`destroy NemoClaw sandbox ${sandboxName}`, async () => { - const result = await this.host.nemoclaw([sandboxName, "destroy", "--yes"], { - artifactName: `cleanup-destroy-${artifactLabel(sandboxName)}`, - env: buildAvailabilityProbeEnv(), - timeoutMs: DEFAULT_TIMEOUT_MS, - }); - if (result.exitCode !== 0 && !hasMissingSandboxDeleteSignature(result)) { - assertExitZero(result, `cleanup destroy sandbox ${sandboxName}`); - } + await this.destroySandbox(sandboxName); }); } diff --git a/test/e2e-scenario/fixtures/phases/state-validation.ts b/test/e2e-scenario/fixtures/phases/state-validation.ts index 47651635f27..ac15064b135 100644 --- a/test/e2e-scenario/fixtures/phases/state-validation.ts +++ b/test/e2e-scenario/fixtures/phases/state-validation.ts @@ -23,6 +23,8 @@ import type { NemoClawInstance } from "./onboarding.ts"; // `src/lib/**` (CLI source) — that boundary keeps the live runner // honest about probing only host-observable state. const NEMOCLAW_REGISTRY_RELPATH = [".nemoclaw", "sandboxes.json"] as const; +const NEMOCLAW_ONBOARD_SESSION_RELPATH = [".nemoclaw", "onboard-session.json"] as const; +const REBUILD_BACKUPS_RELPATH = [".nemoclaw", "rebuild-backups"] as const; const OPENSHELL_SANDBOX_NAME_LABEL = "openshell.ai/sandbox-name"; export interface ProbeIO { @@ -34,6 +36,16 @@ function defaultRegistryPath(): string { return path.join(home, ...NEMOCLAW_REGISTRY_RELPATH); } +function defaultOnboardSessionPath(): string { + const home = process.env.HOME ?? os.homedir(); + return path.join(home, ...NEMOCLAW_ONBOARD_SESSION_RELPATH); +} + +function defaultRebuildBackupsRoot(): string { + const home = process.env.HOME ?? os.homedir(); + return path.join(home, ...REBUILD_BACKUPS_RELPATH); +} + function defaultReadRegistry(): { entries: Record } | null { const file = defaultRegistryPath(); if (!fs.existsSync(file)) return null; @@ -90,6 +102,10 @@ function gatewayBaseEndpoint(gatewayUrl: string): string { return trustedProviderEndpoint(gatewayUrl).url; } +function resultText(result: ShellProbeResult): string { + return [result.stdout, result.stderr].filter(Boolean).join("\n"); +} + function resultHttpCode(result: ShellProbeResult): string { return result.stdout.trim(); } @@ -108,6 +124,151 @@ function isMissingOpenShellError(error: unknown): boolean { return code === "ENOENT" || /\bENOENT\b/.test(errorMessage(error)); } +export interface FileSnapshot { + exists: boolean; + content?: string; +} + +export interface RegistrySnapshot { + registry: FileSnapshot; + session: FileSnapshot; +} + +export interface RegistryEntryPatchOptions { + registryPath?: string; +} + +export interface MarkerFileOptions { + artifactName?: string; + env?: NodeJS.ProcessEnv; + timeoutMs?: number; +} + +export interface RebuildBackupOptions { + backupRoot?: string; +} + +export interface CredentialLeakScanOptions extends RebuildBackupOptions { + extraSecrets?: string[]; +} + +export function snapshotFile(file: string): FileSnapshot { + return fs.existsSync(file) + ? { exists: true, content: fs.readFileSync(file, "utf8") } + : { exists: false }; +} + +export function restoreFile(file: string, snapshot: FileSnapshot): void { + if (!snapshot.exists) { + fs.rmSync(file, { force: true }); + return; + } + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, snapshot.content ?? "", "utf8"); +} + +export function snapshotRegistryAndSession(): RegistrySnapshot { + return { + registry: snapshotFile(defaultRegistryPath()), + session: snapshotFile(defaultOnboardSessionPath()), + }; +} + +export function restoreRegistryAndSession(snapshot: RegistrySnapshot): void { + restoreFile(defaultRegistryPath(), snapshot.registry); + restoreFile(defaultOnboardSessionPath(), snapshot.session); +} + +export function readRegistrySandboxEntry( + sandboxName: string, + options: RegistryEntryPatchOptions = {}, +): Record { + const registryPath = options.registryPath ?? defaultRegistryPath(); + const data = JSON.parse(fs.readFileSync(registryPath, "utf8")) as { + sandboxes?: Record>; + }; + const entry = data.sandboxes?.[sandboxName]; + if (!entry) throw new Error(`registry entry missing for ${sandboxName}`); + return entry; +} + +export function patchRegistrySandboxEntry( + sandboxName: string, + patch: Record, + options: RegistryEntryPatchOptions = {}, +): Record { + const registryPath = options.registryPath ?? defaultRegistryPath(); + const data = JSON.parse(fs.readFileSync(registryPath, "utf8")) as { + sandboxes?: Record>; + }; + data.sandboxes = data.sandboxes ?? {}; + const entry = data.sandboxes[sandboxName]; + if (!entry) throw new Error(`registry entry missing for ${sandboxName}`); + Object.assign(entry, patch); + fs.writeFileSync(registryPath, `${JSON.stringify(data, null, 2)}\n`, "utf8"); + return entry; +} + +export function latestRebuildBackupDir( + sandboxName: string, + options: RebuildBackupOptions = {}, +): string | undefined { + const sandboxRoot = path.join(options.backupRoot ?? defaultRebuildBackupsRoot(), sandboxName); + if (!fs.existsSync(sandboxRoot)) return undefined; + const latest = fs + .readdirSync(sandboxRoot, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort() + .at(-1); + return latest ? path.join(sandboxRoot, latest) : undefined; +} + +export function readRebuildBackupManifest(backupDir: string): Record { + const manifestPath = path.join(backupDir, "rebuild-manifest.json"); + if (!fs.existsSync(manifestPath)) throw new Error(`backup manifest missing: ${manifestPath}`); + return JSON.parse(fs.readFileSync(manifestPath, "utf8")) as Record; +} + +export function listCredentialLeakPaths( + backupDir: string | undefined, + options: CredentialLeakScanOptions = {}, +): string[] { + if (!backupDir || !fs.existsSync(backupDir)) return []; + const leaks: string[] = []; + const skippedLockfiles = new Set([ + "package-lock.json", + "npm-shrinkwrap.json", + "yarn.lock", + "pnpm-lock.yaml", + "pnpm-lock.yml", + ]); + const candidatePattern = /(?:nvapi-|sk-|Bearer )/; + const extraSecrets = options.extraSecrets?.filter(Boolean) ?? []; + + function scan(dir: string): void { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const fullPath = path.join(dir, entry.name); + if (entry.isDirectory()) { + scan(fullPath); + continue; + } + if (!entry.isFile()) continue; + const text = fs.readFileSync(fullPath, "utf8"); + if (extraSecrets.some((secret) => text.includes(secret))) { + leaks.push(fullPath); + continue; + } + if (skippedLockfiles.has(entry.name)) continue; + const isJsonOrEnv = /\.json$|\.env$|^\.env$/i.test(entry.name); + if (isJsonOrEnv && candidatePattern.test(text)) leaks.push(fullPath); + } + } + + scan(backupDir); + return leaks.sort(); +} + export class StateValidationPhaseFixture { private readonly io: ProbeIO; @@ -121,6 +282,84 @@ export class StateValidationPhaseFixture { this.io = io; } + async writeMarkerFile( + instance: NemoClawInstance | string, + markerPath: string, + content: string, + options: MarkerFileOptions = {}, + ): Promise { + const sandboxName = typeof instance === "string" ? instance : instance.sandboxName; + const result = await this.sandbox.exec( + sandboxName, + [ + "sh", + "-c", + 'mkdir -p "$(dirname "$1")" && printf \'%s\' "$2" > "$1"', + "sh", + markerPath, + content, + ], + { + artifactName: options.artifactName ?? `state-write-marker-${sandboxName}`, + env: { ...buildAvailabilityProbeEnv(), ...(options.env ?? {}) }, + redactionValues: [content], + timeoutMs: options.timeoutMs ?? 30_000, + }, + ); + if (result.exitCode !== 0) { + throw new Error( + `failed to write marker ${markerPath} in ${sandboxName}: ${resultText(result)}`, + ); + } + return result; + } + + async readMarkerFile( + instance: NemoClawInstance | string, + markerPath: string, + options: MarkerFileOptions = {}, + ): Promise { + const sandboxName = typeof instance === "string" ? instance : instance.sandboxName; + const result = await this.sandbox.exec(sandboxName, ["cat", markerPath], { + artifactName: options.artifactName ?? `state-read-marker-${sandboxName}`, + env: { ...buildAvailabilityProbeEnv(), ...(options.env ?? {}) }, + timeoutMs: options.timeoutMs ?? 30_000, + }); + if (result.exitCode !== 0) { + throw new Error( + `failed to read marker ${markerPath} in ${sandboxName}: ${resultText(result)}`, + ); + } + return result.stdout; + } + + async expectMarkerFileContent( + instance: NemoClawInstance | string, + markerPath: string, + expected: string, + options: MarkerFileOptions = {}, + ): Promise { + const actual = await this.readMarkerFile(instance, markerPath, options); + if (actual !== expected && actual.trim() !== expected) { + const sandboxName = typeof instance === "string" ? instance : instance.sandboxName; + throw new Error( + `marker ${markerPath} in ${sandboxName} did not match expected content: got ${JSON.stringify( + actual, + )}`, + ); + } + } + + expectRegistryAgentVersionUpdated(sandboxName: string, staleVersion: string): string { + const version = readRegistrySandboxEntry(sandboxName).agentVersion; + if (typeof version !== "string" || version.length === 0 || version === staleVersion) { + throw new Error( + `registry agentVersion for ${sandboxName} was not refreshed from ${staleVersion}: ${String(version)}`, + ); + } + return version; + } + async from( expectedState: string | ExpectedState, instance?: NemoClawInstance, diff --git a/test/e2e-scenario/live/sandbox-rebuild.test.ts b/test/e2e-scenario/live/sandbox-rebuild.test.ts new file mode 100644 index 00000000000..5dc15a1069a --- /dev/null +++ b/test/e2e-scenario/live/sandbox-rebuild.test.ts @@ -0,0 +1,258 @@ +// 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 { expect, test } from "../fixtures/e2e-test.ts"; +import { shouldRunLiveE2EScenarios } from "../fixtures/live-project-gate.ts"; +import { + latestRebuildBackupDir, + listCredentialLeakPaths, + patchRegistrySandboxEntry, + readRegistrySandboxEntry, + restoreRegistryAndSession, + snapshotRegistryAndSession, +} from "../fixtures/phases/state-validation.ts"; +import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; + +// Direct Vitest replacement coverage for test/e2e/test-sandbox-rebuild.sh. +// This dependent migration reuses the rebuild/state helper shape seeded by the +// OpenClaw rebuild anchor while keeping the contract focused: onboard a real +// sandbox, mark workspace state, force stale registry metadata, run the real +// `nemoclaw rebuild --yes`, then verify state preservation, registry +// refresh, and backup credential hygiene. + +const MARKER_FILE = "/sandbox/.openclaw/workspace/rebuild-marker.txt"; +const STALE_AGENT_VERSION = "0.0.1"; +const TEST_SANDBOX_PREFIX = "e2e-sandbox-rebuild"; +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("-"); +const TEST_TIMEOUT_MS = Number(process.env.NEMOCLAW_E2E_TIMEOUT_SECONDS ?? 1_200) * 1_000; +const CONNECT_PROBE_TIMEOUT_MS = 30_000; +const STATUS_TIMEOUT_MS = 60_000; +const ONBOARD_TIMEOUT_MS = TEST_TIMEOUT_MS; +const REBUILD_TIMEOUT_MS = TEST_TIMEOUT_MS; +const MARKER_CONTENT = `REBUILD_E2E_${Date.now()}`; + +function resultText(result: ShellProbeResult): string { + return [result.stdout, result.stderr].filter(Boolean).join("\n"); +} + +function sandboxRebuildEnv(apiKey: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { + return { + ...buildAvailabilityProbeEnv(), + ...extra, + NVIDIA_API_KEY: apiKey, + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1", + NEMOCLAW_NON_INTERACTIVE: "1", + NEMOCLAW_SANDBOX_NAME: SANDBOX_NAME, + }; +} + +function assertTestOwnedSandboxName(): void { + if (!SANDBOX_NAME.startsWith(TEST_SANDBOX_PREFIX)) { + throw new Error( + `sandbox-rebuild live test is destructive and only accepts sandbox names with prefix ${TEST_SANDBOX_PREFIX}; got ${SANDBOX_NAME}`, + ); + } +} + +async function bestEffort(run: () => Promise): Promise { + try { + await run(); + } catch { + // Cleanup remains best-effort so earlier lifecycle failures stay visible. + } +} + +test.skipIf(!shouldRunLiveE2EScenarios())( + "sandbox-rebuild: rebuild preserves marker state and refreshes registry metadata", + async ({ + artifacts, + cleanup, + environment, + host, + lifecycle, + onboard, + sandbox, + secrets, + skip, + stateValidation, + }) => { + assertTestOwnedSandboxName(); + const apiKey = secrets.required("NVIDIA_API_KEY"); + expect(apiKey.startsWith("nvapi-"), "NVIDIA_API_KEY must start with nvapi-").toBe(true); + + const dockerInfo = await host.command("docker", ["info"], { + artifactName: "prereq-docker-info", + env: buildAvailabilityProbeEnv(), + timeoutMs: 30_000, + }); + if (dockerInfo.exitCode !== 0) { + if (process.env.GITHUB_ACTIONS === "true") { + throw new Error( + `Docker is required for sandbox-rebuild live coverage: ${resultText(dockerInfo)}`, + ); + } + skip("Docker is required for sandbox-rebuild live coverage"); + } + + const ready = await environment.assertReady({ + platform: "ubuntu-local", + install: "repo-current", + runtime: "docker-running", + onboarding: "cloud-openclaw", + }); + + await artifacts.writeJson("contract.json", { + legacySource: "test/e2e/test-sandbox-rebuild.sh", + sandboxName: SANDBOX_NAME, + markerFile: MARKER_FILE, + staleAgentVersion: STALE_AGENT_VERSION, + preservedBoundaries: [ + "real nemoclaw onboard with Docker/OpenShell", + "openshell sandbox exec marker write/read", + "local registry stale agentVersion mutation", + "real nemoclaw rebuild --yes", + "backup credential leak scan under ~/.nemoclaw/rebuild-backups", + ], + }); + + const stateSnapshot = snapshotRegistryAndSession(); + const backupRoot = path.join(os.homedir(), ".nemoclaw", "rebuild-backups", SANDBOX_NAME); + cleanup.add(`restore NemoClaw state files for ${SANDBOX_NAME}`, () => { + restoreRegistryAndSession(stateSnapshot); + fs.rmSync(backupRoot, { recursive: true, force: true }); + }); + cleanup.add(`destroy sandbox ${SANDBOX_NAME}`, async () => { + if (process.env.NEMOCLAW_E2E_KEEP_SANDBOX === "1") return; + await bestEffort(() => onboard.destroySandbox(SANDBOX_NAME, "cleanup-nemoclaw-destroy")); + await bestEffort(() => + sandbox.openshell(["sandbox", "delete", SANDBOX_NAME], { + artifactName: "cleanup-openshell-sandbox-delete", + env: buildAvailabilityProbeEnv(), + timeoutMs: 60_000, + }), + ); + }); + + await bestEffort(() => onboard.destroySandbox(SANDBOX_NAME, "pre-cleanup-nemoclaw-destroy")); + await bestEffort(() => + sandbox.openshell(["sandbox", "delete", SANDBOX_NAME], { + artifactName: "pre-cleanup-openshell-sandbox-delete", + env: buildAvailabilityProbeEnv(), + timeoutMs: 60_000, + }), + ); + + const instance = await onboard.from(ready, { + sandboxName: SANDBOX_NAME, + timeoutMs: ONBOARD_TIMEOUT_MS, + }); + + const status = await host.nemoclaw([SANDBOX_NAME, "status"], { + artifactName: "phase-2-status-version-detection", + env: sandboxRebuildEnv(apiKey), + redactionValues: [apiKey], + timeoutMs: STATUS_TIMEOUT_MS, + }); + await artifacts.writeText("phase-2-status-output.txt", resultText(status)); + if (/Agent:.*v?\d+\.\d+/i.test(resultText(status))) { + await artifacts.writeJson("phase-2-status-version-summary.json", { versionVisible: true }); + } else { + await artifacts.writeJson("phase-2-status-version-summary.json", { + versionVisible: false, + note: "Legacy shell accepted first-run status output without cached version.", + }); + } + + await stateValidationWriteMarker(); + + patchRegistrySandboxEntry(SANDBOX_NAME, { agentVersion: STALE_AGENT_VERSION }); + await artifacts.writeJson("phase-4-stale-registry-summary.json", { + sandboxName: SANDBOX_NAME, + agentVersion: readRegistrySandboxEntry(SANDBOX_NAME).agentVersion, + }); + + const connect = await host.command( + "bash", + [ + "-lc", + 'timeout 10 "$1" "$2" connect <<<"exit"', + "connect-stale", + host.commandPath, + SANDBOX_NAME, + ], + { + artifactName: "phase-4-connect-stale-warning", + env: sandboxRebuildEnv(apiKey), + redactionValues: [apiKey], + timeoutMs: CONNECT_PROBE_TIMEOUT_MS, + }, + ); + if (!/rebuild/i.test(resultText(connect))) { + await artifacts.writeText( + "phase-4-connect-stale-warning-note.txt", + "No rebuild warning was observed; legacy bash treated this as acceptable when the sandbox is not live.\n", + ); + } + + await lifecycle.rebuildSandbox(instance, { + artifactName: "phase-5-nemoclaw-rebuild", + env: sandboxRebuildEnv(apiKey), + redactionValues: [apiKey], + timeoutMs: REBUILD_TIMEOUT_MS, + }); + await lifecycle.assertSandboxReadyAfterRebuild(instance, { + artifactNamePrefix: "phase-5-sandbox-ready-after-rebuild", + env: buildAvailabilityProbeEnv(), + attempts: 12, + delayMs: 5_000, + }); + + await stateValidation.expectMarkerFileContent(instance, MARKER_FILE, MARKER_CONTENT, { + artifactName: "phase-6-read-marker-after-rebuild", + env: buildAvailabilityProbeEnv(), + timeoutMs: 60_000, + }); + + const updatedVersion = stateValidation.expectRegistryAgentVersionUpdated( + SANDBOX_NAME, + STALE_AGENT_VERSION, + ); + await artifacts.writeJson("phase-7-registry-version-summary.json", { + sandboxName: SANDBOX_NAME, + staleVersion: STALE_AGENT_VERSION, + updatedVersion, + }); + + const backupDir = latestRebuildBackupDir(SANDBOX_NAME); + const leaks = listCredentialLeakPaths(backupDir, { extraSecrets: [apiKey] }); + await artifacts.writeJson("phase-8-backup-credential-scan.json", { + backupDir: backupDir ?? null, + leaks, + note: backupDir ? undefined : "No backup directory found; legacy shell skipped this check.", + }); + expect(leaks, "backup files must not contain credential-shaped values").toEqual([]); + + async function stateValidationWriteMarker(): Promise { + await stateValidation.writeMarkerFile(instance, MARKER_FILE, MARKER_CONTENT, { + artifactName: "phase-3-write-marker", + env: buildAvailabilityProbeEnv(), + timeoutMs: 60_000, + }); + await stateValidation.expectMarkerFileContent(instance, MARKER_FILE, MARKER_CONTENT, { + artifactName: "phase-3-read-marker-before-rebuild", + env: buildAvailabilityProbeEnv(), + timeoutMs: 60_000, + }); + } + }, + TEST_TIMEOUT_MS * 3, +); diff --git a/test/e2e-scenario/support-tests/e2e-phase-state-validation.test.ts b/test/e2e-scenario/support-tests/e2e-phase-state-validation.test.ts index 6372ca48fb2..391f4ac8fec 100644 --- a/test/e2e-scenario/support-tests/e2e-phase-state-validation.test.ts +++ b/test/e2e-scenario/support-tests/e2e-phase-state-validation.test.ts @@ -16,6 +16,15 @@ import { } from "../fixtures/clients/index.ts"; import type { E2EScenarioFixtures } from "../fixtures/e2e-test.ts"; import { StateValidationPhaseFixture, type NemoClawInstance } from "../fixtures/phases/index.ts"; +import { + latestRebuildBackupDir, + listCredentialLeakPaths, + patchRegistrySandboxEntry, + readRebuildBackupManifest, + readRegistrySandboxEntry, + restoreRegistryAndSession, + snapshotRegistryAndSession, +} from "../fixtures/phases/state-validation.ts"; import type { ShellProbeResult, ShellProbeRunOptions, @@ -621,4 +630,109 @@ describe("state-validation host-side probes", () => { /could not query Docker for label.*exit 1/, ); }); + + it("writes, reads, and asserts sandbox marker files through OpenShell exec", async () => { + const runner = new FakeRunner(); + runner.enqueue(shellResult(0)); + runner.enqueue(shellResult(0, "marker-value")); + const fx = fixture(runner); + + await fx.writeMarkerFile( + "e2e-marker", + "/sandbox/.openclaw/workspace/rebuild-marker.txt", + "marker-value", + ); + await fx.expectMarkerFileContent( + "e2e-marker", + "/sandbox/.openclaw/workspace/rebuild-marker.txt", + "marker-value", + ); + + expect(runner.calls.map((call) => call.args)).toEqual([ + [ + "sandbox", + "exec", + "-n", + "e2e-marker", + "--", + "sh", + "-c", + 'mkdir -p "$(dirname "$1")" && printf \'%s\' "$2" > "$1"', + "sh", + "/sandbox/.openclaw/workspace/rebuild-marker.txt", + "marker-value", + ], + [ + "sandbox", + "exec", + "-n", + "e2e-marker", + "--", + "cat", + "/sandbox/.openclaw/workspace/rebuild-marker.txt", + ], + ]); + }); + + it("patches registry entries and validates refreshed agentVersion", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-registry-")); + const registryPath = path.join(tmp, "sandboxes.json"); + fs.writeFileSync( + registryPath, + JSON.stringify({ sandboxes: { "e2e-rebuild": { agentVersion: "0.0.1" } } }), + ); + try { + patchRegistrySandboxEntry("e2e-rebuild", { agentVersion: "1.2.3" }, { registryPath }); + expect(readRegistrySandboxEntry("e2e-rebuild", { registryPath }).agentVersion).toBe("1.2.3"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("snapshots and restores registry/session files", () => { + const oldHome = process.env.HOME; + const home = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-home-")); + process.env.HOME = home; + try { + const stateDir = path.join(home, ".nemoclaw"); + fs.mkdirSync(stateDir, { recursive: true }); + const registryPath = path.join(stateDir, "sandboxes.json"); + const sessionPath = path.join(stateDir, "onboard-session.json"); + fs.writeFileSync(registryPath, "registry-before"); + fs.writeFileSync(sessionPath, "session-before"); + + const snapshot = snapshotRegistryAndSession(); + fs.writeFileSync(registryPath, "registry-after"); + fs.rmSync(sessionPath); + restoreRegistryAndSession(snapshot); + + expect(fs.readFileSync(registryPath, "utf8")).toBe("registry-before"); + expect(fs.readFileSync(sessionPath, "utf8")).toBe("session-before"); + } finally { + if (oldHome === undefined) delete process.env.HOME; + else process.env.HOME = oldHome; + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("discovers backup manifests and reports credential leak paths", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-backups-")); + const backupRoot = path.join(home, "rebuild-backups"); + const backupDir = path.join(backupRoot, "e2e-rebuild", "2026-06-12T00-00-00Z"); + fs.mkdirSync(backupDir, { recursive: true }); + fs.writeFileSync( + path.join(backupDir, "rebuild-manifest.json"), + JSON.stringify({ stateDirs: [] }), + ); + fs.writeFileSync(path.join(backupDir, "safe.json"), JSON.stringify({ value: "ok" })); + fs.writeFileSync(path.join(backupDir, "leak.json"), JSON.stringify({ key: "nvapi-secret" })); + try { + const latest = latestRebuildBackupDir("e2e-rebuild", { backupRoot }); + expect(latest).toBe(backupDir); + expect(readRebuildBackupManifest(latest!)).toEqual({ stateDirs: [] }); + expect(listCredentialLeakPaths(latest)).toEqual([path.join(backupDir, "leak.json")]); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); }); 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 c4cfe853e5c..75ca272134c 100644 --- a/test/e2e-scenario/support-tests/e2e-scenarios-workflow.test.ts +++ b/test/e2e-scenario/support-tests/e2e-scenarios-workflow.test.ts @@ -184,6 +184,22 @@ describe("e2e-vitest-scenarios workflow boundary", () => { selectedFreeStandingJobs: ["rebuild-openclaw-vitest"], registryScenarios: [], }); + expect( + evaluateE2eVitestWorkflowDispatchSelectors({ scenarios: "sandbox-rebuild" }), + ).toMatchObject({ + valid: true, + liveScenariosRuns: false, + selectedFreeStandingJobs: ["sandbox-rebuild-vitest"], + registryScenarios: [], + }); + expect( + evaluateE2eVitestWorkflowDispatchSelectors({ jobs: "sandbox-rebuild-vitest" }), + ).toMatchObject({ + valid: true, + liveScenariosRuns: false, + selectedFreeStandingJobs: ["sandbox-rebuild-vitest"], + registryScenarios: [], + }); expect( evaluateE2eVitestWorkflowDispatchSelectors({ scenarios: "model-router-provider-routed-inference", @@ -253,6 +269,16 @@ describe("e2e-vitest-scenarios workflow boundary", () => { hermes_selected: "false", matrix: "[]", }); + expect( + generateMatrixForDispatch({ JOBS: "sandbox-rebuild-vitest", SCENARIOS: "" }), + ).toMatchObject({ + hermes_selected: "false", + matrix: "[]", + }); + expect(generateMatrixForDispatch({ JOBS: "", SCENARIOS: "sandbox-rebuild" })).toMatchObject({ + hermes_selected: "false", + matrix: "[]", + }); expect(generateMatrixForDispatch({ JOBS: "", SCENARIOS: "hermes-e2e" })).toMatchObject({ hermes_selected: "true", matrix: "[]", @@ -504,6 +530,7 @@ jobs: "step 'Validate free-standing job selector' run script must include Invalid scenario input; use comma-separated scenario ids", "step 'Validate free-standing job selector' run script must include allowed_jobs=", "step 'Validate free-standing job selector' run script must include runtime-overrides-vitest", + "step 'Validate free-standing job selector' run script must include sandbox-rebuild-vitest", "step 'Validate free-standing job selector' run script must include double-onboard-vitest", "step 'Validate free-standing job selector' run script must include hermes-e2e-vitest", "step 'Validate free-standing job selector' run script must include Invalid jobs input; use comma-separated job ids", @@ -620,6 +647,8 @@ jobs: "report-to-pr job must wait for credential-migration-vitest", "report-to-pr job must wait for runtime-overrides-vitest", "report-to-pr job must wait for network-policy-vitest", + "workflow missing sandbox-rebuild-vitest job", + "report-to-pr job must wait for sandbox-rebuild-vitest", "double-onboard-vitest job must depend on validate-jobs", "double-onboard-vitest job must use the shared jobs selector condition", "double-onboard-vitest job must set NEMOCLAW_RUN_E2E_SCENARIOS=1", diff --git a/tools/e2e-scenarios/workflow-boundary.mts b/tools/e2e-scenarios/workflow-boundary.mts index 0f259f6d11b..f81e7e47842 100644 --- a/tools/e2e-scenarios/workflow-boundary.mts +++ b/tools/e2e-scenarios/workflow-boundary.mts @@ -27,6 +27,7 @@ const FREE_STANDING_SCENARIO_JOBS = new Map([ ["hermes-root-entrypoint-smoke", "hermes-root-entrypoint-smoke-vitest"], ["network-policy", "network-policy-vitest"], ["rebuild-openclaw", "rebuild-openclaw-vitest"], + ["sandbox-rebuild", "sandbox-rebuild-vitest"], ["token-rotation", "token-rotation-vitest"], ["openclaw-tui-chat-correlation", "openclaw-tui-chat-correlation-vitest"], ["issue-4434-tui-unreachable-inference", "issue-4434-tui-unreachable-inference-vitest"], @@ -290,6 +291,7 @@ function validateJobsSelector(errors: string[], jobs: WorkflowRecord): void { requireRunContains(errors, validate, "hermes-root-entrypoint-smoke-vitest"); requireRunContains(errors, validate, "network-policy-vitest"); requireRunContains(errors, validate, "rebuild-openclaw-vitest"); + requireRunContains(errors, validate, "sandbox-rebuild-vitest"); requireRunContains(errors, validate, "token-rotation-vitest"); requireRunContains(errors, validate, "openclaw-tui-chat-correlation-vitest"); requireRunContains(errors, validate, "gateway-guard-recovery"); @@ -619,6 +621,117 @@ function validateRebuildOpenClawVitestJob(errors: string[], jobs: WorkflowRecord } } +function validateSandboxRebuildVitestJob(errors: string[], jobs: WorkflowRecord): void { + const jobName = "sandbox-rebuild-vitest"; + const scenarioName = "sandbox-rebuild"; + const job = asRecord(jobs[jobName]); + if (Object.keys(job).length === 0) { + errors.push("workflow missing sandbox-rebuild-vitest job"); + return; + } + + if (job["runs-on"] !== "ubuntu-latest") { + errors.push("sandbox-rebuild-vitest job must run on ubuntu-latest"); + } + validateFreeStandingJobSelector(errors, jobs, jobName, scenarioName); + if (job["timeout-minutes"] !== 90) { + errors.push("sandbox-rebuild-vitest job must keep the legacy 90 minute timeout"); + } + const jobEnv = asRecord(job.env); + if (jobEnv.NEMOCLAW_RUN_E2E_SCENARIOS !== "1") { + errors.push("sandbox-rebuild-vitest job must set NEMOCLAW_RUN_E2E_SCENARIOS=1"); + } + if (jobEnv.E2E_ARTIFACT_DIR !== "${{ github.workspace }}/e2e-artifacts/vitest/sandbox-rebuild") { + errors.push("sandbox-rebuild-vitest job must write artifacts under e2e-artifacts/vitest/sandbox-rebuild"); + } + if (jobEnv.NEMOCLAW_CLI_BIN !== "${{ github.workspace }}/bin/nemoclaw.js") { + errors.push("sandbox-rebuild-vitest job must point NEMOCLAW_CLI_BIN at the repo CLI"); + } + if (jobEnv.OPENSHELL_GATEWAY !== "nemoclaw") { + errors.push("sandbox-rebuild-vitest job must force OPENSHELL_GATEWAY=nemoclaw"); + } + for (const secret of ["NVIDIA_API_KEY", "DOCKERHUB_USERNAME", "DOCKERHUB_TOKEN", "GITHUB_TOKEN"]) { + requireEnvDoesNotExposeSecret(errors, "sandbox-rebuild-vitest job", jobEnv, secret); + } + + const steps = asSteps(job.steps); + requireNoDispatchInputInterpolation(errors, steps); + for (const step of steps) { + const stepName = `sandbox-rebuild-vitest step '${step.name ?? step.uses ?? ""}'`; + const stepEnv = asRecord(step.env); + if (step.name !== "Run sandbox rebuild live test") { + 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("sandbox-rebuild-vitest job missing checkout step"); + requireFullShaAction(errors, checkout, "sandbox-rebuild-vitest checkout"); + if (asRecord(checkout?.with)["persist-credentials"] !== false) { + errors.push("sandbox-rebuild-vitest checkout step must set persist-credentials=false"); + } + + const dockerHubAuth = requireJobStep(errors, jobName, steps, "Authenticate to Docker Hub"); + const dockerHubEnv = asRecord(dockerHubAuth?.env); + if (dockerHubEnv.DOCKERHUB_USERNAME !== "${{ secrets.DOCKERHUB_USERNAME }}") { + errors.push("sandbox-rebuild-vitest Docker Hub auth must receive DOCKERHUB_USERNAME from secrets"); + } + if (dockerHubEnv.DOCKERHUB_TOKEN !== "${{ secrets.DOCKERHUB_TOKEN }}") { + errors.push("sandbox-rebuild-vitest Docker Hub auth must receive DOCKERHUB_TOKEN from secrets"); + } + 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("sandbox-rebuild-vitest job missing step: Set up Node"); + requireFullShaAction(errors, setupNode, "sandbox-rebuild-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"); + requireRunContains(errors, installOpenShell, "bash scripts/install-openshell.sh"); + requireRunContains(errors, installOpenShell, "env -u DOCKER_CONFIG"); + requireRunContains(errors, installOpenShell, "-u NVIDIA_API_KEY"); + requireRunContains(errors, installOpenShell, "-u GITHUB_TOKEN"); + + const runVitest = requireJobStep(errors, jobName, steps, "Run sandbox rebuild live test"); + const runVitestEnv = asRecord(runVitest?.env); + if (runVitestEnv.NVIDIA_API_KEY !== "${{ secrets.NVIDIA_API_KEY }}") { + errors.push("sandbox-rebuild-vitest step must receive NVIDIA_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/sandbox-rebuild.test.ts"); + + const upload = requireJobStep(errors, jobName, steps, "Upload sandbox rebuild artifacts"); + requireFullShaAction(errors, upload, "sandbox-rebuild-vitest upload-artifact"); + const uploadWith = asRecord(upload?.with); + if (uploadWith.name !== "e2e-vitest-scenarios-sandbox-rebuild") { + errors.push("sandbox-rebuild-vitest artifact upload name must be stable"); + } + const uploadPath = stringValue(uploadWith.path); + requireUploadPathContains(errors, uploadPath, "e2e-artifacts/vitest/sandbox-rebuild/"); + if (uploadWith["include-hidden-files"] !== false) { + errors.push("sandbox-rebuild-vitest artifact upload must set include-hidden-files: false"); + } + if (uploadWith["if-no-files-found"] !== "ignore") { + errors.push("sandbox-rebuild-vitest artifact upload must ignore missing fixture artifacts"); + } + if (uploadWith["retention-days"] !== 14) { + errors.push("sandbox-rebuild-vitest artifact upload retention-days must be 14"); + } +} + function validateTokenRotationVitestJob(errors: string[], jobs: WorkflowRecord): void { const jobName = "token-rotation-vitest"; const job = asRecord(jobs[jobName]); @@ -1528,6 +1641,8 @@ export function validateE2eVitestScenariosWorkflowBoundary( requireRunContains(errors, generate, "hermes-root-entrypoint-smoke"); requireRunContains(errors, generate, "network-policy-vitest"); requireRunContains(errors, generate, "rebuild-openclaw-vitest"); + requireRunContains(errors, generate, "sandbox-rebuild-vitest"); + requireRunContains(errors, generate, "sandbox-rebuild"); requireRunContains(errors, generate, "token-rotation-vitest"); requireRunContains(errors, generate, "model-router-provider-routed-inference-vitest"); requireRunContains(errors, generate, "model-router-provider-routed-inference"); @@ -1691,6 +1806,7 @@ export function validateE2eVitestScenariosWorkflowBoundary( validateHermesRootEntrypointSmokeVitestJob(errors, jobs); validateNetworkPolicyVitestJob(errors, jobs); validateRebuildOpenClawVitestJob(errors, jobs); + validateSandboxRebuildVitestJob(errors, jobs); validateTokenRotationVitestJob(errors, jobs); validateFreeStandingJobSelector( errors, @@ -1725,6 +1841,7 @@ export function validateE2eVitestScenariosWorkflowBoundary( "hermes-root-entrypoint-smoke-vitest", "network-policy-vitest", "rebuild-openclaw-vitest", + "sandbox-rebuild-vitest", "token-rotation-vitest", "double-onboard-vitest", "openclaw-tui-chat-correlation-vitest", From d706c57c4f2877317681a569b8b116aab1445d56 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Fri, 12 Jun 2026 10:02:34 -0400 Subject: [PATCH 2/3] ci(e2e): fix vitest dispatch workflow parse --- .github/workflows/e2e-vitest-scenarios.yaml | 2 +- tools/e2e-scenarios/workflow-boundary.mts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/e2e-vitest-scenarios.yaml b/.github/workflows/e2e-vitest-scenarios.yaml index 485487d60ec..5376c2b86c4 100644 --- a/.github/workflows/e2e-vitest-scenarios.yaml +++ b/.github/workflows/e2e-vitest-scenarios.yaml @@ -1219,7 +1219,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 45 env: - DOCKER_CONFIG: ${{ runner.temp }}/docker-config-model-router-provider-routed-inference + DOCKER_CONFIG: ${{ github.workspace }}/.docker-config-model-router-provider-routed-inference E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/vitest/model-router-provider-routed-inference NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js NEMOCLAW_RUN_E2E_SCENARIOS: "1" diff --git a/tools/e2e-scenarios/workflow-boundary.mts b/tools/e2e-scenarios/workflow-boundary.mts index f81e7e47842..8dac9e1b2e0 100644 --- a/tools/e2e-scenarios/workflow-boundary.mts +++ b/tools/e2e-scenarios/workflow-boundary.mts @@ -1412,10 +1412,10 @@ function validateModelRouterProviderRoutedInferenceVitestJob( const jobEnv = asRecord(job.env); if ( jobEnv.DOCKER_CONFIG !== - "${{ runner.temp }}/docker-config-model-router-provider-routed-inference" + "${{ github.workspace }}/.docker-config-model-router-provider-routed-inference" ) { errors.push( - "model-router-provider-routed-inference-vitest job must isolate Docker auth with DOCKER_CONFIG under runner.temp", + "model-router-provider-routed-inference-vitest job must isolate Docker auth under the workflow workspace", ); } if ( From dc38e5d131130cf735a901cf180f40ed54dca632 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Fri, 12 Jun 2026 10:23:18 -0400 Subject: [PATCH 3/3] test(e2e): tolerate colored rebuild readiness output --- .../e2e-scenario/fixtures/phases/lifecycle.ts | 8 +++++++- .../support-tests/e2e-phase-lifecycle.test.ts | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/test/e2e-scenario/fixtures/phases/lifecycle.ts b/test/e2e-scenario/fixtures/phases/lifecycle.ts index c457898e4e4..42c2eb5e1e4 100644 --- a/test/e2e-scenario/fixtures/phases/lifecycle.ts +++ b/test/e2e-scenario/fixtures/phases/lifecycle.ts @@ -84,9 +84,15 @@ function instanceName(instance: NemoClawInstance | string): string { return name; } +function stripAnsi(text: string): string { + return text.replace(/\u001b\[[0-9;]*m/g, ""); +} + function outputContainsReadySandbox(result: ShellProbeResult, sandboxName: string): boolean { const escaped = sandboxName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`${escaped}.*\\bReady\\b`, "i").test(`${result.stdout}\n${result.stderr}`); + return new RegExp(`${escaped}.*\\bReady\\b`, "i").test( + stripAnsi(`${result.stdout}\n${result.stderr}`), + ); } export class LifecyclePhaseFixture { diff --git a/test/e2e-scenario/support-tests/e2e-phase-lifecycle.test.ts b/test/e2e-scenario/support-tests/e2e-phase-lifecycle.test.ts index a960495412d..218a34fd472 100644 --- a/test/e2e-scenario/support-tests/e2e-phase-lifecycle.test.ts +++ b/test/e2e-scenario/support-tests/e2e-phase-lifecycle.test.ts @@ -197,6 +197,25 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (rename-to-gpu-bac }); }); +describe("LifecyclePhaseFixture rebuild helpers", () => { + it("accepts ANSI-colored Ready output when waiting after rebuild", async () => { + const runner = new FakeRunner(); + runner.enqueue(shellResult(0, "NAME PHASE\ne2e-x \u001b[32mReady\u001b[39m\n")); + const cleanup = new FakeCleanup(); + + const result = await fixture(runner, cleanup).assertSandboxReadyAfterRebuild("e2e-x", { + attempts: 1, + delayMs: 0, + }); + + expect(result.stdout).toContain("Ready"); + expect(runner.calls[0]).toMatchObject({ + command: "openshell", + args: ["sandbox", "list"], + }); + }); +}); + describe("LifecyclePhaseFixture profile dispatch", () => { it("rejects unknown lifecycle profiles", async () => { const runner = new FakeRunner();