import assert from 'node:assert/strict'
import { readFile, stat } from 'node:fs/promises'
import path from 'node:path'
const root = process.cwd()
const createRoutePath = path.join(root, 'app/api/sandbox/create/route.ts')
const deleteRoutePath = path.join(root, 'app/api/sandbox/delete/route.ts')
const hostCommandsPath = path.join(root, 'app/lib/hostCommands.ts')
const telemetryRoutePath = path.join(root, 'app/api/telemetry/real/route.ts')
const inferenceRoutePath = path.join(root, 'app/api/inference/route.ts')
const vllmApplyRoutePath = path.join(root, 'app/api/inference/vllm/apply/route.ts')
const vllmRestartRoutePath = path.join(root, 'app/api/inference/vllm/restart/route.ts')
const inferenceEndpointUrlPath = path.join(root, 'app/lib/inferenceEndpointUrl.ts')
const inferenceRouteStorePath = path.join(root, 'app/lib/inferenceRouteStore.ts')
const ollamaModelsRoutePath = path.join(root, 'app/api/ollama/models/route.ts')
const sandboxInferenceRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/inference/route.ts')
const sandboxInferenceApplyRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/inference/apply/route.ts')
const sandboxInferenceApplyLibPath = path.join(root, 'app/lib/sandboxInferenceApply.ts')
const sandboxInferenceStorePath = path.join(root, 'app/lib/sandboxInferenceStore.ts')
const sandboxRestartRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/restart/route.ts')
const gatewayRepairRoutePath = path.join(root, 'app/api/openshell/gateway/repair/route.ts')
const sandboxPrivilegedFilesPath = path.join(root, 'app/lib/sandboxPrivilegedFiles.ts')
const versionedInstallerPath = path.join(root, 'install_versioned_nemoclaw_openshell.sh')
const hookPath = path.join(root, 'app/hooks/useSandboxInventory.ts')
const pagePath = path.join(root, 'app/page.tsx')
const configPanelPath = path.join(root, 'app/components/ConfigurationPanel.tsx')
const activityPanelPath = path.join(root, 'app/components/ActivityPanel.tsx')
const inferencePanelPath = path.join(root, 'app/components/InferenceEndpointPanel.tsx')
const sandboxInferencePanelPath = path.join(root, 'app/components/SandboxInferencePanel.tsx')
const sidebarPath = path.join(root, 'app/components/Sidebar.tsx')
const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx')
const openClawLogoPath = path.join(root, 'public/sandbox-logos/openclaw.svg')
const hermesLogoPath = path.join(root, 'public/sandbox-logos/hermes.png')
const createRouteSource = await readFile(createRoutePath, 'utf8')
const deleteRouteSource = await readFile(deleteRoutePath, 'utf8')
const hostCommandsSource = await readFile(hostCommandsPath, 'utf8')
const telemetryRouteSource = await readFile(telemetryRoutePath, 'utf8')
const inferenceRouteSource = await readFile(inferenceRoutePath, 'utf8')
const vllmApplyRouteSource = await readFile(vllmApplyRoutePath, 'utf8')
const vllmRestartRouteSource = await readFile(vllmRestartRoutePath, 'utf8')
const inferenceEndpointUrlSource = await readFile(inferenceEndpointUrlPath, 'utf8')
const inferenceRouteStoreSource = await readFile(inferenceRouteStorePath, 'utf8')
const ollamaModelsRouteSource = await readFile(ollamaModelsRoutePath, 'utf8')
const sandboxInferenceRouteSource = await readFile(sandboxInferenceRoutePath, 'utf8')
const sandboxInferenceApplyRouteSource = await readFile(sandboxInferenceApplyRoutePath, 'utf8')
const sandboxInferenceApplyLibSource = await readFile(sandboxInferenceApplyLibPath, 'utf8')
const sandboxInferenceStoreSource = await readFile(sandboxInferenceStorePath, 'utf8')
const sandboxRestartRouteSource = await readFile(sandboxRestartRoutePath, 'utf8')
const gatewayRepairRouteSource = await readFile(gatewayRepairRoutePath, 'utf8')
const sandboxPrivilegedFilesSource = await readFile(sandboxPrivilegedFilesPath, 'utf8')
const versionedInstallerSource = await readFile(versionedInstallerPath, 'utf8')
const hookSource = await readFile(hookPath, 'utf8')
const pageSource = await readFile(pagePath, 'utf8')
const configPanelSource = await readFile(configPanelPath, 'utf8')
const activityPanelSource = await readFile(activityPanelPath, 'utf8')
const inferencePanelSource = await readFile(inferencePanelPath, 'utf8')
const sandboxInferencePanelSource = await readFile(sandboxInferencePanelPath, 'utf8')
const sidebarSource = await readFile(sidebarPath, 'utf8')
const sandboxListSource = await readFile(sandboxListPath, 'utf8')
const openClawLogoStat = await stat(openClawLogoPath)
const hermesLogoStat = await stat(hermesLogoPath)
assert.match(
createRouteSource,
/const readiness = await waitForSandboxReady\(sandboxName, 90000, 2000\)/,
'blueprint create must poll authoritative readiness before returning success',
)
assert.match(
createRouteSource,
/readiness:\s*\{\s*attempts: readiness\.attempts,\s*elapsedMs: readiness\.elapsedMs,/,
'blueprint create response must expose readiness polling metadata',
)
assert.match(createRouteSource, /recordActivity/, 'sandbox create route must persist create progress to the activity log')
assert.match(createRouteSource, /async function recordCreateActivity/, 'sandbox create activity logging must be isolated behind a best-effort helper')
assert.match(createRouteSource, /activity-log:error/, 'sandbox create activity logging failures must be reported without failing creation')
assert.match(createRouteSource, /sandbox\.create\.start/, 'sandbox create route must record a durable start event before long-running work')
assert.match(createRouteSource, /sandbox\.create\.success/, 'sandbox create route must record a durable success event')
assert.match(createRouteSource, /sandbox\.create\.error/, 'sandbox create route must record durable failure events')
assert.ok(createRouteSource.indexOf('if (!blueprint)') < createRouteSource.indexOf('sandbox.create.start'), 'sandbox create route must validate required blueprint before recording a start event')
assert.match(createRouteSource, /sandbox\.create\.error[\s\S]*unknown blueprint/, 'unknown blueprint must be paired with a durable error event after a start event')
assert.match(pageSource, //, 'dashboard must surface the activity log so create progress remains visible after navigation')
assert.match(activityPanelSource, /sandbox creation/, 'activity panel copy must include sandbox creation progress events')
assert.match(createRouteSource, /"onboard",[\s\S]*"--non-interactive",[\s\S]*"--recreate-sandbox"/, 'blueprint create must use the Monday-era normal NemoClaw onboard flow')
assert.match(createRouteSource, /type NemoClawAgent = "openclaw" \| "hermes"/, 'blueprint create must model OpenClaw and Hermes NemoClaw agents')
assert.match(createRouteSource, /function nemoClawAgentForBlueprint\(blueprint: string\): NemoClawAgent/, 'blueprint create must map dashboard blueprints to NemoClaw agents')
assert.match(createRouteSource, /blueprint === "nemoclaw-hermes" \? "hermes" : "openclaw"/, 'Hermes blueprint must select the Hermes NemoClaw agent without changing the OpenClaw default')
assert.match(createRouteSource, /agent === "hermes" \? \["--agent", "hermes"\] : \[\]/, 'Hermes sandbox creation must pass --agent hermes to NemoClaw')
assert.match(createRouteSource, /type CreateGpuMode = "none" \| "auto" \| "required"/, 'blueprint create must model explicit GPU passthrough modes')
assert.match(createRouteSource, /process\.env\.OPENSHELL_CONTROL_CREATE_GPU_MODE \|\| "none"/, 'sandbox create must default to no GPU passthrough unless requested')
assert.match(createRouteSource, /mode === "required"[\s\S]*return \["--gpu"\]/, 'NemoClaw create must pass --gpu when GPU passthrough is required')
assert.match(createRouteSource, /mode === "none"[\s\S]*return \["--no-gpu"\]/, 'NemoClaw create must pass --no-gpu by default to avoid CDI failures')
assert.match(createRouteSource, /openShellGpuArgs\(mode: CreateGpuMode\)/, 'OpenShell create paths must share GPU request handling')
assert.doesNotMatch(createRouteSource, /resolvePreferredNemoClawDockerfile|prepareDashboardOwnedNemoClawDockerfile/, 'blueprint create must not force the explicit Dockerfile path')
assert.match(createRouteSource, /NEMOCLAW_SANDBOX_NAME: sandboxName/, 'blueprint create must pass the requested sandbox name to NemoClaw onboarding')
assert.match(createRouteSource, /id: "redeploy-image"/, 'create API must expose image redeploy as a sandbox creation path')
assert.match(createRouteSource, /label: "Quick Deploy New NemoClaw Sandbox"/, 'image redeploy must be labeled as the quick deploy default path')
assert.match(createRouteSource, /label: "Fresh NemoClaw Image"/, 'full rebuild path must be labeled as fresh image creation')
assert.match(createRouteSource, /id: "nemoclaw-hermes"/, 'create API must expose Hermes sandbox creation')
assert.match(createRouteSource, /label: "Fresh Hermes Sandbox"/, 'Hermes sandbox creation must be labeled clearly in the create API')
assert.match(createRouteSource, /source: "~\/NemoClaw\/agents\/hermes\/Dockerfile"/, 'Hermes sandbox creation must point at the upstream Hermes agent source')
assert.match(createRouteSource, /readNemoClawRegistry/, 'image redeploy must discover the default NemoClaw sandbox image automatically')
assert.match(createRouteSource, /listOpenShellSandboxNames/, 'image redeploy must fall back to live OpenShell inventory when registry entries are stale')
assert.match(createRouteSource, /resolveSourcePodImage\(sourceSandboxName, sandboxName\)/, 'image redeploy must allow optional explicit source while defaulting automatically')
assert.match(createRouteSource, /"--from",\s*sourceImage/, 'image redeploy must pass the resolved image to openshell sandbox create')
assert.match(createRouteSource, /"--auto-providers"/, 'image redeploy must use OpenShell auto providers for provider-backed images')
assert.match(createRouteSource, /registerNemoClawImageRedeploy/, 'image redeploy must register the new sandbox without a full NemoClaw rebuild')
assert.match(createRouteSource, /readyVerification\?: SandboxVerification/, 'ready-aware create command must carry the authoritative verification result')
assert.match(createRouteSource, /readyVerification: verification/, 'ready-aware create command must return the verification that proved readiness')
assert.match(createRouteSource, /createAttempt\.readyVerification\?\.verified[\s\S]*await waitForSandboxReady\(sandboxName, 90000, 2000\)/, 'image redeploy must reuse the ready-command verification instead of always polling readiness twice')
assert.match(createRouteSource, /const requestedMode = typeof raw\.mode === "string" \? raw\.mode : "vllm"/, 'blueprint create must default to vLLM experimental onboarding when the UI payload is absent')
assert.match(createRouteSource, /NEMOCLAW_EXPERIMENTAL = "1"/, 'blueprint create must support NemoClaw experimental provider onboarding')
assert.match(createRouteSource, /NEMOCLAW_PROVIDER = "vllm"/, 'blueprint create must support the vLLM onboarding provider')
assert.match(createRouteSource, /NEMOCLAW_PROVIDER = "nim-local"/, 'blueprint create must support the NVIDIA NIM onboarding provider')
assert.match(createRouteSource, /NEMOCLAW_PROVIDER_KEY = apiKey/, 'blueprint create must pass NVIDIA API keys through provider env without changing NemoClaw')
assert.match(versionedInstallerSource, /OPENSHELL_VERSION="\$\{OPENSHELL_VERSION:-v0\.0\.44\}"/, 'versioned installer must default to the OpenShell release supported by current NemoClaw main')
assert.match(versionedInstallerSource, /NEMOCLAW_INSTALL_REF="\$\{NEMOCLAW_INSTALL_REF:-\$\{NEMOCLAW_INSTALL_TAG:-main\}\}"/, 'versioned installer must track the current NemoClaw main ref by default while preserving the legacy tag override')
assert.match(versionedInstallerSource, /OPENCLAW_VERSION="\$\{OPENCLAW_VERSION:-2026\.5\.27\}"/, 'versioned installer must pin the current NemoClaw-compatible OpenClaw base image version')
assert.match(versionedInstallerSource, /git -C "\$source_dir" fetch[\s\S]*"\$NEMOCLAW_INSTALL_REF"/, 'versioned installer must fetch NemoClaw by git ref so branch heads and tags both work')
assert.match(versionedInstallerSource, /docker build[\s\S]*Dockerfile\.base[\s\S]*--build-arg "OPENCLAW_VERSION=\$OPENCLAW_VERSION"[\s\S]*"\$source_dir"/, 'versioned installer must rebuild the stock NemoClaw base image with the pinned OpenClaw version')
assert.doesNotMatch(createRouteSource, /repairOpenClawRuntimePolicy|runtimePolicyRepair/, 'sandbox create must not mutate OpenShell filesystem policy for OpenClaw')
assert.doesNotMatch(createRouteSource, /stabilizeOpenClawGatewayConfig|gatewayConfigRepair|repairOpenClawWorkspacePermissions|workspaceRepair/, 'sandbox create must not patch OpenClaw internals after the Monday rollback')
assert.match(createRouteSource, /repairOpenClawExecApprovalsFile/, 'sandbox create may apply the narrow exec approvals symlink compatibility repair')
assert.match(createRouteSource, /execApprovalsRepair/, 'sandbox create response must report the narrow exec approvals compatibility repair')
assert.match(createRouteSource, /created && isOpenClawAgent \? await repairOpenClawExecApprovalsFile/, 'Hermes create must skip OpenClaw-only exec approvals repair')
assert.match(createRouteSource, /created && isOpenClawAgent \? await approveOpenClawDeviceRequests/, 'Hermes create must skip OpenClaw-only device approval')
assert.doesNotMatch(sandboxPrivilegedFilesSource, /openshell-openclaw-policy-|"policy", "set"|withoutReadOnlyOpenClaw/, 'OpenClaw repair must not mutate OpenShell filesystem policy')
assert.match(sandboxPrivilegedFilesSource, /plugins\.entries\.bonjour/, 'gateway config stabilization must disable the crashing Bonjour plugin')
assert.match(sandboxPrivilegedFilesSource, /sha256sum openclaw\.json > \.config-hash/, 'gateway config stabilization must refresh OpenClaw config hash')
assert.match(sandboxPrivilegedFilesSource, /openclaw gateway run/, 'gateway config stabilization must restart the OpenClaw gateway')
assert.match(sandboxPrivilegedFilesSource, /"workspace"/, 'workspace repair must target the OpenClaw workspace directory')
assert.match(sandboxPrivilegedFilesSource, /\/sandbox\/\.openclaw-data\/\$dir/, 'workspace repair must use the policy-writable OpenClaw data tree')
assert.match(sandboxPrivilegedFilesSource, /ln -sfn/, 'workspace repair must link the OpenClaw workspace path into writable storage')
assert.match(sandboxPrivilegedFilesSource, /"flows"/, 'workspace repair must include the stock NemoClaw flows symlink')
assert.match(sandboxPrivilegedFilesSource, /"plugin-runtime-deps"/, 'workspace repair must include the OpenClaw plugin runtime dependency directory')
assert.match(sandboxPrivilegedFilesSource, /"update-check\.json"/, 'workspace repair must include the stock NemoClaw update-check symlink')
assert.match(sandboxPrivilegedFilesSource, /exec-approvals\.json/, 'workspace repair must include exec approval state handling')
assert.match(sandboxPrivilegedFilesSource, /const mutableFiles = \[\s*"update-check\.json",\s*\]/, 'workspace repair must not leave exec approvals in the symlinked mutable files list for newer OpenClaw')
assert.match(sandboxPrivilegedFilesSource, /chmod 0600 \/sandbox\/\.openclaw\/exec-approvals\.json/, 'workspace repair must make exec approvals a real writable file for newer OpenClaw')
assert.match(sandboxPrivilegedFilesSource, /chown -R sandbox:sandbox \/sandbox\/\.openclaw-data/, 'workspace repair must restore stock NemoClaw ownership for OpenClaw data')
assert.match(sandboxPrivilegedFilesSource, /AGENTS\.md/, 'workspace repair note must document the AGENTS.md permission failure it prevents')
assert.match(sandboxPrivilegedFilesSource, /"agents"/, 'workspace repair must target the OpenClaw agent directory so sessions are writable through .openclaw-data')
assert.match(sandboxPrivilegedFilesSource, /"agents"[\s\S]*"workspace"[\s\S]*"memory"/, 'workspace repair must cover NemoClaw expected OpenClaw mutable symlink directories')
assert.match(sandboxPrivilegedFilesSource, /sessions\.json\.lock|session lock/, 'workspace repair note must document the sessions.json.lock permission failure it prevents')
assert.match(sandboxPrivilegedFilesSource, /bundled OpenClaw expects/, 'workspace repair note must document the dashboard reconciles to the bundled OpenClaw expectations')
assert.match(hookSource, /type RefreshOptions = \{\s*force\?: boolean\s*\}/, 'inventory refresh must accept a force option')
assert.match(hookSource, /!refreshOptions\?\.force && inFlightRef\.current/, 'forced inventory refresh must bypass existing in-flight reads')
assert.match(hookSource, /requestIdRef = useRef\(0\)/, 'inventory refresh must guard against stale concurrent responses')
assert.match(deleteRouteSource, /OPENSHELL_BIN/, 'delete route must use the shared OpenShell CLI resolver')
assert.match(hostCommandsSource, /export const OPENSHELL_BIN[\s\S]*"openshell"/, 'shared command resolver must fall back to the OpenShell CLI')
assert.match(deleteRouteSource, /\["sandbox", "delete", sandboxName\]/, 'delete route must call openshell sandbox delete with the sandbox name')
assert.match(deleteRouteSource, /validateSandboxName/, 'delete route must validate sandbox names before execution')
assert.match(deleteRouteSource, /resolveSandboxRef/, 'delete route must resolve sandbox ids to names before deleting')
assert.match(deleteRouteSource, /OPENSHELL_GATEWAY: process\.env\.OPENSHELL_GATEWAY \|\| "nemoclaw"/, 'delete route must use the NemoClaw gateway context')
assert.match(hostCommandsSource, /export function hostCommandEnv/, 'host commands must provide a shared environment for OpenShell child processes')
assert.match(hostCommandsSource, /XDG_CONFIG_HOME/, 'shared host command environment must preserve the OpenShell config home')
assert.match(hostCommandsSource, /export function openshellGatewayAddressEnv/, 'shared host command environment must expose gateway address override variables')
assert.match(hostCommandsSource, /OPENSHELL_GATEWAY_HOST/, 'shared host command environment must pass a configurable gateway host to child processes')
assert.match(hostCommandsSource, /OPENSHELL_GATEWAY_PORT/, 'shared host command environment must pass a configurable gateway port to child processes')
assert.match(hostCommandsSource, /OPENSHELL_GATEWAY_URL/, 'shared host command environment must pass or synthesize a gateway URL for child processes')
assert.match(hostCommandsSource, /gateway\.json/, 'shared host command environment must read gateway address config from the OpenShell config directory')
assert.match(hostCommandsSource, /config\.json/, 'shared host command environment must also support the general OpenShell config file')
assert.match(hostCommandsSource, /gatewayHost/, 'OpenShell gateway address config must support a top-level gatewayHost key')
assert.match(hostCommandsSource, /gateway\.host/, 'OpenShell gateway address config must support a nested gateway host key')
assert.match(createRouteSource, /const env: NodeJS\.ProcessEnv = hostCommandEnv\(\{[\s\S]*NEMOCLAW_SANDBOX_NAME: sandboxName[\s\S]*OPENSHELL_GATEWAY: process\.env\.OPENSHELL_GATEWAY \|\| "nemoclaw"/, 'NemoClaw onboard must receive the shared host command environment')
assert.match(createRouteSource, /NEMOCLAW_AGENT: agent/, 'NemoClaw onboard must receive the selected dashboard agent')
assert.match(deleteRouteSource, /env: hostCommandEnv\(\{[\s\S]*OPENSHELL_GATEWAY: process\.env\.OPENSHELL_GATEWAY \|\| "nemoclaw"/, 'delete route must pass the shared host command environment to OpenShell')
assert.match(deleteRouteSource, /waitForSandboxDeleted/, 'delete route must poll authoritative inventory until the sandbox is gone')
assert.doesNotMatch(deleteRouteSource, /cleanupNemoClawSandbox/, 'delete route must not run NemoClaw destroy cleanup after OpenShell deletion')
assert.doesNotMatch(deleteRouteSource, /isNemoClawSandboxNotRegistered/, 'delete route must not keep NemoClaw registry cleanup helpers')
assert.doesNotMatch(deleteRouteSource, /\[sandboxName, "destroy", "--yes"\]/, 'delete route must not call nemoclaw destroy because it can delete the gateway')
assert.doesNotMatch(deleteRouteSource, /Pruned NemoClaw registry entry without destroying the shared OpenShell gateway|cleanupGatewayAfterLastSandbox/, 'delete route must not include the later registry-prune rewrite')
assert.match(deleteRouteSource, /openShellAlreadyGone/, 'delete route must tolerate sandboxes that OpenShell already deleted while NemoClaw still has registry state')
assert.doesNotMatch(deleteRouteSource, /isGatewayRecoverable|recoverableGateway/, 'delete route must not include the later gateway-repair branching')
assert.match(telemetryRouteSource, /const names = parseOpenShellSandboxNames\(sandboxListStdout\)/, 'telemetry must derive inventory from OpenShell before consulting NemoClaw')
assert.match(telemetryRouteSource, /names\.length > 0[\s\S]*execNemoclaw\(\["list"\]\)[\s\S]*execNemoclaw\(\["status"\]\)/, 'telemetry must skip NemoClaw list/status when OpenShell reports zero live sandboxes')
assert.match(telemetryRouteSource, /readNemoClawRegistry/, 'telemetry must read the NemoClaw registry for agent metadata')
assert.match(telemetryRouteSource, /resolveSandboxAgent/, 'telemetry must resolve OpenClaw versus Hermes agent metadata')
assert.match(telemetryRouteSource, /"nemoclaw\.ai\/agent": agent/, 'telemetry pod labels must include the selected NemoClaw agent')
assert.match(hookSource, /agent\?: string/, 'inventory items must carry optional agent metadata')
assert.match(hookSource, /agent: typeof sandbox\.agent === 'string' && sandbox\.agent \? sandbox\.agent : 'openclaw'/, 'inventory summary mapping must default older registry entries to OpenClaw')
assert.match(sandboxListSource, /function displaySandboxAgent\(agent\?: string\)/, 'sandbox list must render agent labels')
assert.match(sandboxListSource, /function SandboxTypeLogo\(\{ agent \}/, 'sandbox list must render per-agent sandbox logos')
assert.match(sandboxListSource, /const OPENCLAW_SANDBOX_LOGO = '\/sandbox-logos\/openclaw\.svg'/, 'OpenClaw sandboxes must use the local OpenClaw favicon asset')
assert.match(sandboxListSource, /const HERMES_SANDBOX_LOGO = '\/sandbox-logos\/hermes\.png'/, 'Hermes sandboxes must use the local Hermes favicon asset')
assert.match(sandboxListSource, /const logoSrc = isHermes \? HERMES_SANDBOX_LOGO : OPENCLAW_SANDBOX_LOGO/, 'sandbox type logo must switch assets by agent type')
assert.ok(openClawLogoStat.size > 0, 'OpenClaw favicon asset must be vendored locally')
assert.ok(hermesLogoStat.size > 0, 'Hermes favicon asset must be vendored locally')
assert.match(sandboxListSource, /selectedSandbox\?\.agent === 'hermes'/, 'sandbox operations must detect Hermes sandboxes')
assert.match(sandboxListSource, /Connect to Hermes/, 'sandbox operations must show a Hermes connect action instead of an OpenClaw dashboard action')
assert.match(sandboxListSource, /launch: 'hermes'/, 'Hermes connect action must open the operator terminal in Hermes launch mode')
assert.match(sandboxListSource, /dashboardSessionId/, 'Hermes connect action must preserve the dashboard terminal session id')
assert.match(sandboxListSource, /DISMISSED_PERMISSION_ALERTS_STORAGE_KEY/, 'sandbox list must persist locally hidden permission alerts')
assert.match(sandboxListSource, /visiblePendingRequests\(feed, sandbox, dismissedPermissionAlerts\)/, 'sandbox permission dropdown must hide dismissed pending alerts')
assert.match(sandboxListSource, /