diff --git a/.github/workflows/code-scanning.yaml b/.github/workflows/code-scanning.yaml index 0284923cfcf..0737a61be24 100644 --- a/.github/workflows/code-scanning.yaml +++ b/.github/workflows/code-scanning.yaml @@ -24,7 +24,8 @@ jobs: codeql: name: CodeQL (${{ matrix.language }}) runs-on: ubuntu-latest - timeout-minutes: 15 + # Keep matrix keys stable because CodeQL uses them in its analysis identity. + timeout-minutes: ${{ matrix.language == 'javascript-typescript' && 20 || 15 }} strategy: fail-fast: false matrix: diff --git a/.github/workflows/windows-native-installer-trusted.yaml b/.github/workflows/windows-native-installer-trusted.yaml new file mode 100644 index 00000000000..8d20a4faeeb --- /dev/null +++ b/.github/workflows/windows-native-installer-trusted.yaml @@ -0,0 +1,636 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +name: CI / Trusted Windows Installer Qualification + +# This workflow is deliberately callable only from the same commit as its +# caller. The caller admits only an exact, current refs/heads/main dispatch, so +# qualification remains unavailable until both workflow files land on main. +on: + workflow_call: + inputs: + qualification_phase: + description: Runtime bootstrap cannot publish; final retains all installer gates + required: false + default: final + type: string + pr_number: + required: true + type: string + candidate_repository: + required: true + type: string + candidate_sha: + required: true + type: string + base_sha: + required: true + type: string + workflow_sha: + required: true + type: string + agent: + required: true + type: string + product_version: + required: true + type: string + installer_cache_key: + required: true + type: string + installer_manifest_sha256: + required: true + type: string + application_manifest_sha256: + required: true + type: string + candidate_migration_evidence_id: + required: false + default: "" + type: string + candidate_migration_proof_sha256: + required: false + default: "" + type: string + outputs: + availability_id: + description: Independently reviewed exact-runtime availability artifact + value: ${{ jobs.review-runtime-availability.outputs.availability_id }} + availability_sha256: + description: Reviewed decision file SHA-256 + value: ${{ jobs.review-runtime-availability.outputs.availability_sha256 }} + preview_id: + description: Artifact ID of the fully qualified runnable installer + value: ${{ jobs.publish-qualified-installer.outputs.preview_id }} + preview_digest: + description: Artifact digest of the fully qualified runnable installer + value: ${{ jobs.publish-qualified-installer.outputs.preview_digest }} + +permissions: + actions: read + contents: read + pull-requests: read + +jobs: + authorize: + name: Reauthorize exact PR against exact current main + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + trusted_main: ${{ steps.authorization.outputs.trusted_main }} + exact_workflow: ${{ steps.authorization.outputs.exact_workflow }} + exact_pr: ${{ steps.authorization.outputs.exact_pr }} + credential_authorized: ${{ steps.authorization.outputs.credential_authorized }} + steps: + - name: Require current main controller and exact internal PR identity + id: authorization + shell: bash + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.pr_number }} + CANDIDATE_REPOSITORY: ${{ inputs.candidate_repository }} + CANDIDATE_SHA: ${{ inputs.candidate_sha }} + BASE_SHA: ${{ inputs.base_sha }} + WORKFLOW_SHA: ${{ inputs.workflow_sha }} + SELECTED_AGENT: ${{ inputs.agent }} + PRODUCT_VERSION: ${{ inputs.product_version }} + INSTALLER_CACHE_KEY: ${{ inputs.installer_cache_key }} + INSTALLER_MANIFEST: ${{ inputs.installer_manifest_sha256 }} + APPLICATION_MANIFEST: ${{ inputs.application_manifest_sha256 }} + CANDIDATE_MIGRATION_EVIDENCE_ID: ${{ inputs.candidate_migration_evidence_id }} + CANDIDATE_MIGRATION_PROOF_SHA256: ${{ inputs.candidate_migration_proof_sha256 }} + QUALIFICATION_PHASE: ${{ inputs.qualification_phase }} + ACTOR: ${{ github.actor }} + TRIGGERING_ACTOR: ${{ github.triggering_actor }} + run: | + set -euo pipefail + [[ "$GITHUB_REPOSITORY" == 'NVIDIA/NemoClaw' && "$GITHUB_REF" == 'refs/heads/main' ]] + [[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ && "$CANDIDATE_REPOSITORY" == 'NVIDIA/NemoClaw' ]] + [[ "$CANDIDATE_SHA" =~ ^[a-f0-9]{40}$ && "$BASE_SHA" =~ ^[a-f0-9]{40}$ && "$WORKFLOW_SHA" =~ ^[a-f0-9]{40}$ ]] + [[ "$INSTALLER_MANIFEST" =~ ^[a-f0-9]{64}$ && "$APPLICATION_MANIFEST" =~ ^[a-f0-9]{64}$ ]] + if [[ "$QUALIFICATION_PHASE" == 'runtime-bootstrap' ]]; then + [[ "$SELECTED_AGENT" =~ ^(openclaw|hermes)$ && -z "$CANDIDATE_MIGRATION_EVIDENCE_ID" && -z "$CANDIDATE_MIGRATION_PROOF_SHA256" ]] + else + [[ "$QUALIFICATION_PHASE" == 'final' ]] + [[ "$CANDIDATE_MIGRATION_EVIDENCE_ID" =~ ^[1-9][0-9]*$ && "$CANDIDATE_MIGRATION_PROOF_SHA256" =~ ^[a-f0-9]{64}$ ]] + fi + [[ "$SELECTED_AGENT" =~ ^(openclaw|hermes)$ && "$PRODUCT_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] + [[ "$INSTALLER_CACHE_KEY" == "windows-finished-installer-v1-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT-$CANDIDATE_SHA-$SELECTED_AGENT" || + ( "$QUALIFICATION_PHASE" == 'final' && "$INSTALLER_CACHE_KEY" == "windows-finished-reviewed-installer-v1-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT-$CANDIDATE_SHA-$SELECTED_AGENT" ) ]] + [[ "$BASE_SHA" == "$WORKFLOW_SHA" ]] + main_sha="$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha')" + [[ "$main_sha" == "$WORKFLOW_SHA" ]] + pr="$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")" + [[ "$(jq -r '.state' <<<"$pr")" == 'open' ]] + [[ "$(jq -r '.base.repo.full_name' <<<"$pr")" == "$GITHUB_REPOSITORY" ]] + [[ "$(jq -r '.base.ref' <<<"$pr")" == 'main' ]] + [[ "$(jq -r '.base.sha' <<<"$pr")" == "$BASE_SHA" ]] + [[ "$(jq -r '.head.repo.full_name' <<<"$pr")" == "$CANDIDATE_REPOSITORY" ]] + [[ "$(jq -r '.head.repo.owner.login' <<<"$pr")" == 'NVIDIA' ]] + [[ "$(jq -r '.head.repo.owner.type' <<<"$pr")" == 'Organization' ]] + [[ "$(jq -r '.head.sha' <<<"$pr")" == "$CANDIDATE_SHA" ]] + comparison="$(gh api "repos/$GITHUB_REPOSITORY/compare/$WORKFLOW_SHA...$CANDIDATE_SHA")" + [[ "$(jq -r '.merge_base_commit.sha' <<<"$comparison")" == "$WORKFLOW_SHA" ]] + [[ "$(jq -r '.behind_by' <<<"$comparison")" == '0' ]] + for principal in "$ACTOR" "$TRIGGERING_ACTOR"; do + permission="$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$principal/permission" --jq '.permission')" + [[ "$permission" =~ ^(admin|maintain|write)$ ]] + done + { + echo 'trusted_main=true' + echo 'exact_workflow=true' + echo 'exact_pr=true' + echo 'credential_authorized=true' + } >> "$GITHUB_OUTPUT" + + candidate-migration-proof: + name: Verify same-run candidate migration controller evidence + needs: authorize + if: ${{ inputs.qualification_phase == 'final' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Download candidate migration evidence from this run + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ inputs.candidate_migration_evidence_id }} + path: ${{ runner.temp }}/candidate-migration-proof + merge-multiple: true + - name: Verify candidate controller and artifact identities + shell: python + env: + PROOF_ROOT: ${{ runner.temp }}/candidate-migration-proof + PROOF_SHA256: ${{ inputs.candidate_migration_proof_sha256 }} + CANDIDATE_SHA: ${{ inputs.candidate_sha }} + INSTALLER_MANIFEST: ${{ inputs.installer_manifest_sha256 }} + SELECTED_AGENT: ${{ inputs.agent }} + run: | + import hashlib, json, os, pathlib, re, stat + root = pathlib.Path(os.environ['PROOF_ROOT']).resolve(strict=True) + def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError('Duplicate migration evidence property') + result[key] = value + return result + def read_json(relative, digest): + file = root / relative + assert file.resolve(strict=True) == file and not file.is_symlink() + with file.open('rb') as stream: + opened = os.fstat(stream.fileno()) + assert stat.S_ISREG(opened.st_mode) and opened.st_nlink == 1 + data = stream.read(1048577) + assert len(data) <= 1048576 and re.fullmatch('[a-f0-9]{64}', digest) + assert hashlib.sha256(data).hexdigest() == digest + return json.loads(data, object_pairs_hook=unique_object) + proof = read_json('candidate-migration-controller.json', os.environ['PROOF_SHA256']) + assert proof['schemaVersion'] == 1 and proof['passed'] is True + assert proof['classification'] == 'same-run-candidate-migration-controllers' + assert proof['controllerSourceRevision'] == os.environ['CANDIDATE_SHA'] + assert proof['artifactSourceRevision'] == os.environ['CANDIDATE_SHA'] + assert proof['installerManifestSha256'] == os.environ['INSTALLER_MANIFEST'] + assert proof['agent'] == os.environ['SELECTED_AGENT'] + assert proof['workflowRunId'] == os.environ['GITHUB_RUN_ID'] + assert proof['workflowRunAttempt'] == os.environ['GITHUB_RUN_ATTEMPT'] + expected = ['diagnostics-fixture/fixture.json', 'burn-diagnostics/burn-diagnostics.json', 'migration/preview-migration.json'] + assert [item['file'] for item in proof['files']] == expected + fixture, burn, migration = [read_json(item['file'], item['sha256']) for item in proof['files']] + assert all(report['sourceRevision'] == os.environ['CANDIDATE_SHA'] for report in [fixture, burn, migration]) + assert fixture['classification'] == 'actual-burn-host-preparation-failure-fixture' + assert fixture['intendedForDistribution'] is False + assert burn['classification'] == 'actual-burn-prerequisite-failure-qualification' + assert burn['agent'] == os.environ['SELECTED_AGENT'] and burn['status'] == 'pass' + assert burn['cleanupErrors'] == [] and burn['packageNotInstalled'] is True + assert migration['classification'] == 'actual-published-preview-native-migration' + assert migration['newAgent'] == os.environ['SELECTED_AGENT'] and migration['status'] == 'pass' + assert migration['cleanupErrors'] == [] and migration['installationRootRemoved'] is True + assert [case['kind'] for case in migration['cases']] == ['conventional-reinstall', 'native-replace-preview'] + assert all(case['resetVerified'] is True for case in migration['cases']) + print('Candidate migration controller evidence matches this run and installer.') + + full-installed-acceptance: + name: Protected full installed acceptance (ARM64) + needs: [authorize, candidate-migration-proof] + if: ${{ always() && !cancelled() && needs.authorize.result == 'success' && needs.authorize.outputs.trusted_main == 'true' && needs.authorize.outputs.exact_workflow == 'true' && needs.authorize.outputs.exact_pr == 'true' && needs.authorize.outputs.credential_authorized == 'true' && ((inputs.qualification_phase == 'runtime-bootstrap' && contains(fromJSON('["openclaw","hermes"]'), inputs.agent)) || (inputs.qualification_phase == 'final' && needs.candidate-migration-proof.result == 'success')) }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 60 + outputs: + evidence_id: ${{ steps.full_artifact.outputs.artifact-id }} + evidence_manifest_sha256: ${{ steps.full_evidence.outputs.manifest_sha256 }} + # External security boundary required before first use: administrators must + # create this environment with main-only deployment branches, required reviewers, + # prevent-self-review, and fresh environment-only READY + qualification + # inference secrets. Never define the WINDOWS_NATIVE_INSTALLER_* secrets at + # repository/organization scope or rely on generic repository-key fallback; + # rotate any qualification key previously exposed to the legacy workflow. + # Without that setup this job fails before candidate code executes. The + # legacy Actions workflow ID 350766812 must also be permanently disabled. + environment: windows-native-installer-qualification + env: + CANDIDATE_SHA: ${{ inputs.candidate_sha }} + CONTROLLER_SHA: ${{ inputs.workflow_sha }} + SELECTED_AGENT: ${{ inputs.agent }} + PRODUCT_VERSION: ${{ inputs.product_version }} + TRUSTED_CONTROLLER_NODE: ${{ github.workspace }}\trusted-controller-node\node.exe + QUALIFICATION_PHASE: ${{ inputs.qualification_phase }} + steps: + - name: Require configured protected qualification environment + shell: pwsh + env: + ENVIRONMENT_READY: ${{ secrets.WINDOWS_NATIVE_INSTALLER_QUALIFICATION_READY }} + run: | + if ($env:ENVIRONMENT_READY -cne 'reviewed-main-v1') { + throw 'The protected qualification environment is not configured; no candidate code will receive credentials.' + } + - name: Check out the exact trusted main controller + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NVIDIA/NemoClaw + ref: ${{ inputs.workflow_sha }} + path: controller + persist-credentials: false + - name: Check out selected-agent candidate source as comparison data + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NVIDIA/NemoClaw + ref: ${{ inputs.candidate_sha }} + path: artifact-source + persist-credentials: false + submodules: false + lfs: false + - name: Restore exact same-run installer cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-product-transfer + key: ${{ inputs.installer_cache_key }} + fail-on-cache-miss: true + - name: Verify and materialize exact qualified inputs + shell: pwsh + env: + INSTALLER_MANIFEST: ${{ inputs.installer_manifest_sha256 }} + APPLICATION_MANIFEST: ${{ inputs.application_manifest_sha256 }} + run: | + $controllerHead = (& git -C "$env:GITHUB_WORKSPACE\controller" rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $controllerHead -cne $env:CONTROLLER_SHA) { throw 'The trusted controller checkout is not exact.' } + $product = "$env:RUNNER_TEMP\finished-windows-product-transfer" + $application = "$product\compiled-application" + $verifiedProduct = @(& "$env:GITHUB_WORKSPACE\controller\scripts\checks\windows-native-transfer.ps1" -Mode Verify -Root $product ` + -Kind finished-installer -SourceRevision $env:CANDIDATE_SHA -Agent $env:SELECTED_AGENT ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:INSTALLER_MANIFEST) + $verifiedApplication = @(& "$env:GITHUB_WORKSPACE\controller\scripts\checks\windows-native-transfer.ps1" -Mode Verify -Root $application ` + -Kind compiled-application -SourceRevision $env:CANDIDATE_SHA -Agent $env:SELECTED_AGENT ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:APPLICATION_MANIFEST) + if ($verifiedProduct.Count -ne 1 -or [string]$verifiedProduct[0] -cne $env:INSTALLER_MANIFEST -or + $verifiedApplication.Count -ne 1 -or [string]$verifiedApplication[0] -cne $env:APPLICATION_MANIFEST) { + throw 'A qualification transfer did not match its producer.' + } + $work = "$env:RUNNER_TEMP\finished-windows" + [void][IO.Directory]::CreateDirectory($work) + Copy-Item -LiteralPath "$product\package" -Destination "$work\package" -Recurse + Copy-Item -LiteralPath "$product\assembled" -Destination "$work\assembled" -Recurse + Copy-Item -LiteralPath "$application\application" -Destination "$work\application" -Recurse + $trustedNodeSha256 = '97cce5301a815d2dce07ac5bfd1e6039eae88185ec1d10ae4f8cb712f1732878' + $transferredNode = Get-Item -LiteralPath "$work\application\node\node.exe" -Force + if (($transferredNode.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or + (Get-FileHash -LiteralPath $transferredNode.FullName -Algorithm SHA256).Hash.ToLowerInvariant() -cne $trustedNodeSha256) { + throw 'The transferred controller Node executable is not the pinned trusted input.' + } + $trustedNodeDirectory = Split-Path -Parent $env:TRUSTED_CONTROLLER_NODE + if (Test-Path -LiteralPath $trustedNodeDirectory) { throw 'The trusted controller Node directory must be fresh.' } + [void][IO.Directory]::CreateDirectory($trustedNodeDirectory) + Copy-Item -LiteralPath $transferredNode.FullName -Destination $env:TRUSTED_CONTROLLER_NODE + $trustedNodeFiles = @(Get-ChildItem -LiteralPath $trustedNodeDirectory -Force) + if ($trustedNodeFiles.Count -ne 1 -or $trustedNodeFiles[0] -isnot [IO.FileInfo] -or + $trustedNodeFiles[0].Name -cne 'node.exe' -or + ($trustedNodeFiles[0].Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or + (Get-FileHash -LiteralPath $env:TRUSTED_CONTROLLER_NODE -Algorithm SHA256).Hash.ToLowerInvariant() -cne $trustedNodeSha256) { + throw 'The isolated trusted controller Node inventory is invalid.' + } + - name: Rebuild acceptance-controller proof from trusted main + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CONTROLLER_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + $output = "$work\application\controls" + [void][IO.Directory]::CreateDirectory($output) + $tests = @( + 'packaging/windows/installer/control-installed-openclaw-input.test.mts', + 'packaging/windows/installer/run-installed-acceptance.test.mts', + 'packaging/windows/installer/qualify-finished-package.test.mts', + 'packaging/windows/runtime/native-ui-tunnel.test.mts' + ) + $absoluteTests = @($tests | ForEach-Object { Join-Path "$env:GITHUB_WORKSPACE\controller" $_ }) + & $env:TRUSTED_CONTROLLER_NODE --experimental-strip-types --no-warnings --test @absoluteTests + if ($LASTEXITCODE -ne 0) { throw 'The trusted acceptance-controller controls failed.' } + $files = @($tests | ForEach-Object { + $file = Join-Path "$env:GITHUB_WORKSPACE\controller" $_ + @{ file = $_; bytes = (Get-Item -LiteralPath $file).Length; sha256 = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() } + }) + [IO.File]::WriteAllText("$output\installed-acceptance-controller.json", (@{ + schemaVersion = 1 + classification = 'same-run-installed-acceptance-controller-controls' + sourceRevision = $env:CONTROLLER_SHA + nodeSha256 = (Get-FileHash -LiteralPath $env:TRUSTED_CONTROLLER_NODE -Algorithm SHA256).Hash.ToLowerInvariant() + passed = $true + files = $files + } | ConvertTo-Json -Depth 5), [Text.UTF8Encoding]::new($false)) + - name: Verify retained-state qualifier controls from trusted main + shell: pwsh + run: | + $relative = switch -CaseSensitive ($env:SELECTED_AGENT) { + 'openclaw' { 'packaging/windows/installer/qualify-installed-openclaw.test.mts' } + 'hermes' { 'packaging/windows/installer/qualify-installed-hermes.test.mts' } + default { throw 'Unsupported retained-state qualifier agent.' } + } + $controls = Join-Path "$env:GITHUB_WORKSPACE/controller" $relative + & $env:TRUSTED_CONTROLLER_NODE --experimental-strip-types --no-warnings --test ` + $controls + if ($LASTEXITCODE -ne 0) { throw 'The trusted selected-agent retained-state qualifier controls failed.' } + - name: Exercise installed preview, real inference and owned cleanup + # The main-resident controller strips inherited keys from product children. + # Full acceptance then deliberately supplies a test key through installed + # configuration and Windows Credential Manager. Protected approval must + # authorize that candidate credential access; this is not secret isolation + # from the candidate. PR-triggered startup controls remain credential-free. + shell: pwsh + env: + NVIDIA_API_KEY: ${{ secrets.WINDOWS_NATIVE_INSTALLER_NVIDIA_API_KEY }} + NVIDIA_INFERENCE_API_KEY: ${{ secrets.WINDOWS_NATIVE_INSTALLER_NVIDIA_INFERENCE_API_KEY }} + run: | + $env:GITHUB_SHA = $env:CONTROLLER_SHA + if (-not $env:NVIDIA_API_KEY -and -not $env:NVIDIA_INFERENCE_API_KEY) { throw 'The protected environment has no inference credential.' } + & "$env:GITHUB_WORKSPACE\controller\packaging\windows\installer\run-installed-acceptance.ps1" ` + -SourceRoot "$env:GITHUB_WORKSPACE\controller" -WorkDirectory "$env:RUNNER_TEMP\finished-windows" ` + -ProductVersion $env:PRODUCT_VERSION -ArtifactSourceRevision $env:CANDIDATE_SHA -Mode current-build ` + -Agent $env:SELECTED_AGENT -ControllerNodePath $env:TRUSTED_CONTROLLER_NODE -ArtifactSourceRoot "$env:GITHUB_WORKSPACE\artifact-source" ` + -RuntimeBootstrap:($env:SELECTED_AGENT -ceq 'hermes' -and $env:QUALIFICATION_PHASE -ceq 'runtime-bootstrap') + - name: Stage only non-runnable full acceptance evidence + id: full_evidence + if: ${{ always() }} + shell: pwsh + env: + NVIDIA_API_KEY: ${{ secrets.WINDOWS_NATIVE_INSTALLER_NVIDIA_API_KEY }} + NVIDIA_INFERENCE_API_KEY: ${{ secrets.WINDOWS_NATIVE_INSTALLER_NVIDIA_INFERENCE_API_KEY }} + run: | + $work = "$env:RUNNER_TEMP\finished-windows" + $inputs = @( + "$work\installed-smoke", "$work\installed-acceptance", + "$work\installed-acceptance-warm", "$work\installed-stage-timings.json", "$work\$($env:SELECTED_AGENT)-artifact-source.json" + ) + foreach ($pattern in @("$work\*.log", "$work\package\*.json")) { + $inputs += @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | ForEach-Object FullName) + } + & "$env:GITHUB_WORKSPACE\controller\scripts\checks\stage-windows-native-evidence.ps1" ` + -SourceBase $work -InputPath $inputs -OutputRoot "$env:RUNNER_TEMP\finished-windows-full-evidence" -RequireProtectedCredential + "manifest_sha256=$((Get-FileHash -LiteralPath "$env:RUNNER_TEMP\finished-windows-full-evidence\evidence-manifest.json" -Algorithm SHA256).Hash.ToLowerInvariant())" >> $env:GITHUB_OUTPUT + - name: Preserve full installed acceptance evidence + id: full_artifact + if: ${{ always() && steps.full_evidence.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: finished-windows-full-acceptance-${{ inputs.candidate_sha }}-${{ github.run_attempt }}-${{ inputs.qualification_phase }} + path: ${{ runner.temp }}/finished-windows-full-evidence/ + if-no-files-found: warn + retention-days: 14 + + review-runtime-availability: + name: Independently review completed selected-agent runtime acceptance + needs: [authorize, full-installed-acceptance] + if: ${{ inputs.qualification_phase == 'runtime-bootstrap' && contains(fromJSON('["openclaw","hermes"]'), inputs.agent) && needs.authorize.outputs.credential_authorized == 'true' && needs.full-installed-acceptance.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 10 + # Separate main-only environment with required reviewers, prevent-self-review + # and an environment-only READY sentinel. Review the completed evidence before + # approving this job. It has no inference credentials and executes no candidate. + environment: windows-native-installer-availability + outputs: + availability_id: ${{ steps.availability_artifact.outputs.artifact-id }} + availability_sha256: ${{ steps.decision.outputs.sha256 }} + steps: + - name: Require independently reviewed availability environment + shell: bash + env: + ENVIRONMENT_READY: ${{ secrets.WINDOWS_NATIVE_INSTALLER_AVAILABILITY_READY }} + run: | + set -euo pipefail + [[ "$ENVIRONMENT_READY" == 'reviewed-main-v1' ]] + - name: Check out exact trusted availability controller + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NVIDIA/NemoClaw + ref: ${{ inputs.workflow_sha }} + persist-credentials: false + - name: Prepare pinned review Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 22.23.2 + - name: Download this controller's completed runtime evidence + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.full-installed-acceptance.outputs.evidence_id }} + path: ${{ runner.temp }}/runtime-availability-evidence + merge-multiple: true + - name: Bind reviewed availability to exact successful runtime evidence + id: decision + shell: bash + env: + EVIDENCE_SHA256: ${{ needs.full-installed-acceptance.outputs.evidence_manifest_sha256 }} + CANDIDATE_SHA: ${{ inputs.candidate_sha }} + CONTROLLER_SHA: ${{ inputs.workflow_sha }} + SELECTED_AGENT: ${{ inputs.agent }} + run: | + set -euo pipefail + [[ "$(git rev-parse HEAD)" == "$CONTROLLER_SHA" ]] + case "$SELECTED_AGENT" in + openclaw) + controls=packaging/windows/installer/qualify-installed-openclaw.test.mts + reviewer=packaging/windows/installer/review-openclaw-availability.mts + ;; + hermes) + controls=packaging/windows/installer/review-hermes-availability.test.mts + reviewer=packaging/windows/installer/review-hermes-availability.mts + ;; + *) echo 'Unsupported runtime availability agent.' >&2; exit 1 ;; + esac + node --experimental-strip-types --no-warnings --test "$controls" + decision_sha="$(node --experimental-strip-types --no-warnings "$reviewer" \ + --evidence-root "$RUNNER_TEMP/runtime-availability-evidence" --evidence-manifest-sha256 "$EVIDENCE_SHA256" \ + --source-revision "$CANDIDATE_SHA" --controller-source-revision "$CONTROLLER_SHA" \ + --controller-run "$GITHUB_RUN_ID:$GITHUB_RUN_ATTEMPT" --output "$RUNNER_TEMP/reviewed-availability.json")" + [[ "$decision_sha" =~ ^[a-f0-9]{64}$ ]] + echo "sha256=$decision_sha" >> "$GITHUB_OUTPUT" + - name: Preserve reviewed availability decision only + id: availability_artifact + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: reviewed-${{ inputs.agent }}-availability-${{ inputs.candidate_sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/reviewed-availability.json + if-no-files-found: error + retention-days: 14 + + migration: + name: Trusted same-product setup and migration acceptance (ARM64) + needs: [authorize, full-installed-acceptance] + if: ${{ inputs.qualification_phase == 'final' && needs.authorize.outputs.credential_authorized == 'true' && needs.full-installed-acceptance.result == 'success' }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 35 + env: + CANDIDATE_SHA: ${{ inputs.candidate_sha }} + CONTROLLER_SHA: ${{ inputs.workflow_sha }} + SELECTED_AGENT: ${{ inputs.agent }} + PRODUCT_VERSION: ${{ inputs.product_version }} + steps: + - name: Check out the exact trusted migration controller + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NVIDIA/NemoClaw + ref: ${{ inputs.workflow_sha }} + path: controller + persist-credentials: false + - name: Restore exact same-run installer cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-product-transfer + key: ${{ inputs.installer_cache_key }} + fail-on-cache-miss: true + - name: Verify and materialize exact migration input + shell: pwsh + env: + INSTALLER_MANIFEST: ${{ inputs.installer_manifest_sha256 }} + run: | + $product = "$env:RUNNER_TEMP\finished-windows-product-transfer" + $verifiedManifest = @(& "$env:GITHUB_WORKSPACE\controller\scripts\checks\windows-native-transfer.ps1" -Mode Verify -Root $product ` + -Kind finished-installer -SourceRevision $env:CANDIDATE_SHA -Agent $env:SELECTED_AGENT ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:INSTALLER_MANIFEST) + if ($verifiedManifest.Count -ne 1 -or [string]$verifiedManifest[0] -cne $env:INSTALLER_MANIFEST) { + throw 'The migration transfer did not match its producer.' + } + [void][IO.Directory]::CreateDirectory("$env:RUNNER_TEMP\finished-windows") + Copy-Item -LiteralPath "$product\package" -Destination "$env:RUNNER_TEMP\finished-windows\package" -Recurse + Copy-Item -LiteralPath "$product\assembled" -Destination "$env:RUNNER_TEMP\finished-windows\assembled" -Recurse + - name: Prepare pinned native fixture compiler + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.95.0 + target: aarch64-pc-windows-msvc + cache: false + - name: Build actual Burn failure fixture from the same native UI + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $tools = "$env:RUNNER_TEMP\finished-windows\setup-regression-tools" + & "$env:GITHUB_WORKSPACE\controller\packaging\windows\installer\install-pinned-wix.ps1" -ToolDirectory $tools + & "$env:GITHUB_WORKSPACE\controller\packaging\windows\installer\build-burn-diagnostics-fixture.ps1" -SourceRoot "$env:GITHUB_WORKSPACE\controller" -PackageDirectory "$env:RUNNER_TEMP\finished-windows\package" -OutputDirectory "$env:RUNNER_TEMP\finished-windows\diagnostics-fixture" -ProductVersion $env:PRODUCT_VERSION -WixPath "$tools\wix.exe" + - name: Exercise backend-specific native prerequisite selection + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & "$env:GITHUB_WORKSPACE\controller\packaging\windows\installer\test-burn-diagnostics.ps1" -FixtureDirectory "$env:RUNNER_TEMP\finished-windows\diagnostics-fixture" -OutputDirectory "$env:RUNNER_TEMP\finished-windows\burn-diagnostics" -Agent $env:SELECTED_AGENT + - name: Exercise previous EXE migration and native selective reset + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & "$env:GITHUB_WORKSPACE\controller\packaging\windows\installer\run-preview-migration.ps1" -WorkDirectory "$env:RUNNER_TEMP\finished-windows" -ProductVersion $env:PRODUCT_VERSION -NewAgent $env:SELECTED_AGENT + - name: Record trusted migration controller identity separately + shell: pwsh + run: | + $head = (& git -C "$env:GITHUB_WORKSPACE\controller" rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $head -cne $env:CONTROLLER_SHA) { throw 'The trusted migration controller differs.' } + # GITHUB_SHA in the child scripts identifies the product under test. + # It does not identify the trusted scripts that produced these reports. + [IO.File]::WriteAllText("$env:RUNNER_TEMP\finished-windows\trusted-migration-controller.json", (@{ + schemaVersion=1;classification='same-run-trusted-migration-controller';passed=$true + controllerSourceRevision=$env:CONTROLLER_SHA;artifactSourceRevision=$env:CANDIDATE_SHA + workflowRunId=$env:GITHUB_RUN_ID;workflowRunAttempt=$env:GITHUB_RUN_ATTEMPT + } | ConvertTo-Json), [Text.UTF8Encoding]::new($false)) + - name: Stage only non-runnable setup and migration evidence + id: migration_evidence + if: ${{ always() }} + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\finished-windows" + $inputs = @("$work\diagnostics-fixture\fixture.json", "$work\trusted-migration-controller.json", "$work\setup-regression-tools\wix-input.json") + $allowed = @('.csv', '.etl', '.jpeg', '.jpg', '.json', '.log', '.md', '.png', '.txt', '.xml') + foreach ($directory in @("$work\burn-diagnostics", "$work\migration")) { + $inputs += @(Get-ChildItem -LiteralPath $directory -Recurse -File -ErrorAction SilentlyContinue | + Where-Object { $_.Extension -in $allowed } | ForEach-Object FullName) + } + & "$env:GITHUB_WORKSPACE\controller\scripts\checks\stage-windows-native-evidence.ps1" ` + -SourceBase $work -InputPath $inputs -OutputRoot "$env:RUNNER_TEMP\finished-windows-migration-evidence" + - name: Preserve setup and migration evidence + if: ${{ always() && steps.migration_evidence.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: windows-setup-migration-${{ inputs.candidate_sha }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/finished-windows-migration-evidence/ + if-no-files-found: warn + retention-days: 14 + + publish-qualified-installer: + name: Publish only fully qualified runnable installer + needs: [authorize, candidate-migration-proof, full-installed-acceptance, migration] + if: ${{ inputs.qualification_phase == 'final' && needs.authorize.outputs.credential_authorized == 'true' && needs.candidate-migration-proof.result == 'success' && needs.full-installed-acceptance.result == 'success' && needs.migration.result == 'success' }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 15 + # External security boundary required before first use: create a separate + # environment with main-only deployment branches, required reviewers and + # prevent-self-review, then define its READY sentinel only at environment scope. + environment: windows-native-installer-publication + outputs: + preview_id: ${{ steps.preview.outputs.artifact-id }} + preview_digest: ${{ steps.preview.outputs.artifact-digest }} + env: + CANDIDATE_SHA: ${{ inputs.candidate_sha }} + CONTROLLER_SHA: ${{ inputs.workflow_sha }} + SELECTED_AGENT: ${{ inputs.agent }} + PRODUCT_VERSION: ${{ inputs.product_version }} + steps: + - name: Require configured protected publication environment + shell: pwsh + env: + ENVIRONMENT_READY: ${{ secrets.WINDOWS_NATIVE_INSTALLER_PUBLICATION_READY }} + run: | + if ($env:ENVIRONMENT_READY -cne 'reviewed-main-v1') { throw 'The protected publication environment is not configured.' } + - name: Check out the exact trusted publication controller + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NVIDIA/NemoClaw + ref: ${{ inputs.workflow_sha }} + path: controller + persist-credentials: false + - name: Restore exact accepted installer cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-product-transfer + key: ${{ inputs.installer_cache_key }} + fail-on-cache-miss: true + - name: Verify exact accepted installer bytes + shell: pwsh + env: + INSTALLER_MANIFEST: ${{ inputs.installer_manifest_sha256 }} + run: | + $expectedMsi = "NemoClaw-$env:PRODUCT_VERSION-windows-arm64.msi" + $expectedSetup = "NemoClawSetup-$env:PRODUCT_VERSION-windows-arm64.exe" + $verifiedManifest = @(& "$env:GITHUB_WORKSPACE\controller\scripts\checks\windows-native-transfer.ps1" -Mode Verify ` + -Root "$env:RUNNER_TEMP\finished-windows-product-transfer" -Kind finished-installer ` + -SourceRevision $env:CANDIDATE_SHA -Agent $env:SELECTED_AGENT ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:INSTALLER_MANIFEST ` + -ExpectedPackageRunnables @($expectedMsi, $expectedSetup)) + if ($verifiedManifest.Count -ne 1 -or [string]$verifiedManifest[0] -cne $env:INSTALLER_MANIFEST) { + throw 'The publication transfer did not match the accepted bytes.' + } + - name: Publish fully qualified runnable installer + id: preview + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: qualified-windows-installer-${{ inputs.candidate_sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/finished-windows-product-transfer/package/NemoClawSetup-${{ inputs.product_version }}-windows-arm64.exe + ${{ runner.temp }}/finished-windows-product-transfer/package/immutable-package-build.json + ${{ runner.temp }}/finished-windows-product-transfer/package/compiled-msi.json + ${{ runner.temp }}/finished-windows-product-transfer/package/migration-inputs.json + ${{ runner.temp }}/finished-windows-product-transfer/assembled/runtime-identity.json + ${{ runner.temp }}/finished-windows-product-transfer/transfer-manifest.json + if-no-files-found: error + retention-days: 14 diff --git a/.github/workflows/windows-native-installer-v2.yaml b/.github/workflows/windows-native-installer-v2.yaml new file mode 100644 index 00000000000..38eff778c78 --- /dev/null +++ b/.github/workflows/windows-native-installer-v2.yaml @@ -0,0 +1,3235 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +name: CI / Native Windows Installer Candidate v2 + +# External prerequisite for secure use: administrators must permanently disable +# legacy Actions workflow ID 350766812 before enabling this fresh v2 workflow. +# This caller contains no secret references; qualification secrets belong only +# to the protected environments owned by its same-commit reusable controller. +# Finished installer publication requires explicit dispatch. +# The pinned legacy payload is used only by isolated diagnostic/profiling lanes. +on: + pull_request: + types: [opened, synchronize, reopened] + paths: + - ".github/actions/setup-reviewed-npm/**" + - ".github/workflows/windows-native-installer-v2.yaml" + - ".github/workflows/windows-native-installer-trusted.yaml" + - "bin/nemoclaw.js" + - "ci/reviewed-npm-audit.json" + - "packaging/windows/**" + - "scripts/checks/*windows-native*" + - "scripts/install-windows-native.ps1" + - "src/lib/onboard/runtime-provider/**" + - "test/automation/pull-requests/windows-native-installer-workflow.test.ts" + - "test/automation/pull-requests/windows-native-installer-bootstrap.test.ts" + - "test/automation/pull-requests/windows-native-installer-review.test.ts" + - "test/automation/pull-requests/windows-native-installer-process.test.ts" + - "test/automation/pull-requests/windows-native-installer-process.support.ts" + - "test/security/windows-native-*.test.ts" + - "test/support/windows-native-*.ts" + - "tools/windows-installer/**" + workflow_dispatch: + inputs: + finished_windows_pr_number: + description: Open internal PR number whose exact head will be qualified + required: false + default: "" + type: string + finished_windows_candidate_repository: + description: Exact internal head repository reported by that PR + required: false + default: "" + type: string + finished_windows_candidate_sha: + description: Exact 40-character PR head SHA to build + required: false + default: "" + type: string + finished_windows_base_sha: + description: Exact 40-character PR base SHA observed before dispatch + required: false + default: "" + type: string + finished_windows_workflow_sha: + description: Exact workflow SHA (main for qualification, PR head for credential-free build) + required: false + default: "" + type: string + finished_windows_agent: + description: Include only this agent in the finished installer + required: false + default: openclaw + type: choice + options: + - openclaw + - hermes + finished_windows_product_version: + description: MSI product version for the finished preview (must be newer than the legacy preview) + required: false + default: "0.1.10" + type: string + finished_windows_validation_scope: + description: Protected full lifecycle, credential-free OpenClaw startup, or candidate build only + required: false + default: full-acceptance + type: choice + options: + - full-acceptance + - startup-only + - build-only + build_windows_native_candidate: + description: Build an exact internal PR installer without credentials or installation; provide an unqualified Hermes download + required: false + default: false + type: boolean + run_windows_native_installer: + description: Build the selected finished native preview installer, then test it + required: false + default: false + type: boolean + windows_native_diagnostic_source_run_id: + description: Replay the fixed built 0.1.3 installer (source run 34555046495; no runtime overlay) + required: false + default: "" + type: string + profile_native_windows: + description: Diagnostic profiling of the exact installed f8 baseline only (no installer publication or comparison) + required: false + default: false + type: boolean + test_native_windows_runtime: + description: Run native ownership and guardian controls with isolated MSI fixtures + required: false + default: false + type: boolean + probe_official_hermes_components: + description: Run the selected official Hermes Windows probe without publishing an installer + required: false + default: false + type: boolean + record_hermes_startup: + description: Record a bounded diagnostic trace during the Personal Hermes probe + required: false + default: false + type: boolean + capture_hermes_renderer_context: + description: Capture bounded renderer context only in the failure debugger diagnostic + required: false + default: false + type: boolean + official_hermes_phase: + description: Official Hermes probe phase (requires the probe input above) + required: false + default: components + type: choice + options: + - components + - python + - runtime + - npm-shims + - export-controls + - edge-host-prerequisite + - personal-candidate + - personal-browser-first + - personal-cold-job + - personal-renderer-wer + - personal-postmortem + - trace-analysis + - bash-compat + - host-prerequisites + - system-drive + - application + +permissions: + actions: read + contents: read + +concurrency: + group: windows-native-installer-${{ github.ref }}${{ inputs.run_windows_native_installer && inputs.windows_native_diagnostic_source_run_id == '' && '-finished-package' || inputs.test_native_windows_runtime && '-runtime-controls' || inputs.profile_native_windows && '-profiling' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'python' && '-hermes-python' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'runtime' && '-hermes-runtime' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'npm-shims' && '-hermes-npm-shims' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'bash-compat' && '-bash-compat' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'personal-browser-first' && '-hermes-personal-browser-first' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'personal-postmortem' && '-hermes-personal-postmortem' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'personal-renderer-wer' && '-hermes-personal-renderer-wer' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'personal-cold-job' && '-hermes-personal-cold-job' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'personal-candidate' && '-hermes-personal-candidate' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'trace-analysis' && '-hermes-trace-analysis' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'export-controls' && '-hermes-export-controls' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'application' && '-compiled-application' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'host-prerequisites' && '-host-prerequisites' || inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'system-drive' && '-system-drive' || inputs.probe_official_hermes_components && '-hermes-components' || inputs.windows_native_diagnostic_source_run_id != '' && '-package-diagnostic' || '' }} + # Preserve explicit evidence runs while replacing stale pull request controls. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + windows-finished-request: + name: Resolve exact credential-free or trusted finished-installer request + if: ${{ github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + pull-requests: read + outputs: + request_kind: ${{ steps.pull_request.outputs.request_kind || steps.candidate_build.outputs.request_kind || steps.authorize.outputs.request_kind || steps.diagnostic.outputs.request_kind }} + candidate_repository: ${{ steps.pull_request.outputs.candidate_repository || steps.candidate_build.outputs.candidate_repository || steps.authorize.outputs.candidate_repository || steps.diagnostic.outputs.candidate_repository }} + candidate_sha: ${{ steps.pull_request.outputs.candidate_sha || steps.candidate_build.outputs.candidate_sha || steps.authorize.outputs.candidate_sha || steps.diagnostic.outputs.candidate_sha }} + base_sha: ${{ steps.pull_request.outputs.base_sha || steps.candidate_build.outputs.base_sha || steps.authorize.outputs.base_sha || steps.diagnostic.outputs.base_sha }} + pr_number: ${{ steps.pull_request.outputs.pr_number || steps.candidate_build.outputs.pr_number || steps.authorize.outputs.pr_number }} + workflow_sha: ${{ steps.pull_request.outputs.workflow_sha || steps.candidate_build.outputs.workflow_sha || steps.authorize.outputs.workflow_sha || steps.diagnostic.outputs.workflow_sha }} + agent: ${{ steps.pull_request.outputs.agent || steps.candidate_build.outputs.agent || steps.authorize.outputs.agent || steps.diagnostic.outputs.agent }} + product_version: ${{ steps.pull_request.outputs.product_version || steps.candidate_build.outputs.product_version || steps.authorize.outputs.product_version || steps.diagnostic.outputs.product_version }} + validation_scope: ${{ steps.pull_request.outputs.validation_scope || steps.candidate_build.outputs.validation_scope || steps.authorize.outputs.validation_scope || steps.diagnostic.outputs.validation_scope }} + build_allowed: ${{ steps.pull_request.outputs.build_allowed || steps.candidate_build.outputs.build_allowed || steps.authorize.outputs.build_allowed || steps.diagnostic.outputs.build_allowed }} + trusted_main: ${{ steps.pull_request.outputs.trusted_main || steps.candidate_build.outputs.trusted_main || steps.authorize.outputs.trusted_main || steps.diagnostic.outputs.trusted_main }} + exact_workflow: ${{ steps.pull_request.outputs.exact_workflow || steps.candidate_build.outputs.exact_workflow || steps.authorize.outputs.exact_workflow || steps.diagnostic.outputs.exact_workflow }} + exact_pr: ${{ steps.pull_request.outputs.exact_pr || steps.candidate_build.outputs.exact_pr || steps.authorize.outputs.exact_pr || steps.diagnostic.outputs.exact_pr }} + credential_authorized: ${{ steps.pull_request.outputs.credential_authorized || steps.candidate_build.outputs.credential_authorized || steps.authorize.outputs.credential_authorized || steps.diagnostic.outputs.credential_authorized }} + steps: + - name: Admit the exact pull request head without credentials + id: pull_request + if: ${{ github.event_name == 'pull_request' }} + shell: bash + env: + CANDIDATE_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }} + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + PR_NUMBER: ${{ github.event.pull_request.number }} + WORKFLOW_SHA: ${{ github.workflow_sha }} + run: | + set -euo pipefail + [[ "$CANDIDATE_REPOSITORY" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] + [[ "$CANDIDATE_SHA" =~ ^[a-f0-9]{40}$ && "$BASE_SHA" =~ ^[a-f0-9]{40}$ ]] + { + echo 'request_kind=pull-request' + echo "candidate_repository=$CANDIDATE_REPOSITORY" + echo "candidate_sha=$CANDIDATE_SHA" + echo "base_sha=$BASE_SHA" + echo "pr_number=$PR_NUMBER" + echo "workflow_sha=$WORKFLOW_SHA" + echo 'agent=openclaw' + echo 'product_version=0.1.10' + echo 'validation_scope=startup-only' + echo 'build_allowed=true' + echo 'trusted_main=false' + echo 'exact_workflow=false' + echo 'exact_pr=true' + echo 'credential_authorized=false' + } >> "$GITHUB_OUTPUT" + - name: Admit an exact credential-free candidate build + id: candidate_build + if: ${{ github.event_name == 'workflow_dispatch' && inputs.build_windows_native_candidate }} + shell: bash + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.finished_windows_pr_number }} + CANDIDATE_REPOSITORY: ${{ inputs.finished_windows_candidate_repository }} + CANDIDATE_SHA: ${{ inputs.finished_windows_candidate_sha }} + BASE_SHA: ${{ inputs.finished_windows_base_sha }} + EXPECTED_WORKFLOW_SHA: ${{ inputs.finished_windows_workflow_sha }} + SELECTED_AGENT: ${{ inputs.finished_windows_agent }} + PRODUCT_VERSION: ${{ inputs.finished_windows_product_version }} + VALIDATION_SCOPE: ${{ inputs.finished_windows_validation_scope }} + EVENT_SHA: ${{ github.sha }} + EVENT_WORKFLOW_SHA: ${{ github.workflow_sha }} + EVENT_REF: ${{ github.ref }} + ACTOR: ${{ github.actor }} + TRIGGERING_ACTOR: ${{ github.triggering_actor }} + PROTECTED_REQUEST: ${{ inputs.run_windows_native_installer }} + OTHER_COMPONENTS: ${{ inputs.probe_official_hermes_components }} + OTHER_PROFILE: ${{ inputs.profile_native_windows }} + OTHER_RUNTIME: ${{ inputs.test_native_windows_runtime }} + DIAGNOSTIC_SOURCE_RUN: ${{ inputs.windows_native_diagnostic_source_run_id }} + run: | + set -euo pipefail + [[ "$GITHUB_REPOSITORY" == 'NVIDIA/NemoClaw' && "$CANDIDATE_REPOSITORY" == "$GITHUB_REPOSITORY" ]] + [[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]] + [[ "$CANDIDATE_SHA" =~ ^[a-f0-9]{40}$ && "$BASE_SHA" =~ ^[a-f0-9]{40}$ ]] + [[ "$EXPECTED_WORKFLOW_SHA" == "$CANDIDATE_SHA" && "$EVENT_SHA" == "$CANDIDATE_SHA" && "$EVENT_WORKFLOW_SHA" == "$CANDIDATE_SHA" ]] + [[ "$SELECTED_AGENT" =~ ^(openclaw|hermes)$ && "$VALIDATION_SCOPE" == 'build-only' ]] + [[ "$PRODUCT_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] + [[ "$PROTECTED_REQUEST" == 'false' && "$OTHER_COMPONENTS" == 'false' && "$OTHER_PROFILE" == 'false' && "$OTHER_RUNTIME" == 'false' && -z "$DIAGNOSTIC_SOURCE_RUN" ]] + pr="$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")" + [[ "$(jq -r '.number' <<<"$pr")" == "$PR_NUMBER" && "$(jq -r '.state' <<<"$pr")" == 'open' ]] + [[ "$(jq -r '.base.repo.full_name' <<<"$pr")" == "$GITHUB_REPOSITORY" && "$(jq -r '.base.ref' <<<"$pr")" == 'main' ]] + [[ "$(jq -r '.base.sha' <<<"$pr")" == "$BASE_SHA" ]] + [[ "$(jq -r '.head.repo.full_name' <<<"$pr")" == "$CANDIDATE_REPOSITORY" ]] + [[ "$(jq -r '.head.repo.owner.login' <<<"$pr")" == 'NVIDIA' && "$(jq -r '.head.repo.owner.type' <<<"$pr")" == 'Organization' ]] + [[ "$(jq -r '.head.sha' <<<"$pr")" == "$CANDIDATE_SHA" ]] + [[ "$EVENT_REF" == "refs/heads/$(jq -r '.head.ref' <<<"$pr")" && "$EVENT_REF" != 'refs/heads/main' ]] + for principal in "$ACTOR" "$TRIGGERING_ACTOR"; do + permission="$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$principal/permission" --jq '.permission')" + [[ "$permission" =~ ^(admin|maintain|write)$ ]] + done + current="$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")" + for field in '.number' '.state' '.base.repo.full_name' '.base.ref' '.base.sha' '.head.repo.full_name' '.head.repo.owner.login' '.head.repo.owner.type' '.head.ref' '.head.sha'; do + [[ "$(jq -r "$field" <<<"$current")" == "$(jq -r "$field" <<<"$pr")" ]] + done + { + echo 'request_kind=candidate-build' + echo "candidate_repository=$CANDIDATE_REPOSITORY" + echo "candidate_sha=$CANDIDATE_SHA" + echo "base_sha=$BASE_SHA" + echo "pr_number=$PR_NUMBER" + echo "workflow_sha=$EXPECTED_WORKFLOW_SHA" + echo "agent=$SELECTED_AGENT" + echo "product_version=$PRODUCT_VERSION" + echo 'validation_scope=build-only' + echo 'build_allowed=true' + echo 'trusted_main=false' + echo 'exact_workflow=false' + echo 'exact_pr=true' + echo 'credential_authorized=false' + } >> "$GITHUB_OUTPUT" + - name: Resolve a credential-free diagnostic dispatch + id: diagnostic + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.build_windows_native_candidate && !(inputs.run_windows_native_installer && inputs.windows_native_diagnostic_source_run_id == '') }} + shell: bash + env: + CANDIDATE_SHA: ${{ github.sha }} + WORKFLOW_SHA: ${{ github.workflow_sha }} + SELECTED_AGENT: ${{ inputs.finished_windows_agent || 'openclaw' }} + PRODUCT_VERSION: ${{ inputs.finished_windows_product_version || '0.1.10' }} + VALIDATION_SCOPE: ${{ inputs.finished_windows_validation_scope || 'startup-only' }} + run: | + set -euo pipefail + { + echo 'request_kind=diagnostic' + echo "candidate_repository=$GITHUB_REPOSITORY" + echo "candidate_sha=$CANDIDATE_SHA" + echo "base_sha=$CANDIDATE_SHA" + echo "workflow_sha=$WORKFLOW_SHA" + echo "agent=$SELECTED_AGENT" + echo "product_version=$PRODUCT_VERSION" + echo "validation_scope=$VALIDATION_SCOPE" + echo 'build_allowed=false' + echo 'trusted_main=false' + echo 'exact_workflow=false' + echo 'exact_pr=false' + echo 'credential_authorized=false' + } >> "$GITHUB_OUTPUT" + - name: Authorize exact internal PR from the exact main controller + id: authorize + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.build_windows_native_candidate && inputs.run_windows_native_installer && inputs.windows_native_diagnostic_source_run_id == '' }} + shell: bash + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.finished_windows_pr_number }} + CANDIDATE_REPOSITORY: ${{ inputs.finished_windows_candidate_repository }} + CANDIDATE_SHA: ${{ inputs.finished_windows_candidate_sha }} + BASE_SHA: ${{ inputs.finished_windows_base_sha }} + EXPECTED_WORKFLOW_SHA: ${{ inputs.finished_windows_workflow_sha }} + SELECTED_AGENT: ${{ inputs.finished_windows_agent }} + PRODUCT_VERSION: ${{ inputs.finished_windows_product_version }} + VALIDATION_SCOPE: ${{ inputs.finished_windows_validation_scope }} + EVENT_SHA: ${{ github.sha }} + EVENT_WORKFLOW_SHA: ${{ github.workflow_sha }} + EVENT_REF: ${{ github.ref }} + ACTOR: ${{ github.actor }} + TRIGGERING_ACTOR: ${{ github.triggering_actor }} + run: | + set -euo pipefail + [[ "$GITHUB_REPOSITORY" == 'NVIDIA/NemoClaw' && "$EVENT_REF" == 'refs/heads/main' ]] + [[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]] + [[ "$CANDIDATE_REPOSITORY" == 'NVIDIA/NemoClaw' ]] + [[ "$CANDIDATE_SHA" =~ ^[a-f0-9]{40}$ && "$BASE_SHA" =~ ^[a-f0-9]{40}$ && "$EXPECTED_WORKFLOW_SHA" =~ ^[a-f0-9]{40}$ ]] + [[ "$EVENT_SHA" == "$EXPECTED_WORKFLOW_SHA" && "$EVENT_WORKFLOW_SHA" == "$EXPECTED_WORKFLOW_SHA" ]] + [[ "$BASE_SHA" == "$EXPECTED_WORKFLOW_SHA" ]] + [[ "$SELECTED_AGENT" =~ ^(openclaw|hermes)$ && "$VALIDATION_SCOPE" == 'full-acceptance' ]] + [[ "$PRODUCT_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] + pr="$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")" + [[ "$(jq -r '.state' <<<"$pr")" == 'open' ]] + [[ "$(jq -r '.base.repo.full_name' <<<"$pr")" == "$GITHUB_REPOSITORY" ]] + [[ "$(jq -r '.base.ref' <<<"$pr")" == 'main' ]] + [[ "$(jq -r '.base.sha' <<<"$pr")" == "$BASE_SHA" ]] + [[ "$(jq -r '.head.repo.full_name' <<<"$pr")" == "$CANDIDATE_REPOSITORY" ]] + [[ "$(jq -r '.head.repo.owner.login' <<<"$pr")" == 'NVIDIA' ]] + [[ "$(jq -r '.head.repo.owner.type' <<<"$pr")" == 'Organization' ]] + [[ "$(jq -r '.head.sha' <<<"$pr")" == "$CANDIDATE_SHA" ]] + comparison="$(gh api "repos/$GITHUB_REPOSITORY/compare/$EXPECTED_WORKFLOW_SHA...$CANDIDATE_SHA")" + [[ "$(jq -r '.merge_base_commit.sha' <<<"$comparison")" == "$EXPECTED_WORKFLOW_SHA" ]] + [[ "$(jq -r '.behind_by' <<<"$comparison")" == '0' ]] + for principal in "$ACTOR" "$TRIGGERING_ACTOR"; do + permission="$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$principal/permission" --jq '.permission')" + [[ "$permission" =~ ^(admin|maintain|write)$ ]] + done + { + echo 'request_kind=trusted-manual' + echo "candidate_repository=$CANDIDATE_REPOSITORY" + echo "candidate_sha=$CANDIDATE_SHA" + echo "base_sha=$BASE_SHA" + echo "pr_number=$PR_NUMBER" + echo "workflow_sha=$EXPECTED_WORKFLOW_SHA" + echo "agent=$SELECTED_AGENT" + echo "product_version=$PRODUCT_VERSION" + echo "validation_scope=$VALIDATION_SCOPE" + echo 'build_allowed=true' + echo 'trusted_main=true' + echo 'exact_workflow=true' + echo 'exact_pr=true' + echo 'credential_authorized=true' + } >> "$GITHUB_OUTPUT" + + windows-personal-trace-analysis: + name: Recorded Hermes Personal trace analysis (no application execution) + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && !inputs.profile_native_windows && !inputs.test_native_windows_runtime && inputs.windows_native_diagnostic_source_run_id == '' && inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'trace-analysis' }} + runs-on: windows-11-vs2026-arm + # Fixed recorded input; eight bounded analysis commands plus intake/upload. + timeout-minutes: 25 + steps: + - name: Check out the trace analysis controller + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Verify and analyze the exact recorded 51e3 light trace + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: | + & "$env:GITHUB_WORKSPACE\packaging\windows\performance\analyze-personal-wpr.ps1" ` + -ArtifactDirectory "$env:RUNNER_TEMP\personal-trace-analysis" + - name: Preserve bounded analysis reports and original small trace metadata + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: official-hermes-personal-trace-analysis-${{ github.sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/personal-trace-analysis/ + !${{ runner.temp }}/personal-trace-analysis/recorded-trace.zip + !${{ runner.temp }}/personal-trace-analysis/input/**/*.etl + if-no-files-found: error + retention-days: 14 + + windows-finished-installer: + name: Finished Windows ${{ needs.windows-finished-request.outputs.agent }} candidate installer (ARM64) + needs: + [windows-finished-request, windows-compiled-application, windows-bash-compatibility-reuse] + if: ${{ always() && !cancelled() && needs.windows-finished-request.result == 'success' && needs.windows-finished-request.outputs.build_allowed == 'true' && needs.windows-compiled-application.result == 'success' && (needs.windows-finished-request.outputs.agent != 'hermes' || needs.windows-bash-compatibility-reuse.result == 'success') }} + runs-on: windows-11-vs2026-arm + timeout-minutes: ${{ needs.windows-finished-request.outputs.agent == 'hermes' && 180 || 120 }} + outputs: + installer_cache_key: ${{ steps.product_manifest.outputs.cache_key }} + installer_manifest_sha256: ${{ steps.product_manifest.outputs.manifest_sha256 }} + env: + CANDIDATE_SHA: ${{ needs.windows-finished-request.outputs.candidate_sha }} + SELECTED_AGENT: ${{ needs.windows-finished-request.outputs.agent }} + PRODUCT_VERSION: ${{ needs.windows-finished-request.outputs.product_version }} + steps: + - name: Check out the finished Windows application source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ needs.windows-finished-request.outputs.candidate_repository }} + ref: ${{ needs.windows-finished-request.outputs.candidate_sha }} + path: candidate + persist-credentials: false + - name: Validate the dedicated finished preview request + shell: pwsh + env: + OTHER_COMPONENTS: ${{ inputs.probe_official_hermes_components }} + OTHER_PROFILE: ${{ inputs.profile_native_windows }} + OTHER_RUNTIME: ${{ inputs.test_native_windows_runtime }} + run: | + $parsedVersion = $null + if ($env:PRODUCT_VERSION -cnotmatch '^[0-9]+\.[0-9]+\.[0-9]+$' -or -not [version]::TryParse($env:PRODUCT_VERSION, [ref]$parsedVersion) -or $parsedVersion -le [version]'0.1.4') { + throw 'The finished preview needs an explicit MSI version newer than migration baseline 0.1.4.' + } + if (@($env:OTHER_COMPONENTS, $env:OTHER_PROFILE, $env:OTHER_RUNTIME) -contains 'true') { + throw 'The finished preview requires its own explicit dispatch.' + } + - name: Restore exact compiled units from the same-run cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-application-transfer + key: ${{ needs.windows-compiled-application.outputs.application_cache_key }} + fail-on-cache-miss: true + - name: Verify and materialize the exact compiled units + shell: pwsh + env: + EXPECTED_MANIFEST: ${{ needs.windows-compiled-application.outputs.application_manifest_sha256 }} + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $transfer = "$env:RUNNER_TEMP\finished-windows-application-transfer" + $verifiedManifest = @(& "$env:GITHUB_WORKSPACE\candidate\scripts\checks\windows-native-transfer.ps1" -Mode Verify -Root $transfer ` + -Kind compiled-application -SourceRevision $env:CANDIDATE_SHA -Agent $env:SELECTED_AGENT ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:EXPECTED_MANIFEST) + if ($verifiedManifest.Count -ne 1 -or [string]$verifiedManifest[0] -cne $env:EXPECTED_MANIFEST) { + throw 'The compiled application transfer is not exact.' + } + $work = "$env:RUNNER_TEMP\finished-windows" + [void][IO.Directory]::CreateDirectory($work) + Copy-Item -LiteralPath "$transfer\application" -Destination "$work\application" -Recurse + Copy-Item -LiteralPath "$transfer\runtime" -Destination "$work\runtime" -Recurse + - name: Prepare pinned native Rust + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.95.0-aarch64-pc-windows-msvc + target: aarch64-pc-windows-msvc + cache: false + rustflags: "" + - name: Prepare pinned native .NET + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 8.0.419 + - name: Prepare build-only Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.1.0 + with: + python-version: 3.13.13 + architecture: arm64 + - name: Check exact helper-proof consumption controls + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & python -m unittest discover -s "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer" -p 'test_verify_system_drive_proof.py' -v + if ($LASTEXITCODE -ne 0) { throw 'The helper-proof consumption controls failed.' } + & python -m unittest discover -s "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer" -p 'test_materialize_compiled_executable.py' -v + if ($LASTEXITCODE -ne 0) { throw 'The compiled artifact materialization controls failed.' } + & python -m unittest discover -s "$env:GITHUB_WORKSPACE\candidate\packaging\windows\app" -p 'test_materialize_openclaw_build.py' -v + if ($LASTEXITCODE -ne 0) { throw 'The locked OpenClaw dependency materialization controls failed.' } + & python -m unittest discover -s "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer" -p 'test_prepare_finished_host.py' -v + if ($LASTEXITCODE -ne 0) { throw 'The native host inventory and license controls failed.' } + & python -m unittest discover -s "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer" -p 'test_openshell_source.py' -v + if ($LASTEXITCODE -ne 0) { throw 'The locked OpenShell source controls failed.' } + - name: Check out the pinned OpenShell host source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NVIDIA/OpenShell + ref: 624f55b3c6affedd4f2757c7eb32132196b4c3e8 + path: openshell + persist-credentials: false + - name: Build and test the pinned OpenShell host-supervisor stack + working-directory: openshell + shell: pwsh + env: + RUSTUP_TOOLCHAIN: 1.95.0-aarch64-pc-windows-msvc + run: | + $ErrorActionPreference = 'Stop' + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + $revision = (& git rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $revision -cne '624f55b3c6affedd4f2757c7eb32132196b4c3e8') { throw 'Unexpected OpenShell source.' } + $status = & git status --porcelain + if ($LASTEXITCODE -ne 0 -or $status) { throw 'The OpenShell checkout is not clean.' } + $sourceHelper = "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\openshell_source.py" + $sourceJson = & python $sourceHelper apply $PWD.Path + if ($LASTEXITCODE -ne 0) { throw 'The locked OpenShell derivative could not be applied.' } + $sourceIdentity = $sourceJson | ConvertFrom-Json + $env:CARGO_TARGET_DIR = "$work\openshell-target" + if (Test-Path -LiteralPath $env:CARGO_TARGET_DIR) { throw 'OpenShell must build into a fresh target directory.' } + # Load the pinned build helpers without running their unlocked build action. + . .\tasks\scripts\windows-msvc.ps1 artifacts aarch64-pc-windows-msvc -LogDir "$work\openshell-logs" + if ($env:Z3_LIBRARY_PATH_OVERRIDE) { throw 'The host build requires the pinned prebuilt Z3, not a machine override.' } + $z3Features = Configure-Z3 + $env:LIBCLANG_PATH = Resolve-LibclangPath + Add-PathEntry $env:LIBCLANG_PATH + Configure-Arm64CrossBuild @('aarch64-pc-windows-msvc') + Invoke-VsCargo -RustTarget 'aarch64-pc-windows-msvc' ` + -CargoArgs "cargo build --locked --release --target aarch64-pc-windows-msvc --bin openshell --bin openshell-gateway --bin openshell-supervisor --bin openshell-windows-sandbox $($z3Features.WorkspaceFeatures)" ` + -LogName 'host-supervisor-build.log' + Stage-Z3Runtime 'aarch64-pc-windows-msvc' + Assert-NativeTestTarget 'aarch64-pc-windows-msvc' + Invoke-VsCargo -RustTarget 'aarch64-pc-windows-msvc' ` + -CargoArgs 'cargo test --locked --release --target aarch64-pc-windows-msvc -p openshell-driver-mxc -p openshell-mxc-boundary --lib -- --test-threads=1' ` + -LogName 'mxc-driver-tests.log' + & python $sourceHelper verify $PWD.Path + if ($LASTEXITCODE -ne 0) { throw 'OpenShell source changed during the build.' } + $afterRevision = (& git rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $afterRevision -cne $revision) { throw 'OpenShell revision changed during the build.' } + $output = "$work\openshell-binaries" + New-Item -ItemType Directory -Path $output -ErrorAction Stop | Out-Null + $files = foreach ($name in @('openshell.exe', 'openshell-gateway.exe', 'openshell-supervisor.exe', 'openshell-windows-sandbox.exe', 'libz3.dll')) { + $binary = Join-Path $env:CARGO_TARGET_DIR "aarch64-pc-windows-msvc\release\$name" + $hash = (Get-FileHash -LiteralPath $binary -Algorithm SHA256).Hash.ToLowerInvariant() + $copy = Join-Path $output $name + Copy-Item -LiteralPath $binary -Destination $copy -ErrorAction Stop + if ((Get-FileHash -LiteralPath $copy -Algorithm SHA256).Hash.ToLowerInvariant() -cne $hash) { throw 'OpenShell build copy changed.' } + @{ file = $name; bytes = (Get-Item -LiteralPath $copy).Length; sha256 = $hash } + } + @{ + schemaVersion = 1 + classification = 'ci-built-openshell-host-binaries' + requestedSourceRevision = $env:GITHUB_SHA + openshellRevision = $revision + derivativePatchSha256 = $sourceIdentity.patchSha256 + sourceTree = $sourceIdentity.patchedTree + sourceUnchanged = $true + rustToolchain = $env:RUSTUP_TOOLCHAIN + rustTarget = 'aarch64-pc-windows-msvc' + workflowRunId = $env:GITHUB_RUN_ID + workflowRunAttempt = $env:GITHUB_RUN_ATTEMPT + files = @($files) + currentPackageQualification = $false + } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath "$output\openshell-build.json" -Encoding utf8NoBOM + # The verified binaries and logs above are the downstream inputs. + $completedCargoTarget = [IO.Path]::GetFullPath($env:CARGO_TARGET_DIR) + $expectedCargoTarget = [IO.Path]::GetFullPath((Join-Path $env:RUNNER_TEMP 'finished-windows\openshell-target')) + if ($completedCargoTarget -cne $expectedCargoTarget -or (Get-Item -LiteralPath $completedCargoTarget).Attributes.HasFlag([IO.FileAttributes]::ReparsePoint) -or + @(Get-ChildItem -LiteralPath $completedCargoTarget -Recurse -Force -Attributes ReparsePoint).Count -ne 0) { + throw 'The completed OpenShell build target is not an ordinary runner-owned tree.' + } + Remove-Item -LiteralPath $completedCargoTarget -Recurse -Force + - name: Check out the MXC source used by the Windows-tip qualification + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: microsoft/mxc + ref: 7cd00d1ee6af9208322c924ef64e5113f6704639 + path: mxc + persist-credentials: false + - name: Build the pinned MXC executor and host preparation tool + working-directory: mxc/src + shell: pwsh + env: + RUSTUP_TOOLCHAIN: 1.93.0-aarch64-pc-windows-msvc + run: | + $ErrorActionPreference = 'Stop' + $work = "$env:RUNNER_TEMP\finished-windows" + $revision = (& git rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $revision -cne '7cd00d1ee6af9208322c924ef64e5113f6704639') { throw 'Unexpected MXC source.' } + $status = & git status --porcelain + if ($LASTEXITCODE -ne 0 -or $status) { throw 'The MXC checkout is not clean.' } + & rustup toolchain install $env:RUSTUP_TOOLCHAIN --profile minimal + if ($LASTEXITCODE -ne 0) { throw 'Installing the pinned MXC Rust toolchain failed.' } + $env:CARGO_TARGET_DIR = "$work\mxc-target" + if (Test-Path -LiteralPath $env:CARGO_TARGET_DIR) { throw 'MXC must build into a fresh target directory.' } + . "$env:GITHUB_WORKSPACE\openshell\tasks\scripts\windows-msvc.ps1" artifacts aarch64-pc-windows-msvc -LogDir "$work\mxc-logs" + Assert-NativeTestTarget 'aarch64-pc-windows-msvc' + Invoke-VsCargo -RustTarget 'aarch64-pc-windows-msvc' ` + -CargoArgs 'cargo build --locked --release --target aarch64-pc-windows-msvc --bin wxc-exec --bin wxc-host-prep' ` + -LogName 'mxc-host-build.log' + $status = & git status --porcelain + if ($LASTEXITCODE -ne 0 -or $status) { throw 'MXC source changed during the build.' } + $afterRevision = (& git rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $afterRevision -cne $revision) { throw 'MXC revision changed during the build.' } + $output = "$work\mxc-binaries" + New-Item -ItemType Directory -Path $output -ErrorAction Stop | Out-Null + $files = foreach ($name in @('wxc-exec.exe', 'wxc-host-prep.exe')) { + $binary = Join-Path $env:CARGO_TARGET_DIR "aarch64-pc-windows-msvc\release\$name" + $hash = (Get-FileHash -LiteralPath $binary -Algorithm SHA256).Hash.ToLowerInvariant() + $copy = Join-Path $output $name + Copy-Item -LiteralPath $binary -Destination $copy -ErrorAction Stop + if ((Get-FileHash -LiteralPath $copy -Algorithm SHA256).Hash.ToLowerInvariant() -cne $hash) { throw 'MXC build copy changed.' } + @{ file = $name; bytes = (Get-Item -LiteralPath $copy).Length; sha256 = $hash } + } + Copy-Item -LiteralPath '..\LICENSE.md' -Destination "$output\LICENSE.md" -ErrorAction Stop + $licenseHash = (Get-FileHash -LiteralPath "$output\LICENSE.md" -Algorithm SHA256).Hash.ToLowerInvariant() + if ($licenseHash -cne 'd9a1b1e30d633d5732ea18e3cba9538d293ebc53e1a9e4e96ab739e0c5c4f1cb') { throw 'Unexpected MXC license.' } + @{ + schemaVersion = 1 + classification = 'ci-built-mxc-host-binaries' + requestedSourceRevision = $env:CANDIDATE_SHA + mxcRevision = $revision + sourceUnchanged = $true + rustToolchain = $env:RUSTUP_TOOLCHAIN + rustTarget = 'aarch64-pc-windows-msvc' + workflowRunId = $env:GITHUB_RUN_ID + workflowRunAttempt = $env:GITHUB_RUN_ATTEMPT + licenseSha256 = $licenseHash + files = @($files) + currentPackageQualification = $false + } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath "$output\mxc-build.json" -Encoding utf8NoBOM + $completedCargoTarget = [IO.Path]::GetFullPath($env:CARGO_TARGET_DIR) + $expectedCargoTarget = [IO.Path]::GetFullPath((Join-Path $env:RUNNER_TEMP 'finished-windows\mxc-target')) + if ($completedCargoTarget -cne $expectedCargoTarget -or (Get-Item -LiteralPath $completedCargoTarget).Attributes.HasFlag([IO.FileAttributes]::ReparsePoint) -or + @(Get-ChildItem -LiteralPath $completedCargoTarget -Recurse -Force -Attributes ReparsePoint).Count -ne 0) { + throw 'The completed MXC build target is not an ordinary runner-owned tree.' + } + Remove-Item -LiteralPath $completedCargoTarget -Recurse -Force + - name: Prepare native host files without any legacy agent tree + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + & python "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\prepare-finished-host.py" ` + --source-root "$env:GITHUB_WORKSPACE\candidate" --openshell-binaries "$work\openshell-binaries" ` + --mxc-binaries "$work\mxc-binaries" --node-root "$work\application\node" --output "$work\host" + if ($LASTEXITCODE -ne 0) { throw 'Native host input preparation failed.' } + - name: Build and prove the exact native system-drive prerequisite + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + $owner = "$env:GITHUB_WORKSPACE\candidate\packaging\windows\host-preparation" + & "$owner\build-helper.ps1" -OutputDirectory "$work\system-drive-helper" + & "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -File "$owner\test-system-root-mxc.ps1" ` + -HelperPath "$work\system-drive-helper\NemoClawHostPreparation.exe" -MxcDirectory "$work\host\mxc" ` + -NodePath "$work\host\bin\node.exe" -ArtifactDirectory "$work\system-drive-proof" ` + -HostPayloadReceipt "$work\host\runtime-payload-receipt.json" + if ($LASTEXITCODE -ne 0) { throw 'The exact helper did not pass actual system-root and contained Node proof.' } + - name: Seal the finished application and selected OpenClaw resources + if: ${{ needs.windows-finished-request.outputs.agent == 'openclaw' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + $owner = "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer" + $inputs = @("$work\host\runtime-payload-receipt.json", "$work\application\build\app\openclaw-resource-closure.json", "$work\runtime\workers\build.json", "$work\runtime\executable\build.json") + $identityText = ($inputs | ForEach-Object { (Get-FileHash -LiteralPath $_ -Algorithm SHA256).Hash.ToLowerInvariant() }) -join "`n" + $component = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($identityText))).ToLowerInvariant() + & python "$owner\assign_runtime_namespace.py" --receipt "$work\namespace.json" --source-revision $env:GITHUB_SHA --component-identity $component + if ($LASTEXITCODE -ne 0) { throw 'Immutable namespace assignment failed.' } + & python "$owner\assemble_runtime.py" --output "$work\assembled" ` + --agent "openclaw=$work\application\build\app" --shared-node "$work\host\bin\node.exe" ` + --node-version 22.23.2 --source-revision $env:GITHUB_SHA --component-identity $component ` + --namespace-receipt "$work\namespace.json" --worker-build "$work\runtime\workers" --executable-build "$work\runtime\executable" + if ($LASTEXITCODE -ne 0) { throw 'The finished runtime could not be sealed.' } + - name: Restore the exact same-run compatibility component and proof + if: ${{ needs.windows-finished-request.outputs.agent == 'hermes' }} + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-bash-transfer + key: ${{ needs.windows-bash-compatibility-reuse.outputs.compatibility_cache_key }} + fail-on-cache-miss: true + enableCrossOsArchive: true + - name: Verify and materialize exact same-run compatibility proof + if: ${{ needs.windows-finished-request.outputs.agent == 'hermes' }} + shell: pwsh + env: + EXPECTED_MANIFEST: ${{ needs.windows-bash-compatibility-reuse.outputs.compatibility_manifest_sha256 }} + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $transfer = "$env:RUNNER_TEMP\finished-windows-bash-transfer" + $verifiedManifest = @(& "$env:GITHUB_WORKSPACE\candidate\scripts\checks\windows-native-transfer.ps1" -Mode Verify -Root $transfer ` + -Kind bash-compatibility -SourceRevision $env:CANDIDATE_SHA -Agent hermes ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:EXPECTED_MANIFEST) + if ($verifiedManifest.Count -ne 1 -or [string]$verifiedManifest[0] -cne $env:EXPECTED_MANIFEST) { + throw 'The Bash compatibility transfer is not exact.' + } + Copy-Item -LiteralPath "$transfer\native-proof" -Destination "$env:RUNNER_TEMP\finished-windows\native-proof" -Recurse + - name: Prepare pinned interpreters for the finished Hermes producer + if: ${{ needs.windows-finished-request.outputs.agent == 'hermes' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\hermes\test-official-runtime-export.ps1" ` + -ArtifactDirectory "$env:RUNNER_TEMP\finished-windows\personal-bootstrap" + - name: Produce and test Hermes with the same-run native binaries + if: ${{ needs.windows-finished-request.outputs.agent == 'hermes' }} + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + $revision = (& git -C "$env:GITHUB_WORKSPACE\candidate" rev-parse HEAD | Out-String).Trim() + if ($LASTEXITCODE -ne 0 -or $revision -cne $env:CANDIDATE_SHA) { throw 'Hermes producer checkout differs from the admitted candidate.' } + $rustc = & rustup which --toolchain 1.95.0-aarch64-pc-windows-msvc rustc + if ($LASTEXITCODE -ne 0) { throw 'The pinned ConPTY compiler is unavailable.' } + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\hermes\probe-personal-candidate.ps1" ` + -ArtifactDirectory "$work\personal-production" -BootstrapDirectory "$work\personal-bootstrap" ` + -HelperDirectory "$work\system-drive-helper" -NativeCompatibilityDirectory "$work\native-proof\bash-compat-evidence" ` + -PreparedHostRoot "$work\host" -PreparedSystemRootProof "$work\system-drive-proof" ` + -RustBinDirectory (Split-Path -Parent $rustc) + - name: Admit the same-run Personal-passing complete Hermes candidate + if: ${{ needs.windows-finished-request.outputs.agent == 'hermes' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + & python "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\prepare-finished-hermes.py" ` + --same-run-personal-directory "$work\personal-production" ` + --output "$work\hermes-input" --native-proof-directory "$work\native-proof\bash-compat-evidence" --source-revision $env:GITHUB_SHA + if ($LASTEXITCODE -ne 0) { throw 'The exact complete Personal-passing Hermes input was not admitted.' } + - name: Seal only Hermes with current-source native compatibility and precompiled workers + if: ${{ needs.windows-finished-request.outputs.agent == 'hermes' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + $owner = "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer" + $proof = "$work\native-proof\bash-compat-evidence" + $installedRoot = Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::ProgramFiles)) 'NVIDIA\NemoClaw' + $inputs = @("$work\host\runtime-payload-receipt.json", "$work\hermes-input\intake.json", "$proof\result.json", "$proof\compatibility-build\build-receipt.json", "$proof\mxc-token-inspection-build\mxc-token-inspection-build.json", "$work\runtime\workers\build.json", "$work\runtime\executable\build.json") + $identityText = ($inputs | ForEach-Object { (Get-FileHash -LiteralPath $_ -Algorithm SHA256).Hash.ToLowerInvariant() }) -join "`n" + $component = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($identityText))).ToLowerInvariant() + & python "$owner\assign_runtime_namespace.py" --receipt "$work\namespace.json" --source-revision $env:GITHUB_SHA --component-identity $component + if ($LASTEXITCODE -ne 0) { throw 'Immutable Hermes namespace assignment failed.' } + $intake = Get-Content -LiteralPath "$work\hermes-input\intake.json" -Raw | ConvertFrom-Json + $candidatePath = "$work\hermes-input\candidate\runtime-candidate.json" + if ((Get-FileHash -LiteralPath $candidatePath -Algorithm SHA256).Hash.ToLowerInvariant() -cne $intake.personalInput.candidateReceiptSha256) { + throw 'The admitted Hermes candidate receipt changed before worker compilation.' + } + $candidate = Get-Content -LiteralPath $candidatePath -Raw | ConvertFrom-Json + $inventoryPath = "$work\hermes-input\candidate\payload-inventory.json" + if ((Get-FileHash -LiteralPath $inventoryPath -Algorithm SHA256).Hash.ToLowerInvariant() -cne $candidate.inventorySha256) { + throw 'The admitted Hermes interpreter inventory changed.' + } + $inventory = Get-Content -LiteralPath $inventoryPath -Raw | ConvertFrom-Json + $pythonRelative = 'hermes-agent/.hermes-runtime/python/cpython-3.11.16-windows-aarch64-none/python.exe' + $pythonRows = @($inventory.files | Where-Object path -CEQ $pythonRelative) + $hermesPython = Join-Path "$work\hermes-input\runtime" $pythonRelative + $pythonFile = Get-Item -LiteralPath $hermesPython -Force + if ($pythonRows.Count -ne 1 -or $pythonFile.PSIsContainer -or $pythonFile.Attributes.HasFlag([IO.FileAttributes]::ReparsePoint) -or + $pythonFile.Length -ne $pythonRows[0].bytes -or (Get-FileHash -LiteralPath $hermesPython -Algorithm SHA256).Hash.ToLowerInvariant() -cne $pythonRows[0].sha256) { + throw 'The shipping Hermes core interpreter differs from its admitted bytes.' + } + $namespace = Get-Content -LiteralPath "$work\namespace.json" -Raw | ConvertFrom-Json + if ([string]$namespace.runtimeId -cnotmatch '^[a-f0-9]{64}$') { throw 'The assigned Hermes worker namespace is invalid.' } + $installedWorkers = Join-Path (Join-Path $installedRoot ('runtimes\'+$namespace.runtimeId)) 'workers' + $pythonWorkers = "$work\runtime\workers\python\hermes" + & $hermesPython -I -S -B "$env:GITHUB_WORKSPACE\candidate\packaging\windows\distribution\prepare-python-bytecode.py" ` + --agent hermes --worker-inputs "$work\runtime\workers\python-build-inputs" --workers-output $pythonWorkers ` + --installed-workers $installedWorkers --report "$pythonWorkers\bytecode.json" + if ($LASTEXITCODE -ne 0) { throw 'The shipping Hermes interpreter could not compile the static workers in CI.' } + & python "$owner\assemble_runtime.py" --output "$work\assembled" ` + --agent "hermes=$work\hermes-input\runtime" --canonical-hermes-receipt "$work\hermes-input\candidate\runtime-candidate.json" ` + --canonical-hermes-personal-proof "$work\hermes-input\personal-feasibility.json" --target-install-root $installedRoot ` + --hermes-executor-directory "$proof\mxc-token-inspection-build" --hermes-compatibility-directory "$proof\compatibility-build" --hermes-compatibility-proof "$proof\result.json" ` + --shared-node "$work\host\bin\node.exe" --node-version 22.23.2 --source-revision $env:GITHUB_SHA --component-identity $component ` + --namespace-receipt "$work\namespace.json" --worker-build "$work\runtime\workers" --executable-build "$work\runtime\executable" + if ($LASTEXITCODE -ne 0) { throw 'The complete Hermes runtime could not be finalized and sealed.' } + - name: Build the selected runtime as one finished application image + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + $identity = Get-Content -LiteralPath "$work\assembled\runtime-identity.json" -Raw | ConvertFrom-Json + if ($env:SELECTED_AGENT -ceq 'hermes') { + Remove-Item -LiteralPath "$work\hermes-input\runtime" -Recurse -Force + } + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\build-finished-runtime-image.ps1" ` + -RuntimeRoot "$work\assembled\runtimes\$($identity.runtimeId)" -RuntimeId $identity.runtimeId ` + -OutputImage "$work\runtime-image\$($identity.runtimeId).vhdx" ` + -ReceiptPath "$work\runtime-image\runtime-image.json" + - name: Build the finished WPF, guarded launcher, transactional MSI and Burn preview + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + $tools = "$work\tools" + [IO.File]::WriteAllText("$work\global.json", '{"sdk":{"version":"8.0.419","rollForward":"disable","allowPrerelease":false}}', [Text.UTF8Encoding]::new($false)) + Push-Location $work + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\install-pinned-wix.ps1" -ToolDirectory $tools + $identity = Get-Content -LiteralPath "$work\assembled\runtime-identity.json" -Raw | ConvertFrom-Json + $imageArguments = @{ + RuntimeImage = "$work\runtime-image\$($identity.runtimeId).vhdx" + RuntimeImageReceipt = "$work\runtime-image\runtime-image.json" + } + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\build-immutable-package.ps1" ` + -SourceRoot "$env:GITHUB_WORKSPACE\candidate" -SourceRevision $env:GITHUB_SHA -ProductVersion $env:PRODUCT_VERSION ` + -HostPayloadRoot "$work\host" -RuntimeAssemblyRoot "$work\assembled" -OutputDirectory "$work\package" ` + -PythonPath (Get-Command python.exe -CommandType Application | Select-Object -First 1).Source ` + -DotNetPath (Get-Command dotnet.exe -CommandType Application | Select-Object -First 1).Source -WixPath "$tools\wix.exe" ` + -SystemDrivePrepPath "$work\system-drive-helper\NemoClawHostPreparation.exe" ` + -SystemDriveBuildReceipt "$work\system-drive-helper\build-receipt.json" -SystemDriveProofDirectory "$work\system-drive-proof" @imageArguments + Pop-Location + - name: Record exact native UI inputs for independent setup regression + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $package = "$env:RUNNER_TEMP\finished-windows\package" + $paths = @('build/BootstrapperPayloads.wxs','build/payload/mxc/wxc-host-prep.exe','build/payload/mxc/wxc-exec.exe') + @(Get-ChildItem -LiteralPath "$package\build\bootstrapper" -File | ForEach-Object { 'build/bootstrapper/' + $_.Name }) + $files = @($paths | ForEach-Object { $file = Join-Path $package $_; @{file=$_;bytes=(Get-Item -LiteralPath $file).Length;sha256=(Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant()} }) + [IO.File]::WriteAllText("$package\migration-inputs.json", (@{schemaVersion=1;sourceRevision=$env:GITHUB_SHA;files=$files}|ConvertTo-Json -Depth 5), [Text.UTF8Encoding]::new($false)) + - name: Seal the installer for same-run private qualification + id: product_manifest + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $source = "$env:RUNNER_TEMP\finished-windows" + $transfer = "$env:RUNNER_TEMP\finished-windows-product-transfer" + if (Test-Path -LiteralPath $transfer) { throw 'The installer transfer root must be fresh.' } + [void][IO.Directory]::CreateDirectory($transfer) + Copy-Item -LiteralPath "$source\package" -Destination "$transfer\package" -Recurse + [void][IO.Directory]::CreateDirectory("$transfer\assembled") + Copy-Item -LiteralPath "$source\assembled\runtime-identity.json" -Destination "$transfer\assembled\runtime-identity.json" + if ($env:SELECTED_AGENT -ceq 'openclaw') { + # Retain the exact small build inputs needed to repackage reviewed + # availability around the existing runtime and native artifacts. + # These stay inside the same-run, content-bound private transfer. + Copy-Item -LiteralPath "$source\assembled\assembly.json" -Destination "$transfer\assembled\assembly.json" + $recomposition = "$transfer\recomposition-inputs" + foreach ($relative in @( + 'host/runtime-payload-receipt.json', 'host/bin/node.exe', + 'host/mxc/wxc-exec.exe', 'host/mxc/wxc-host-prep.exe', + 'system-drive-helper/NemoClawHostPreparation.exe', 'system-drive-helper/build-receipt.json', + 'system-drive-proof/system-root-mxc-proof.json', 'system-drive-proof/policy.json', + 'system-drive-proof/mxc-native.log' + )) { + $destination = Join-Path $recomposition $relative + [void][IO.Directory]::CreateDirectory((Split-Path -Parent $destination)) + Copy-Item -LiteralPath (Join-Path $source $relative) -Destination $destination + } + } + # Keep the original sealed controller/application transfer beside the MSI. + # Acceptance must not depend on an older cache surviving the entire build. + Copy-Item -LiteralPath "$env:RUNNER_TEMP\finished-windows-application-transfer" -Destination "$transfer\compiled-application" -Recurse + $manifest = @(& "$env:GITHUB_WORKSPACE\candidate\scripts\checks\windows-native-transfer.ps1" -Mode Create -Root $transfer ` + -Kind finished-installer -SourceRevision $env:CANDIDATE_SHA -Agent $env:SELECTED_AGENT ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT) + if ($manifest.Count -ne 1 -or [string]$manifest[0] -cnotmatch '^[a-f0-9]{64}$') { throw 'The installer transfer manifest failed.' } + "manifest_sha256=$([string]$manifest[0])" >> $env:GITHUB_OUTPUT + "cache_key=windows-finished-installer-v1-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT-$env:CANDIDATE_SHA-$env:SELECTED_AGENT" >> $env:GITHUB_OUTPUT + - name: Save the executable installer only in the same-run cache + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-product-transfer + key: ${{ steps.product_manifest.outputs.cache_key }} + - name: Verify and label the unqualified OpenClaw preview + id: unqualified_preview + if: ${{ success() && github.event_name == 'pull_request' && needs.windows-finished-request.outputs.request_kind == 'pull-request' && needs.windows-finished-request.outputs.candidate_repository == github.repository && needs.windows-finished-request.outputs.agent == 'openclaw' && needs.windows-finished-request.outputs.credential_authorized == 'false' }} + shell: pwsh + env: + INSTALLER_MANIFEST: ${{ steps.product_manifest.outputs.manifest_sha256 }} + run: | + $ErrorActionPreference = 'Stop' + if ($env:PRODUCT_VERSION -cnotmatch '^[0-9]+\.[0-9]+\.[0-9]+$') { throw 'Invalid preview product version.' } + $product = "$env:RUNNER_TEMP\finished-windows-product-transfer" + $expectedMsi = "NemoClaw-$env:PRODUCT_VERSION-windows-arm64.msi" + $expectedSetup = "NemoClawSetup-$env:PRODUCT_VERSION-windows-arm64.exe" + $verifiedManifest = @(& "$env:GITHUB_WORKSPACE\candidate\scripts\checks\windows-native-transfer.ps1" -Mode Verify ` + -Root $product -Kind finished-installer -SourceRevision $env:CANDIDATE_SHA -Agent openclaw ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:INSTALLER_MANIFEST ` + -ExpectedPackageRunnables @($expectedMsi, $expectedSetup)) + if ($verifiedManifest.Count -ne 1 -or [string]$verifiedManifest[0] -cne $env:INSTALLER_MANIFEST) { + throw 'The preview transfer did not match the built bytes.' + } + $receipt = Get-Content -LiteralPath "$product\package\immutable-package-build.json" -Raw | ConvertFrom-Json + $preview = [ordered]@{ + schemaVersion = 1 + classification = 'unqualified-openclaw-installer-preview' + warning = 'Preview only. Full installed acceptance and release qualification have not been established.' + agent = 'openclaw' + sourceRevision = $env:CANDIDATE_SHA + workflowRunId = $env:GITHUB_RUN_ID + workflowRunAttempt = $env:GITHUB_RUN_ATTEMPT + transferManifestSha256 = $env:INSTALLER_MANIFEST + installer = @($receipt.files | Where-Object { $_.file -ceq $expectedSetup })[0] + installedAcceptance = $false + windowsQualified = $false + release = $false + } + $label = "$env:RUNNER_TEMP\unqualified-openclaw-preview.json" + if (Test-Path -LiteralPath $label) { throw 'The preview label must be fresh.' } + [IO.File]::WriteAllText($label, ($preview | ConvertTo-Json -Depth 5), [Text.UTF8Encoding]::new($false)) + - name: Publish the unqualified OpenClaw preview download + if: ${{ success() && steps.unqualified_preview.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: unqualified-openclaw-preview-${{ needs.windows-finished-request.outputs.candidate_sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/finished-windows-product-transfer/package/NemoClawSetup-${{ needs.windows-finished-request.outputs.product_version }}-windows-arm64.exe + ${{ runner.temp }}/finished-windows-product-transfer/package/immutable-package-build.json + ${{ runner.temp }}/finished-windows-product-transfer/package/compiled-msi.json + ${{ runner.temp }}/finished-windows-product-transfer/assembled/runtime-identity.json + ${{ runner.temp }}/finished-windows-product-transfer/transfer-manifest.json + ${{ runner.temp }}/unqualified-openclaw-preview.json + if-no-files-found: error + retention-days: 14 + - name: Verify and label the unqualified Hermes preview + id: unqualified_hermes_preview + if: ${{ success() && github.event_name == 'workflow_dispatch' && inputs.build_windows_native_candidate && needs.windows-finished-request.outputs.request_kind == 'candidate-build' && needs.windows-finished-request.outputs.candidate_repository == github.repository && needs.windows-finished-request.outputs.agent == 'hermes' && needs.windows-finished-request.outputs.validation_scope == 'build-only' && needs.windows-finished-request.outputs.credential_authorized == 'false' }} + shell: pwsh + env: + INSTALLER_MANIFEST: ${{ steps.product_manifest.outputs.manifest_sha256 }} + run: | + $ErrorActionPreference = 'Stop' + if ($env:PRODUCT_VERSION -cnotmatch '^[0-9]+\.[0-9]+\.[0-9]+$') { throw 'Invalid preview product version.' } + $product = "$env:RUNNER_TEMP\finished-windows-product-transfer" + $expectedMsi = "NemoClaw-$env:PRODUCT_VERSION-windows-arm64.msi" + $expectedSetup = "NemoClawSetup-$env:PRODUCT_VERSION-windows-arm64.exe" + $verifiedManifest = @(& "$env:GITHUB_WORKSPACE\candidate\scripts\checks\windows-native-transfer.ps1" -Mode Verify ` + -Root $product -Kind finished-installer -SourceRevision $env:CANDIDATE_SHA -Agent hermes ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:INSTALLER_MANIFEST ` + -ExpectedPackageRunnables @($expectedMsi, $expectedSetup)) + if ($verifiedManifest.Count -ne 1 -or [string]$verifiedManifest[0] -cne $env:INSTALLER_MANIFEST) { + throw 'The preview transfer did not match the built bytes.' + } + $receipt = Get-Content -LiteralPath "$product\package\immutable-package-build.json" -Raw | ConvertFrom-Json + $preview = [ordered]@{ + schemaVersion = 1 + classification = 'unqualified-hermes-installer-preview' + warning = 'Preview only. Full installed acceptance and release qualification have not been established.' + agent = 'hermes' + sourceRevision = $env:CANDIDATE_SHA + workflowRunId = $env:GITHUB_RUN_ID + workflowRunAttempt = $env:GITHUB_RUN_ATTEMPT + transferManifestSha256 = $env:INSTALLER_MANIFEST + installer = @($receipt.files | Where-Object { $_.file -ceq $expectedSetup })[0] + msi = @($receipt.files | Where-Object { $_.file -ceq $expectedMsi })[0] + installedAcceptance = $false + windowsQualified = $false + release = $false + } + $label = "$env:RUNNER_TEMP\unqualified-hermes-preview.json" + if (Test-Path -LiteralPath $label) { throw 'The preview label must be fresh.' } + [IO.File]::WriteAllText($label, ($preview | ConvertTo-Json -Depth 5), [Text.UTF8Encoding]::new($false)) + - name: Publish the unqualified Hermes preview download + if: ${{ success() && steps.unqualified_hermes_preview.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: unqualified-hermes-preview-${{ needs.windows-finished-request.outputs.candidate_sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/finished-windows-product-transfer/package/NemoClawSetup-${{ needs.windows-finished-request.outputs.product_version }}-windows-arm64.exe + ${{ runner.temp }}/finished-windows-product-transfer/package/NemoClaw-${{ needs.windows-finished-request.outputs.product_version }}-windows-arm64.msi + ${{ runner.temp }}/finished-windows-product-transfer/package/immutable-package-build.json + ${{ runner.temp }}/finished-windows-product-transfer/package/compiled-msi.json + ${{ runner.temp }}/finished-windows-product-transfer/assembled/runtime-identity.json + ${{ runner.temp }}/finished-windows-product-transfer/transfer-manifest.json + ${{ runner.temp }}/unqualified-hermes-preview.json + if-no-files-found: error + retention-days: 14 + - name: Stage only non-runnable finished build evidence + id: finished_evidence + if: ${{ always() }} + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\finished-windows" + $inputs = @( + "$work\host\runtime-payload-receipt.json", + "$work\tools\wix-input.json", + "$work\runtime-image\runtime-image.json", + "$work\runtime-image\runtime-image.robocopy.log", + "$work\runtime-image\runtime-image.diskpart.log", + "$work\hermes-input\intake.json", + "$work\hermes-input\personal-feasibility.json", + "$work\hermes-input\personal-request.json", + "$work\hermes-input\mxc-native.log", + "$work\personal-bootstrap\export-controls.json", + "$work\hermes-input\current-native-proof.json", + "$work\hermes-input\current-msys-build.json", + "$work\hermes-input\current-mxc-build.json", + "$work\assembled\diagnostics", + "$work\openshell-binaries\openshell-build.json", + "$work\system-drive-helper\build-receipt.json", + "$work\system-drive-helper\build.log", + "$work\system-drive-proof" + ) + foreach ($pattern in @( + "$work\assembled\*.json", "$work\hermes-input\candidate\*.json", + "$work\personal-production\*.json", "$work\personal-production\*.log", + "$work\personal-production\personal-mxc\*.json", "$work\personal-production\personal-mxc\*.log", + "$work\personal-production\system-root-proof\*.json", "$work\personal-production\system-root-proof\*.log", + "$work\personal-production\official-hermes-runtime-build\*.log", + "$work\package\*.json", "$work\package\build\*.log", + "$work\*.log", "$work\openshell-logs\*.log" + )) { + $inputs += @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | ForEach-Object FullName) + } + & "$env:GITHUB_WORKSPACE\candidate\scripts\checks\stage-windows-native-evidence.ps1" ` + -SourceBase $work -InputPath $inputs -OutputRoot "$env:RUNNER_TEMP\finished-windows-build-evidence" + - name: Preserve finished build and helper proof evidence + if: ${{ always() && steps.finished_evidence.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: finished-windows-preview-evidence-${{ github.sha }} + path: ${{ runner.temp }}/finished-windows-build-evidence/ + if-no-files-found: warn + retention-days: 14 + + windows-finished-installed-startup: + name: Credential-free fresh installed OpenClaw startup and cleanup (ARM64) + needs: [windows-finished-request, windows-finished-installer, windows-compiled-application] + if: ${{ always() && !cancelled() && needs.windows-finished-request.result == 'success' && needs.windows-finished-request.outputs.request_kind == 'pull-request' && needs.windows-finished-request.outputs.agent == 'openclaw' && needs.windows-finished-request.outputs.validation_scope == 'startup-only' && needs.windows-finished-installer.result == 'success' && needs.windows-compiled-application.result == 'success' }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 60 + permissions: + actions: read + contents: read + env: + CANDIDATE_SHA: ${{ needs.windows-finished-request.outputs.candidate_sha }} + SELECTED_AGENT: openclaw + PRODUCT_VERSION: ${{ needs.windows-finished-request.outputs.product_version }} + steps: + - name: Check out the exact pull request acceptance controller + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ needs.windows-finished-request.outputs.candidate_repository }} + ref: ${{ needs.windows-finished-request.outputs.candidate_sha }} + path: candidate + persist-credentials: false + - name: Restore exact same-run installer cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-product-transfer + key: ${{ needs.windows-finished-installer.outputs.installer_cache_key }} + fail-on-cache-miss: true + - name: Verify and materialize exact same-run startup inputs + shell: pwsh + env: + INSTALLER_MANIFEST: ${{ needs.windows-finished-installer.outputs.installer_manifest_sha256 }} + APPLICATION_MANIFEST: ${{ needs.windows-compiled-application.outputs.application_manifest_sha256 }} + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $product = "$env:RUNNER_TEMP\finished-windows-product-transfer" + $application = "$product\compiled-application" + $verifiedProduct = @(& "$env:GITHUB_WORKSPACE\candidate\scripts\checks\windows-native-transfer.ps1" -Mode Verify -Root $product ` + -Kind finished-installer -SourceRevision $env:CANDIDATE_SHA -Agent openclaw ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:INSTALLER_MANIFEST) + $verifiedApplication = @(& "$env:GITHUB_WORKSPACE\candidate\scripts\checks\windows-native-transfer.ps1" -Mode Verify -Root $application ` + -Kind compiled-application -SourceRevision $env:CANDIDATE_SHA -Agent openclaw ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:APPLICATION_MANIFEST) + if ($verifiedProduct.Count -ne 1 -or [string]$verifiedProduct[0] -cne $env:INSTALLER_MANIFEST -or + $verifiedApplication.Count -ne 1 -or [string]$verifiedApplication[0] -cne $env:APPLICATION_MANIFEST) { + throw 'A startup transfer did not match its producer.' + } + $work = "$env:RUNNER_TEMP\finished-windows" + [void][IO.Directory]::CreateDirectory($work) + Copy-Item -LiteralPath "$product\package" -Destination "$work\package" -Recurse + Copy-Item -LiteralPath "$product\assembled" -Destination "$work\assembled" -Recurse + Copy-Item -LiteralPath "$application\application" -Destination "$work\application" -Recurse + - name: Exercise installed OpenClaw startup and owned cleanup without credentials + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\run-installed-acceptance.ps1" ` + -SourceRoot "$env:GITHUB_WORKSPACE\candidate" -WorkDirectory "$env:RUNNER_TEMP\finished-windows" ` + -ProductVersion $env:PRODUCT_VERSION -ArtifactSourceRevision $env:CANDIDATE_SHA -Mode current-build -Agent openclaw -ValidationScope startup-only + - name: Stage only non-runnable startup evidence + id: startup_evidence + if: ${{ always() }} + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\finished-windows" + $inputs = @("$work\installed-smoke", "$work\installed-smoke-after-repair", "$work\installed-stage-timings.json") + foreach ($pattern in @("$work\*.log", "$work\package\*.json")) { + $inputs += @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | ForEach-Object FullName) + } + & "$env:GITHUB_WORKSPACE\candidate\scripts\checks\stage-windows-native-evidence.ps1" ` + -SourceBase $work -InputPath $inputs -OutputRoot "$env:RUNNER_TEMP\finished-windows-startup-evidence" + - name: Preserve credential-free fresh install, startup and cleanup evidence + if: ${{ always() && steps.startup_evidence.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: finished-windows-installed-startup-${{ needs.windows-finished-request.outputs.candidate_sha }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/finished-windows-startup-evidence/ + if-no-files-found: warn + retention-days: 14 + + windows-finished-runtime-qualification: + name: Qualify and independently review the selected runtime before UI packaging + needs: [windows-finished-request, windows-finished-installer, windows-compiled-application] + if: ${{ always() && !cancelled() && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && needs.windows-finished-request.result == 'success' && contains(fromJSON('["openclaw","hermes"]'), needs.windows-finished-request.outputs.agent) && needs.windows-finished-request.outputs.trusted_main == 'true' && needs.windows-finished-request.outputs.exact_workflow == 'true' && needs.windows-finished-request.outputs.exact_pr == 'true' && needs.windows-finished-request.outputs.credential_authorized == 'true' && needs.windows-finished-request.outputs.validation_scope == 'full-acceptance' && needs.windows-finished-installer.result == 'success' && needs.windows-compiled-application.result == 'success' }} + permissions: + actions: read + contents: read + pull-requests: read + uses: ./.github/workflows/windows-native-installer-trusted.yaml + with: + qualification_phase: runtime-bootstrap + pr_number: ${{ needs.windows-finished-request.outputs.pr_number }} + candidate_repository: ${{ needs.windows-finished-request.outputs.candidate_repository }} + candidate_sha: ${{ needs.windows-finished-request.outputs.candidate_sha }} + base_sha: ${{ needs.windows-finished-request.outputs.base_sha }} + workflow_sha: ${{ needs.windows-finished-request.outputs.workflow_sha }} + agent: ${{ needs.windows-finished-request.outputs.agent }} + product_version: ${{ needs.windows-finished-request.outputs.product_version }} + installer_cache_key: ${{ needs.windows-finished-installer.outputs.installer_cache_key }} + installer_manifest_sha256: ${{ needs.windows-finished-installer.outputs.installer_manifest_sha256 }} + application_manifest_sha256: ${{ needs.windows-compiled-application.outputs.application_manifest_sha256 }} + + windows-finished-reviewed-installer: + name: Rebuild setup UI around the independently reviewed selected runtime + needs: + [windows-finished-request, windows-finished-installer, windows-finished-runtime-qualification] + if: ${{ always() && !cancelled() && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && needs.windows-finished-request.result == 'success' && contains(fromJSON('["openclaw","hermes"]'), needs.windows-finished-request.outputs.agent) && needs.windows-finished-installer.result == 'success' && needs.windows-finished-runtime-qualification.result == 'success' }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 35 + permissions: + actions: read + contents: read + outputs: + installer_cache_key: ${{ steps.reviewed_manifest.outputs.cache_key }} + installer_manifest_sha256: ${{ steps.reviewed_manifest.outputs.manifest_sha256 }} + env: + CANDIDATE_SHA: ${{ needs.windows-finished-request.outputs.candidate_sha }} + CONTROLLER_SHA: ${{ needs.windows-finished-request.outputs.workflow_sha }} + PRODUCT_VERSION: ${{ needs.windows-finished-request.outputs.product_version }} + SELECTED_AGENT: ${{ needs.windows-finished-request.outputs.agent }} + steps: + - name: Check out exact candidate packaging source without credentials + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ needs.windows-finished-request.outputs.candidate_repository }} + ref: ${{ needs.windows-finished-request.outputs.candidate_sha }} + path: candidate + persist-credentials: false + - name: Check out exact trusted transfer verifier + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NVIDIA/NemoClaw + ref: ${{ needs.windows-finished-request.outputs.workflow_sha }} + path: controller + persist-credentials: false + - name: Restore original same-run package and retained build inputs + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-product-transfer + key: ${{ needs.windows-finished-installer.outputs.installer_cache_key }} + fail-on-cache-miss: true + - name: Download independently reviewed runtime availability + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.windows-finished-runtime-qualification.outputs.availability_id }} + path: ${{ runner.temp }}/reviewed-runtime-availability + merge-multiple: true + - name: Verify original package and exact reviewed decision before executable use + shell: pwsh + env: + INSTALLER_MANIFEST: ${{ needs.windows-finished-installer.outputs.installer_manifest_sha256 }} + AVAILABILITY_SHA256: ${{ needs.windows-finished-runtime-qualification.outputs.availability_sha256 }} + run: | + $head = (& git -C "$env:GITHUB_WORKSPACE\controller" rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $head -cne $env:CONTROLLER_SHA) { throw 'The reviewed packaging controller differs.' } + $product = "$env:RUNNER_TEMP\finished-windows-product-transfer" + $verified = @(& "$env:GITHUB_WORKSPACE\controller\scripts\checks\windows-native-transfer.ps1" -Mode Verify -Root $product ` + -Kind finished-installer -SourceRevision $env:CANDIDATE_SHA -Agent $env:SELECTED_AGENT ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:INSTALLER_MANIFEST) + if ($verified.Count -ne 1 -or [string]$verified[0] -cne $env:INSTALLER_MANIFEST) { throw 'The original package transfer changed.' } + $decision = Get-Item -LiteralPath "$env:RUNNER_TEMP\reviewed-runtime-availability\reviewed-availability.json" -Force + if ($decision -isnot [IO.FileInfo] -or $decision.Length -le 0 -or $decision.Length -gt 65536 -or + ($decision.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or $env:AVAILABILITY_SHA256 -cnotmatch '^[a-f0-9]{64}$' -or + (Get-FileHash -LiteralPath $decision.FullName -Algorithm SHA256).Hash.ToLowerInvariant() -cne $env:AVAILABILITY_SHA256) { + throw 'The independently reviewed decision changed.' + } + $work = "$env:RUNNER_TEMP\finished-windows" + if (Test-Path -LiteralPath $work) { throw 'The reviewed packaging work directory must be fresh.' } + [void][IO.Directory]::CreateDirectory($work) + Copy-Item -LiteralPath "$product\package" -Destination "$work\unqualified-package" -Recurse + Copy-Item -LiteralPath "$product\assembled" -Destination "$work\assembled" -Recurse + foreach ($name in @('host', 'system-drive-helper', 'system-drive-proof')) { + Copy-Item -LiteralPath "$product\recomposition-inputs\$name" -Destination "$work\$name" -Recurse + } + - name: Prepare pinned native packaging SDK + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 8.0.419 + - name: Prepare pinned build-only Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.1.0 + with: + python-version: 3.13.13 + architecture: arm64 + - name: Rebuild native UI MSI and Burn without rebuilding the qualified runtime + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\finished-windows" + $tools = "$work\tools" + [IO.File]::WriteAllText("$work\global.json", '{"sdk":{"version":"8.0.419","rollForward":"disable","allowPrerelease":false}}', [Text.UTF8Encoding]::new($false)) + Push-Location $work + try { + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\install-pinned-wix.ps1" -ToolDirectory $tools + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\build-immutable-package.ps1" ` + -SourceRoot "$env:GITHUB_WORKSPACE\candidate" -SourceRevision $env:CANDIDATE_SHA -ProductVersion $env:PRODUCT_VERSION ` + -HostPayloadRoot "$work\host" -RuntimeAssemblyRoot "$work\assembled" -OutputDirectory "$work\package" ` + -UnqualifiedPackageDirectory "$work\unqualified-package" -ReviewedAvailability "$env:RUNNER_TEMP\reviewed-runtime-availability\reviewed-availability.json" ` + -PythonPath (Get-Command python.exe -CommandType Application | Select-Object -First 1).Source ` + -DotNetPath (Get-Command dotnet.exe -CommandType Application | Select-Object -First 1).Source -WixPath "$tools\wix.exe" ` + -SystemDrivePrepPath "$work\system-drive-helper\NemoClawHostPreparation.exe" ` + -SystemDriveBuildReceipt "$work\system-drive-helper\build-receipt.json" -SystemDriveProofDirectory "$work\system-drive-proof" + } finally { Pop-Location } + Copy-Item -LiteralPath "$env:RUNNER_TEMP\reviewed-runtime-availability\reviewed-availability.json" -Destination "$work\package\reviewed-availability.json" + $package = "$work\package" + $paths = @('build/BootstrapperPayloads.wxs','build/payload/mxc/wxc-host-prep.exe','build/payload/mxc/wxc-exec.exe') + @(Get-ChildItem -LiteralPath "$package\build\bootstrapper" -File | ForEach-Object { 'build/bootstrapper/' + $_.Name }) + $files = @($paths | ForEach-Object { $file = Join-Path $package $_; @{file=$_;bytes=(Get-Item -LiteralPath $file).Length;sha256=(Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant()} }) + [IO.File]::WriteAllText("$package\migration-inputs.json", (@{schemaVersion=1;sourceRevision=$env:CANDIDATE_SHA;files=$files}|ConvertTo-Json -Depth 5), [Text.UTF8Encoding]::new($false)) + - name: Seal the rebuilt installer under a distinct same-run identity + id: reviewed_manifest + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\finished-windows" + $transfer = "$env:RUNNER_TEMP\finished-windows-reviewed-transfer" + if (Test-Path -LiteralPath $transfer) { throw 'The reviewed installer transfer must be fresh.' } + [void][IO.Directory]::CreateDirectory($transfer) + Copy-Item -LiteralPath "$work\package" -Destination "$transfer\package" -Recurse + Copy-Item -LiteralPath "$work\assembled" -Destination "$transfer\assembled" -Recurse + Copy-Item -LiteralPath "$env:RUNNER_TEMP\finished-windows-product-transfer\compiled-application" -Destination "$transfer\compiled-application" -Recurse + $manifest = @(& "$env:GITHUB_WORKSPACE\controller\scripts\checks\windows-native-transfer.ps1" -Mode Create -Root $transfer ` + -Kind finished-installer -SourceRevision $env:CANDIDATE_SHA -Agent $env:SELECTED_AGENT ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT) + if ($manifest.Count -ne 1 -or [string]$manifest[0] -cnotmatch '^[a-f0-9]{64}$') { throw 'The reviewed installer transfer manifest failed.' } + # Cache versions include the saved path. Preserve the original locally, + # then publish the new bytes from the same path every consumer restores. + $cacheRoot = [IO.Path]::GetFullPath($env:RUNNER_TEMP).TrimEnd('\') + '\' + $product = [IO.Path]::GetFullPath((Join-Path $cacheRoot 'finished-windows-product-transfer')) + $original = [IO.Path]::GetFullPath((Join-Path $work 'original-transfer')) + foreach ($candidate in @($transfer, $product, $original)) { + if (-not [IO.Path]::GetFullPath($candidate).StartsWith($cacheRoot, [StringComparison]::OrdinalIgnoreCase)) { + throw 'The reviewed cache relocation escaped the runner temporary directory.' + } + } + if (Test-Path -LiteralPath $original) { throw 'The original transfer preservation path must be fresh.' } + Move-Item -LiteralPath $product -Destination $original + Move-Item -LiteralPath $transfer -Destination $product + "manifest_sha256=$([string]$manifest[0])" >> $env:GITHUB_OUTPUT + "cache_key=windows-finished-reviewed-installer-v1-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT-$env:CANDIDATE_SHA-$env:SELECTED_AGENT" >> $env:GITHUB_OUTPUT + - name: Retain rebuilt executables only in the same-run private cache + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-product-transfer + key: ${{ steps.reviewed_manifest.outputs.cache_key }} + - name: Stage only non-runnable reviewed build evidence + id: reviewed_evidence + if: ${{ always() }} + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\finished-windows" + $inputs = @() + foreach ($pattern in @("$work\package\*.json", "$work\package\build\*.log", "$work\tools\wix-input.json")) { + $inputs += @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | ForEach-Object FullName) + } + & "$env:GITHUB_WORKSPACE\controller\scripts\checks\stage-windows-native-evidence.ps1" ` + -SourceBase $work -InputPath $inputs -OutputRoot "$env:RUNNER_TEMP\finished-windows-reviewed-evidence" + - name: Preserve reviewed build diagnostics only + if: ${{ always() && steps.reviewed_evidence.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: finished-windows-reviewed-evidence-${{ needs.windows-finished-request.outputs.candidate_sha }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/finished-windows-reviewed-evidence/ + if-no-files-found: warn + retention-days: 14 + + windows-finished-candidate-migration: + name: Credential-free candidate migration controllers (ARM64) + needs: + [windows-finished-request, windows-finished-installer, windows-finished-reviewed-installer] + if: ${{ always() && !cancelled() && needs.windows-finished-request.result == 'success' && needs.windows-finished-request.outputs.request_kind != 'candidate-build' && needs.windows-finished-installer.result == 'success' && needs.windows-finished-reviewed-installer.result == 'success' }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 35 + permissions: + actions: read + contents: read + outputs: + evidence_id: ${{ steps.migration_upload.outputs.artifact-id }} + proof_sha256: ${{ steps.migration_proof.outputs.sha256 }} + env: + CANDIDATE_SHA: ${{ needs.windows-finished-request.outputs.candidate_sha }} + SELECTED_AGENT: ${{ needs.windows-finished-request.outputs.agent }} + PRODUCT_VERSION: ${{ needs.windows-finished-request.outputs.product_version }} + INSTALLER_MANIFEST: ${{ needs.windows-finished-reviewed-installer.outputs.installer_manifest_sha256 }} + steps: + - name: Check out the exact candidate migration controllers + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ needs.windows-finished-request.outputs.candidate_repository }} + ref: ${{ needs.windows-finished-request.outputs.candidate_sha }} + path: candidate + persist-credentials: false + - name: Restore exact same-run installer cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-product-transfer + key: ${{ needs.windows-finished-reviewed-installer.outputs.installer_cache_key }} + fail-on-cache-miss: true + - name: Verify and materialize candidate migration inputs + shell: pwsh + run: | + $head = (& git -C "$env:GITHUB_WORKSPACE\candidate" rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $head -cne $env:CANDIDATE_SHA) { throw 'The candidate migration checkout differs.' } + $product = "$env:RUNNER_TEMP\finished-windows-product-transfer" + $verified = @(& "$env:GITHUB_WORKSPACE\candidate\scripts\checks\windows-native-transfer.ps1" -Mode Verify -Root $product ` + -Kind finished-installer -SourceRevision $env:CANDIDATE_SHA -Agent $env:SELECTED_AGENT ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT -ExpectedManifestSha256 $env:INSTALLER_MANIFEST) + if ($verified.Count -ne 1 -or [string]$verified[0] -cne $env:INSTALLER_MANIFEST) { throw 'The candidate migration input differs from its producer.' } + $work = "$env:RUNNER_TEMP\finished-windows" + if (Test-Path -LiteralPath $work) { throw 'Candidate migration requires a fresh work directory.' } + [void][IO.Directory]::CreateDirectory($work) + Copy-Item -LiteralPath "$product\package" -Destination "$work\package" -Recurse + Copy-Item -LiteralPath "$product\assembled" -Destination "$work\assembled" -Recurse + - name: Prepare pinned candidate fixture compiler + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.95.0 + target: aarch64-pc-windows-msvc + cache: false + - name: Exercise candidate Burn fixture and diagnostics + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $tools = "$env:RUNNER_TEMP\finished-windows\setup-regression-tools" + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\install-pinned-wix.ps1" -ToolDirectory $tools + $owner = "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer" + $work = "$env:RUNNER_TEMP\finished-windows" + & "$owner\build-burn-diagnostics-fixture.ps1" -SourceRoot "$env:GITHUB_WORKSPACE\candidate" -PackageDirectory "$work\package" -OutputDirectory "$work\diagnostics-fixture" -ProductVersion $env:PRODUCT_VERSION -WixPath "$tools\wix.exe" + & "$owner\test-burn-diagnostics.ps1" -FixtureDirectory "$work\diagnostics-fixture" -OutputDirectory "$work\burn-diagnostics" -Agent $env:SELECTED_AGENT + - name: Exercise candidate preview migration and selective reset + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\run-preview-migration.ps1" -WorkDirectory "$env:RUNNER_TEMP\finished-windows" -ProductVersion $env:PRODUCT_VERSION -NewAgent $env:SELECTED_AGENT + - name: Bind candidate migration proof to controller and installer + id: migration_proof + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\finished-windows" + & git -C "$env:GITHUB_WORKSPACE\candidate" diff --exit-code $env:CANDIDATE_SHA -- packaging/windows + if ($LASTEXITCODE -ne 0) { throw 'Candidate migration source changed during qualification.' } + $reports = @('diagnostics-fixture/fixture.json', 'burn-diagnostics/burn-diagnostics.json', 'migration/preview-migration.json') + $files = @($reports | ForEach-Object { + $file = Get-Item -LiteralPath (Join-Path $work $_) -Force + if ($file.PSIsContainer -or $file.Attributes.HasFlag([IO.FileAttributes]::ReparsePoint) -or $file.Length -gt 1048576) { throw 'Candidate migration evidence is invalid.' } + @{file=$_;sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant()} + }) + $burn = Get-Content -LiteralPath "$work\burn-diagnostics\burn-diagnostics.json" -Raw | ConvertFrom-Json + $migration = Get-Content -LiteralPath "$work\migration\preview-migration.json" -Raw | ConvertFrom-Json + if ($burn.sourceRevision -cne $env:CANDIDATE_SHA -or $burn.status -cne 'pass' -or $burn.packageNotInstalled -ne $true -or @($burn.cleanupErrors).Count -ne 0 -or + $migration.sourceRevision -cne $env:CANDIDATE_SHA -or $migration.status -cne 'pass' -or $migration.installationRootRemoved -ne $true -or @($migration.cleanupErrors).Count -ne 0 -or @($migration.cases).Count -ne 2 -or + @($migration.cases | Where-Object resetVerified -NE $true).Count -ne 0) { throw 'Candidate migration did not complete cleanly.' } + $proof = "$work\candidate-migration-controller.json" + [IO.File]::WriteAllText($proof, (@{ + schemaVersion=1;classification='same-run-candidate-migration-controllers';passed=$true + controllerSourceRevision=$env:CANDIDATE_SHA;artifactSourceRevision=$env:CANDIDATE_SHA + installerManifestSha256=$env:INSTALLER_MANIFEST;agent=$env:SELECTED_AGENT + workflowRunId=$env:GITHUB_RUN_ID;workflowRunAttempt=$env:GITHUB_RUN_ATTEMPT;files=$files + } | ConvertTo-Json -Depth 5), [Text.UTF8Encoding]::new($false)) + "sha256=$((Get-FileHash -LiteralPath $proof -Algorithm SHA256).Hash.ToLowerInvariant())" >> $env:GITHUB_OUTPUT + - name: Stage only non-runnable candidate migration evidence + id: migration_evidence + if: ${{ always() }} + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\finished-windows" + $inputs = @("$work\candidate-migration-controller.json", "$work\diagnostics-fixture\fixture.json", "$work\setup-regression-tools\wix-input.json") + $allowed = @('.csv', '.etl', '.jpeg', '.jpg', '.json', '.log', '.md', '.png', '.txt', '.xml') + foreach ($directory in @("$work\burn-diagnostics", "$work\migration")) { + $inputs += @(Get-ChildItem -LiteralPath $directory -Recurse -File -ErrorAction SilentlyContinue | + Where-Object { $_.Extension -in $allowed } | ForEach-Object FullName) + } + & "$env:GITHUB_WORKSPACE\candidate\scripts\checks\stage-windows-native-evidence.ps1" ` + -SourceBase $work -InputPath $inputs -OutputRoot "$env:RUNNER_TEMP\candidate-windows-migration-evidence" + - name: Preserve candidate migration controller evidence + id: migration_upload + if: ${{ always() && steps.migration_evidence.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: candidate-windows-migration-${{ needs.windows-finished-request.outputs.candidate_sha }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/candidate-windows-migration-evidence/ + if-no-files-found: error + retention-days: 14 + + # The same-commit reusable controller is callable only after both workflow + # files land on main. It repeats every identity check and owns both protected + # environments; this feature-branch workflow is not itself a trust boundary. + windows-finished-trusted-qualification: + name: Trusted full acceptance, migration and qualified publication + needs: + [ + windows-finished-request, + windows-finished-installer, + windows-compiled-application, + windows-finished-candidate-migration, + windows-finished-reviewed-installer, + ] + if: ${{ always() && !cancelled() && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && needs.windows-finished-request.result == 'success' && needs.windows-finished-request.outputs.trusted_main == 'true' && needs.windows-finished-request.outputs.exact_workflow == 'true' && needs.windows-finished-request.outputs.exact_pr == 'true' && needs.windows-finished-request.outputs.credential_authorized == 'true' && needs.windows-finished-request.outputs.validation_scope == 'full-acceptance' && needs.windows-finished-installer.result == 'success' && needs.windows-compiled-application.result == 'success' && needs.windows-finished-candidate-migration.result == 'success' }} + permissions: + actions: read + contents: read + pull-requests: read + uses: ./.github/workflows/windows-native-installer-trusted.yaml + with: + qualification_phase: final + pr_number: ${{ needs.windows-finished-request.outputs.pr_number }} + candidate_repository: ${{ needs.windows-finished-request.outputs.candidate_repository }} + candidate_sha: ${{ needs.windows-finished-request.outputs.candidate_sha }} + base_sha: ${{ needs.windows-finished-request.outputs.base_sha }} + workflow_sha: ${{ needs.windows-finished-request.outputs.workflow_sha }} + agent: ${{ needs.windows-finished-request.outputs.agent }} + product_version: ${{ needs.windows-finished-request.outputs.product_version }} + installer_cache_key: ${{ needs.windows-finished-reviewed-installer.outputs.installer_cache_key }} + installer_manifest_sha256: ${{ needs.windows-finished-reviewed-installer.outputs.installer_manifest_sha256 }} + application_manifest_sha256: ${{ needs.windows-compiled-application.outputs.application_manifest_sha256 }} + candidate_migration_evidence_id: ${{ needs.windows-finished-candidate-migration.outputs.evidence_id }} + candidate_migration_proof_sha256: ${{ needs.windows-finished-candidate-migration.outputs.proof_sha256 }} + + windows-runtime-preflight: + name: Windows observer and cleanup preflight (Node ${{ matrix.node }}) + needs: windows-finished-request + if: ${{ needs.windows-finished-request.result == 'success' && (needs.windows-finished-request.outputs.build_allowed == 'true' || (github.event_name == 'workflow_dispatch' && (inputs.test_native_windows_runtime || (inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'application')))) }} + permissions: + contents: read + runs-on: windows-11-vs2026-arm + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + node: ["22.23.2", "24.18.1"] + steps: + - name: Check out the exact candidate preflight + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ needs.windows-finished-request.outputs.candidate_repository }} + ref: ${{ needs.windows-finished-request.outputs.candidate_sha }} + persist-credentials: false + - name: Set up pinned ARM64 preflight Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: ${{ matrix.node }} + architecture: arm64 + - name: Set up the pinned gateway certificate control compiler + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 8.0.419 + - name: Verify private gateway certificate generation and Node interoperability + shell: powershell + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-preflight' + [void][IO.Directory]::CreateDirectory($output) + $helperRoot = Join-Path $env:RUNNER_TEMP 'gateway-tls-helper' + & dotnet publish packaging/windows/tests/gateway-auth/Gateway.Auth.Controls.csproj ` + --configuration Release --runtime win-arm64 --self-contained true --output $helperRoot + if ($LASTEXITCODE -ne 0) { throw 'The self-contained gateway certificate fixture did not build.' } + $env:NEMOCLAW_GATEWAY_TLS_CONTROL = Join-Path $helperRoot 'Gateway.Auth.Controls.exe' + $log = Join-Path $output 'gateway-certificate-tests.log' + try { + $ErrorActionPreference = 'Continue' + & $env:NEMOCLAW_GATEWAY_TLS_CONTROL 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($result -ne 0 -or (Get-Content -LiteralPath $log -Raw) -notmatch '(?m)^Gateway TLS controls: 14 passed; no keys written to disk or certificate stores\.\r?$') { + throw 'All fourteen gateway certificate controls must execute.' + } + $log = Join-Path $output 'gateway-tls-node-tests.log' + try { + $ErrorActionPreference = 'Continue' + & node --experimental-strip-types --no-warnings --test --test-reporter=tap ` + packaging/windows/runtime/native-gateway-tls.test.mts packaging/windows/runtime/native-gateway-session.test.mts ` + 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + $text = Get-Content -LiteralPath $log -Raw + if ($result -ne 0 -or $text -notmatch '(?m)^# pass 30\r?$' -or $text -notmatch '(?m)^# skipped 0\r?$') { + throw 'All thirty import-boundary, command-custody, private-session, private-pipe and Node TLS controls must execute without skips.' + } + $ownerRoot = Join-Path $env:RUNNER_TEMP 'gateway-process-helper' + & dotnet publish packaging/windows/tests/gateway-process/Gateway.Process.Controls.csproj ` + --configuration Release --runtime win-arm64 --self-contained true --output $ownerRoot + if ($LASTEXITCODE -ne 0) { throw 'The gateway process-ownership fixture did not build.' } + $env:NEMOCLAW_GATEWAY_PROCESS_CONTROL = Join-Path $ownerRoot 'Gateway.Process.Controls.exe' + $log = Join-Path $output 'gateway-process-tests.log' + try { + $ErrorActionPreference = 'Continue' + & node --experimental-strip-types --no-warnings --test --test-reporter=tap ` + packaging/windows/runtime/native-gateway-process.test.mts 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + $text = Get-Content -LiteralPath $log -Raw + if ($result -ne 0 -or $text -notmatch '(?m)^# pass 6\r?$' -or $text -notmatch '(?m)^# skipped 0\r?$') { + throw 'All six gateway process-ownership controls must execute without skips.' + } + - name: Verify observer shutdown and qualification cleanup before building + shell: powershell + env: + PREFLIGHT_NODE_VERSION: ${{ matrix.node }} + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $identityText = & node --print 'JSON.stringify({platform:process.platform,arch:process.arch,version:process.versions.node})' + if ($LASTEXITCODE -ne 0) { throw 'Preflight Node identity could not be read.' } + $identity = $identityText | ConvertFrom-Json + if ($identity.platform -cne 'win32' -or $identity.arch -cne 'arm64' -or $identity.version -cne $env:PREFLIGHT_NODE_VERSION) { + throw 'Preflight requires the selected native Windows ARM64 Node.' + } + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-preflight' + [void][IO.Directory]::CreateDirectory($output) + $log = Join-Path $output 'observer-cleanup-tests.log' + $tests = @( + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/app/runtime-published-resources.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/build-immutable-package-cleanup.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/control-installed-openclaw-input.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/qualify-installed-openclaw.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/review-hermes-availability.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/mxc-probe-identity.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/install-pinned-wix.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/runtime-image-storage.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-ui-lifecycle.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-ui-relay.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-web-session.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-gateway-configuration.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-openclaw-models.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-turn-cleanup.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-hermes-turn-cleanup.test.mts') + ) + try { + $ErrorActionPreference = 'Continue' + & node --experimental-strip-types --no-warnings --test --test-reporter=tap @tests ` + 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($result -ne 0) { throw 'Windows observer or qualification cleanup preflight failed.' } + - name: Verify compiled MXC probe admission without running MXC + shell: powershell + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $log = Join-Path $env:RUNNER_TEMP 'windows-runtime-preflight\probe-identity-tests.log' + try { + $ErrorActionPreference = 'Continue' + & dotnet run --configuration Release --project ` + packaging/windows/tests/host-preparation-diagnostics/HostPreparation.Diagnostics.Controls.csproj ` + 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($result -ne 0) { throw 'The compiled MXC probe admission controls failed.' } + - name: Verify bootstrapper choices through the runtime configuration writer + shell: powershell + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $build = Join-Path $env:RUNNER_TEMP 'bootstrapper-configuration-controls' + & dotnet build packaging/windows/tests/prebuilt-configuration/PrebuiltConfiguration.csproj --configuration Release --output $build + if ($LASTEXITCODE -ne 0) { throw 'The bootstrapper configuration controls did not build.' } + $requests = Join-Path $env:RUNNER_TEMP 'windows-runtime-preflight\bootstrapper-requests.log' + & dotnet (Join-Path $build 'PrebuiltConfiguration.dll') | Set-Content -LiteralPath $requests -Encoding UTF8 + if ($LASTEXITCODE -ne 0) { throw 'The bootstrapper configuration controls failed.' } + & node --experimental-strip-types --no-warnings packaging/windows/tests/prebuilt-configuration/verify-runtime-requests.mts $requests + if ($LASTEXITCODE -ne 0) { throw 'Bootstrapper choices did not match the runtime configuration contract.' } + - name: Retain preflight results for each Node version + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: windows-runtime-preflight-${{ matrix.node }}-${{ needs.windows-finished-request.outputs.candidate_sha }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/windows-runtime-preflight/*.log + if-no-files-found: warn + retention-days: 14 + + windows-compiled-application: + name: Compile exact Windows application units (ARM64) + needs: [windows-finished-request, windows-runtime-preflight] + outputs: + application_cache_key: ${{ steps.transfer_manifest.outputs.cache_key }} + application_manifest_sha256: ${{ steps.transfer_manifest.outputs.manifest_sha256 }} + if: ${{ always() && !cancelled() && needs.windows-finished-request.result == 'success' && needs.windows-runtime-preflight.result == 'success' && ((needs.windows-finished-request.outputs.build_allowed == 'true') || (github.event_name == 'workflow_dispatch' && inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'application')) }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 30 + env: + CANDIDATE_SHA: ${{ needs.windows-finished-request.outputs.candidate_sha }} + SELECTED_AGENT: ${{ needs.windows-finished-request.outputs.agent }} + steps: + - name: Check out Windows application packaging + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ needs.windows-finished-request.outputs.candidate_repository }} + ref: ${{ needs.windows-finished-request.outputs.candidate_sha }} + persist-credentials: false + - name: Prepare a fresh compiled application workspace + shell: pwsh + run: | + $runnerTemp = [IO.Path]::GetFullPath($env:RUNNER_TEMP) + $work = [IO.Path]::GetFullPath((Join-Path $runnerTemp 'compiled-windows-app')) + if ([IO.Path]::GetRelativePath($runnerTemp, $work) -cne 'compiled-windows-app') { + throw 'The compiled application workspace escaped RUNNER_TEMP.' + } + if (Test-Path -LiteralPath $work) { + Remove-Item -LiteralPath $work -Recurse -Force + } + New-Item -ItemType Directory -Path $work | Out-Null + - name: Reject unsupported finished-installer validation scopes + if: ${{ needs.windows-finished-request.outputs.build_allowed == 'true' }} + shell: pwsh + env: + VALIDATION_SCOPE: ${{ needs.windows-finished-request.outputs.validation_scope }} + run: | + if ($env:SELECTED_AGENT -ceq 'hermes' -and $env:VALIDATION_SCOPE -ceq 'startup-only') { throw 'Hermes requires its existing full-acceptance lane.' } + - name: Prepare the pinned native application compiler + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & packaging/windows/app/prepare-app-node.ps1 ` + -LockPath packaging/windows/hermes/official-runtime.lock.json ` + -OutputDirectory "$env:RUNNER_TEMP\compiled-windows-app\node" + - name: Verify installed acceptance controller Windows compatibility + if: ${{ needs.windows-finished-request.outputs.build_allowed == 'true' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\compiled-windows-app" + $output = "$work\controls" + New-Item -ItemType Directory -Path $output -Force | Out-Null + $tests = @( + 'packaging/windows/installer/control-installed-openclaw-input.test.mts', + 'packaging/windows/installer/run-installed-acceptance.test.mts', + 'packaging/windows/installer/qualify-finished-package.test.mts', + 'packaging/windows/runtime/native-ui-tunnel.test.mts' + ) + & "$work\node\node.exe" --experimental-strip-types --no-warnings --test @tests ` + 1>"$output\installed-acceptance-controller.stdout.log" ` + 2>"$output\installed-acceptance-controller.stderr.log" + if ($LASTEXITCODE -ne 0) { throw 'The Windows installed-acceptance controller controls failed.' } + & "$work\node\node.exe" --experimental-strip-types --no-warnings --test ` + packaging/windows/app/choice-inspect-diagnostics.test.mts ` + packaging/windows/installer/qualify-installed-hermes.test.mts ` + packaging/windows/installer/qualify-installed-openclaw.test.mts ` + packaging/windows/installer/windows-native-transfer.test.mts ` + packaging/windows/runtime/native-configuration-credentials.test.mts ` + packaging/windows/runtime/native-setup-transaction.test.mts ` + packaging/windows/runtime/native-remove-data.test.mts ` + packaging/windows/runtime/native-local-models.test.mts ` + packaging/windows/runtime/native-bundled-inference.test.mts ` + packaging/windows/runtime/native-inference.test.mts ` + packaging/windows/runtime/native-setup-local-models.test.mts + if ($LASTEXITCODE -ne 0) { throw 'The Windows Hermes and configuration transaction controls failed.' } + $files = @($tests | ForEach-Object { + $file = Join-Path $env:GITHUB_WORKSPACE $_ + @{ file = $_; bytes = (Get-Item -LiteralPath $file).Length; sha256 = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() } + }) + [IO.File]::WriteAllText("$output\installed-acceptance-controller.json", (@{ + schemaVersion = 1 + classification = 'same-run-installed-acceptance-controller-controls' + sourceRevision = $env:GITHUB_SHA + nodeSha256 = (Get-FileHash -LiteralPath "$work\node\node.exe" -Algorithm SHA256).Hash.ToLowerInvariant() + passed = $true + files = $files + } | ConvertTo-Json -Depth 5), [Text.UTF8Encoding]::new($false)) + - name: Restore immutable application build inputs + if: ${{ needs.windows-finished-request.outputs.agent == 'openclaw' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + python packaging/windows/app/materialize-openclaw-build.py ` + --output "$env:RUNNER_TEMP\compiled-windows-app\inputs" ` + --cache "$env:RUNNER_TEMP\compiled-windows-app\downloads" + if ($LASTEXITCODE -ne 0) { throw 'Application build inputs failed verification.' } + - name: Verify Windows native plugin file URL loading + if: ${{ needs.windows-finished-request.outputs.agent == 'openclaw' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & "$env:RUNNER_TEMP\compiled-windows-app\node\node.exe" ` + --experimental-strip-types packaging/windows/app/test-windows-plugin-file-url.mts ` + --source-root "$env:RUNNER_TEMP\compiled-windows-app\inputs\node_modules\openclaw" + if ($LASTEXITCODE -ne 0) { throw 'Windows native plugin loading controls failed.' } + & "$env:RUNNER_TEMP\compiled-windows-app\node\node.exe" ` + --experimental-strip-types packaging/windows/app/test-windows-update-owner.mts ` + --source-root "$env:RUNNER_TEMP\compiled-windows-app\inputs\node_modules\openclaw" + if ($LASTEXITCODE -ne 0) { throw 'Installer-owned update controls failed.' } + & "$env:RUNNER_TEMP\compiled-windows-app\node\node.exe" ` + --experimental-strip-types packaging/windows/app/test-windows-configured-plugin-install.mts ` + --source-root "$env:RUNNER_TEMP\compiled-windows-app\inputs\node_modules\openclaw" + if ($LASTEXITCODE -ne 0) { throw 'Installer-owned configured-plugin controls failed.' } + & "$env:RUNNER_TEMP\compiled-windows-app\node\node.exe" ` + --experimental-strip-types packaging/windows/app/test-windows-eager-ollama.mts ` + --source-root "$env:RUNNER_TEMP\compiled-windows-app\inputs\node_modules\openclaw" ` + --tool-root "$env:RUNNER_TEMP\compiled-windows-app\inputs\tools" + if ($LASTEXITCODE -ne 0) { throw 'Eager Ollama compilation controls failed.' } + & "$env:RUNNER_TEMP\compiled-windows-app\node\node.exe" ` + --experimental-strip-types packaging/windows/app/test-prebuilt-plugin-consent-records.mts ` + --source-root "$env:RUNNER_TEMP\compiled-windows-app\inputs\node_modules\openclaw" ` + --tool-root "$env:RUNNER_TEMP\compiled-windows-app\inputs\tools" + if ($LASTEXITCODE -ne 0) { throw 'Packaged plugin consent persistence controls failed.' } + - name: Compile the OpenClaw application unit + if: ${{ needs.windows-finished-request.outputs.agent == 'openclaw' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & "$env:RUNNER_TEMP\compiled-windows-app\node\node.exe" ` + --experimental-strip-types --max-old-space-size=8192 ` + packaging/windows/app/build-openclaw-app.mts ` + --source-root "$env:RUNNER_TEMP\compiled-windows-app\inputs\node_modules\openclaw" ` + --tool-root "$env:RUNNER_TEMP\compiled-windows-app\inputs\tools" ` + --output "$env:RUNNER_TEMP\compiled-windows-app\build" + if ($LASTEXITCODE -ne 0) { throw 'The Windows application compilation failed.' } + - name: Execute the compiled application through its CLI and Worker API + if: ${{ needs.windows-finished-request.outputs.agent == 'openclaw' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & "$env:RUNNER_TEMP\compiled-windows-app\node\node.exe" ` + --experimental-strip-types packaging/windows/app/test-windows-private-directory-library.mts ` + --source-root "$env:RUNNER_TEMP\compiled-windows-app\inputs\node_modules\openclaw" ` + --app-root "$env:RUNNER_TEMP\compiled-windows-app\build\app" + if ($LASTEXITCODE -ne 0) { throw 'The compiled private-directory permission controls failed.' } + & "$env:RUNNER_TEMP\compiled-windows-app\node\node.exe" ` + --experimental-strip-types packaging/windows/app/test-compiled-openclaw.mts ` + --app-root "$env:RUNNER_TEMP\compiled-windows-app\build\app" ` + --output "$env:RUNNER_TEMP\compiled-windows-app\controls\compiled-openclaw" + if ($LASTEXITCODE -ne 0) { throw 'The compiled Windows application controls failed.' } + - name: Exercise compiled provider, tools and all packaged onboarding choices + id: configured_choices + if: ${{ needs.windows-finished-request.outputs.agent == 'openclaw' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\compiled-windows-app" + $ciNode = "$work\node\node.exe" + $application = "$work\build\app" + $diagnostics = "$work\build\diagnostics" + $source = "$env:GITHUB_WORKSPACE\packaging\windows\app" + & $ciNode --experimental-strip-types "$source\test-compiled-openclaw-model-tools.mts" ` + --app-root $application --output "$diagnostics\local-model-tools" + if ($LASTEXITCODE -ne 0) { throw 'The compiled local-provider and actual tool execution checks failed.' } + # OpenClaw Discord is deferred until packaged plugin provenance is supported. + # Setup rejects that selection; its upstream trust checks remain unchanged. + $choices = @('brave', 'slack', 'tavily') + $checks = @($choices | ForEach-Object -Parallel { + $ErrorActionPreference = 'Stop' + $choice = $_ + $output = Join-Path $using:diagnostics ('choice-' + $choice) + & $using:ciNode --experimental-strip-types (Join-Path $using:source 'test-prebuilt-choice-plugins.mts') ` + --app-root $using:application --choice $choice --output $output ` + 1>($output + '.controller.stdout.log') 2>($output + '.controller.stderr.log') + [pscustomobject]@{ choice=$choice; exitCode=$LASTEXITCODE } + } -ThrottleLimit 4) + $checks | ConvertTo-Json -Depth 3 | Set-Content -LiteralPath "$diagnostics\configured-choice-results.json" -Encoding utf8 + if ($checks.Count -ne 3 -or @($checks | Where-Object exitCode -NE 0).Count -ne 0) { + throw 'A packaged onboarding choice did not complete its configured gateway checks.' + } + - name: Prepare the compiler for failure-only readonly-worker diagnostics + id: readonly_diagnostic_compiler + if: ${{ failure() && steps.configured_choices.outcome == 'failure' }} + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 8.0.419 + - name: Diagnose the compiled readonly worker without changing acceptance + if: ${{ failure() && steps.configured_choices.outcome == 'failure' && steps.readonly_diagnostic_compiler.outcome == 'success' }} + timeout-minutes: 5 + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\compiled-windows-app" + $ownerRoot = "$work\readonly-process-owner" + & dotnet publish packaging/windows/tests/gateway-process/Gateway.Process.Controls.csproj ` + --configuration Release --runtime win-arm64 --self-contained true --output $ownerRoot + if ($LASTEXITCODE -ne 0) { throw 'The diagnostic process owner did not build.' } + & "$work\node\node.exe" --experimental-strip-types ` + packaging/windows/app/diagnose-compiled-sqlite-readonly.mts ` + --app-root "$work\build\app" --process-owner "$ownerRoot\Gateway.Process.Controls.exe" ` + --output "$work\build\diagnostics\readonly-worker" + if ($LASTEXITCODE -ne 0) { throw 'The readonly worker diagnostic failed; acceptance remains failed.' } + - name: Verify the compiled dashboard and packaged resources in a real browser + if: ${{ needs.windows-finished-request.outputs.agent == 'openclaw' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\compiled-windows-app" + $browsers = @( + "${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe", + "$env:ProgramFiles\Microsoft\Edge\Application\msedge.exe", + "$env:ProgramFiles\Google\Chrome\Application\chrome.exe" + ) + $browser = $browsers | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | Select-Object -First 1 + if (-not $browser) { throw 'The Windows runner has no preinstalled browser for dashboard validation.' } + & "$work\node\node.exe" --experimental-strip-types ` + packaging/windows/app/test-compiled-openclaw-gateway.mts ` + --app-root "$work\build\app" --output "$work\first-run-consent-control" ` + --browser-executable $browser --with-brave --browser-setup-control --browser-plugin-consent-control + if ($LASTEXITCODE -ne 0) { throw 'The first-run dashboard or plugin consent control failed.' } + & "$work\node\node.exe" --experimental-strip-types ` + packaging/windows/app/test-compiled-openclaw-gateway.mts ` + --app-root "$work\build\app" --output "$work\gateway-control" ` + --browser-executable $browser + if ($LASTEXITCODE -ne 0) { throw 'The compiled Windows dashboard or resource control failed.' } + - name: Prepare only shared compiler and browser-observer tools for Hermes + if: ${{ needs.windows-finished-request.outputs.agent != 'openclaw' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + python packaging/windows/distribution/prepare-native-build-tools.py ` + --output "$env:RUNNER_TEMP\compiled-windows-app\inputs" --cache "$env:RUNNER_TEMP\compiled-windows-app\downloads" + if ($LASTEXITCODE -ne 0) { throw 'The shared runtime compiler tools failed verification.' } + - name: Prepare the pinned executable resource injector + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + python packaging/windows/distribution/prepare-executable-tools.py ` + --output "$env:RUNNER_TEMP\compiled-windows-app\executable-tools" ` + --cache "$env:RUNNER_TEMP\compiled-windows-app\downloads" + if ($LASTEXITCODE -ne 0) { throw 'Executable build tools failed verification.' } + - name: Compile the native application dispatcher and static workers + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\compiled-windows-app" + if ($env:SELECTED_AGENT -eq 'openclaw') { + New-Item -ItemType Junction -Path "$work\inputs\tools\node_modules\typescript" ` + -Target "$work\inputs\node_modules\openclaw\node_modules\typescript" | Out-Null + } + New-Item -ItemType Junction -Path "$env:GITHUB_WORKSPACE\node_modules" ` + -Target "$work\inputs\tools\node_modules" | Out-Null + & "$work\node\node.exe" --experimental-strip-types --no-warnings --test ` + packaging/windows/app/native-model-catalog-build.test.mts ` + packaging/windows/app/native-pipe-transport-build.test.mts ` + packaging/windows/runtime/native-inference-broker.test.mts + if ($LASTEXITCODE -ne 0) { throw 'Native provider catalog and broker controls failed.' } + & "$work\node\node.exe" --experimental-strip-types --no-warnings --test packaging/windows/app/runtime-external-packages.test.mts packaging/windows/app/sqlite-canonical-path.test.mts + if ($LASTEXITCODE -ne 0) { throw 'OpenClaw dependency-location controls failed.' } + & "$work\node\node.exe" --experimental-strip-types --no-warnings --test packaging/windows/runtime/native-openclaw-migration.test.mts + if ($LASTEXITCODE -ne 0) { throw 'OpenClaw session migration controls failed.' } + & "$work\node\node.exe" --experimental-strip-types ` + packaging/windows/distribution/build-native-workers.mts "$work\workers" + if ($LASTEXITCODE -ne 0) { throw 'Static application worker compilation failed.' } + - name: Migrate synthetic history with the compiled OpenClaw importer + if: ${{ needs.windows-finished-request.outputs.agent == 'openclaw' }} + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\compiled-windows-app" + & "$work\node\node.exe" --experimental-strip-types ` + packaging/windows/app/test-compiled-openclaw-migration.mts ` + --app-root "$work\build\app" --runtime-root $work ` + --output "$work\controls\compiled-migration" + if ($LASTEXITCODE -ne 0) { throw 'The compiled OpenClaw history migration failed.' } + - name: Build and execute the Windows application EXE + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $work = "$env:RUNNER_TEMP\compiled-windows-app" + & "$work\node\node.exe" --experimental-strip-types ` + packaging/windows/distribution/prepare-native-executable.mts ` + "$work\workers\native-runtime.cjs" ` + "$work\executable-tools\postject\dist\api.js" "$work\executable" + if ($LASTEXITCODE -ne 0) { throw 'The Windows application EXE build or execution failed.' } + - name: Seal exact executable units for same-run private transfer + id: transfer_manifest + shell: pwsh + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + $source = "$env:RUNNER_TEMP\compiled-windows-app" + $transfer = "$env:RUNNER_TEMP\finished-windows-application-transfer" + if (Test-Path -LiteralPath $transfer) { throw 'The application transfer root must be fresh.' } + [void][IO.Directory]::CreateDirectory($transfer) + function Copy-TransferInput([string]$Group, [string]$Relative) { + $input = Join-Path $source $Relative + if (-not (Test-Path -LiteralPath $input)) { return } + $output = Join-Path (Join-Path $transfer $Group) $Relative + [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($output)) + Copy-Item -LiteralPath $input -Destination $output -Recurse -Force + } + @( + 'build/app', 'build/build-receipt.json', 'node', + 'controls/installed-acceptance-controller.json', + 'inputs/tools/node_modules/playwright-core', 'inputs/tools/node_modules/esbuild', + 'inputs/tools/node_modules/@esbuild/win32-arm64', 'inputs/materialization-receipt.json' + ) | ForEach-Object { Copy-TransferInput application $_ } + @('executable', 'workers') | ForEach-Object { Copy-TransferInput runtime $_ } + $manifest = @(& scripts/checks/windows-native-transfer.ps1 -Mode Create -Root $transfer ` + -Kind compiled-application -SourceRevision $env:CANDIDATE_SHA -Agent $env:SELECTED_AGENT ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT) + if ($manifest.Count -ne 1 -or [string]$manifest[0] -cnotmatch '^[a-f0-9]{64}$') { throw 'The application transfer manifest failed.' } + "manifest_sha256=$([string]$manifest[0])" >> $env:GITHUB_OUTPUT + "cache_key=windows-finished-application-v1-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT-$env:CANDIDATE_SHA-$env:SELECTED_AGENT" >> $env:GITHUB_OUTPUT + - name: Save exact executable units only in the same-run cache + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-application-transfer + key: ${{ steps.transfer_manifest.outputs.cache_key }} + - name: Stage only non-runnable application diagnostics + id: application_evidence + if: ${{ always() }} + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\compiled-windows-app" + $inputs = @( + "$work\controls\installed-acceptance-controller.json", + "$work\controls\installed-acceptance-controller.stdout.log", + "$work\controls\installed-acceptance-controller.stderr.log", + "$work\controls\compiled-openclaw\compiled-controls.json", + "$work\controls\compiled-openclaw\direct-version.log", + "$work\controls\compiled-openclaw\worker-version.log", + "$work\controls\compiled-openclaw\config-validate.log", + "$work\controls\compiled-migration\migration-controls.json", + "$work\first-run-consent-control\gateway-control.json", + "$work\first-run-consent-control\browser-control.json", + "$work\first-run-consent-control\compiled-dashboard-failed.png", + "$work\first-run-consent-control\stdout.log", "$work\first-run-consent-control\stderr.log", + "$work\gateway-control\gateway-control.json", + "$work\gateway-control\browser-control.json", + "$work\gateway-control\compiled-dashboard-failed.png", + "$work\gateway-control\stdout.log", "$work\gateway-control\stderr.log", + "$work\workers\build.json", "$work\workers\source-adaptation.json", + "$work\executable-tools\tools-input.json", + "$work\build\diagnostics\configured-choice-results.json", + "$work\build\diagnostics\readonly-worker\readonly-diagnostic.json", + "$work\build\diagnostics\readonly-worker\delete-closed.trace.log", + "$work\build\diagnostics\readonly-worker\wal-held.trace.log", + "$work\build\diagnostics\local-model-tools\result.json", + "$work\build\diagnostics\local-model-tools\undici-instances.json", + "$work\build\diagnostics\local-model-tools\stdout.log", + "$work\build\diagnostics\local-model-tools\stderr.log", + "$work\build\build-receipt.json", "$work\build\build-failure.json", + "$work\inputs\materialization-receipt.json", "$work\node\node-input.json" + ) + foreach ($choice in @('brave', 'slack', 'tavily')) { + $choiceRoot = "$work\build\diagnostics\choice-$choice" + $inputs += @("$choiceRoot\result.json", "$choiceRoot\registered.json", "$choiceRoot\inspect.timeline.log") + } + foreach ($pattern in @( + "$work\build\diagnostics\choice-*.controller.stdout.log", + "$work\build\diagnostics\choice-*.controller.stderr.log", + "$work\build\diagnostics\choice-*\*.stdout.log", + "$work\build\diagnostics\choice-*\*.stderr.log", + "$work\executable\*.json", "$work\executable\*.log" + )) { + $inputs += @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | ForEach-Object FullName) + } + & "$env:GITHUB_WORKSPACE\scripts\checks\stage-windows-native-evidence.ps1" ` + -SourceBase $work -InputPath $inputs -OutputRoot "$env:RUNNER_TEMP\compiled-windows-application-evidence" + - name: Preserve application build diagnostics + if: ${{ always() && steps.application_evidence.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: compiled-windows-application-diagnostics-${{ github.sha }} + path: ${{ runner.temp }}/compiled-windows-application-evidence/ + if-no-files-found: error + retention-days: 14 + + windows-system-drive-proof: + name: Native system-drive preparation and MXC proof (ARM64) + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'system-drive' }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 12 + steps: + - name: Check out the fixed-purpose Windows helper + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up pinned native Rust + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.95.0 + target: aarch64-pc-windows-msvc + cache: false + - name: Prepare only the pinned Node and MXC executables + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\system-drive-inputs" + & packaging/windows/app/prepare-app-node.ps1 ` + -LockPath packaging/windows/hermes/official-runtime.lock.json -OutputDirectory "$work\node" + $archive = "$work\mxc-sdk.tgz" + Invoke-WebRequest 'https://registry.npmjs.org/@microsoft/mxc-sdk/-/mxc-sdk-0.8.0.tgz' -OutFile $archive -TimeoutSec 60 + if ((Get-FileHash $archive -Algorithm SHA256).Hash.ToLowerInvariant() -cne '06bb2399d7e98ab1907acf851e12a4e44748dd467b79d3e53c2f2fbf569da14e') { + throw 'The MXC SDK differs from its immutable archive.' + } + & "$env:SystemRoot\System32\tar.exe" -xzf $archive -C $work package/bin/arm64/wxc-exec.exe package/bin/arm64/wxc-host-prep.exe + if ($LASTEXITCODE -ne 0) { throw 'The two pinned MXC executables could not be extracted.' } + - name: Compile and exercise the native metadata helper + shell: pwsh + run: | + $work = "$env:RUNNER_TEMP\host-preparation-helper" + & packaging/windows/host-preparation/build-helper.ps1 -OutputDirectory $work + & rustup run 1.95.0-aarch64-pc-windows-msvc cargo test --locked --offline ` + --target aarch64-pc-windows-msvc --manifest-path packaging/windows/host-preparation/Cargo.toml ` + --target-dir "$work\rust-target" -- --test-threads=1 2>&1 | Tee-Object -FilePath "$work\native-controls.log" + if ($LASTEXITCODE -ne 0) { throw 'The actual native metadata controls failed.' } + - name: Verify retained preparation errors and Setup diagnostics + shell: pwsh + run: | + & dotnet run --project packaging/windows/tests/host-preparation-diagnostics/HostPreparation.Diagnostics.Controls.csproj ` + -p:MxcProbeSha256=dde1c592270e9a659b01dccad70362da7b99fec114885fa4d625507aa775a503 ` + -- "$env:RUNNER_TEMP\system-drive-inputs\package\bin\arm64\wxc-exec.exe" + if ($LASTEXITCODE -ne 0) { throw 'The preparation diagnostic controls failed.' } + - name: Verify the actual system root and contained Node access + shell: pwsh + run: | + & "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -File "$env:GITHUB_WORKSPACE\packaging\windows\host-preparation\test-system-root-mxc.ps1" ` + -HelperPath "$env:RUNNER_TEMP\host-preparation-helper\NemoClawHostPreparation.exe" ` + -MxcDirectory "$env:RUNNER_TEMP\system-drive-inputs\package\bin\arm64" ` + -NodePath "$env:RUNNER_TEMP\system-drive-inputs\node\node.exe" ` + -ArtifactDirectory "$env:RUNNER_TEMP\system-root-mxc-proof" + if ($LASTEXITCODE -ne 0) { throw 'The Windows PowerShell 5.1 system-drive proof failed.' } + - name: Set up pinned proof verifier Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.1.0 + with: + python-version: 3.13.13 + architecture: arm64 + - name: Verify the historical SDK proof without package admission + shell: pwsh + run: | + & python packaging/windows/installer/verify-system-drive-proof.py ` + --helper "$env:RUNNER_TEMP\host-preparation-helper\NemoClawHostPreparation.exe" ` + --build-receipt "$env:RUNNER_TEMP\host-preparation-helper\build-receipt.json" ` + --proof-directory "$env:RUNNER_TEMP\system-root-mxc-proof" ` + --source-root $env:GITHUB_WORKSPACE --source-revision $env:GITHUB_SHA ` + --node-path "$env:RUNNER_TEMP\system-drive-inputs\node\node.exe" ` + --legacy-mxc-directory "$env:RUNNER_TEMP\system-drive-inputs\package\bin\arm64" ` + --output "$env:RUNNER_TEMP\system-root-mxc-proof\historical-sdk-proof.json" + if ($LASTEXITCODE -ne 0) { throw 'The verifier rejected the historical SDK system-drive proof.' } + & python packaging/windows/hermes/test-native-adapter-paths.py -v + if ($LASTEXITCODE -ne 0) { throw 'The native Hermes adapter path controls failed.' } + & python packaging/windows/hermes/test_generated_finder_paths.py -v + if ($LASTEXITCODE -ne 0) { throw 'The generated Hermes finder controls failed.' } + - name: Verify acceptance-controller Windows shell compatibility + shell: pwsh + run: | + & "$env:RUNNER_TEMP\system-drive-inputs\node\node.exe" --experimental-strip-types --no-warnings ` + --test --test-reporter=tap ` + packaging/windows/installer/control-installed-openclaw-input.test.mts ` + packaging/windows/installer/run-installed-acceptance.test.mts + if ($LASTEXITCODE -ne 0) { throw 'The Windows acceptance-controller shell controls failed.' } + - name: Preserve fixed-purpose preparation evidence + if: ${{ always() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: windows-system-drive-mxc-proof-${{ github.sha }} + path: | + ${{ runner.temp }}/host-preparation-helper/*.json + ${{ runner.temp }}/host-preparation-helper/*.log + ${{ runner.temp }}/host-preparation-helper/NemoClawHostPreparation.exe + ${{ runner.temp }}/system-root-mxc-proof/ + ${{ runner.temp }}/system-drive-inputs/node/node-input.json + if-no-files-found: error + retention-days: 14 + + windows-host-prerequisite-proof: + name: Isolated Windows directory permission proof (ARM64) + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'host-prerequisites' }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 10 + steps: + - name: Check out the Windows packaging controls + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Build isolated permission controls + id: permission-controls-build + shell: pwsh + run: | + dotnet build packaging/windows/tests/host-prerequisites/HandleAcl.Controls.csproj --configuration Release + if ($LASTEXITCODE -ne 0) { throw 'The isolated permission controls did not build.' } + - name: Measure intended metadata handling and directory enumeration + shell: pwsh + run: | + & "$env:GITHUB_WORKSPACE\packaging\windows\tests\host-prerequisites\test-capture-process.ps1" + & "$env:GITHUB_WORKSPACE\packaging\windows\tests\host-prerequisites\measure-directory-enumeration.ps1" ` + -ArtifactDirectory "$env:RUNNER_TEMP\handle-acl-large" + - name: Exercise permission handling on disposable directories + if: ${{ always() && steps.permission-controls-build.outcome == 'success' }} + shell: pwsh + run: | + dotnet run --project packaging/windows/tests/host-prerequisites/HandleAcl.Controls.csproj ` + --configuration Release --no-build -- "$env:RUNNER_TEMP\handle-acl-proof" + if ($LASTEXITCODE -ne 0) { throw 'The isolated directory permission proof failed.' } + - name: Preserve the permission proof result + if: ${{ always() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: windows-directory-permission-proof-${{ github.sha }} + path: | + ${{ runner.temp }}/handle-acl-proof/handle-acl-proof.json + ${{ runner.temp }}/handle-acl-large/*.json + ${{ runner.temp }}/handle-acl-large/*.etl + ${{ runner.temp }}/handle-acl-large/*.xml + ${{ runner.temp }}/handle-acl-large/*.txt + ${{ runner.temp }}/handle-acl-large/*.log + ${{ runner.temp }}/handle-acl-large/measurement/*.json + if-no-files-found: error + + windows-native-package-diagnostic: + name: Built 0.1.3 installed replay (disabled until trusted-controller migration) + # This legacy caller-ref lane formerly received repository inference keys. + # Keep it fail-closed; only the default-branch reusable controller may own + # protected-environment credentials after repository setup is complete. + if: ${{ false }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 60 + steps: + - name: Check out the current Windows acceptance controller + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: candidate + persist-credentials: false + - name: Verify and extract the fixed built 0.1.3 artifacts + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + SOURCE_RUN_ID: ${{ inputs.windows_native_diagnostic_source_run_id }} + PRODUCT_VERSION: ${{ inputs.finished_windows_product_version }} + run: | + & "$env:GITHUB_WORKSPACE\candidate\packaging\windows\installer\download-published-preview.ps1" ` + -OutputDirectory "$env:RUNNER_TEMP\finished-windows" -SourceRunId $env:SOURCE_RUN_ID -ProductVersion $env:PRODUCT_VERSION + - name: Replay ordinary installed model, tools, Stop and uninstall + shell: pwsh + run: | + throw 'Legacy secret-bearing replay is disabled; use the trusted default-branch qualification workflow.' + - name: Preserve built-preview replay identity, timing and installed diagnostics + if: ${{ always() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: built013-installed-replay-${{ github.sha }} + path: | + ${{ runner.temp }}/finished-windows/replay-inputs.json + ${{ runner.temp }}/finished-windows/downloads/*.json + ${{ runner.temp }}/finished-windows/downloads/*.stderr.log + ${{ runner.temp }}/finished-windows/installed-smoke/ + ${{ runner.temp }}/finished-windows/installed-acceptance/ + ${{ runner.temp }}/finished-windows/installed-acceptance-warm/ + ${{ runner.temp }}/finished-windows/installed-stage-timings.json + ${{ runner.temp }}/finished-windows/*.log + ${{ runner.temp }}/finished-windows/package/*.json + if-no-files-found: warn + retention-days: 14 + + official-hermes-npm-shims: + name: Official npm12 Windows command discovery (ARM64) + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'npm-shims' && !inputs.test_native_windows_runtime && !inputs.profile_native_windows }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 10 + steps: + - name: Check out the bounded compiler diagnostic + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Prove original and delimited PATHEXT with the exact official npm shims + shell: pwsh + run: | + & "$env:GITHUB_WORKSPACE\packaging\windows\hermes\probe-official-npm-shims.ps1" ` + -ArtifactDirectory "$env:RUNNER_TEMP\official-hermes-npm-shims" + - name: Retain exact compiler input and Windows command evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: official-hermes-npm-shims-${{ github.sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/official-hermes-npm-shims/ + !${{ runner.temp }}/official-hermes-npm-shims/tools/ + if-no-files-found: error + retention-days: 14 + + official-hermes-export-controls: + name: Official runtime export path controls (Windows ARM64) + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'export-controls' && !inputs.test_native_windows_runtime && !inputs.profile_native_windows }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 10 + steps: + - name: Check out the bounded export controls + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Check exact alias paths, outside links and archive integrity + shell: pwsh + run: | + & "$env:GITHUB_WORKSPACE\packaging\windows\hermes\test-official-runtime-export.ps1" ` + -ArtifactDirectory "$env:RUNNER_TEMP\official-hermes-export-controls" + - name: Retain interpreter inputs and export-control evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: official-hermes-export-controls-${{ github.sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/official-hermes-export-controls/ + !${{ runner.temp }}/official-hermes-export-controls/tools/ + if-no-files-found: error + retention-days: 14 + + official-hermes-edge-host-prerequisite: + name: Native ARM64 Microsoft Edge prerequisite + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'edge-host-prerequisite' && !inputs.test_native_windows_runtime && !inputs.profile_native_windows }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 10 + permissions: + contents: read + steps: + - name: Check out the Windows Edge prerequisite + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Build the installed native Edge trust owner + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.95.0-aarch64-pc-windows-msvc + target: aarch64-pc-windows-msvc + cache: false + rustflags: "" + - name: Verify standard signed native ARM64 Microsoft Edge + shell: pwsh + run: | + $output = "$env:RUNNER_TEMP\native-edge-prerequisite" + $null = New-Item -ItemType Directory -Path $output + rustup run 1.95.0-aarch64-pc-windows-msvc cargo rustc --locked --release ` + --target aarch64-pc-windows-msvc --features immutable-runtime ` + --manifest-path "$env:GITHUB_WORKSPACE\packaging\windows\launcher\Cargo.toml" ` + --target-dir "$output\target" -- -C target-feature=+crt-static + if ($LASTEXITCODE -ne 0) { throw 'The native Edge trust owner did not compile.' } + $install = "$output\install" + $null = New-Item -ItemType Directory -Path "$install\bin" + Copy-Item -LiteralPath "$output\target\aarch64-pc-windows-msvc\release\NemoClaw.exe" -Destination "$install\bin\NemoClaw.exe" + $env:NEMOCLAW_NATIVE_INSTALL_ROOT = $install + node --experimental-strip-types --input-type=module -e @' + import assert from "node:assert/strict"; + import { spawnSync } from "node:child_process"; + import fs from "node:fs"; + import path from "node:path"; + import { detectNativeEdge } from "./packaging/windows/runtime/native-edge-browser.mts"; + if (process.platform !== "win32" || process.arch !== "arm64") throw new Error("Expected native Windows ARM64 Node."); + try { + const launcher = path.join(process.env.NEMOCLAW_NATIVE_INSTALL_ROOT, "bin", "NemoClaw.exe"); + const denial = spawnSync(launcher, ["--edge-trust", launcher], { encoding: "utf8", windowsHide: true }); + const denialReceipt = { schemaVersion: 1, classification: "native-edge-unsigned-denial", exitCode: denial.status, stdout: denial.stdout.trim(), stderr: denial.stderr.trim() }; + fs.writeFileSync(path.join(process.env.RUNNER_TEMP, "native-edge-prerequisite", "unsigned-denial.json"), JSON.stringify(denialReceipt, null, 2) + "\n", { flag: "wx" }); + assert.equal(denial.error, undefined); + assert.equal(denial.signal, null); + assert.equal(denial.status, 2); + assert.equal(denial.stdout, ""); + assert.match(denial.stderr, /^Microsoft Edge native identity verification failed \(0x[0-9a-f]{8}\)\.\r?\n$/u); + const generationResult = spawnSync(launcher, ["--edge-process-identity", String(process.pid)], { encoding: "utf8", windowsHide: true }); + assert.equal(generationResult.error, undefined); + assert.equal(generationResult.signal, null); + assert.equal(generationResult.status, 0); + assert.equal(generationResult.stderr, ""); + const generation = JSON.parse(generationResult.stdout); + assert.equal(generation.pid, process.pid); + assert.equal(generation.path.toLowerCase(), process.execPath.toLowerCase()); + assert.match(generation.creationFiletime, /^[0-9]{15,20}$/u); + const identity = await detectNativeEdge(); + fs.writeFileSync(path.join(process.env.RUNNER_TEMP, "native-edge-prerequisite", "edge-identity.json"), JSON.stringify({ ...identity, executed: false }, null, 2) + "\n", { flag: "wx" }); + } catch (error) { + fs.writeFileSync(path.join(process.env.RUNNER_TEMP, "native-edge-prerequisite", "edge-failure.json"), JSON.stringify({ schemaVersion: 1, classificationCategory: "native-edge-prerequisite", message: error instanceof Error ? error.message : "Edge validation failed" }, null, 2) + "\n", { flag: "wx" }); + throw error; + } + '@ + - name: Preserve Microsoft Edge identity evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: native-edge-prerequisite-${{ github.sha }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/native-edge-prerequisite/ + if-no-files-found: error + retention-days: 14 + + windows-bash-compatibility-reuse: + # Keep the job/output identity used by the same-run installer transfer. + name: Build and qualify current native Bash inputs + needs: windows-finished-request + if: ${{ needs.windows-finished-request.outputs.build_allowed == 'true' && needs.windows-finished-request.outputs.agent == 'hermes' }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 25 + permissions: + contents: read + outputs: + compatibility_cache_key: ${{ steps.compatibility_manifest.outputs.cache_key }} + compatibility_manifest_sha256: ${{ steps.compatibility_manifest.outputs.manifest_sha256 }} + steps: + - name: Check out current Bash qualification inputs + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ needs.windows-finished-request.outputs.candidate_repository }} + ref: ${{ needs.windows-finished-request.outputs.candidate_sha }} + path: current + persist-credentials: false + - name: Verify exact native producer source + shell: pwsh + env: + CANDIDATE_SHA: ${{ needs.windows-finished-request.outputs.candidate_sha }} + run: | + $revision = (& git -C current rev-parse HEAD | Out-String).Trim() + if ($LASTEXITCODE -ne 0 -or $revision -cne $env:CANDIDATE_SHA) { throw 'The native producer checkout differs from the admitted candidate.' } + - name: Prepare pinned Rust for the existing metadata helper + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.95.0 + target: aarch64-pc-windows-msvc + cache: false + - name: Build the existing fixed-purpose system-drive metadata helper + shell: pwsh + env: + CANDIDATE_SHA: ${{ needs.windows-finished-request.outputs.candidate_sha }} + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & current/packaging/windows/host-preparation/build-helper.ps1 -OutputDirectory "$env:RUNNER_TEMP\finished-bash-helper" + - name: Prepare upstream-pinned Rust for MXC token inspection + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.93.0 + target: aarch64-pc-windows-msvc + cache: false + override: false + - name: Build and qualify exact current native compatibility + shell: pwsh + env: + CANDIDATE_SHA: ${{ needs.windows-finished-request.outputs.candidate_sha }} + run: | + $env:GITHUB_SHA = $env:CANDIDATE_SHA + & current/packaging/windows/mxc-bash/run-bash-compat.ps1 ` + -SourceRoot "$env:GITHUB_WORKSPACE\current" ` + -ArtifactDirectory "$env:RUNNER_TEMP\finished-bash-evidence" ` + -HelperDirectory "$env:RUNNER_TEMP\finished-bash-helper" + - name: Seal same-run exact-input Bash evidence + id: compatibility_manifest + shell: pwsh + env: + CANDIDATE_SHA: ${{ needs.windows-finished-request.outputs.candidate_sha }} + run: | + $evidence = Join-Path $env:RUNNER_TEMP 'finished-bash-evidence' + $proof = Get-Content -LiteralPath (Join-Path $evidence 'result.json') -Raw | ConvertFrom-Json + $runner = Get-Content -LiteralPath (Join-Path $evidence 'runner-result.json') -Raw | ConvertFrom-Json + if ($proof.schemaVersion -ne 2 -or $proof.classification -cne 'small-msys-native-basecontainer-compatibility-proof' -or + $proof.sourceRevision -cne $env:CANDIDATE_SHA -or $proof.passed -cne $true -or $proof.normalCleanup -cne $true -or + $runner.sourceRevision -cne $env:CANDIDATE_SHA -or $runner.status -cne 'pass' -or + $runner.cleanup.workRootRemoved -cne $true -or $runner.cleanup.workRetainedForUnconfirmedExecutor -cne $false) { + throw 'The current native Bash execution or cleanup did not pass.' + } + $transfer = Join-Path $env:RUNNER_TEMP 'finished-windows-bash-transfer' + if (Test-Path -LiteralPath $transfer) { throw 'The native Bash transfer must be fresh.' } + $destination = Join-Path $transfer 'native-proof/bash-compat-evidence' + [void][IO.Directory]::CreateDirectory($destination) + # Preserve the producer's evidence layout, excluding only the same + # build/download trees omitted by the standalone Bash evidence lane. + $items = @(Get-ChildItem -LiteralPath $evidence -Recurse -Force) + if (@($items | Where-Object { $_.Attributes.HasFlag([IO.FileAttributes]::ReparsePoint) }).Count -ne 0) { + throw 'Native Bash evidence contains a reparse point.' + } + foreach ($file in $items | Where-Object { $_ -is [IO.FileInfo] }) { + $relative = [IO.Path]::GetRelativePath($evidence, $file.FullName).Replace('\', '/') + if ($relative -match '^(?:downloads|build|compatibility-build/build|mxc-token-inspection-build/build)/' -or + $relative -eq 'node/node.exe' -or $relative -match '^node/[^/]+\.zip$') { continue } + $target = Join-Path $destination $relative + [void][IO.Directory]::CreateDirectory((Split-Path -Parent $target)) + Copy-Item -LiteralPath $file.FullName -Destination $target + } + $manifest = @(& current/scripts/checks/windows-native-transfer.ps1 -Mode Create -Root $transfer ` + -Kind bash-compatibility -SourceRevision $env:CANDIDATE_SHA -Agent hermes ` + -RunId $env:GITHUB_RUN_ID -RunAttempt $env:GITHUB_RUN_ATTEMPT) + if ($manifest.Count -ne 1 -or [string]$manifest[0] -cnotmatch '^[a-f0-9]{64}$') { throw 'The Bash transfer manifest failed.' } + "manifest_sha256=$([string]$manifest[0])" >> $env:GITHUB_OUTPUT + "cache_key=windows-finished-bash-v2-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT-$env:CANDIDATE_SHA-hermes" >> $env:GITHUB_OUTPUT + - name: Save executable-bearing compatibility inputs only in the same-run cache + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/finished-windows-bash-transfer + key: ${{ steps.compatibility_manifest.outputs.cache_key }} + enableCrossOsArchive: true + - name: Preserve current native Bash diagnostic records without executables + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: finished-native-bash-records-${{ needs.windows-finished-request.outputs.candidate_sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/finished-bash-evidence/**/*.json + ${{ runner.temp }}/finished-bash-evidence/**/*.log + !${{ runner.temp }}/finished-bash-evidence/downloads/ + !${{ runner.temp }}/finished-bash-evidence/build/ + !${{ runner.temp }}/finished-bash-evidence/compatibility-build/build/ + !${{ runner.temp }}/finished-bash-evidence/mxc-token-inspection-build/build/ + if-no-files-found: warn + retention-days: 7 + + windows-bash-compatibility: + name: Canonical Bash private-namespace prototype (Windows ARM64) + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && inputs.probe_official_hermes_components && inputs.official_hermes_phase == 'bash-compat' && !inputs.test_native_windows_runtime && !inputs.profile_native_windows }} + outputs: + compatibility_id: ${{ steps.compatibility_artifact.outputs.artifact-id }} + runs-on: windows-11-vs2026-arm + timeout-minutes: 25 + permissions: + contents: read + steps: + - name: Check out the Windows compatibility prototype + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Prepare pinned Rust for the existing metadata helper + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.95.0 + target: aarch64-pc-windows-msvc + cache: false + - name: Build the existing fixed-purpose system-drive metadata helper + shell: pwsh + run: | + & packaging/windows/host-preparation/build-helper.ps1 -OutputDirectory "$env:RUNNER_TEMP\bash-compat-helper" + - name: Prepare upstream-pinned Rust for MXC token inspection + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.93.0 + target: aarch64-pc-windows-msvc + cache: false + override: false + - name: Build and test the isolated canonical Bash compatibility prototype + shell: pwsh + run: | + & packaging/windows/mxc-bash/run-bash-compat.ps1 ` + -SourceRoot "$env:GITHUB_WORKSPACE" ` + -ArtifactDirectory "$env:RUNNER_TEMP\bash-compat-evidence" ` + -HelperDirectory "$env:RUNNER_TEMP\bash-compat-helper" + - name: Preserve bounded compatibility evidence + id: compatibility_artifact + if: ${{ always() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: bash-compatibility-${{ github.sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/bash-compat-evidence/ + !${{ runner.temp }}/bash-compat-evidence/downloads/ + !${{ runner.temp }}/bash-compat-evidence/build/ + !${{ runner.temp }}/bash-compat-evidence/compatibility-build/build/ + !${{ runner.temp }}/bash-compat-evidence/mxc-token-inspection-build/build/ + !${{ runner.temp }}/bash-compat-evidence/node/node.exe + !${{ runner.temp }}/bash-compat-evidence/node/*.zip + ${{ runner.temp }}/bash-compat-helper/build-receipt.json + ${{ runner.temp }}/bash-compat-helper/build.log + if-no-files-found: error + retention-days: 7 + + official-hermes-personal-candidate: + name: Canonical Hermes candidate Personal MXC feasibility (Windows ARM64) + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && inputs.probe_official_hermes_components && (inputs.official_hermes_phase == 'personal-browser-first' || inputs.official_hermes_phase == 'personal-candidate' || inputs.official_hermes_phase == 'personal-cold-job' || inputs.official_hermes_phase == 'personal-renderer-wer' || inputs.official_hermes_phase == 'personal-postmortem') && !inputs.test_native_windows_runtime && !inputs.profile_native_windows }} + runs-on: windows-11-vs2026-arm + # Ordinary qualification derives the current complete base with same-run native proof. + # Explicit historical diagnostic phases retain their immutable replay contract. + # The contained component/startup deadlines remain unchanged. + timeout-minutes: 60 + permissions: + contents: read + actions: read + steps: + - name: Check out the Windows feasibility controller + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Prepare pinned native Rust for the admitted metadata helper + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.95.0 + target: aarch64-pc-windows-msvc + cache: false + - name: Verify pinned interpreters and archive admission controls + shell: pwsh + run: | + $bootstrap = "$env:RUNNER_TEMP\personal-bootstrap" + & packaging/windows/hermes/test-official-runtime-export.ps1 -ArtifactDirectory $bootstrap + $record = Get-Content -LiteralPath "$bootstrap\export-controls.json" -Raw | ConvertFrom-Json + $env:NEMOCLAW_TEST_PYTHON = $record.pythonPath + $env:NEMOCLAW_PERSONAL_CONTROL_EVIDENCE = "$env:RUNNER_TEMP\personal-controls" + $null = New-Item -ItemType Directory -Path $env:NEMOCLAW_PERSONAL_CONTROL_EVIDENCE + & "$bootstrap\tools\node\node-v22.23.2-win-arm64\node.exe" --experimental-strip-types --no-warnings --test packaging/windows/hermes/personal-candidate.test.mts + if ($LASTEXITCODE -ne 0) { throw 'The candidate admission/Personal controls failed.' } + - name: Build the fixed-purpose system-drive metadata helper + shell: pwsh + run: | + & packaging/windows/host-preparation/build-helper.ps1 -OutputDirectory "$env:RUNNER_TEMP\personal-helper" + - name: Prepare pinned native Rust for Personal compatibility + if: ${{ inputs.official_hermes_phase == 'personal-candidate' }} + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.93.0 + target: aarch64-pc-windows-msvc + override: false + cache: false + - name: Build and qualify current Personal native inputs + if: ${{ inputs.official_hermes_phase == 'personal-candidate' }} + shell: pwsh + run: | + $head = (& git rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $head -cne $env:GITHUB_SHA) { throw 'Personal producer checkout differs from its source.' } + & packaging/windows/mxc-bash/run-bash-compat.ps1 -SourceRoot $env:GITHUB_WORKSPACE ` + -ArtifactDirectory "$env:RUNNER_TEMP\personal-native-inputs" -HelperDirectory "$env:RUNNER_TEMP\personal-helper" + - name: Prepare the complete candidate and test canonical Personal components + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: | + $native = @{} + if ("${{ inputs.official_hermes_phase }}" -ceq 'personal-candidate') { + $rustc = & rustup which --toolchain 1.95.0 rustc + if ($LASTEXITCODE -ne 0) { throw 'The pinned ConPTY Rust compiler is unavailable.' } + $native = @{ NativeCompatibilityDirectory = "$env:RUNNER_TEMP\personal-native-inputs"; RustBinDirectory = (Split-Path -Parent $rustc) } + } + & packaging/windows/hermes/probe-personal-candidate.ps1 ` + -ArtifactDirectory "$env:RUNNER_TEMP\official-hermes-personal" ` + -BootstrapDirectory "$env:RUNNER_TEMP\personal-bootstrap" ` + -HelperDirectory "$env:RUNNER_TEMP\personal-helper" ` + -RecordStartup:("${{ inputs.record_hermes_startup }}" -ceq 'true') ` + -CaptureRendererContext:("${{ inputs.capture_hermes_renderer_context }}" -ceq 'true') ` + -ColdJobProbe:("${{ inputs.official_hermes_phase }}" -ceq 'personal-cold-job') ` + -RendererWer:("${{ inputs.official_hermes_phase }}" -ceq 'personal-renderer-wer') ` + -RendererPostmortem:("${{ inputs.official_hermes_phase }}" -ceq 'personal-postmortem') ` + -BrowserFirst:("${{ inputs.official_hermes_phase }}" -ceq 'personal-browser-first') @native + - name: Preserve current native Personal runtime inputs + if: ${{ success() && inputs.official_hermes_phase == 'personal-candidate' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: official-hermes-native-personal-runtime-${{ github.sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-candidate/ + ${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-build/official-runtime-build.json + ${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-build/native-adaptation.json + ${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-phase.json + ${{ runner.temp }}/official-hermes-personal/personal-phase.json + ${{ runner.temp }}/official-hermes-personal/personal-mxc/ + ${{ runner.temp }}/personal-native-inputs/ + !${{ runner.temp }}/personal-native-inputs/downloads/ + !${{ runner.temp }}/personal-native-inputs/build/ + !${{ runner.temp }}/personal-native-inputs/compatibility-build/build/ + !${{ runner.temp }}/personal-native-inputs/mxc-token-inspection-build/build/ + !${{ runner.temp }}/personal-native-inputs/node/node.exe + !${{ runner.temp }}/personal-native-inputs/node/*.zip + if-no-files-found: error + retention-days: 7 + - name: Preserve small exact-candidate feasibility evidence + if: ${{ always() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: official-hermes-personal-feasibility-${{ github.sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/official-hermes-personal/ + !${{ runner.temp }}/official-hermes-personal/downloads/ + !${{ runner.temp }}/official-hermes-personal/primary-wpr/ + !${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-build/pywinpty/tools/ + !${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-build/pywinpty/downloads/ + !${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-build/pywinpty/source/ + !${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-build/pywinpty/cargo-home/ + !${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-build/pywinpty/build-env/ + !${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-build/pywinpty/target/ + !${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-build/pywinpty/uv-cache/ + !${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-build/pywinpty/npm-cache/ + !${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-candidate/*.tar.gz + !${{ runner.temp }}/official-hermes-personal/official-hermes-runtime-candidate/*.tar.gz.partial + ${{ runner.temp }}/personal-bootstrap/export-controls.json + ${{ runner.temp }}/personal-bootstrap/results/ + ${{ runner.temp }}/personal-controls/ + ${{ runner.temp }}/personal-helper/build-receipt.json + ${{ runner.temp }}/personal-helper/build.log + ${{ runner.temp }}/personal-native-inputs/**/*.json + ${{ runner.temp }}/personal-native-inputs/**/*.log + !${{ runner.temp }}/personal-native-inputs/downloads/ + !${{ runner.temp }}/personal-native-inputs/build/ + !${{ runner.temp }}/personal-native-inputs/compatibility-build/build/ + !${{ runner.temp }}/personal-native-inputs/mxc-token-inspection-build/build/ + if-no-files-found: error + retention-days: 7 + + - name: Retain bounded ordinary Personal WPR evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: official-hermes-personal-trace-${{ github.sha }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/official-hermes-personal/primary-wpr/ + if-no-files-found: warn + retention-days: 14 + + official-hermes-components: + name: Official Hermes ${{ inputs.official_hermes_phase || 'components' }} probe (Windows ARM64) + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && inputs.probe_official_hermes_components && inputs.official_hermes_phase != 'host-prerequisites' && inputs.official_hermes_phase != 'application' && inputs.official_hermes_phase != 'system-drive' && inputs.official_hermes_phase != 'npm-shims' && inputs.official_hermes_phase != 'export-controls' && inputs.official_hermes_phase != 'edge-host-prerequisite' && inputs.official_hermes_phase != 'personal-browser-first' && inputs.official_hermes_phase != 'personal-candidate' && inputs.official_hermes_phase != 'personal-cold-job' && inputs.official_hermes_phase != 'personal-renderer-wer' && inputs.official_hermes_phase != 'personal-postmortem' && inputs.official_hermes_phase != 'trace-analysis' && inputs.official_hermes_phase != 'bash-compat' && !inputs.test_native_windows_runtime && !inputs.profile_native_windows }} + runs-on: windows-11-vs2026-arm + timeout-minutes: ${{ inputs.official_hermes_phase == 'runtime' && 180 || 90 }} + steps: + - name: Check out the component probe + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Provision pinned official Hermes components + id: hermes-components + shell: powershell + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $runtimeRoot = "$env:SystemDrive\NemoClawHermesProbe-$([guid]::NewGuid().ToString('N').Substring(0, 12))" + "runtime_root=$runtimeRoot" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append + & "$env:GITHUB_WORKSPACE\packaging\windows\hermes\prepare-official-components.ps1" ` + -RuntimeRoot $runtimeRoot ` + -ArtifactDirectory "$env:RUNNER_TEMP\official-hermes-components" + + - name: Check the canonical Python phase result contract + if: ${{ (inputs.official_hermes_phase == 'python' || inputs.official_hermes_phase == 'runtime') }} + shell: powershell + env: + HERMES_COMPONENT_ROOT: ${{ steps.hermes-components.outputs.runtime_root }} + run: | + & "$env:GITHUB_WORKSPACE\packaging\windows\hermes\test-official-python.ps1" + & "$env:GITHUB_WORKSPACE\packaging\windows\hermes\test-official-python-process.ps1" + & "$env:GITHUB_WORKSPACE\packaging\windows\hermes\test-official-msvc-tools.ps1" + & "$env:GITHUB_WORKSPACE\packaging\windows\hermes\test-official-python-semantics.ps1" ` + -OfficialInstallerPath "$env:HERMES_COMPONENT_ROOT\hermes-agent\scripts\install.ps1" + & "$env:GITHUB_WORKSPACE\packaging\windows\hermes\test-official-registry-path.ps1" ` + -OfficialInstallerPath "$env:HERMES_COMPONENT_ROOT\hermes-agent\scripts\install.ps1" ` + -ReceiptPath "$env:RUNNER_TEMP\official-hermes-components\python-registry-path-controls.json" + + - name: Set up pinned native Rust for canonical Hermes Python + if: ${{ (inputs.official_hermes_phase == 'python' || inputs.official_hermes_phase == 'runtime') }} + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.95.0-aarch64-pc-windows-msvc + target: aarch64-pc-windows-msvc + cache: false + rustflags: "" + + - name: Provision canonical Hermes Python before baseline setup + if: ${{ (inputs.official_hermes_phase == 'python' || inputs.official_hermes_phase == 'runtime') }} + id: hermes-python + shell: powershell + # Pinned OpenSSL SDK build precedes the unchanged 20-minute Python stage. + timeout-minutes: ${{ inputs.official_hermes_phase == 'runtime' && 165 || 55 }} + env: + HERMES_COMPONENT_ROOT: ${{ steps.hermes-components.outputs.runtime_root }} + HERMES_SELECTED_PHASE: ${{ inputs.official_hermes_phase }} + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $toolchain = '1.95.0-aarch64-pc-windows-msvc' + $rustc = (& rustup which --toolchain $toolchain rustc).Trim() + if ($LASTEXITCODE -ne 0) { throw 'The pinned native Rust compiler is missing.' } + $cargo = (& rustup which --toolchain $toolchain cargo).Trim() + if ($LASTEXITCODE -ne 0) { throw 'The pinned native Cargo is missing.' } + $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' + $vsDevCmd = (& $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.ARM64 -find 'Common7\Tools\VsDevCmd.bat' | Select-Object -First 1) + if ($LASTEXITCODE -ne 0 -or -not $vsDevCmd) { throw 'The runner does not contain the required Visual Studio ARM64 tools.' } + $powershell = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' + $entry = if ($env:HERMES_SELECTED_PHASE -eq 'runtime') { 'prepare-official-runtime.ps1' } else { 'prepare-official-python.ps1' } + $script = Join-Path "$env:GITHUB_WORKSPACE\packaging\windows\hermes" $entry + $phaseLock = "$env:GITHUB_WORKSPACE\packaging\windows\hermes\official-python.lock.json" + $evidence = "$env:RUNNER_TEMP\official-hermes-python" + $components = "$env:RUNNER_TEMP\official-hermes-components" + foreach ($value in @($vsDevCmd, $powershell, $script, $phaseLock, $evidence, $components, $rustc, $cargo, $env:HERMES_COMPONENT_ROOT)) { + if ($value -match '["\r\n%!]') { throw 'A build-prerequisite path cannot be represented safely.' } + } + $command = 'call "' + $vsDevCmd + '" -arch=arm64 -host_arch=arm64 && "' + $powershell + '" -NoProfile -ExecutionPolicy Bypass -File "' + $script + '" -LockPath "' + $phaseLock + '" -RuntimeRoot "' + $env:HERMES_COMPONENT_ROOT + '" -ArtifactDirectory "' + $evidence + '" -ComponentEvidenceDirectory "' + $components + '" -RustcPath "' + $rustc + '" -CargoPath "' + $cargo + '"' + if ($env:HERMES_SELECTED_PHASE -eq 'runtime') { $command += ' -ControllerSource "' + $env:GITHUB_SHA + '"' } + & "$env:SystemRoot\System32\cmd.exe" /d /c $command + if ($LASTEXITCODE -ne 0) { throw 'The canonical Hermes Python phase failed; baseline setup will not run.' } + + - name: Upload the complete unqualified official runtime candidate + if: ${{ always() && inputs.official_hermes_phase == 'runtime' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: official-hermes-runtime-candidate-${{ github.sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/official-hermes-runtime-candidate/ + ${{ runner.temp }}/official-hermes-runtime-build/ + ${{ runner.temp }}/official-hermes-runtime-phase.json + ${{ runner.temp }}/official-hermes-export-controls/ + !${{ runner.temp }}/official-hermes-export-controls/tools/ + ${{ runner.temp }}/official-hermes-components/ + ${{ runner.temp }}/official-hermes-python/ + !${{ runner.temp }}/official-hermes-components/downloads/ + !${{ runner.temp }}/official-hermes-python/downloads/ + !${{ runner.temp }}/official-hermes-python/cargo-home/ + !${{ runner.temp }}/official-hermes-python/dependency-stage/uv-cache/ + !${{ runner.temp }}/official-hermes-python/openssl/downloads/ + !${{ runner.temp }}/official-hermes-python/openssl/strawberryperl/ + !${{ runner.temp }}/official-hermes-python/openssl/nasm-windows-bin/ + !${{ runner.temp }}/official-hermes-python/openssl/jom-windows-bin/ + !${{ runner.temp }}/official-hermes-python/openssl/openssl/ + !${{ runner.temp }}/official-hermes-runtime-build/downloads/ + !${{ runner.temp }}/official-hermes-runtime-build/browser-use-wheels/ + !${{ runner.temp }}/official-hermes-runtime-build/uv-cache/ + !${{ runner.temp }}/official-hermes-runtime-build/npm-cache/ + !${{ runner.temp }}/official-hermes-runtime-build/node-build/ + !${{ runner.temp }}/official-hermes-runtime-build/node-build-tools/ + !${{ runner.temp }}/official-hermes-runtime-build/node-addon-headers/ + if-no-files-found: error + retention-days: 14 + + - name: Install the immutable MXC baseline + if: ${{ inputs.official_hermes_phase != 'python' && inputs.official_hermes_phase != 'runtime' }} + id: component-baseline + shell: powershell + run: | + & "$env:GITHUB_WORKSPACE\packaging\windows\hermes\component-probe-baseline.ps1" ` + -ArtifactDirectory "$env:RUNNER_TEMP\official-hermes-baseline" + + - name: Check bounded component process diagnostics on Windows + if: ${{ steps.component-baseline.outcome == 'success' }} + id: component-controls + shell: powershell + run: | + & "$env:GITHUB_WORKSPACE\packaging\windows\performance\acl-snapshot.test.ps1" + $node = Join-Path $env:ProgramFiles 'NVIDIA\NemoClaw\bin\node.exe' + & $node --experimental-strip-types --no-warnings --test ` + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/hermes/probe-components.test.mts') ` + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/hermes/portable-git-arguments.test.mts') ` + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/hermes/probe-python-temp.test.mts') ` + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/performance/measurement.test.mts') ` + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/performance/compile-cache-experiment.test.mts') + if ($LASTEXITCODE -ne 0) { throw 'The component process diagnostic controls failed.' } + + - name: Execute the official components inside MXC + if: ${{ steps.component-baseline.outcome == 'success' && steps.component-controls.outcome == 'success' }} + shell: powershell + env: + HERMES_COMPONENT_ROOT: ${{ steps.hermes-components.outputs.runtime_root }} + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $installRoot = Join-Path $env:ProgramFiles 'NVIDIA\NemoClaw' + & "$installRoot\bin\node.exe" --experimental-strip-types --no-warnings ` + "$env:GITHUB_WORKSPACE\packaging\windows\hermes\probe-official-components.mts" ` + --install-root $installRoot ` + --runtime-root $env:HERMES_COMPONENT_ROOT ` + --artifact-directory "$env:RUNNER_TEMP\official-hermes-mxc" + if ($LASTEXITCODE -ne 0) { throw 'The official Hermes MXC component probe failed.' } + + - name: Check official Python temp permissions before and after the startup adapter + if: ${{ !cancelled() && steps.component-baseline.outcome == 'success' && steps.component-controls.outcome == 'success' }} + shell: powershell + env: + HERMES_COMPONENT_ROOT: ${{ steps.hermes-components.outputs.runtime_root }} + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $installRoot = Join-Path $env:ProgramFiles 'NVIDIA\NemoClaw' + & "$installRoot\bin\node.exe" --experimental-strip-types --no-warnings ` + "$env:GITHUB_WORKSPACE\packaging\windows\hermes\probe-official-python-adapter.mts" ` + --install-root $installRoot ` + --runtime-root $env:HERMES_COMPONENT_ROOT ` + --artifact-directory "$env:RUNNER_TEMP\official-hermes-python-temp" + if ($LASTEXITCODE -ne 0) { throw 'The official Python before/after temp adapter control failed.' } + + - name: Probe installed runtime access and contained compile-cache A/B + if: ${{ !cancelled() && steps.component-baseline.outcome == 'success' && steps.component-controls.outcome == 'success' }} + shell: powershell + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $installRoot = Join-Path $env:ProgramFiles 'NVIDIA\NemoClaw' + & "$installRoot\bin\node.exe" --experimental-strip-types --no-warnings ` + "$env:GITHUB_WORKSPACE\packaging\windows\performance\probe-installed-readonly.mts" ` + --install-root $installRoot ` + --source-revision f8a1d8c702c879d2984d76d2e0419641bb1ccd97 ` + --artifact-directory "$env:RUNNER_TEMP\installed-runtime-readonly" ` + --compile-cache-experiment ` + --runtime-manifest-sha256 d36e977401cf8188350e657137bf649c654f4554a6c4da299f9b2b9353e7066e + if ($LASTEXITCODE -ne 0) { throw 'The installed read-only runtime probe failed.' } + + - name: Upload failed component evidence before baseline cleanup + if: ${{ failure() && inputs.official_hermes_phase != 'runtime' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: official-hermes-windows-mxc-components-precleanup-${{ github.sha }} + path: | + ${{ runner.temp }}/official-hermes-components/ + ${{ runner.temp }}/official-hermes-python/ + ${{ runner.temp }}/official-hermes-python-temp/ + ${{ runner.temp }}/official-hermes-mxc/ + ${{ runner.temp }}/installed-runtime-readonly/ + !${{ runner.temp }}/official-hermes-components/downloads/ + !${{ runner.temp }}/official-hermes-python/openssl/downloads/ + !${{ runner.temp }}/official-hermes-python/openssl/strawberryperl/ + !${{ runner.temp }}/official-hermes-python/openssl/nasm-windows-bin/ + !${{ runner.temp }}/official-hermes-python/openssl/jom-windows-bin/ + !${{ runner.temp }}/official-hermes-python/openssl/openssl/ + !${{ runner.temp }}/official-hermes-python/downloads/ + !${{ runner.temp }}/official-hermes-python/cargo-home/ + !${{ runner.temp }}/official-hermes-python/dependency-stage/uv-cache/ + if-no-files-found: warn + retention-days: 14 + + - name: Uninstall the component probe baseline + if: ${{ always() && inputs.official_hermes_phase != 'runtime' && steps.component-baseline.outcome != 'skipped' }} + shell: powershell + run: | + & "$env:GITHUB_WORKSPACE\packaging\windows\hermes\component-probe-baseline.ps1" ` + -ArtifactDirectory "$env:RUNNER_TEMP\official-hermes-baseline" -Uninstall + + - name: Upload official Hermes component evidence + if: ${{ always() && inputs.official_hermes_phase != 'runtime' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: official-hermes-windows-mxc-components-${{ github.sha }} + path: | + ${{ runner.temp }}/official-hermes-baseline/ + ${{ runner.temp }}/official-hermes-components/ + ${{ runner.temp }}/official-hermes-python/ + ${{ runner.temp }}/official-hermes-python-temp/ + ${{ runner.temp }}/official-hermes-mxc/ + ${{ runner.temp }}/installed-runtime-readonly/ + !${{ runner.temp }}/official-hermes-baseline/baseline-setup.exe + !${{ runner.temp }}/official-hermes-components/downloads/ + !${{ runner.temp }}/official-hermes-python/openssl/downloads/ + !${{ runner.temp }}/official-hermes-python/openssl/strawberryperl/ + !${{ runner.temp }}/official-hermes-python/openssl/nasm-windows-bin/ + !${{ runner.temp }}/official-hermes-python/openssl/jom-windows-bin/ + !${{ runner.temp }}/official-hermes-python/openssl/openssl/ + !${{ runner.temp }}/official-hermes-python/downloads/ + !${{ runner.temp }}/official-hermes-python/cargo-home/ + !${{ runner.temp }}/official-hermes-python/dependency-stage/uv-cache/ + if-no-files-found: error + retention-days: 14 + + windows-native-profiling: + name: Installed Windows baseline profiling (diagnostic only) + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && inputs.profile_native_windows && !inputs.test_native_windows_runtime }} + runs-on: windows-11-vs2026-arm + # Existing target allowances: 15m install + 30m warm prep + 45m replays + # + 15m uninstall; download/recording finalization retain bounded headroom. + timeout-minutes: 150 + steps: + - name: Check out the profiling controller + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Validate the explicit profiling request + shell: powershell + env: + OTHER_BUILD: ${{ inputs.run_windows_native_installer }} + OTHER_COMPONENTS: ${{ inputs.probe_official_hermes_components }} + OTHER_DIAGNOSTIC: ${{ inputs.windows_native_diagnostic_source_run_id }} + run: | + if ($env:OTHER_BUILD -eq 'true' -or $env:OTHER_COMPONENTS -eq 'true' -or $env:OTHER_DIAGNOSTIC) { + throw 'Profiling is a separate explicit dispatch and cannot also build or run component diagnostics.' + } + + - name: Set up the profiling controller Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24.18.1 + architecture: arm64 + + - name: Resolve the reviewed npm Git Bash scratch path + id: reviewed-npm-temp + shell: bash + run: | + path="$(cygpath -u "$RUNNER_TEMP")" + [[ "$path" == /* ]] + printf 'path=%s\n' "$path" >> "$GITHUB_OUTPUT" + + - name: Install reviewed npm + uses: ./.github/actions/setup-reviewed-npm + env: + RUNNER_TEMP: ${{ steps.reviewed-npm-temp.outputs.path }} + TAR_OPTIONS: --force-local + + - name: Record actual installation and dashboard CPU and file I/O + shell: powershell + run: | + & "$env:GITHUB_WORKSPACE\packaging\windows\performance\run-profiling-phase.ps1" ` + -ArtifactDirectory "$env:RUNNER_TEMP\windows-native-profiling" ` + -HarnessNodePath ((Get-Command node.exe -CommandType Application | Select-Object -First 1).Source) ` + -ControllerSha $env:GITHUB_SHA + + - name: Upload profiling evidence including failures and capped traces + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: windows-native-profiling-${{ github.sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/windows-native-profiling/ + !${{ runner.temp }}/windows-native-profiling/baseline/baseline-setup.exe + if-no-files-found: warn + compression-level: 6 + retention-days: 14 + + windows-runtime-controls: + name: Native Windows ownership and isolated MSI controls + needs: windows-runtime-preflight + if: ${{ github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && !inputs.run_windows_native_installer && inputs.test_native_windows_runtime) }} + permissions: + contents: read + runs-on: windows-11-vs2026-arm + timeout-minutes: 20 + steps: + - name: Check out the native ownership controls + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Validate the explicit ownership request + shell: powershell + env: + OTHER_BUILD: ${{ inputs.run_windows_native_installer }} + OTHER_COMPONENTS: ${{ inputs.probe_official_hermes_components }} + OTHER_PROFILE: ${{ inputs.profile_native_windows }} + OTHER_DIAGNOSTIC: ${{ inputs.windows_native_diagnostic_source_run_id }} + run: | + if ($env:OTHER_BUILD -eq 'true' -or $env:OTHER_COMPONENTS -eq 'true' -or $env:OTHER_PROFILE -eq 'true' -or $env:OTHER_DIAGNOSTIC) { + throw 'Native ownership controls require a separate explicit dispatch.' + } + + - name: Set up actual ARM64 Node for controller preflight and shared-file fixtures + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24.18.1 + architecture: arm64 + + - name: Exercise installed acceptance controller compatibility + shell: powershell + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-controls' + [IO.Directory]::CreateDirectory($output) | Out-Null + $log = Join-Path $output 'installed-acceptance-controller-tests.log' + $tests = @( + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/control-installed-openclaw-input.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-turn-cleanup.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/run-installed-acceptance.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/qualify-finished-package.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-ui-tunnel.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/qualify-installed-hermes.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/installer/windows-native-transfer.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-configuration-credentials.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-setup-transaction.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-remove-data.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-local-models.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-bundled-inference.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-inference.test.mts'), + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-setup-local-models.test.mts') + ) + try { + $ErrorActionPreference = 'Continue' + & node --experimental-strip-types --no-warnings --test --test-reporter=tap @tests ` + 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($result -ne 0) { throw 'The installed acceptance controller controls failed.' } + + - name: Set up pinned Rust for the native ownership controls + uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.95.0-aarch64-pc-windows-msvc + target: aarch64-pc-windows-msvc + cache: false + rustflags: "" + + - name: Check the native transaction helper + shell: powershell + env: + CARGO_TERM_COLOR: never + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-controls' + [IO.Directory]::CreateDirectory($output) | Out-Null + $log = Join-Path $output 'msi-helper-tests.log' + try { + $ErrorActionPreference = 'Continue' + & rustup run 1.95.0-aarch64-pc-windows-msvc cargo test --locked ` + --manifest-path "$env:GITHUB_WORKSPACE\packaging\windows\installer\Cargo.toml" ` + --target aarch64-pc-windows-msvc --features msi-boundary-fixture -- ` + --nocapture --test-threads=1 --skip runtime_lease:: 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($result -ne 0 -or (Get-Content -LiteralPath $log -Raw) -notmatch 'test result: ok\. 33 passed; 0 failed; 0 ignored;') { + throw 'The thirty-three transaction, image cleanup, manifest, mount ACL and native SHA256 controls did not all pass.' + } + + - name: Exercise native certificate revocation requests + shell: powershell + env: + CARGO_TERM_COLOR: never + run: | + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-controls' + [IO.Directory]::CreateDirectory($output) | Out-Null + $log = Join-Path $output 'edge-trust-tests.log' + try { + $ErrorActionPreference = 'Continue' + & rustup run 1.95.0-aarch64-pc-windows-msvc cargo test --locked ` + --manifest-path "$env:GITHUB_WORKSPACE\packaging\windows\launcher\Cargo.toml" ` + --target aarch64-pc-windows-msvc edge_trust:: -- --nocapture 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($result -ne 0 -or (Get-Content -LiteralPath $log -Raw) -notmatch 'test result: ok\. 6 passed; 0 failed; 0 ignored;') { + throw 'The native Edge certificate trust controls did not all pass.' + } + + - name: Reject unavailable revocation through the native Windows trust API + timeout-minutes: 5 + shell: pwsh + run: | + $output = Join-Path $env:RUNNER_TEMP 'edge-revocation-control' + & rustup run 1.95.0-aarch64-pc-windows-msvc cargo build --locked ` + --manifest-path "$env:GITHUB_WORKSPACE\packaging\windows\launcher\Cargo.toml" ` + --target aarch64-pc-windows-msvc --target-dir "$output\target" + if ($LASTEXITCODE -ne 0) { throw 'The native certificate trust owner did not build.' } + & "$env:GITHUB_WORKSPACE\packaging\windows\tests\edge-trust\run-revocation-control.ps1" ` + -Launcher "$output\target\aarch64-pc-windows-msvc\debug\NemoClaw.exe" + + - name: Exercise real Windows leases and protected fixtures + shell: powershell + env: + CARGO_TERM_COLOR: never + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-controls' + [IO.Directory]::CreateDirectory($output) | Out-Null + $log = Join-Path $output 'runtime-lease-tests.log' + try { + $ErrorActionPreference = 'Continue' + & rustup run 1.95.0-aarch64-pc-windows-msvc cargo test --locked ` + --manifest-path "$env:GITHUB_WORKSPACE\packaging\windows\launcher\Cargo.toml" ` + --target aarch64-pc-windows-msvc runtime_lease:: -- --nocapture --test-threads=1 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($result -ne 0) { throw 'The real native runtime ownership controls failed.' } + if ((Get-Content -LiteralPath $log -Raw) -notmatch 'test result: ok\. 19 passed; 0 failed; 0 ignored;') { + throw 'The six portable and thirteen Windows ownership controls did not all execute.' + } + + - name: Exercise shared configuration and per-agent state ownership + shell: powershell + env: + CARGO_TERM_COLOR: never + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-controls' + $log = Join-Path $output 'state-session-tests.log' + try { + $ErrorActionPreference = 'Continue' + & rustup run 1.95.0-aarch64-pc-windows-msvc cargo test --locked ` + --manifest-path "$env:GITHUB_WORKSPACE\packaging\windows\launcher\Cargo.toml" ` + --target aarch64-pc-windows-msvc state_session:: -- --nocapture --test-threads=1 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + $text = [string](Get-Content -LiteralPath $log -Raw) + if ($result -ne 0 -or $text -notmatch '(?m)^test result: ok\. 18 passed; 0 failed; 0 ignored;') { + throw 'The shared configuration and per-agent state ownership controls did not all pass.' + } + + - name: Exercise owned child and grandchild lifetime + shell: powershell + env: + CARGO_TERM_COLOR: never + NEMOCLAW_BROWSER_PROOF: "1" + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-controls' + [IO.Directory]::CreateDirectory($output) | Out-Null + $log = Join-Path $output 'runtime-host-tests.log' + try { + $ErrorActionPreference = 'Continue' + & rustup run 1.95.0-aarch64-pc-windows-msvc cargo test --locked ` + --manifest-path "$env:GITHUB_WORKSPACE\packaging\windows\launcher\Cargo.toml" ` + --target aarch64-pc-windows-msvc runtime_host:: -- --include-ignored --nocapture --test-threads=1 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($result -ne 0) { throw 'The native runtime guardian controls failed.' } + if ((Get-Content -LiteralPath $log -Raw) -notmatch 'test result: ok\. 23 passed; 0 failed; 0 ignored;') { + throw 'The twenty-two guardian/browser controls and their child-fixture entry did not all execute.' + } + + - name: Set up pinned tools for isolated MSI fixtures + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 8.0.419 + + - name: Verify cached maintenance cancellation and deadline handling + shell: powershell + run: | + & dotnet run --configuration Release --project ` + packaging/windows/tests/maintenance-wait/Maintenance.Wait.Controls.csproj + if ($LASTEXITCODE -ne 0) { throw 'The cached maintenance wait controls failed.' } + + - name: Verify setup cancellation checkpoints before configuration mutation + shell: powershell + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-controls' + [IO.Directory]::CreateDirectory($output) | Out-Null + $log = Join-Path $output 'setup-cancellation-controls.log' + try { + $ErrorActionPreference = 'Continue' + & dotnet run --configuration Release --project ` + packaging/windows/tests/setup-cancellation/Setup.Cancellation.Controls.csproj ` + 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($result -ne 0) { throw 'The setup cancellation checkpoint controls failed.' } + + - name: Resolve the reviewed npm Git Bash scratch path + id: reviewed-npm-temp + shell: bash + run: | + path="$(cygpath -u "$RUNNER_TEMP")" + [[ "$path" == /* ]] + printf 'path=%s\n' "$path" >> "$GITHUB_OUTPUT" + + - name: Install reviewed npm + uses: ./.github/actions/setup-reviewed-npm + env: + RUNNER_TEMP: ${{ steps.reviewed-npm-temp.outputs.path }} + TAR_OPTIONS: --force-local + + - name: Exercise actual browser request channel cleanup + shell: powershell + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $log = Join-Path $env:RUNNER_TEMP 'windows-runtime-controls\runtime-browser-node-tests.log' + try { + $ErrorActionPreference = 'Continue' + & node --experimental-strip-types --no-warnings --test --test-reporter=tap ` + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/runtime/native-runtime-browser.test.mts') 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + $text = Get-Content -LiteralPath $log -Raw + if ($result -ne 0 -or $text -notmatch '(?m)^# pass 6\r?$' -or $text -notmatch '(?m)^# skipped 0\r?$') { + throw 'All six browser origin and actual named-pipe cleanup controls must execute.' + } + + - name: Set up build-only Python for MSI fixture authoring + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.1.0 + with: + python-version: 3.13.13 + architecture: arm64 + + - name: Exercise native file ownership and relay counters + shell: powershell + env: + CARGO_TERM_COLOR: never + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-controls' + $log = Join-Path $output 'native-ui-file-owner-tests.log' + try { + $ErrorActionPreference = 'Continue' + & rustup run 1.95.0-aarch64-pc-windows-msvc cargo test --locked ` + --manifest-path "$env:GITHUB_WORKSPACE\packaging\windows\launcher\Cargo.toml" ` + --target aarch64-pc-windows-msvc native_ui_file_owner:: -- --nocapture --test-threads=1 2>&1 | Tee-Object -FilePath $log + $result = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($result -ne 0 -or (Get-Content -LiteralPath $log -Raw) -notmatch 'test result: ok\. 15 passed; 0 failed; 0 ignored;') { + throw 'The two portable and thirteen Windows file-owner controls did not all pass.' + } + $target = Join-Path $env:RUNNER_TEMP 'windows-runtime-test-launcher' + try { + $ErrorActionPreference = 'Continue' + & rustup run 1.95.0-aarch64-pc-windows-msvc cargo rustc --locked --release --no-default-features ` + --manifest-path "$env:GITHUB_WORKSPACE\packaging\windows\launcher\Cargo.toml" ` + --target aarch64-pc-windows-msvc --target-dir $target -- -C target-feature=+crt-static ` + 2>&1 | Tee-Object -FilePath (Join-Path $output 'relay-launcher-build.log') + $buildResult = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + if ($buildResult -ne 0) { throw 'The native relay fixture launcher did not build.' } + $env:NEMOCLAW_NATIVE_TEST_LAUNCHER = Join-Path $target 'aarch64-pc-windows-msvc\release\NemoClaw.exe' + $relayLog = Join-Path $output 'relay-measurement-tests.log' + try { + $ErrorActionPreference = 'Continue' + & node --experimental-strip-types --no-warnings --test --test-reporter=tap ` + (Join-Path $env:GITHUB_WORKSPACE 'packaging/windows/performance/relay-measurements.test.mts') ` + 2>&1 | Tee-Object -FilePath $relayLog + $relayResult = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + $relayText = Get-Content -LiteralPath $relayLog -Raw + if ($relayResult -ne 0 -or $relayText -notmatch '(?m)^# pass 5\r?$' -or $relayText -notmatch '(?m)^# skipped 0\r?$') { + throw 'All five actual Windows relay measurement controls must run without skips.' + } + + - name: Check MSI manifest controls + shell: powershell + env: + CARGO_TERM_COLOR: never + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $output = Join-Path $env:RUNNER_TEMP 'windows-runtime-controls' + $pythonLog = Join-Path $output 'msi-build-tests.log' + try { + $ErrorActionPreference = 'Continue' + & python -m unittest discover -s "$env:GITHUB_WORKSPACE\packaging\windows\installer" -p 'test_*.py' -v 2>&1 | Tee-Object -FilePath $pythonLog + $pythonResult = $LASTEXITCODE + } finally { $ErrorActionPreference = 'Stop' } + $pythonText = [string](Get-Content -LiteralPath $pythonLog -Raw) + if ($pythonResult -ne 0 -or $pythonText -notmatch '(?m)^Ran 200 tests in [0-9.]+s\r?$' -or $pythonText -notmatch '(?m)^OK\r?$') { + throw 'The 200 MSI build and metadata controls did not all pass.' + } + + - name: Build and exercise actual isolated MSI transactions + shell: pwsh + env: + CARGO_TERM_COLOR: never + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $node = (Get-Command node.exe -CommandType Application | Select-Object -First 1).Source + & "$env:GITHUB_WORKSPACE\packaging\windows\installer\test-runtime-msi-process.ps1" ` + -SourceRoot $env:GITHUB_WORKSPACE ` + -ArtifactDirectory (Join-Path $env:RUNNER_TEMP 'windows-msi-lease-process') -NodePath $node + $tools = Join-Path $env:RUNNER_TEMP 'windows-msi-tools' + & "$env:GITHUB_WORKSPACE\packaging\windows\installer\install-pinned-wix.ps1" -ToolDirectory $tools + $python = (Get-Command python.exe -CommandType Application | Select-Object -First 1).Source + $license = Join-Path (Split-Path -Parent $node) 'LICENSE' + & "$env:GITHUB_WORKSPACE\packaging\windows\installer\test-runtime-msi.ps1" ` + -SourceRoot $env:GITHUB_WORKSPACE ` + -ArtifactDirectory (Join-Path $env:RUNNER_TEMP 'windows-msi-boundary-fixtures') ` + -NodePath $node -NodeLicensePath $license -PythonPath $python ` + -WixPath (Join-Path $tools 'wix.exe') -SourceRevision $env:GITHUB_SHA + + - name: Upload runtime ownership control evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: windows-runtime-controls-${{ github.sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/windows-runtime-controls/ + ${{ runner.temp }}/windows-msi-lease-process/*.json + ${{ runner.temp }}/windows-msi-tools/wix-input.json + ${{ runner.temp }}/windows-msi-boundary-fixtures/*.json + ${{ runner.temp }}/windows-msi-boundary-fixtures/*.log + ${{ runner.temp }}/windows-msi-boundary-fixtures/fixtures/fixtures.json + ${{ runner.temp }}/windows-msi-boundary-fixtures/fixtures/*/namespace.json + if-no-files-found: warn + retention-days: 14 diff --git a/bin/nemoclaw.js b/bin/nemoclaw.js index 46cdad20d0e..84f4272a8f3 100755 --- a/bin/nemoclaw.js +++ b/bin/nemoclaw.js @@ -56,6 +56,8 @@ function handleTopLevelError(error) { } function applyPersistedAutomaticGatewayPort() { + // Native Windows does not use the POSIX installer's automatic-port markers. + if (process.platform === "win32") return; if (process.env.NEMOCLAW_GATEWAY_PORT) { const installerAutomaticPort = process.env.NEMOCLAW_INSTALLING === "1" && diff --git a/packaging/windows/Bundle.wxs b/packaging/windows/Bundle.wxs new file mode 100644 index 00000000000..53964f966f0 --- /dev/null +++ b/packaging/windows/Bundle.wxs @@ -0,0 +1,128 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/CONPTY-LICENSE.txt b/packaging/windows/CONPTY-LICENSE.txt new file mode 100644 index 00000000000..8cb179cdb69 --- /dev/null +++ b/packaging/windows/CONPTY-LICENSE.txt @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packaging/windows/License.rtf b/packaging/windows/License.rtf new file mode 100644 index 00000000000..f87ed67d0f7 --- /dev/null +++ b/packaging/windows/License.rtf @@ -0,0 +1,14 @@ +{\rtf1\ansi\deff0 +{\fonttbl{\f0 Segoe UI;}} +\fs20 +NemoClaw Native Windows Candidate Preview\par +\par +Copyright (c) 2026 NVIDIA Corporation and affiliates.\par +\par +NemoClaw is licensed under the Apache License, Version 2.0. The complete +license is installed with the product as LICENSE.txt and is available in the +NemoClaw source repository.\par +\par +This package is a qualification candidate. It does not establish production +support for native Windows, Microsoft MXC, or any agent runtime.\par +} diff --git a/packaging/windows/MXC-LICENSE.txt b/packaging/windows/MXC-LICENSE.txt new file mode 100644 index 00000000000..22aed37e650 --- /dev/null +++ b/packaging/windows/MXC-LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packaging/windows/NATIVE-PREVIEW.txt b/packaging/windows/NATIVE-PREVIEW.txt new file mode 100644 index 00000000000..c17e6352a25 --- /dev/null +++ b/packaging/windows/NATIVE-PREVIEW.txt @@ -0,0 +1,82 @@ +NemoClaw Native Windows Candidate Preview + +Product decision and ownership + +This PR-scoped package is an engineering candidate under NVIDIA/NemoClaw#8178. +The maintainer decision accepts implementation and qualification in #12014, +with Prekshi Vyas accountable for the work: +https://github.com/NVIDIA/NemoClaw/issues/8178#issuecomment-5984526049 +The current maintainer-directed scope narrows the Windows candidate to OpenClaw +and Hermes. This accepts development, not a supported release or the PR's code. + +Placement remains limited to explicitly dispatched PR workflow artifacts with +their configured retention. There is no support or upgrade SLA. Compatibility +claims are limited to the exact identities and results in each candidate's +receipt. Release activation still requires an accepted exact OpenShell/MXC +distribution, an evidence-backed Windows/build/backend matrix, signing and +distribution authority, update and vulnerability-response ownership, and the +required security and lifecycle evidence. Passing engineering validation does +not satisfy those separate release gates. Do not publish a release, link this +candidate from canonical onboarding, or represent it as supported while those +gates remain unmet. + +Each finished installer contains the NemoClaw CLI and the agent selected when +the package was built: OpenClaw or Hermes. Its embedded availability record +disables the other agent. Standalone Pi, Deep Agents Code, and NemoCUA are no +longer included. Historical state remains eligible for explicit owned-data cleanup. +The MSI installs the selected agent's +required native ARM64 runtime, OpenShell, and Microsoft MXC ProcessContainer +components. WSL, Docker, Linux virtual machines, and unused MXC backend sidecars +are not part of this package. + +Setup and onboarding share one native WPF window. Choose an agent once, select +inference and supported optional services, and follow the named install phases. +Configured sessions select supervised networking, not the Personal direct-network +profile. Host settings remain outside the agent filesystem. Network-policy +enforcement remains unqualified. Setup adds a NemoClaw Setup desktop shortcut and +a shortcut with the selected agent's icon. OpenClaw and Hermes open their web +interfaces in the default browser. Hermes also has an interactive console. +A native control window stops each web session and cleans up its sandbox. + +Run NemoClaw Setup again to change settings or, when installed, uninstall. +Uninstall retains personal data by default. Its explicit data-removal selection +removes only the chosen agent's owned state, settings, and scoped stored keys. +Shared on-device model files are separate from agent data. + +Inference keys are stored in Windows Credential Manager, bound to the agent, +provider, and endpoint. The inference key stays in the host broker. Optional +service keys use separate per-agent bindings and enter only the selected +agent's process environment. Keys are not written into setup JSON or passed as +process arguments. Native state ownership and the UI relay's native file owner +protect their filesystem boundaries through shutdown. + +The host build pins OpenShell 624f55b3c6affedd4f2757c7eb32132196b4c3e8 +and source-built MXC 7cd00d1ee6af9208322c924ef64e5113f6704639. +It includes the OpenShell supervisor, Windows sandbox executable, and Z3 DLL. +The launcher writes the version 2 gateway configuration for that protocol. +Build and startup evidence alone does not qualify the full installer journey. +The separate Windows-tip cycles allowed host loopback. They do not establish +denied host loopback, port-only isolation, live policy revocation, or production +LPAC and governed network-policy parity. New package bytes need new acceptance. + +Microsoft MXC's native elevated system-drive and null-device preparation runs +before MSI installation. Windows resets the null-device preparation at reboot; +persistent production gateway-service ownership remains a separate gate. + +On RTX Spark N1X, eligible Windows ARM64 machines may select native on-device +Express. Pinned llama.cpp/CUDA and Qwen model downloads require compatible +drivers, sufficient memory/storage, complete GPU offload, and an authenticated +real model response before Ready. This is an agent-independent local service; +it does not run the Linux or WSL recipes. Generic ARM64 CI is not physical N1X +qualification. + +Qualification must exercise the selected agent through native setup, its UI, +desktop links, repair/reinstall, data preservation, explicit tester reset, and +cleanup. Hermes requires both its interactive console and dashboard. Qualifying +one package does not qualify agents absent from that package. +Deterministic local inference proves runtime and transport behavior, not live +commercial-provider or messaging-account qualification. Actual Windows screen +captures and receipts identify the exact candidate being tested. + +This is an unsigned PR preview, not a production release. Production signing, +broader host/runtime qualification, and governed deployment remain separate. diff --git a/packaging/windows/NemoClaw.Bundle.wixproj b/packaging/windows/NemoClaw.Bundle.wixproj new file mode 100644 index 00000000000..8ebcbeed3c0 --- /dev/null +++ b/packaging/windows/NemoClaw.Bundle.wixproj @@ -0,0 +1,48 @@ + + + + + Bundle + arm64 + NemoClawSetup-$(ProductVersion)-windows-arm64 + $(PackageOutputRoot) + $(PackageIntermediateRoot)\bundle\ + false + false + false + $(DefineConstants);ProductVersion=$(ProductVersion);SourceRoot=$(SourceRoot);MsiPath=$(MsiPath);WxcHostPrepPath=$(PayloadRoot)\mxc\wxc-host-prep.exe;WxcExecPath=$(PayloadRoot)\mxc\wxc-exec.exe;BootstrapperPath=$(BootstrapperPath);BootstrapperRoot=$(BootstrapperRoot) + true + + 1161 + none + + + + + + + + + + + + + + $(DefineConstants);SystemDriveMetadataPreparation=true;SystemDrivePrepPath=$(SystemDrivePrepPath);SystemDrivePrepSha256=$(SystemDrivePrepSha256) + + + + + + + + + + + + + + + + diff --git a/packaging/windows/NemoClaw.wixproj b/packaging/windows/NemoClaw.wixproj new file mode 100644 index 00000000000..45378f0b794 --- /dev/null +++ b/packaging/windows/NemoClaw.wixproj @@ -0,0 +1,39 @@ + + + + + Package + arm64 + NemoClaw-$(ProductVersion)-windows-arm64 + $(PackageOutputRoot) + $(PackageIntermediateRoot)\msi\ + false + false + false + $(DefineConstants);NativeRuntimeMsiPrototype=$(NativeRuntimeMsiPrototype);NativeRuntimeMsiAuthoring=$(NativeRuntimeMsiAuthoring);ProductVersion=$(ProductVersion);PayloadRoot=$(PayloadRoot);SourceRoot=$(SourceRoot) + true + + ICE60 + none + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/Product.wxs b/packaging/windows/Product.wxs new file mode 100644 index 00000000000..c9cf0e5cdac --- /dev/null +++ b/packaging/windows/Product.wxs @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/README.md b/packaging/windows/README.md new file mode 100644 index 00000000000..0287fc1674c --- /dev/null +++ b/packaging/windows/README.md @@ -0,0 +1,335 @@ + + + +# Native Windows candidate package + +## Agent scope + +This Windows candidate includes OpenClaw and Hermes only. Each finished package +contains its build-selected agent; the other remains unavailable in that package. +Standalone Pi, Deep Agents Code, and NemoCUA integrations have been removed. +Their source remains in Git history. Existing state and credential cleanup still +recognize those historical identities; they cannot start a new agent session. +Setup's selectable data-removal choices are OpenClaw and Hermes only. Historical +shortcut cleanup and recognition of retained legacy state remain separate from +those choices; uninstall does not silently delete retired agents' data or keys. +Non-Windows integrations and OpenClaw's internal dependencies are unchanged. +This scope reduction does not establish installed qualification or release approval. + +An included OpenClaw or Hermes preview can be configured and launched while its package +status remains `unqualified`. Setup displays the pending-runtime-checks warning +during agent selection and configuration. Missing or invalid availability records +and `not-included` agents remain unavailable. Preview selection does not grant +runtime admission, mark evidence qualified, authorize CI credentials, or satisfy +qualified-publication gates. + +Same-repository OpenClaw pull requests publish a downloadable Actions artifact +named `unqualified-openclaw-preview---` after the package +build succeeds. It contains the exact setup EXE, build and runtime identities, +and an explicit unqualified-preview label with the EXE hash. The same-run +transfer and exact package inventory are verified before upload. This download +does not wait for installed acceptance, does not use provider credentials, and +is not a GitHub release. Full qualification and qualified publication retain +their separate protected workflow and approval gates. + +## Windows Preview and Remaining Qualification + +The finished-host build now pins OpenShell +`624f55b3c6affedd4f2757c7eb32132196b4c3e8` from the current `windows` branch +and source-built MXC `7cd00d1ee6af9208322c924ef64e5113f6704639`. +The older `windows-0.0.x-backup` branch is not the build base. Upstream runtime +qualification does not establish installer acceptance. OpenShell also applies +`openshell-native-transport.patch`, bound to its SHA-256 and complete resulting +Git tree in `openshell-native-transport.lock.json`. The build requires a clean +pinned base, verifies the patched tree before and after compilation, and rejects +unexpected staged, unstaged or untracked source. MXC retains its unchanged-source +requirement. Both projects use fresh target directories and record same-run hashes. +The OpenShell inventory includes the CLI, gateway, supervisor, Windows sandbox +executable, and `libz3.dll`. This Windows sandbox executable implements the +OpenShell sandbox protocol; it is not Microsoft's Windows Sandbox backend. + +The OpenClaw web worker uses fixed sandbox-local named pipes for its gateway and +inference broker. The OpenShell derivative carries supervisor control over +inherited standard I/O and forwards declared logical ports to those local pipes, +without adding a broad host-loopback grant. The patch includes the dependent +forwarding and lifecycle repairs in the tested source tree. Host admission now +requires both its patch digest and source-tree identity; the old unpatched receipt +is not accepted. Local real-provider, restart and web-worker evidence does not +qualify a newly built installer or establish outer-network-fence enforcement. + +The compiled launcher supports the OpenClaw Control UI and Hermes dashboard, +including the prepared Hermes PTY runtime. Installed sessions use authenticated +OpenShell gateways and job-owned supervisor cleanup. The installer may publish +these paths as unqualified previews, as described above. + +Functional evidence remains specific to the tested revision and artifact. +A passing preview journey does not establish protected provider qualification, +network-policy enforcement, or release readiness. New runtime changes require +new installed lifecycle evidence; earlier OpenClaw or Hermes results cannot +qualify a replacement package. + +The retained launchers provision fresh TLS and JWT keys through a shared gateway +session owner. Its sibling session directory permits access only to the Windows +user and SYSTEM. It contains gateway keys, imported CLI certificates, and supervisor +state; it is outside the workload share and ordinary logs. The bundled UI helper +returns certificate material through a bounded pipe without using certificate stores. +Launchers require HTTPS and mTLS user authentication. Cleanup stops owned processes +before removing the directory. A failed stop retains the private directory and +reports a cleanup failure. Component tests exercise the real UI helper and private +directory controls; they do not establish OpenShell authorization or installed acceptance. + +The launchers start the gateway through a native job owner. Windows assigns the +gateway to the job before it runs; its supervisor and executor inherit ownership. +Normal gateway exit or a session-bound stop request terminates the job. Private +state is removed only after the owner reports zero active processes. Killing the +owner closes the job, but without a verified shutdown record the launcher retains +private state and reports cleanup failure. Local process controls cover this +behavior; exact-artifact MXC and real-console validation remain required. + +Console launchers now request a sandbox terminal and attach with `sandbox connect` +through the session's authenticated CLI environment. They no longer request legacy +host-console sharing. Success requires matching client and contained-agent exit +statuses. Cleanup stops the private gateway before waiting for the client to drain. +An undrained client reports failure; the native runtime owner retains responsibility +for the complete process tree. Hermes dashboard sessions keep their separate PTY +path. Focused tests cover attachment, exit-status reconciliation, and failure cleanup; +installed interactive acceptance with the selected runtime remains required. + +Hermes reuse now pins base artifact `11995339173` from run `38778013068`, built +from `8f54e647a1cda1c3c879ad4e350700a13bb8fc2e`. This base contains the startup +adapter and native dashboard pipe adapter. Reuse relocates generated path metadata without changing +the adapter or claiming a historical upgrade. The wheel, Git, export, and Personal +probe consumers retain the same base identity. Fresh compatibility proof, moved-root +execution, and installed acceptance remain required. The historical replay and +finished-runtime qualification pins have not been promoted to this new base. + +The passing Windows-tip cycles allowed host loopback through the host-supervisor +protocol. They did not prove denied host loopback, port-only isolation, an outer +network fence, or live policy revocation. Keep those limitations separate from +functional acceptance. Do not replace denied-network evidence with the passing +preview result. Fresh installed OpenClaw and Hermes acceptance must +use the newly built package and record its actual Windows and runtime identities. + +## Existing installer behavior and remaining migration surface + +This directory owns the WiX-authored ARM64 MSI and Burn setup executable for +the native Windows candidate. WiX Toolset 5.0.2 and its standard bootstrapper +application extension are pinned in the project files. +The workflow verifies the WiX CLI package against `installer/wix-tool-input.json` +before installation. NuGet restores that tool from the verified local package, +using fresh caches and no additional package source. + +The package uses only standard Windows Installer and Burn authoring. It has no +custom actions and does not invoke PowerShell, WSL, Bash, Ubuntu, Docker, or a +Linux virtual machine. The package installs the exact assembled ARM64 NemoClaw +runtime payload under `%ProgramFiles%\NVIDIA\NemoClaw`. That payload contains +the NemoClaw CLI, the selected agent and its required runtime, NVIDIA/OpenShell CLI +and gateway binaries, and only the pinned Microsoft MXC ProcessContainer +executor and host-preparation utility. WSLC, Windows Sandbox, test-proxy, +diagnostic, and learning-mode sidecars from the upstream SDK archive are not +packaged. Windows Installer registers normal Add/Remove Programs metadata and +adds the installed `bin` directory to the machine PATH. + +`finished_windows_agent` selects the agent included in each finished installer. +The embedded runtime-availability record marks unselected agents `not-included`, +and setup disables those choices. One package does not qualify all agent variants. + +The finished-installer workflow checks out the OpenShell `windows` revision in +`openshell-native-transport.lock.json`, applies its locked compatibility patch, and builds and tests the +ARM64 derivative. It records both executable hashes, the source and patch identities, +and the workflow run. Host preparation rejects mismatched receipts or binaries; +it does not reuse binaries from a previous MSI. The patch and its exact hash are installed with the +product. Packaged Node workloads explicitly set `windows_ui=true` so the +contained Node process can initialize. Other sandboxes retain MXC's disabled-UI +default. The derivative also adds per-sandbox `host_loopback`, `host_console`, and +`personal_network` options. Configured OpenClaw web sessions and the shared +OpenClaw/Hermes console/dashboard path use the supervised profile. +It sets `pc_allow_local_network=false` and omits direct-network +options; these sessions do not select Personal networking or legacy host-console sharing. +This configuration does not establish network-policy enforcement or grant access +to the Windows user-profile filesystem. + +Qualification networking is separate. Probes check the installed MXC tier: +AppContainer retains its original network policy; BaseContainer +uses `loopback_ports` for the contained mock model and UI listeners. This emits +MXC 0.8 TCP rules for only those `127.0.0.1` ports, with other egress and host +loopback ingress denied. Unknown or inconsistent probes stop qualification. +Port rules cannot be combined with Personal or legacy host-loopback options. +The driver accepts whole ports from 1 through 65535 through protobuf's numeric +representation; fractions, zero, overflow and nonnumeric values are rejected. +The UI reports failed creation before waiting for relay readiness. It skips +sandbox teardown only after definitive rejection and a confirmed empty registry; +transport failures still require ordinary cleanup and reconciliation. + +The tested ARM64 runner selects MXC's AppContainer fallback. The gateway template +retains `pc_least_privilege=false` and `privateNetworkClientServer`. Personal +compatibility probes add `internetClient` for public outbound connections; +configured sessions do not select that profile. The qualification default does +not add that capability. These are +preview compatibility settings across the agent set; they do not establish LPAC +qualification or governed egress-policy parity. The legacy `allowLocalNetwork` +field has version-dependent ingress semantics. Retiring these exceptions needs +agent, broker, negative filesystem, and network evidence on the selected Windows +and MXC builds. Runtime qualification remains tracked in +[#8178](https://github.com/NVIDIA/NemoClaw/issues/8178). + +Each run writes a gateway configuration outside the installed payload. It +preserves the installed template's settings and resolves `wxc_exec_path` from +the actual installation directory, including an overridden `INSTALLFOLDER`. +The qualification turn executes OpenClaw in a worker inside that same contained +Node process, avoiding an unsupported nested-process assumption while retaining +MXC filesystem containment. The package does not bypass OpenShell or call MXC +directly from NemoClaw. The pinned OpenShell CLI watch does not return after the +one-shot MXC workload completes, so the qualification command stops that +client-side watcher after receiving the exact workload result and then deletes +the sandbox through OpenShell. + +Before install or repair, Burn queries its bundled, hash-pinned MXC executable +with `--probe` and records the selected tier. Finished packages compile the probe +digest into Setup from the admitted same-run MXC build and recheck it before Burn +composition. Missing, ambiguous or substituted probe identities stop the build +or launch; external files and environment variables cannot override the compiled +digest. The legacy preview retains its original 0.8.0 probe pin. BaseContainer skips both +AppContainer host prerequisites without changing root or null-device permissions. +AppContainer+DACL retains system-drive metadata preparation and the pinned MXC +null-device preparation through Burn's elevated engine. Existing permission +conflicts still stop preparation. Failed, unknown or inconsistent probes stop +installation; they do not select a fallback. Uninstall does not require a probe. +The null-device setting resets when Windows reboots. This prerequisite selection +does not establish runtime qualification or change the selected session network profile. + +The self-contained ARM64 WPF setup presents one custom-framed window for agent +selection, inference, optional services, installation progress, and completion. +This installer flow does not use HTML, WebView, Edge, or a browser. An explicit +API-key help action can open the service's official page in the user's browser. +The installed launcher's unconfigured web-launch path instead opens browser +onboarding through a local HTTP server. That path saves the agent configuration +before launching the selected agent. +Progress names the current phase and refreshes elapsed time regularly; download +and installer percentages come from actual work, while unknown-duration phases +remain indeterminate. + +Setup creates current-user desktop shortcuts for NemoClaw Setup and each configured +agent, using their own icons. The setup shortcut uses the registered cached +installer for maintenance. Uninstall appears only for an installed product and +preserves data by default; explicit per-agent removal checks ownership and active +sessions before deleting state, settings, and scoped keys. Web agents use the +Windows default browser and a native session-control window with explicit Stop. +Closing that control waits for sandbox, gateway, broker, and state cleanup. + +The selected agent carries through configuration and launch, and the installed +launcher remembers the last configured agent. The same native window edits +settings later. Agent launch is an explicit completion action. +`agent-support.json` records the packaged +implementations and their preview limitations. + +The compiled OpenClaw package retains its published workspace templates under +the canonical package root. Fresh workspace bootstrap needs these files even when +existing-workspace tool checks pass. Resource composition preserves their bytes +and inventory hashes and rejects missing directories or linked input files. + +Hermes uses the corrected pywinpty ARM64 wheel, including its matched `conpty.dll` +and `OpenConsole.exe` beside the native Python extension. The Microsoft ConPTY +notice is installed as `hermes/CONPTY-LICENSE.txt`. An early Windows check loads +that exact library and proves input, output, child-observed resize, and cleanup +before the long runtime build; full packaged qualification repeats the check. +This addresses the omitted binaries documented in the +[pywinpty 3.0.5 release](https://github.com/andfoy/pywinpty/releases/tag/v3.0.5). + +Provider endpoint, model, Personal profile, and optional-service selections are +nonsecret host configuration under Local App Data. WPF sends key bytes through +stdin to the native launcher, which stores them in Windows Credential Manager. +Inference credentials bind to the agent, provider, and canonical endpoint; +optional service credentials bind separately to the agent and service. Inference +provider keys remain in the host broker. Opted-in search and messaging keys are +delivered once through an authenticated local bootstrap into the selected agent's +process environment, without credential values in configuration JSON or process +arguments. These service integrations do not claim OpenShell-managed credential +injection or governed provider parity. + +OpenClaw offers Brave and Tavily search; Hermes offers its native Tavily backend. +OpenClaw offers Telegram and Slack; Hermes also offers Discord. +Discord is deferred for the OpenClaw Windows preview because the packaged plugin +does not meet OpenClaw's trusted-provenance requirements. Setup disables that choice +and rejects it before saving configuration or copying service credentials. +Existing saved options that select OpenClaw Discord fail validation without changing +the saved file or credentials. Remove the selection through Setup before launching. +The plugin inputs remain pinned, but their presence does not establish support. +Plugin trust checks, Hermes Discord behavior, and existing data remain unchanged. +Messaging requires its selected bot/app keys; +empty sender lists keep pairing behavior, and network access does not +authorize arbitrary senders. Hermes starts its actual messaging gateway with the +interactive session, checks selected-channel connectivity, and uses the upstream +planned-stop mechanism when that session closes. + +Configured OpenClaw and console agents keep their data in a stable system-drive-root +directory named `NemoClawState--`. The native launcher +creates it with a protected current-user and SYSTEM DACL and holds exclusive +per-account, per-agent session ownership through sandbox cleanup. Reopening +retains data and checks the directory's owner, permissions, and ordinary-directory +type. Changed permissions or a reparse point stop the launch without resetting +or deleting state. Host configuration remains private in Local App Data; the +agent receives no access to the user-profile directory. The launcher does not +import arbitrary state from older preview locations. Within the retained +OpenClaw state root, configured startup detects the legacy +`.openclaw/agents/main/sessions/sessions.json` store and runs the packaged +OpenClaw dry-run and SQLite import before starting the sandbox. It holds the +private state lease throughout, rejects redirected paths and unsafe records, +and does not load agent plugins or credentials into the migration process. +Successful migration retains the upstream migration archives. A failed or +interrupted migration stops launch and retains original files and available +archives for recovery; do not delete them to force startup. + +If a settings save exceeds its visible deadline, Setup keeps the transaction +helper and blocks overlapping saves. **Check save status** waits briefly for +the owned helper, then queries the installed configuration lease and recovery +record. A free lease alone does not authorize another save while that helper +remains owned. The recovery window identifies the agent, helper PID, and any +unfinished operation returned by the lease-protected query. +If repeated checks cannot confirm completion, record the displayed message, +save other work, and restart Windows through **Start > Power > Restart**. +Reopen NemoClaw Setup, check save status, review the provider and model, and +re-enter required keys before saving. Do not terminate individual Setup +processes or delete configuration, lock, or recovery files to bypass recovery. + +The native Edge identity check requires certificate-chain revocation validation. +Windows may retrieve revocation evidence from certificate authorities. A revoked +chain or unavailable revocation evidence rejects launch. The check does not +disable revocation or accept signer metadata alone when validation fails. + +Web UI file transport uses a native, bounded file owner. It pins the root and +stream directory handles, performs handle-relative I/O, and refuses reparse +points, hard links, path traversal, and oversized frames. Its guarded root has +an explicit MXC filesystem grant and stays pinned through sandbox teardown. +The contained relay accepts authenticated Stop requests before UI readiness and +reports connection permission failures without waiting for the readiness timeout. +Qualification saves redacted diagnostics under its evidence directory, so saving +does not depend on onboarding-created directories. + +Package qualification drives the WPF controls for the included agent and +rejects browser/WebView descendants during setup. Agent-specific checks must +exercise its packaged runtime inside native MXC. The installed configured Hermes +acceptance additionally requires its visible interactive prompt, typed input, +a distinct deterministic provider response, a real console resize, exit, and +sandbox cleanup. The Hermes dashboard also requires three typed turns through +its shipped SPA and native ConPTY, then native Stop and complete cleanup. +One-shot results cannot satisfy either acceptance. Tester reset exercises the +actual maintenance data-removal option and a fresh native reinstall. Actual-window +screenshots and recordings accompany the receipts, including failed-run evidence. +The local deterministic provider proves runtime/transport wiring without a PR +credential; it does not qualify a commercial provider or live messaging account. + +Native on-device Express is a separate host-owned llama.cpp/CUDA implementation +for detected RTX Spark N1X Windows ARM64 machines. With bundled inference available, +setup defaults to Qwen 3.8 27B and offers Qwen 3.6 35B-A3B as an explicit alternative. +The separate legacy Express recipe retains its pinned Qwen 3.6 35B-A3B model. +Both paths are shared across OpenClaw and Hermes and check driver compatibility, available memory +and storage, pinned downloads, full GPU offload, authentication, and an actual +model response before reporting Ready. It does not invoke the existing WSL or +Linux recipes. Model and runtime downloads occur only when selected. Generic +ARM64 package CI does not qualify N1X GPU operation; the physical device check +remains required. + +This remains a preview distribution boundary. Exact candidate package evidence, +physical-host/N1X validation, commercial-provider and messaging validation, +production gateway service ownership, and Authenticode signing are separate gates. diff --git a/packaging/windows/RequiredPayload.props b/packaging/windows/RequiredPayload.props new file mode 100644 index 00000000000..60ecdba6774 --- /dev/null +++ b/packaging/windows/RequiredPayload.props @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/SIGNING.md b/packaging/windows/SIGNING.md new file mode 100644 index 00000000000..edaaa98fabb --- /dev/null +++ b/packaging/windows/SIGNING.md @@ -0,0 +1,28 @@ + + + +# Production signing boundary + +Pull-request workflows build unsigned candidate packages and never receive +Windows code-signing credentials. Production publication remains blocked until +an NVIDIA-owned trusted release workflow performs the following sequence with +an approved Authenticode identity: + +1. Sign and verify `openshell.exe`, `openshell-gateway.exe`, `NemoClaw.exe`, + and the native ARM64 bootstrapper application before MSI or Burn binding. + Verify the approved publisher signatures on the pinned `node.exe`, + `python.exe`, `wxc-exec.exe`, and `wxc-host-prep.exe` inputs, and apply an + NVIDIA signature too if release policy requires it. +2. Build the ARM64 MSI from those signed payloads, then sign and verify the MSI. +3. Build the Burn bundle with the signed MSI embedded. +4. Use the pinned WiX tool to detach the Burn engine, sign and verify the + detached engine, reattach it, then sign and verify the complete setup + executable. +5. Publish hashes and signature verification receipts beside the artifacts. + +The signing implementation must execute only in a protected release context. +It must not copy certificates, private keys, tokens, or signing service +credentials into the repository, pull-request jobs, package payload, logs, or +artifacts. This PR does not create that trusted release workflow because the +repository currently has no approved NVIDIA Windows-signing integration to +reuse. diff --git a/packaging/windows/Theme.wxl b/packaging/windows/Theme.wxl new file mode 100644 index 00000000000..7c9eb494672 --- /dev/null +++ b/packaging/windows/Theme.wxl @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/Z3-LICENSE.txt b/packaging/windows/Z3-LICENSE.txt new file mode 100644 index 00000000000..f52092921d1 --- /dev/null +++ b/packaging/windows/Z3-LICENSE.txt @@ -0,0 +1,10 @@ +Z3 +Copyright (c) Microsoft Corporation +All rights reserved. +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packaging/windows/agent-support.json b/packaging/windows/agent-support.json new file mode 100644 index 00000000000..cefc1d0a062 --- /dev/null +++ b/packaging/windows/agent-support.json @@ -0,0 +1,27 @@ +{ + "schemaVersion": 1, + "platform": "windows-arm64", + "agents": [ + { + "id": "openclaw", + "displayName": "OpenClaw", + "version": "2026.9.2", + "source": "https://registry.npmjs.org/openclaw/-/openclaw-2026.9.2.tgz", + "lockSha256": "0b1253c6570f55881623961c856b430a17d4271f5efe8c5beffa7ac0fc8d0199", + "interface": "OpenClaw Control UI", + "status": "candidate", + "selectable": true, + "limitation": "Candidate Control UI uses a host-side credential broker and requires two consecutive exact-head native MXC qualifications before it is called proven." + }, + { + "id": "hermes", + "displayName": "Hermes Agent", + "version": "0.21.1", + "source": "https://github.com/NousResearch/hermes-agent/tree/2237be355906fbe6065ce1815711eee52b2d646e", + "interface": "Hermes dashboard and native terminal UI", + "status": "candidate", + "selectable": true, + "limitation": "Canonical Nous runtime with native ARM64 ConPTY and host-owned native ARM64 Microsoft Edge CDP. Installed inference, tools, cleanup, and physical N1X validation remain release gates." + } + ] +} diff --git a/packaging/windows/app/build-openclaw-app.mts b/packaging/windows/app/build-openclaw-app.mts new file mode 100644 index 00000000000..c3c1424f9ee --- /dev/null +++ b/packaging/windows/app/build-openclaw-app.mts @@ -0,0 +1,445 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// CI compiler. Dependency/native builds precede this stage; never run it at install/startup. +import fs from "node:fs"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import { createRequire } from "node:module"; +import { buildPrivateDirectoryLibrary } from "./sqlite-private-directory-build.mts"; +import { nativeModelCatalogSource } from "./native-model-catalog-build.mts"; + +import { + compiledPluginPlan, + publishPluginFacades, + publishDynamicImportBridges, + stagePublishedResources, + resourceInventory, + PREBUILT_CHOICE_PLUGINS, + prebuiltPluginRegistrationSource, + runtimeExternalPlugin, + runtimeInputRoot, +} from "./openclaw-app-resources.mts"; + +const require = createRequire(import.meta.url); +const external = [ + "koffi", + "@opentelemetry/api", + "@lydell/node-pty", + "@openclaw/fs-safe", + "@silvia-odwyer/photon-node", + "clawpdf", + "rastermill", + "quickjs-wasi", + "web-tree-sitter", + "tree-sitter-bash", + "playwright-core", + "typescript", + "jiti", + "@snazzah/davey", + "libopus-wasm", + "undici", + "ws", + "@discordjs/voice", +]; +function argument(name: string) { + const index = process.argv.indexOf(name); + if (index < 0 || !process.argv[index + 1]) throw new Error(`Missing ${name}`); + return path.resolve(process.argv[index + 1]); +} +const source = argument("--source-root"); +const output = argument("--output"); +const toolRoot = argument("--tool-root"); +const portable = process.argv.includes("--portable-proof"); +if ( + !portable && + (process.platform !== "win32" || process.arch !== "arm64" || process.versions.node !== "22.23.2") +) + throw new Error("Windows application compilation requires canonical Node 22.23.2 ARM64."); +const compiler = require( + path.join(toolRoot, "node_modules", "esbuild"), +) as typeof import("esbuild"); +if (compiler.version !== "0.27.4") throw new Error("The reviewed compiler is esbuild 0.27.4."); +const materializationBytes = fs.readFileSync( + path.join(runtimeInputRoot(source), "materialization-receipt.json"), +); +const materialization = JSON.parse(materializationBytes.toString("utf8")) as { + classification: string; + source: { sha256: string }; + sourceRoot: string; + dependencyLock: { path: string; sha256: string }; + choiceDependencyLock: { path: string; sha256: string }; + additionalPackages: { + package: string; + version: string; + sha256: string; + integrity: string; + bytes: number; + }[]; +}; +if ( + materialization.classification !== "verified-application-build-inputs" || + materialization.source.sha256 !== + "3431f4cd2d8dbd6b936def2694ac27e19fa0256295cf4ada0f652ecf1c9ee520" || + materialization.sourceRoot !== "node_modules/openclaw" || + materialization.dependencyLock?.path !== "runtime-package-lock.json" || + materialization.dependencyLock.sha256 !== + "0b1253c6570f55881623961c856b430a17d4271f5efe8c5beffa7ac0fc8d0199" || + materialization.choiceDependencyLock?.path !== "choice-package-lock.json" || + materialization.choiceDependencyLock.sha256 !== + "72aecf8caf45e9773cda0e40c9a61adb6eea48c2122d0a5e469a8f6bdcf168f6" || + !Object.values(PREBUILT_CHOICE_PLUGINS).every((expected) => + materialization.additionalPackages?.some( + (item) => + item.package === expected.package && + item.version === "2026.9.2" && + item.sha256 === expected.sha256, + ), + ) +) + throw new Error("The verified complete application input receipt is required."); +const metadata = JSON.parse(fs.readFileSync(path.join(source, "package.json"), "utf8")) as { + name: string; + version: string; +}; +if (metadata.name !== "openclaw" || metadata.version !== "2026.9.2") + throw new Error("The exact selected OpenClaw package is required."); +const dependencyLockBytes = fs.readFileSync( + path.join(runtimeInputRoot(source), materialization.dependencyLock.path), +); +if ( + createHash("sha256").update(dependencyLockBytes).digest("hex") !== + materialization.dependencyLock.sha256 +) + throw new Error("The canonical runtime dependency lock changed after materialization."); +const choiceLockBytes = fs.readFileSync( + path.join(runtimeInputRoot(source), materialization.choiceDependencyLock.path), +); +if ( + createHash("sha256").update(choiceLockBytes).digest("hex") !== + materialization.choiceDependencyLock.sha256 +) + throw new Error("The canonical choice dependency lock changed after materialization."); +if (fs.existsSync(output)) throw new Error("Compilation output must be fresh."); +fs.mkdirSync(output, { recursive: true }); +const app = path.join(output, "app"); +const diagnostics = path.join(output, "diagnostics"); +fs.mkdirSync(app); +fs.mkdirSync(diagnostics); +const sha256 = (bytes: Uint8Array | string) => createHash("sha256").update(bytes).digest("hex"); +const entry = path.join(source, "dist", "cli", "run-main.js"); +const syntaxApi = require( + path.join(source, "node_modules", "typescript"), +) as typeof import("typescript"); +const pluginPlan = compiledPluginPlan(source, syntaxApi, compiler); +const adapter = `${pluginPlan.prelude}${prebuiltPluginRegistrationSource(source)}${nativeModelCatalogSource(source)}export async function runCli(argv = process.argv) { + __nemoPrepareAssetRoot(); + const upstream = await import(${JSON.stringify(entry.replaceAll("\\", "/"))}); + return await upstream.runCli(argv); +} +export const runOpenClaw = runCli; +if (typeof require !== "undefined" && require.main === module) { + runCli().catch(error => { console.error(error instanceof Error ? error.stack ?? error.message : String(error)); process.exitCode = 1; }); +} +`; +const banner = `${pluginPlan.banner}\nlet __nemoAssetDir, __nemoFilename, __nemoModuleUrl; +function __nemoPrepareAssetRoot() { + const path = require("node:path"); + const root = process.env.OPENCLAW_COMPILED_ASSET_ROOT; + if (!root || !path.isAbsolute(root)) throw new Error("The sealed OpenClaw asset root is required."); + const resolved = path.resolve(root); + if (__nemoAssetDir && __nemoAssetDir !== resolved) throw new Error("The compiled OpenClaw asset root cannot change within one process."); + __nemoAssetDir = resolved; + __nemoFilename = path.join(resolved, "openclaw-app.cjs"); + __nemoModuleUrl = require("node:url").pathToFileURL(__nemoFilename).href; +} +function __nemoExternalRequire(specifier) { + return require("node:module").createRequire(__nemoFilename)(specifier); +} +function __nemoExternalResolve(specifier) { + return require("node:module").createRequire(__nemoFilename).resolve(specifier); +} +function __nemoExternalImport(specifier) { + return require("node:module").createRequire(__nemoFilename)("./openclaw-dynamic-import.cjs")(specifier); +}`; +fs.writeFileSync(path.join(diagnostics, "entry-adapter.mjs"), adapter, { flag: "wx" }); +try { + const result = await compiler.build({ + stdin: { + contents: adapter, + resolveDir: source, + sourcefile: "windows-openclaw-entry.mjs", + loader: "js", + }, + outfile: path.join(app, "openclaw-app.cjs"), + bundle: true, + platform: "node", + format: "cjs", + target: "node22.23", + define: { + "process.env.OPENCLAW_BUNDLED_VERSION": JSON.stringify(metadata.version), + }, + banner: { js: banner }, + plugins: [runtimeExternalPlugin(source, external), pluginPlan.plugin], + metafile: true, + sourcemap: "external", + treeShaking: false, + keepNames: true, + logLevel: "warning", + }); + if (!result.metafile) throw new Error("Compiler input/output evidence is missing."); + fs.writeFileSync( + path.join(diagnostics, "metafile.json"), + JSON.stringify(result.metafile, null, 2) + "\n", + { flag: "wx" }, + ); + fs.writeFileSync( + path.join(diagnostics, "warnings.json"), + JSON.stringify(result.warnings, null, 2) + "\n", + { flag: "wx" }, + ); + fs.renameSync( + path.join(app, "openclaw-app.cjs.map"), + path.join(diagnostics, "pre-import-bridge-openclaw-app.cjs.map"), + ); + // Native import() cannot execute from a SEA main with useCodeCache. Delegate + // only these generated external-import expressions to one normal Node module. + // Internal imports are already compiler module-table calls. No source file is edited. + const ts = require(path.join(source, "node_modules", "typescript")) as { + ScriptTarget: { Latest: number }; + ScriptKind: { JS: number }; + SyntaxKind: { ImportKeyword: number; Identifier: number; StringLiteral: number }; + createSourceFile( + name: string, + text: string, + target: number, + parents: boolean, + kind: number, + ): AstNode; + isCallExpression(node: AstNode): boolean; + isPropertyAccessExpression(node: AstNode): boolean; + forEachChild(node: AstNode, visit: (node: AstNode) => void): void; + }; + type AstNode = { + kind: number; + expression?: AstNode; + arguments?: AstNode[]; + text?: string; + name?: { text?: string }; + getStart(source: AstNode): number; + }; + const codePath = path.join(app, "openclaw-app.cjs"); + let codeText = fs.readFileSync(codePath, "utf8"); + const syntax = ts.createSourceFile( + codePath, + codeText, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.JS, + ); + const imports: number[] = []; + const standaloneRequires: number[] = []; + const standaloneResolves: number[] = []; + const standalonePackages = new Set([ + // This optional peer remains absent. Keep its lazy Mistral tracing import + // opaque to the second compiler instead of resolving it at build time. + "@opentelemetry/api", + "undici", + "@snazzah/davey", + "libopus-wasm", + "@discordjs/voice", + ]); + const visit = (node: AstNode) => { + if (ts.isCallExpression(node) && node.expression?.kind === ts.SyntaxKind.ImportKeyword) + imports.push(node.expression.getStart(syntax)); + if ( + ts.isCallExpression(node) && + node.expression?.kind === ts.SyntaxKind.Identifier && + node.expression.text === "require" && + node.arguments?.length === 1 && + node.arguments[0].kind === ts.SyntaxKind.StringLiteral && + (standalonePackages.has(node.arguments[0].text ?? "") || + node.arguments[0].text?.startsWith("./node_modules/") || + node.arguments[0].text?.startsWith("./plugins/")) + ) + standaloneRequires.push(node.expression.getStart(syntax)); + if ( + ts.isCallExpression(node) && + node.expression && + ts.isPropertyAccessExpression(node.expression) && + node.expression.expression?.kind === ts.SyntaxKind.Identifier && + node.expression.expression.text === "require" && + node.expression.name?.text === "resolve" && + node.arguments?.length === 1 && + node.arguments[0].kind === ts.SyntaxKind.StringLiteral && + (node.arguments[0].text?.startsWith("./node_modules/") || + node.arguments[0].text?.startsWith("./plugins/")) + ) + standaloneResolves.push(node.expression.getStart(syntax)); + ts.forEachChild(node, visit); + }; + visit(syntax); + const replacements = [ + ...imports.map((offset) => ({ + offset, + original: "import", + replacement: "__nemoExternalImport", + })), + ...standaloneRequires.map((offset) => ({ + offset, + original: "require", + replacement: "__nemoExternalRequire", + })), + ...standaloneResolves.map((offset) => ({ + offset, + original: "require.resolve", + replacement: "__nemoExternalResolve", + })), + ]; + for (const { offset, original, replacement } of replacements.sort( + (a, b) => b.offset - a.offset, + )) { + if (codeText.slice(offset, offset + original.length) !== original) + throw new Error("Unexpected generated module loading syntax."); + codeText = codeText.slice(0, offset) + replacement + codeText.slice(offset + original.length); + } + fs.writeFileSync(codePath, codeText); + const bridge = publishDynamicImportBridges(app); + const code = Buffer.from(codeText); + publishPluginFacades(app, pluginPlan.entries); + const { + packages: admittedPackages, + controlUiStartup, + controlUiServiceWorker, + } = stagePublishedResources(source, app, portable ? process.platform : "win32"); + const privateDirectoryLibrary = buildPrivateDirectoryLibrary(source, app); + fs.writeFileSync( + path.join(diagnostics, "plugin-registry.json"), + JSON.stringify(pluginPlan.entries, null, 2) + "\n", + { flag: "wx" }, + ); + fs.writeFileSync( + path.join(output, "build-receipt.json"), + JSON.stringify( + { + schemaVersion: 1, + classification: "compiled-openclaw-code-unit", + sourceVersion: metadata.version, + materializationReceiptSha256: sha256(materializationBytes), + sourcePackageSha256: sha256(fs.readFileSync(path.join(source, "package.json"))), + sourceLockSha256: sha256(dependencyLockBytes), + choiceLockSha256: sha256(choiceLockBytes), + entrySourceSha256: sha256(fs.readFileSync(entry)), + adapterSha256: sha256(adapter), + compilerVersion: compiler.version, + platform: process.platform, + architecture: process.arch, + nodeVersion: process.versions.node, + portableProof: portable, + compiledInputs: Object.keys(result.metafile.inputs).length, + code: { file: "app/openclaw-app.cjs", bytes: code.length, sha256: sha256(code) }, + exports: ["runOpenClaw", "runCli", "registerPrebuiltPlugins"], + argvConvention: "full [node, entry, ...args]", + assetRootEnvironment: "OPENCLAW_COMPILED_ASSET_ROOT", + nativeImportBridge: { + file: "app/openclaw-dynamic-import.cjs", + bytes: Buffer.byteLength(bridge), + sha256: sha256(bridge), + rewrittenGeneratedImports: imports.length, + rewrittenStandaloneRequires: standaloneRequires.length, + rewrittenStandaloneResolves: standaloneResolves.length, + standalonePackages: [...standalonePackages], + keepExternalToSea: true, + }, + externalPackages: external, + privateDirectoryLibrary, + controlUiStartup, + controlUiServiceWorker, + optionalUninstalledPeer: "@opentelemetry/api", + resourceContract: + "Original module-relative resource URLs are preserved under the sealed asset root; one shared compiled registry backs canonical plugin facades. Remaining tool/browser execution qualification stays separate.", + runtimeClosureProven: false, + windowsQualified: false, + seaPrepared: false, + cacheCoverage: + "Statically link main CJS into shared SEA useCodeCache. The tiny dynamic-import bridge and separately admitted native/ESM sidecars remain normal Node runtime execution; no whole-runtime cache or native-AOT claim.", + developmentArtifacts: + "diagnostics/ contains the generated adapter, complete compiler map and the explicitly pre-import-bridge source map; it is not a production expansion tree.", + }, + null, + 2, + ) + "\n", + { flag: "wx" }, + ); + const resourceReceipt = { + schemaVersion: 1, + classification: "compiled-openclaw-resource-closure", + package: { + name: metadata.name, + version: metadata.version, + sourceArchiveSha256: "3431f4cd2d8dbd6b936def2694ac27e19fa0256295cf4ada0f652ecf1c9ee520", + dependencyLockSha256: sha256(dependencyLockBytes), + choiceDependencyLockSha256: sha256(choiceLockBytes), + }, + compiler: { + receiptSha256: sha256(fs.readFileSync(path.join(output, "build-receipt.json"))), + mainSha256: sha256(code), + bridgeSha256: sha256(bridge), + pluginRegistryModuleCount: pluginPlan.entries.length, + }, + files: resourceInventory( + app, + pluginPlan.entries.map((entry) => entry.path), + ), + controlUiRoot: "node_modules/openclaw/dist/control-ui", + canonicalPluginEntries: pluginPlan.entries, + admittedPackages, + additionalInputArchives: materialization.additionalPackages.map( + ({ package: name, version, sha256, integrity, bytes }) => ({ + name, + version, + sha256, + integrity, + bytes, + }), + ), + absentOptionalPeers: ["@opentelemetry/api", "bufferutil", "utf-8-validate", "supports-color"], + closureAdmitted: false, + closureAdmissionMeaning: + "Reviewed selected gateway composition with no customer build/install fallback; independent of execution qualification. Pending final sidecar/tool and Windows checks.", + qualification: { + portableGatewayObserved: false, + windowsGatewayObserved: false, + modelTools: false, + }, + }; + fs.writeFileSync( + path.join(app, "openclaw-resource-closure.json"), + JSON.stringify(resourceReceipt, null, 2) + "\n", + { flag: "wx" }, + ); + console.log( + JSON.stringify({ + compiledInputs: Object.keys(result.metafile.inputs).length, + codeBytes: code.length, + externalPackages: external.length, + runtimeClosureProven: false, + }), + ); +} catch (error) { + try { + fs.writeFileSync( + path.join(output, "build-failure.json"), + JSON.stringify( + { + classification: "application-compiler-failure", + error: error instanceof Error ? error.message : "Compilation failed.", + }, + null, + 2, + ) + "\n", + ); + } catch { + /* Failure evidence must not replace the original compiler exception. */ + } + throw error; +} diff --git a/packaging/windows/app/choice-inspect-diagnostics.mts b/packaging/windows/app/choice-inspect-diagnostics.mts new file mode 100644 index 00000000000..1c6e5c82487 --- /dev/null +++ b/packaging/windows/app/choice-inspect-diagnostics.mts @@ -0,0 +1,129 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Inject only into the synthetic inspect process, after its package-manager trap. +// Do not propagate a preload to workers or change their arguments or environment. +export const choiceInspectChildDiagnostics = String.raw` +(() => { + const cp = require("node:child_process"); + const started = performance.now(); + let sequence = 0, records = 0; + const emit = (id, method, category, stage) => { + if (records++ >= 128) return; + try { + process.stderr.write("[nemoclaw-choice-child] " + JSON.stringify({ + id, method, category, stage, elapsedMs: Math.round(performance.now() - started) + }) + "\n"); + } catch {} + }; + for (const method of ["spawn", "spawnSync", "execFile", "execFileSync"]) { + const original = cp[method]; + cp[method] = function(...args) { + const id = ++sequence; + const executable = typeof args[0] === "string" ? args[0] : ""; + const category = executable === process.execPath + ? (Array.isArray(args[1]) && args[1].includes("--openclaw-sqlite-readonly-child") + ? "node-sqlite-readonly" : "node") + : /(?:^|[\\/])(?:powershell|pwsh)(?:\.exe)?$/i.test(executable) + ? "powershell" : "other"; + emit(id, method, category, "start"); + try { + const result = original.apply(this, args); + if (method.endsWith("Sync")) emit(id, method, category, "returned"); + else result.once("close", () => emit(id, method, category, "closed")); + return result; + } catch (error) { + emit(id, method, category, "threw"); + throw error; + } + }; + } + require("node:module").syncBuiltinESMExports(); +})(); +`; + +// Only the separate, synthetic readonly-worker probe loads this preload. +// Acceptance workers keep their original arguments and environment. +export function privateDirectoryDiagnosticCommand(command: string): string | null { + const phases = [ + ["library-loaded", "Add-Type -LiteralPath $nativeLibrary"], + ["identity-read", "$current = [System.Security.Principal.WindowsIdentity]::GetCurrent().User"], + ["acl-built", "$sddl = $security.GetSecurityDescriptorSddlForm($sections)"], + ["directory-created", "$errorCode = [OpenClawPrivateDirectory]::Create($path, $sddl)"], + ]; + const commands = command.split("; "); + if (phases.some(([, statement]) => commands.filter((part) => part === statement).length !== 1)) + return null; + const mark = (stage: string) => + `[Console]::Error.WriteLine('[nemoclaw-private-directory] {"stage":"${stage}","elapsedMs":' + $nemoPrivateDirectoryTimer.ElapsedMilliseconds + '}')`; + const traced = commands.flatMap((statement) => { + const phase = phases.find(([, expected]) => expected === statement); + return phase ? [statement, mark(phase[0])] : [statement]; + }); + return [ + "$nemoPrivateDirectoryTimer = [Diagnostics.Stopwatch]::StartNew()", + mark("script-start"), + ...traced, + ].join("; "); +} + +export const sqliteReadonlyWorkerDiagnostics = + choiceInspectChildDiagnostics + + ` +(() => { + const instrument = ${privateDirectoryDiagnosticCommand.toString()}; + const cp = require("node:child_process"), original = cp.execFile; + const started = performance.now(); + cp.execFile = function(...args) { + const executable = typeof args[0] === "string" ? args[0] : ""; + const argv = args[1]; + if (!/(?:^|[\\\\/])powershell(?:\\.exe)?$/i.test(executable) || !Array.isArray(argv) || + argv.length !== 5 || argv[0] !== "-NoLogo" || argv[1] !== "-NoProfile" || + argv[2] !== "-NonInteractive" || argv[3] !== "-EncodedCommand" || typeof argv[4] !== "string") + return original.apply(this, args); + const command = instrument(Buffer.from(argv[4], "base64").toString("utf16le")); + if (command === null) return original.apply(this, args); + const child = original.apply(this, [args[0], [...argv.slice(0, 4), Buffer.from(command, "utf16le").toString("base64")], ...args.slice(2)]); + let pending = "", bytes = 0, records = 0; + child.stderr.on("data", chunk => { + bytes += chunk.length; + if (bytes > 65536) return; + pending += chunk.toString("utf8"); + const lines = pending.split(/\\r?\\n/u); + pending = lines.pop(); + for (const line of lines) { + if (records >= 5 || !/^\\[nemoclaw-private-directory\\] \\{"stage":"(?:script-start|library-loaded|identity-read|acl-built|directory-created)","elapsedMs":[0-9]{1,8}\\}$/u.test(line)) continue; + records++; + process.stderr.write(line.slice(0, -1) + ',"observedAtMs":' + Math.round(performance.now() - started) + '}\\n'); + } + }); + return child; + }; + require("node:module").syncBuiltinESMExports(); +})(); +` + + String.raw` +(() => { + const sqlite = require("node:sqlite"), original = sqlite.backup; + const started = performance.now(); + let records = 0; + const mark = stage => { + if (records++ >= 128) return; + try { + process.stderr.write("[nemoclaw-snapshot-backup] " + JSON.stringify({ + stage, elapsedMs: Math.round(performance.now() - started) + }) + "\n"); + } catch {} + }; + mark("preload-started"); + sqlite.backup = function(...args) { + mark("start"); + let result; + try { result = original.apply(this, args); } + catch (error) { mark("threw"); throw error; } + result.then(() => mark("finished"), () => mark("rejected")); + return result; + }; + require("node:module").syncBuiltinESMExports(); +})(); +`; diff --git a/packaging/windows/app/choice-inspect-diagnostics.test.mts b/packaging/windows/app/choice-inspect-diagnostics.test.mts new file mode 100644 index 00000000000..e60e0397116 --- /dev/null +++ b/packaging/windows/app/choice-inspect-diagnostics.test.mts @@ -0,0 +1,288 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { EventEmitter } from "node:events"; +import test from "node:test"; +import { runInNewContext } from "node:vm"; +import { + choiceInspectChildDiagnostics, + privateDirectoryDiagnosticCommand, + sqliteReadonlyWorkerDiagnostics, +} from "./choice-inspect-diagnostics.mts"; + +const privateDirectoryCommand = [ + "$ErrorActionPreference = 'Stop'", + "$nativeLibrary = 'private-library-path'", + "Add-Type -LiteralPath $nativeLibrary", + "$current = [System.Security.Principal.WindowsIdentity]::GetCurrent().User", + "$sddl = $security.GetSecurityDescriptorSddlForm($sections)", + "$errorCode = [OpenClawPrivateDirectory]::Create($path, $sddl)", + "if ($errorCode -ne 0) { throw 'retained-error' }", +].join("; "); + +test("private-directory phase diagnostics retain every original statement and reject unknown scripts", () => { + const instrumented = privateDirectoryDiagnosticCommand(privateDirectoryCommand); + assert(instrumented); + assert.equal( + instrumented + .split("; ") + .filter( + (statement) => + !statement.startsWith("$nemoPrivateDirectoryTimer =") && + !statement.startsWith("[Console]::Error.WriteLine('[nemoclaw-private-directory]"), + ) + .join("; "), + privateDirectoryCommand, + ); + for (const changed of [ + "unrelated", + privateDirectoryCommand.replace( + "Add-Type -LiteralPath $nativeLibrary", + "Add-Type -TypeDefinition $nativeSource", + ), + privateDirectoryCommand + "; Add-Type -LiteralPath $nativeLibrary", + ]) + assert.equal(privateDirectoryDiagnosticCommand(changed), null); +}); + +test("readonly PowerShell instrumentation preserves call ownership and exports only bounded phase records", () => { + const child = Object.assign(new EventEmitter(), { stderr: new EventEmitter() }); + const lines: string[] = []; + const receiver = {}, + options = { env: { SECRET: "private-environment" }, timeout: 60000 }; + const callback = () => {}; + const argv = [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-EncodedCommand", + Buffer.from(privateDirectoryCommand, "utf16le").toString("base64"), + ]; + let seen: unknown[] = []; + const cp = { + execFile(this: unknown, ...args: unknown[]) { + assert.equal(this, receiver); + seen = args; + return child; + }, + spawn() {}, + spawnSync() {}, + execFileSync() {}, + }; + runInNewContext(sqliteReadonlyWorkerDiagnostics, { + Buffer, + require(name: string) { + if (name === "node:child_process") return cp; + if (name === "node:sqlite") return { backup() {} }; + assert.equal(name, "node:module"); + return { syncBuiltinESMExports() {} }; + }, + process: { execPath: "/private/node", stderr: { write: (line: string) => lines.push(line) } }, + performance: { now: () => 10 }, + }); + assert.equal( + cp.execFile.call(receiver, "C:\\Windows\\powershell.exe", argv, options, callback), + child, + ); + assert.equal(seen[0], "C:\\Windows\\powershell.exe"); + assert.equal(seen[2], options); + assert.equal(seen[3], callback); + assert.notEqual(seen[1], argv); + assert.equal(Buffer.from(argv[4], "base64").toString("utf16le"), privateDirectoryCommand); + assert.equal( + Buffer.from((seen[1] as string[])[4], "base64").toString("utf16le"), + privateDirectoryDiagnosticCommand(privateDirectoryCommand), + ); + const record = '[nemoclaw-private-directory] {"stage":"library-loaded","elapsedMs":123}\r\n'; + child.stderr.emit("data", Buffer.from(record.slice(0, 17))); + child.stderr.emit( + "data", + Buffer.from( + record.slice(17) + + "private stderr\n" + + '[nemoclaw-private-directory] {"stage":"private-secret","elapsedMs":1}\n' + + record.repeat(10), + ), + ); + const phases = lines.filter((line) => line.startsWith("[nemoclaw-private-directory]")); + assert.equal(phases.length, 5); + assert(phases.every((line) => line === record.replace("}\r\n", ',"observedAtMs":0}\n'))); + assert.doesNotMatch( + lines.join(""), + /private-secret|private stderr|private-environment|private-library-path/, + ); + const originalArgs = ["-NoProfile", "-Command", "unchanged"]; + cp.execFile.call(receiver, "C:\\Windows\\powershell.exe", originalArgs, options, callback); + assert.equal(seen[1], originalArgs); +}); + +function fixture(invoke: (...args: unknown[]) => unknown) { + const methods = ["spawn", "spawnSync", "execFile", "execFileSync"]; + const cp = Object.fromEntries(methods.map((method) => [method, invoke])); + const lines: string[] = []; + let syncs = 0; + runInNewContext(choiceInspectChildDiagnostics, { + require(name: string) { + if (name === "node:child_process") return cp; + assert.equal(name, "node:module"); + return { syncBuiltinESMExports: () => syncs++ }; + }, + process: { execPath: "/private/node", stderr: { write: (line: string) => lines.push(line) } }, + performance: { now: () => 10 }, + }); + assert.equal(syncs, 1); + const records = () => lines.map((line) => JSON.parse(line.slice(line.indexOf("{")).trim())); + return { cp, lines, records }; +} + +test("inspect diagnostics preserve child calls and disclose only bounded categories", () => { + const child = new EventEmitter(); + const args = ["--openclaw-sqlite-readonly-child", "secret-database-path"]; + const options = { env: { SECRET: "secret-environment" } }; + const callback = () => {}; + const receiver = {}; + const { cp, lines, records } = fixture(function (this: unknown, ...actual) { + assert.equal(this, receiver); + assert.deepEqual(actual, ["/private/node", args, options, callback]); + assert.equal(actual[1], args); + assert.equal(actual[2], options); + assert.equal(actual[3], callback); + return child; + }); + assert.equal(cp.execFile.call(receiver, "/private/node", args, options, callback), child); + assert.equal(records().length, 1); + child.emit("close", 1, "SIGTERM"); + assert.deepEqual(records(), [ + { id: 1, method: "execFile", category: "node-sqlite-readonly", stage: "start", elapsedMs: 0 }, + { id: 1, method: "execFile", category: "node-sqlite-readonly", stage: "closed", elapsedMs: 0 }, + ]); + assert.doesNotMatch(lines.join(""), /private|secret|SIGTERM/); +}); + +test("inspect diagnostics preserve synchronous results and thrown errors", () => { + const result = { status: 1, stderr: "secret-output" }; + const returned = fixture(() => result); + assert.equal(returned.cp.spawnSync("C:\\Windows\\powershell.exe", ["secret-script"]), result); + assert.deepEqual( + returned.records().map(({ category, stage }) => [category, stage]), + [ + ["powershell", "start"], + ["powershell", "returned"], + ], + ); + const failure = new Error("secret-failure"); + const thrown = fixture(() => { + throw failure; + }); + assert.throws( + () => thrown.cp.execFileSync("private-executable"), + (error) => error === failure, + ); + assert.deepEqual( + thrown.records().map(({ category, stage }) => [category, stage]), + [ + ["other", "start"], + ["other", "threw"], + ], + ); + assert.doesNotMatch([...returned.lines, ...thrown.lines].join(""), /secret|private|Windows/); +}); + +test("inspect diagnostics stop recording without stopping child calls", () => { + let calls = 0; + const { cp, records } = fixture(() => { + calls++; + return {}; + }); + for (let i = 0; i < 200; i++) cp.spawnSync("/private/node"); + assert.equal(calls, 200); + assert.equal(records().length, 128); + assert(records().every(({ category }) => category === "node")); +}); + +test("inspect diagnostics retain the package-manager trap and real Node callback output", () => { + const result = spawnSync( + process.execPath, + [ + "-e", + ` + const assert = require("node:assert/strict"), cp = require("node:child_process"); + const original = cp.execFile; + const refusal = new Error("synthetic package-manager refusal"); + cp.execFile = function(...args) { + if (args[0] === "npm") throw refusal; + return original.apply(this, args); + }; + ${choiceInspectChildDiagnostics} + assert.throws(() => cp.execFile("npm"), error => error === refusal); + cp.execFile(process.execPath, ["-e", "process.stdout.write('retained-output')"], + {encoding:"utf8"}, (error, stdout) => { + assert.ifError(error); + assert.equal(stdout, "retained-output"); + process.stdout.write("callback-preserved"); + }); + `, + ], + { encoding: "utf8", timeout: 10000, windowsHide: true }, + ); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout, "callback-preserved"); + assert.match(result.stderr, /"stage":"threw"/); + assert.match(result.stderr, /"category":"node","stage":"closed"/); + assert.doesNotMatch(result.stderr, /retained-output|package-manager refusal|process\.stdout/); +}); + +test("readonly diagnostic preserves backup arguments, receiver, promise and failures without leaking data", async () => { + for (const outcome of ["success", "reject", "throw"] as const) { + const secret = new Error("private database failure"); + const args = [{ privateDatabase: true }, "private-destination"]; + const receiver = {}; + const promise = + outcome === "reject" ? Promise.reject(secret) : Promise.resolve("private-result"); + const lines: string[] = []; + const sqlite = { + backup(this: unknown, ...actual: unknown[]) { + assert.equal(this, receiver); + assert.equal(actual[0], args[0]); + assert.equal(actual[1], args[1]); + if (outcome === "throw") throw secret; + return promise; + }, + }; + const cp = Object.fromEntries( + ["spawn", "spawnSync", "execFile", "execFileSync"].map((name) => [name, () => {}]), + ); + runInNewContext(sqliteReadonlyWorkerDiagnostics, { + require(name: string) { + if (name === "node:child_process") return cp; + if (name === "node:sqlite") return sqlite; + assert.equal(name, "node:module"); + return { syncBuiltinESMExports() {} }; + }, + process: { execPath: "/private/node", stderr: { write: (line: string) => lines.push(line) } }, + performance: { now: () => 10 }, + }); + if (outcome === "throw") + assert.throws( + () => sqlite.backup.call(receiver, ...args), + (error) => error === secret, + ); + else { + const actual = sqlite.backup.call(receiver, ...args); + assert.equal(actual, promise); + if (outcome === "reject") await assert.rejects(actual, (error) => error === secret); + else assert.equal(await actual, "private-result"); + } + const records = lines.map((line) => JSON.parse(line.slice(line.indexOf("{")))); + assert.deepEqual(records, [ + { stage: "preload-started", elapsedMs: 0 }, + { stage: "start", elapsedMs: 0 }, + { + stage: outcome === "success" ? "finished" : outcome === "reject" ? "rejected" : "threw", + elapsedMs: 0, + }, + ]); + assert.doesNotMatch(lines.join(""), /private|destination|database|result/); + } +}); diff --git a/packaging/windows/app/diagnose-compiled-sqlite-readonly.mts b/packaging/windows/app/diagnose-compiled-sqlite-readonly.mts new file mode 100644 index 00000000000..2f2e8873c5a --- /dev/null +++ b/packaging/windows/app/diagnose-compiled-sqlite-readonly.mts @@ -0,0 +1,256 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Failure-only diagnostic, never installer acceptance. Exercise the unchanged +// compiled worker with synthetic SQLite data and a separate diagnostic preload. +// The preload adds fixed phase timings to its PowerShell child, not acceptance. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { createHash, randomBytes } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { sqliteReadonlyWorkerDiagnostics } from "./choice-inspect-diagnostics.mts"; + +function argument(name: string) { + const index = process.argv.indexOf(name); + assert(index >= 0 && process.argv[index + 1], `Missing ${name}`); + return path.resolve(process.argv[index + 1]); +} +const app = argument("--app-root"); +const owner = argument("--process-owner"); +const output = argument("--output"); +assert.equal(process.platform, "win32"); +assert.equal(process.arch, "arm64"); +assert.equal(process.versions.node, "22.23.2"); +const hash = (file: string) => createHash("sha256").update(fs.readFileSync(file)).digest("hex"); +const entry = path.join(app, "openclaw-app.cjs"); +const worker = path.join( + app, + "node_modules/openclaw/dist/infra/sqlite-readonly-location.worker.js", +); +const appSha256 = hash(entry), + workerSha256 = hash(worker), + ownerSha256 = hash(owner); +assert.equal( + JSON.parse(fs.readFileSync(path.join(app, "openclaw-resource-closure.json"), "utf8")).compiler + .mainSha256, + appSha256, +); +assert.equal(fs.existsSync(output), false, "Diagnostic output must be fresh."); +fs.mkdirSync(output, { recursive: true }); +const preload = path.join(output, "readonly-diagnostics.cjs"); +fs.writeFileSync(preload, sqliteReadonlyWorkerDiagnostics, { flag: "wx" }); +const result = { + schemaVersion: 1, + classification: "compiled-sqlite-readonly-diagnostic", + installedAcceptance: false, + instrumented: true, + powerShellPhaseInstrumentation: true, + platform: process.platform, + architecture: process.arch, + nodeVersion: process.version, + appSha256, + workerSha256, + ownerSha256, + cases: [] as { + scenario: string; + timedOut: boolean; + forcedOwnerStop: boolean; + ownerExitCode: number | null; + jobDrained: boolean; + snapshotRetained: boolean; + syntheticStateRemoved: boolean; + elapsedMs: number; + failed: boolean; + }[], +}; +try { + for (const journal of ["DELETE", "WAL"] as const) { + const scenario = journal === "WAL" ? "wal-held" : "delete-closed"; + const root = path.join(output, scenario), + home = path.join(root, "synthetic-home"); + fs.mkdirSync(home, { recursive: true }); + const stop = path.join(root, "stop"), + receipt = path.join(root, "stopped.json"); + const nonce = randomBytes(24).toString("hex"), + started = performance.now(); + const row = { + scenario, + timedOut: false, + forcedOwnerStop: false, + ownerExitCode: null as number | null, + jobDrained: false, + snapshotRetained: false, + syntheticStateRemoved: false, + elapsedMs: 0, + failed: true, + }; + result.cases.push(row); + let source: DatabaseSync | undefined; + let launched = false; + try { + const input = path.join(home, "source.sqlite"); + source = new DatabaseSync(input); + source.exec(`PRAGMA journal_mode=${journal}; CREATE TABLE probe(value TEXT); + INSERT INTO probe VALUES ('synthetic snapshot retained');`); + if (journal === "DELETE") { + source.close(); + source = undefined; + } + const env: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(process.env)) + if ( + [ + "systemroot", + "windir", + "systemdrive", + "comspec", + "pathext", + "programfiles", + "programfiles(x86)", + "os", + "processor_architecture", + ].includes(key.toLowerCase()) + ) + env[key] = value; + const systemRoot = Object.entries(env).find( + ([key]) => key.toLowerCase() === "systemroot", + )?.[1]; + assert(systemRoot && path.isAbsolute(systemRoot)); + Object.assign(env, { + PATH: [path.dirname(process.execPath), path.join(systemRoot, "System32"), systemRoot].join( + path.delimiter, + ), + HOME: home, + USERPROFILE: home, + LOCALAPPDATA: home, + APPDATA: home, + TEMP: home, + TMP: home, + OPENCLAW_COMPILED_ASSET_ROOT: app, + NODE_DISABLE_COMPILE_CACHE: "1", + }); + // Reuse the tested owner: assignment to a non-breakaway Windows job occurs + // at process creation. A stop drains Node and its PowerShell descendants. + const child = spawn( + owner, + [ + "--owner", + process.execPath, + stop, + receipt, + nonce, + "--require", + preload, + worker, + "--openclaw-sqlite-readonly-child", + "async", + input, + ], + { cwd: app, env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }, + ); + launched = true; + let stdout = "", + stderr = "", + spawnFailed = false; + child.stdout.on("data", (chunk) => { + stdout = (stdout + chunk.toString()).slice(0, 65536); + }); + child.stderr.on("data", (chunk) => { + stderr = (stderr + chunk.toString()).slice(0, 262144); + }); + child.once("error", () => { + spawnFailed = true; + }); + const stopTimer = setTimeout(() => { + row.timedOut = true; + try { + fs.writeFileSync(stop + ".pending", nonce, { flag: "wx" }); + fs.renameSync(stop + ".pending", stop); + } catch { + row.forcedOwnerStop = true; + child.kill(); + } + }, 30000); + const killTimer = setTimeout(() => { + row.forcedOwnerStop = true; + child.kill(); + }, 45000); + try { + row.ownerExitCode = await new Promise((resolve) => + child.once("close", resolve), + ); + } finally { + clearTimeout(stopTimer); + clearTimeout(killTimer); + // Never retain worker stdout, exception text, arguments, or environment. + const trace = stderr + .split(/\r?\n/u) + .filter((line) => + /^\[nemoclaw-(?:choice-child|snapshot-backup|private-directory)\] \{/u.test(line), + ) + .join("\n"); + fs.writeFileSync(path.join(output, scenario + ".trace.log"), trace + "\n", { flag: "wx" }); + } + const drained = JSON.parse(fs.readFileSync(receipt, "utf8")); + assert.equal(drained.schemaVersion, 1); + assert.equal(drained.nonce, nonce); + assert.equal(drained.activeProcesses, 0); + assert.equal(drained.stopped, true); + row.jobDrained = true; + assert.equal(row.timedOut || row.forcedOwnerStop || spawnFailed, false); + assert.equal(row.ownerExitCode, 0); + assert.equal(drained.requested, false); + assert.equal(drained.gatewayExitCode, 0); + const snapshot = JSON.parse(stdout); + assert.equal(snapshot.ok, true); + assert.equal(typeof snapshot.location, "string"); + const relative = path.relative(home, snapshot.location); + assert( + relative && + !path.isAbsolute(relative) && + relative !== ".." && + !relative.startsWith(".." + path.sep), + ); + const database = new DatabaseSync(snapshot.location, { readOnly: true }); + try { + assert.equal( + database.prepare("SELECT value FROM probe").get()?.value, + "synthetic snapshot retained", + ); + } finally { + database.close(); + } + row.snapshotRetained = true; + assert.equal(hash(entry), appSha256); + assert.equal(hash(worker), workerSha256); + row.failed = false; + } catch { + // Stage markers and fixed booleans are sufficient; no raw error export. + row.failed = true; + } finally { + try { + source?.close(); + if (!launched || row.jobDrained) { + fs.rmSync(home, { recursive: true, force: true }); + row.syntheticStateRemoved = !fs.existsSync(home); + } + } catch { + row.failed = true; + } + row.elapsedMs = Math.round(performance.now() - started); + } + } +} finally { + fs.writeFileSync( + path.join(output, "readonly-diagnostic.json"), + JSON.stringify(result, null, 2) + "\n", + { flag: "wx" }, + ); +} +if (result.cases.some((row) => row.failed || !row.syntheticStateRemoved)) + throw new Error( + "Readonly worker diagnostic failed; inspect the bounded stage trace and cleanup receipt.", + ); +console.log("Readonly worker diagnostic completed; this is not installed acceptance."); diff --git a/packaging/windows/app/gateway-control-browser-diagnostics.mts b/packaging/windows/app/gateway-control-browser-diagnostics.mts new file mode 100644 index 00000000000..6b4ec747cd5 --- /dev/null +++ b/packaging/windows/app/gateway-control-browser-diagnostics.mts @@ -0,0 +1,349 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +type GatewaySnapshot = { + phase?: string; + client?: unknown; + hello?: { + auth?: { role?: string; scopes?: string[] }; + features?: { methods?: string[] }; + snapshot?: { sessionDefaults?: { defaultAgentId?: string; modelConfigured?: boolean } }; + }; +}; +type GatewayContext = { + gateway?: { + snapshot?: GatewaySnapshot; + subscribe?: (listener: (snapshot: GatewaySnapshot) => void) => () => void; + }; + agentSelection?: { state?: { selectedId?: string } }; +}; + +function record(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; +} + +// Preserve only routing predicates, never device tokens, request IDs or configuration. +export function summarizeGatewayHello(value: unknown) { + const message = record(value); + const payload = record(message.payload); + if (message.type !== "res" || message.ok !== true || payload.type !== "hello-ok") return null; + const defaults = record(record(payload.snapshot).sessionDefaults); + const methods = record(payload.features).methods; + const scopes = record(payload.auth).scopes; + return { + defaultAgentIsMain: defaults.defaultAgentId === "main", + soleAgent: defaults.ownership === "sole", + modelConfigured: + typeof defaults.modelConfigured === "boolean" ? defaults.modelConfigured : null, + selectionRequired: + typeof defaults.selectionRequired === "boolean" ? defaults.selectionRequired : null, + setupDetectionAvailable: Array.isArray(methods) && methods.includes("openclaw.setup.detect"), + adminScope: Array.isArray(scopes) && scopes.includes("operator.admin"), + }; +} + +export function gatewayBrowserRoute(value: string) { + try { + const pathname = new URL(value).pathname; + if (pathname === "/settings/model-setup") return "model-setup"; + if (pathname === "/settings/plugins") return "plugins"; + if (pathname === "/chat") return "chat-root"; + if (pathname.startsWith("/chat/")) return "chat-session"; + return "other"; + } catch { + return "unavailable"; + } +} + +export function gatewayBrowserMajorVersion(value: string) { + const match = /^(\d+)\./u.exec(value); + const major = match ? Number(match[1]) : NaN; + return Number.isSafeInteger(major) && major > 0 ? major : null; +} + +export function gatewayBrowserConsoleFailure(value: string) { + if (value.startsWith("[openclaw] application start failed")) return "application-start"; + if (value.startsWith("[openclaw] initial session location failed")) return "initial-location"; + if (value.startsWith("[openclaw] route navigation failed")) return "route-navigation"; + if (value.startsWith("[gateway] snapshot handler error:")) return "gateway-snapshot"; + return "other"; +} + +// Playwright serializes this function. Keep it independent of module scope. +export function installGatewayBrowserRouteTrace() { + const scope = globalThis as unknown as { + location: { pathname: string; hash?: string; search?: string }; + history: Record< + "pushState" | "replaceState", + (data: unknown, unused: string, url?: string | URL | null) => unknown + >; + addEventListener: (type: string, listener: () => void) => void; + customElements?: { whenDefined: (name: string) => Promise }; + navigator?: { + serviceWorker?: { + addEventListener: (type: string, listener: (event: { data?: unknown }) => void) => void; + }; + }; + document?: { querySelector: (selector: string) => { context?: GatewayContext } | null }; + __nemoclawRouteTrace?: unknown; + }; + const trace = { + routes: [] as string[], + truncated: false, + snapshots: [] as unknown[], + snapshotsTruncated: false, + gatewayObserved: false, + observerFailed: false, + fragmentEvents: [] as unknown[], + fragmentsTruncated: false, + }; + scope.__nemoclawRouteTrace = trace; + const initialHash = scope.location.hash ?? ""; + let previousHash = initialHash; + const captureFragment = (event: string) => { + try { + if (trace.fragmentEvents.length >= 64) { + trace.fragmentsTruncated = true; + return; + } + const hash = scope.location.hash ?? ""; + trace.fragmentEvents.push({ + event, + present: hash !== "", + equalsInitial: hash === initialHash, + changed: hash !== previousHash, + mountRecovery: /(?:^\?|&)openclaw_mount_recovery(?:=|&|$)/u.test( + scope.location.search ?? "", + ), + }); + previousHash = hash; + } catch { + trace.observerFailed = true; + } + }; + const observe = () => { + const pathname = scope.location.pathname; + const route = + pathname === "/settings/model-setup" + ? "model-setup" + : pathname === "/settings/plugins" + ? "plugins" + : pathname === "/chat" + ? "chat-root" + : pathname.startsWith("/chat/") + ? "chat-session" + : "other"; + if (trace.routes.at(-1) === route) return; + if (trace.routes.length >= 64) trace.truncated = true; + else trace.routes.push(route); + }; + for (const method of ["pushState", "replaceState"] as const) { + const original = scope.history[method].bind(scope.history); + scope.history[method] = (...args) => { + const result = original(...args); + observe(); + captureFragment(method); + return result; + }; + } + scope.addEventListener("popstate", observe); + for (const event of [ + "popstate", + "hashchange", + "DOMContentLoaded", + "load", + "openclaw-control-ui-rendered", + ]) { + scope.addEventListener(event, () => captureFragment(event)); + } + observe(); + captureFragment("initial"); + // Observe activation beside URL changes without replying to probes, starting the + // message queue, or retaining worker versions, URLs, message ports or credentials. + try { + const worker = scope.navigator?.serviceWorker; + worker?.addEventListener("controllerchange", () => captureFragment("sw-controllerchange")); + worker?.addEventListener("message", (event) => { + try { + const data = event.data; + if (!data || typeof data !== "object" || !("type" in data)) return; + if (data.type === "sw-version-probe" || data.type === "sw-updated") + captureFragment(data.type); + } catch { + trace.observerFailed = true; + } + }); + } catch { + trace.observerFailed = true; + } + // Subscribe when the dashboard element is defined, before waiting for navigation. + // A final connected snapshot cannot explain an earlier one-time routing decision. + void scope.customElements + ?.whenDefined("openclaw-app") + .then(() => { + const context = scope.document?.querySelector("openclaw-app")?.context; + const gateway = context?.gateway; + if (!gateway?.subscribe) return; + const capture = (snapshot: GatewaySnapshot) => { + try { + captureFragment("gateway-snapshot"); + if (trace.snapshots.length >= 64) { + trace.snapshotsTruncated = true; + return; + } + const selected = context?.agentSelection?.state?.selectedId?.trim(); + const defaults = snapshot.hello?.snapshot?.sessionDefaults; + const defaultAgent = defaults?.defaultAgentId?.trim(); + trace.snapshots.push({ + phase: [ + "starting", + "connecting", + "connected", + "reconnecting", + "offline", + "reload-required", + "stopped", + ].includes(snapshot.phase ?? "") + ? snapshot.phase + : "other", + route: trace.routes.at(-1) ?? "other", + hasHello: Boolean(snapshot.hello), + hasClient: Boolean(snapshot.client), + operatorRole: snapshot.hello?.auth?.role === "operator", + setupDetectionAvailable: + snapshot.hello?.features?.methods?.includes("openclaw.setup.detect") === true, + adminScope: snapshot.hello?.auth?.scopes?.includes("operator.admin") === true, + selectedIsDefault: defaultAgent ? !selected || selected === defaultAgent : null, + modelConfigured: + typeof defaults?.modelConfigured === "boolean" ? defaults.modelConfigured : null, + }); + } catch { + trace.observerFailed = true; + } + }; + const unsubscribe = gateway.subscribe(capture); + trace.gatewayObserved = true; + if (gateway.snapshot) capture(gateway.snapshot); + scope.addEventListener("pagehide", () => { + try { + unsubscribe(); + } catch { + trace.observerFailed = true; + } + }); + }) + .catch(() => { + trace.observerFailed = true; + }); +} + +// Read only categorical state from the pinned dashboard's public context getter. +export function readGatewayBrowserRouteTrace() { + const scope = globalThis as unknown as { + document: { querySelector: (selector: string) => unknown }; + __nemoclawRouteTrace?: unknown; + }; + const app = scope.document.querySelector("openclaw-app") as { context?: GatewayContext } | null; + const snapshot = app?.context?.gateway?.snapshot; + const selected = app?.context?.agentSelection?.state?.selectedId?.trim(); + const defaultAgent = snapshot?.hello?.snapshot?.sessionDefaults?.defaultAgentId?.trim(); + return { + trace: scope.__nemoclawRouteTrace, + connected: snapshot?.phase === "connected", + hasClient: Boolean(snapshot?.client), + operatorRole: snapshot?.hello?.auth?.role === "operator", + selectedIsDefault: defaultAgent ? !selected || selected === defaultAgent : null, + }; +} + +export function summarizeGatewayBrowserRouteTrace(value: unknown) { + const state = record(value); + const trace = record(state.trace); + const allowed = new Set(["model-setup", "plugins", "chat-root", "chat-session", "other"]); + const fragmentEvents = new Set([ + "initial", + "pushState", + "replaceState", + "popstate", + "hashchange", + "DOMContentLoaded", + "load", + "gateway-snapshot", + "openclaw-control-ui-rendered", + "sw-controllerchange", + "sw-version-probe", + "sw-updated", + ]); + return { + routes: Array.isArray(trace.routes) + ? trace.routes + .slice(0, 64) + .filter((route): route is string => typeof route === "string" && allowed.has(route)) + : [], + truncated: + trace.truncated === true || (Array.isArray(trace.routes) && trace.routes.length > 64), + connected: state.connected === true, + hasClient: state.hasClient === true, + operatorRole: state.operatorRole === true, + selectedIsDefault: + typeof state.selectedIsDefault === "boolean" ? state.selectedIsDefault : null, + gatewayObserved: trace.gatewayObserved === true, + observerFailed: trace.observerFailed === true, + fragmentsTruncated: + trace.fragmentsTruncated === true || + (Array.isArray(trace.fragmentEvents) && trace.fragmentEvents.length > 64), + fragmentEvents: Array.isArray(trace.fragmentEvents) + ? trace.fragmentEvents.slice(0, 64).map((value) => { + const fragment = record(value); + return { + event: + typeof fragment.event === "string" && fragmentEvents.has(fragment.event) + ? fragment.event + : "other", + present: fragment.present === true, + equalsInitial: fragment.equalsInitial === true, + changed: fragment.changed === true, + mountRecovery: fragment.mountRecovery === true, + }; + }) + : [], + snapshotsTruncated: + trace.snapshotsTruncated === true || + (Array.isArray(trace.snapshots) && trace.snapshots.length > 64), + snapshots: Array.isArray(trace.snapshots) + ? trace.snapshots.slice(0, 64).map((value) => { + const snapshot = record(value); + return { + phase: + typeof snapshot.phase === "string" && + [ + "starting", + "connecting", + "connected", + "reconnecting", + "offline", + "reload-required", + "stopped", + ].includes(snapshot.phase) + ? snapshot.phase + : "other", + route: + typeof snapshot.route === "string" && allowed.has(snapshot.route) + ? snapshot.route + : "other", + hasHello: snapshot.hasHello === true, + hasClient: snapshot.hasClient === true, + operatorRole: snapshot.operatorRole === true, + setupDetectionAvailable: snapshot.setupDetectionAvailable === true, + adminScope: snapshot.adminScope === true, + selectedIsDefault: + typeof snapshot.selectedIsDefault === "boolean" ? snapshot.selectedIsDefault : null, + modelConfigured: + typeof snapshot.modelConfigured === "boolean" ? snapshot.modelConfigured : null, + }; + }) + : [], + }; +} diff --git a/packaging/windows/app/gateway-control-model-fixture.mts b/packaging/windows/app/gateway-control-model-fixture.mts new file mode 100644 index 00000000000..482b16a0cb0 --- /dev/null +++ b/packaging/windows/app/gateway-control-model-fixture.mts @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export function gatewayControlModelProviders(port: number, configured: boolean) { + const origin = `http://127.0.0.1:${port}`; + return { + // Local discovery must not borrow a model from the machine running the control. + ollama: { + baseUrl: origin, + apiKey: "ollama-local", + api: "ollama", + models: [], + }, + lmstudio: { + baseUrl: `${origin}/v1`, + apiKey: "lmstudio-local", + api: "openai-completions", + models: [], + }, + ...(configured + ? { + nemoclawnative: { + baseUrl: `${origin}/v1`, + apiKey: "owned-local-model-control", + api: "openai-completions", + models: [ + { + id: "fixture", + name: "fixture", + reasoning: false, + input: ["text"], + contextWindow: 131072, + maxTokens: 4096, + }, + ], + }, + } + : {}), + }; +} + +export function isGatewayControlDiscoveryRequest(method?: string, url?: string) { + return method === "GET" && ["/api/ps", "/api/tags", "/api/v1/models"].includes(url ?? ""); +} diff --git a/packaging/windows/app/gateway-control-route-decisions.mts b/packaging/windows/app/gateway-control-route-decisions.mts new file mode 100644 index 00000000000..90489500641 --- /dev/null +++ b/packaging/windows/app/gateway-control-route-decisions.mts @@ -0,0 +1,173 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import { createHash } from "node:crypto"; + +export const gatewayDecisionAsset = "control-ui-core-Rwzhj6nO.js"; +const decisionAssetSha256 = "dd93631fe62c97a4b27181385bf3c02358458ed1a8488ba2bb6e661f5e3c8267"; + +// These logpoints observe the pinned first-run decision without rewriting served assets. +// They belong only to the disposable, credential-free compiled gateway control. +export function gatewayDecisionLogpoints(source: string, expectedSha256 = decisionAssetSha256) { + if (createHash("sha256").update(source).digest("hex") !== expectedSha256) return null; + const start = source.indexOf("async function Qm(e){"); + const end = source.indexOf("function $m()", start); + const callback = source.indexOf("s=e=>{if(a)return;", start); + const location = source.indexOf("r=()=>lt(e.history.location(),t)", start); + if ( + start < 0 || + end <= start || + callback <= start || + callback >= end || + location <= start || + location >= callback + ) + return null; + const points = [ + { + offset: start + "async function Qm(e){".length, + value: '{kind:"entry",enabled:e.enabled===true}', + }, + { + offset: callback + "s=e=>{".length, + value: + '{kind:"snapshot",phase:e.phase,alreadyDecided:a,eligible:Yt(e,`openclaw.setup.detect`,`operator.admin`),sameLanding:r(),selectedIsDefault:!n.agentSelection.state.selectedId?.trim()||n.agentSelection.state.selectedId?.trim()===or(e)?.defaultAgentId?.trim(),configured:or(e)?.modelConfigured??null}', + }, + { + offset: location + "r=()=>".length, + value: + '{kind:"location",pathnameEqual:location.pathname===t.pathname,searchEqual:location.search===t.search,hashEqual:location.hash===t.hash}', + }, + ]; + return points.map(({ offset, value }) => { + const prefix = source.slice(0, offset); + return { + lineNumber: prefix.split("\n").length - 1, + columnNumber: offset - prefix.lastIndexOf("\n") - 1, + urlRegex: "/control-ui-core-Rwzhj6nO\\.js(?:\\?.*)?$", + condition: `(()=>{try{const events=globalThis.__nemoclawRouteDecisions;if(Array.isArray(events)&&events.length<64)events.push(${value})}catch{}return false})()`, + }; + }); +} + +type DecisionSession = { + send(method: string, params?: Record): Promise; + on(event: "Debugger.paused", listener: () => void): void; + detach(): Promise; +}; +export type DecisionPage = { + addInitScript(script: () => void): Promise; + evaluate(script: () => T): Promise; + context(): { newCDPSession(page: DecisionPage): Promise }; +}; + +function readDecisionEvents() { + const events = (globalThis as unknown as { __nemoclawRouteDecisions?: unknown }) + .__nemoclawRouteDecisions; + return Array.isArray(events) ? events.slice(0, 64) : []; +} + +type DecisionEvent = + | { kind: "entry"; enabled: boolean } + | { kind: "location"; pathnameEqual: boolean; searchEqual: boolean; hashEqual: boolean } + | { + kind: "snapshot"; + phase: string; + alreadyDecided: boolean; + eligible: boolean; + sameLanding: boolean; + selectedIsDefault: boolean; + configured: boolean | null; + }; + +export function summarizeGatewayDecisions(value: unknown): DecisionEvent[] { + if (!Array.isArray(value)) return []; + return value.slice(0, 64).flatMap((item) => { + if (!item || typeof item !== "object") return []; + const event = item as Record; + if (event.kind === "entry") return [{ kind: "entry", enabled: event.enabled === true }]; + if (event.kind === "location") + return [ + { + kind: "location", + pathnameEqual: event.pathnameEqual === true, + searchEqual: event.searchEqual === true, + hashEqual: event.hashEqual === true, + }, + ]; + if (event.kind !== "snapshot") return []; + return [ + { + kind: "snapshot", + phase: + typeof event.phase === "string" && + [ + "starting", + "connecting", + "connected", + "reconnecting", + "offline", + "reload-required", + "stopped", + ].includes(event.phase) + ? event.phase + : "other", + alreadyDecided: event.alreadyDecided === true, + eligible: event.eligible === true, + sameLanding: event.sameLanding === true, + selectedIsDefault: event.selectedIsDefault === true, + configured: typeof event.configured === "boolean" ? event.configured : null, + }, + ]; + }); +} + +export async function observeGatewayDecisions( + page: DecisionPage, + points: ReturnType, +) { + const status = { supported: points !== null, installed: 0, unexpectedPauses: 0, failed: false }; + let session: DecisionSession | undefined; + try { + if (points) { + await page.addInitScript(() => { + ( + globalThis as unknown as { __nemoclawRouteDecisions: unknown[] } + ).__nemoclawRouteDecisions = []; + }); + session = await page.context().newCDPSession(page); + await session.send("Debugger.enable"); + const client = session; + client.on("Debugger.paused", () => { + status.unexpectedPauses = Math.min(64, status.unexpectedPauses + 1); + status.failed = true; + void client.send("Debugger.resume").catch(() => { + status.failed = true; + }); + }); + for (const point of points) { + await client.send("Debugger.setBreakpointByUrl", point); + status.installed++; + } + } + } catch { + // Diagnostic failure must not replace the product assertion or expose browser errors. + status.failed = true; + } + return { + async finish() { + let events: ReturnType = []; + try { + events = summarizeGatewayDecisions(await page.evaluate(readDecisionEvents)); + } catch { + status.failed = true; + } finally { + try { + await session?.detach(); + } catch { + status.failed = true; + } + } + return { ...status, events }; + }, + }; +} diff --git a/packaging/windows/app/materialize-openclaw-build.py b/packaging/windows/app/materialize-openclaw-build.py new file mode 100644 index 00000000000..d1e5c4480d4 --- /dev/null +++ b/packaging/windows/app/materialize-openclaw-build.py @@ -0,0 +1,256 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Restore exact published app/compiler bytes in CI; never executes package hooks.""" +import argparse +import base64 +import concurrent.futures +import hashlib +import json +import os +from pathlib import Path +import tarfile +import time +import urllib.parse +import urllib.request + + +def require(value, message): + if not value: + raise ValueError(message) + + +def safe_parts(value, allow_current=False): + require(isinstance(value, str) and value and "\\" not in value, "Invalid package path.") + require(not value.startswith("/"), "Absolute package path.") + parts = value.rstrip("/").split("/") + if allow_current: + parts = [part for part in parts if part != "."] + require(parts, "Empty package path.") + devices = {"CON", "PRN", "AUX", "NUL", "CLOCK$"} | { + prefix + digit for prefix in ("COM", "LPT") for digit in "123456789¹²³" + } + for part in parts: + require(part not in ("", ".", "..") and part[-1:] not in (".", " "), "Aliased package path.") + require(not any(ord(char) < 32 or char in '<>:"|?*' for char in part), "Invalid Windows package path character.") + require(part.split(".", 1)[0].upper() not in devices, "Reserved Windows package path.") + return tuple(parts) + + +def fetch(item, cache, deadline): + url = item["url"] + parsed = urllib.parse.urlsplit(url) + require(parsed.scheme == "https" and parsed.hostname == "registry.npmjs.org", "Unexpected package source.") + filename = cache / (hashlib.sha256(url.encode()).hexdigest() + ".tgz") + if not filename.exists(): + temporary = filename.with_suffix(".part") + with urllib.request.urlopen(urllib.request.Request(url, headers={"Accept-Encoding": "identity"}), timeout=30) as response, temporary.open("xb") as target: + count = 0 + while data := response.read(1024 * 1024): + count += len(data) + require(count <= 128 * 1024 * 1024 and time.monotonic() < deadline, "Package download exceeds its bound.") + target.write(data) + target.flush() + os.fsync(target.fileno()) + os.replace(temporary, filename) + data = filename.read_bytes() + require(len(data) <= 128 * 1024 * 1024, "Oversized package archive.") + algorithm, expected = item["integrity"].split("-", 1) + require(algorithm == "sha512" and hashlib.sha512(data).digest() == base64.b64decode(expected), "Package SRI mismatch.") + if "sha256" in item: + require(hashlib.sha256(data).hexdigest() == item["sha256"], "Package SHA256 mismatch.") + if "bytes" in item: + require(len(data) == item["bytes"], "Package archive length mismatch.") + return {"url": url, "archive": str(filename), "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(), "integrity": item["integrity"]} + + +def extract(archive, destination): + destination.mkdir(parents=True, exist_ok=True) + files = 0 + total = 0 + with tarfile.open(archive, "r:gz") as source: + prefix = None + for member in source: + parts = safe_parts(member.name, allow_current=True) + prefix = parts[0] if prefix is None else prefix + require(parts[0] == prefix, "Multiple package archive roots.") + target = destination.joinpath(*parts[1:]) + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + continue + require(member.isfile() and member.size <= 128 * 1024 * 1024, "Nonregular or oversized package member.") + files += 1 + total += member.size + require(files <= 50000 and total <= 1024 * 1024 * 1024, "Expanded package exceeds its bound.") + target.parent.mkdir(parents=True, exist_ok=True) + with source.extractfile(member) as incoming: + data = incoming.read(member.size + 1) + require(len(data) == member.size, "Truncated package member.") + if target.exists() or target.is_symlink(): + require(target.is_file() and not target.is_symlink() and target.stat().st_nlink == 1, "Nonregular overlapping package path.") + require(target.read_bytes() == data, "Overlapping package members differ.") + else: + with target.open("xb") as output: + output.write(data) + os.chmod(target, member.mode & 0o755) + return {"files": files, "bytes": total} + + +def dependency_plan(lock, lock_file): + """Keep the canonical wrapper's hoisted and nested package locations intact.""" + dependency_lock = lock["dependencyLock"] + lock_path = (lock_file.parent / dependency_lock["path"]).resolve() + lock_bytes = lock_path.read_bytes() + require(hashlib.sha256(lock_bytes).hexdigest() == dependency_lock["sha256"], "Dependency lock SHA256 mismatch.") + document = json.loads(lock_bytes) + require(document.get("name") == "nemoclaw-openclaw-runtime" and document.get("lockfileVersion") == 3, "Unexpected runtime dependency lock.") + packages = document["packages"] + core_path = "node_modules/openclaw" + core = packages[core_path] + expected = lock["openclaw"] + require(packages[""]["dependencies"]["openclaw"] == expected["version"], "Runtime wrapper version differs from the selected source.") + require(core["version"] == expected["version"] and core["resolved"] == expected["url"] and core["integrity"] == expected["integrity"], "Runtime source differs from the dependency lock.") + requested = {} + destinations = set() + plan = [] + for name, item in packages.items(): + if not name: + continue + parts = safe_parts(name) + remaining = list(parts) + while remaining: + require(len(remaining) >= 2 and remaining.pop(0) == "node_modules", "Invalid locked package location.") + package_name = remaining.pop(0) + if package_name.startswith("@"): + require(len(package_name) > 1 and remaining and not remaining[0].startswith("@"), "Invalid scoped package location.") + remaining.pop(0) + require(name.casefold() not in destinations and not item.get("link"), "Aliased or linked dependency location.") + destinations.add(name.casefold()) + require(isinstance(item.get("version"), str) and item["version"], "Missing locked dependency version.") + archive = {"url": item["resolved"], "integrity": item["integrity"]} + if archive["url"] in requested: + require(requested[archive["url"]]["integrity"] == archive["integrity"], "Conflicting dependency archive integrity.") + requested[archive["url"]] = archive + plan.append((name, parts, item)) + return lock_bytes, core_path, plan, requested + + +def choice_dependency_plan(lock, lock_file, core_plan): + """Complete published channel bundles from main's approved messaging lock.""" + selected = lock.get("choiceDependencyLock") + if selected is None: + return None, [] + raw = (lock_file.parent / selected["path"]).resolve().read_bytes() + require(hashlib.sha256(raw).hexdigest() == selected["sha256"], "Choice dependency lock SHA256 mismatch.") + document = json.loads(raw) + require(document.get("name") == "nemoclaw-managed-image-messaging-runtime" and document.get("lockfileVersion") == 3, "Unexpected choice dependency lock.") + packages = document["packages"] + additional = {item["package"]: item for item in lock["additionalPackages"]} + plan = [] + for name in selected["packages"]: + item = additional[name] + prefix = "node_modules/" + name + owner = packages[prefix] + require(owner["version"] == item["version"] and owner["resolved"] == item["url"] and owner["integrity"] == item["integrity"], "Choice package differs from its dependency lock.") + target = safe_parts(item["target"]) + require(target[:1] == ("plugins",), "Choice dependencies require the plugins namespace.") + for location, dependency in packages.items(): + if location.startswith(prefix + "/node_modules/"): + suffix = location[len(prefix) + 1:] + plan.append(("/".join((*target, *safe_parts(suffix))), location.rsplit("node_modules/", 1)[1], dependency)) + core = {name: item for name, _, item in core_plan} + for name in selected["sharedPackages"]: + location = "node_modules/" + name + safe_parts(location) + item = packages[location] + if location in core: + require(all(core[location][field] == item[field] for field in ("version", "resolved", "integrity")), "Conflicting shared choice dependency.") + plan.append((location, name, item)) + seen = set() + for location, _, item in plan: + require(location.casefold() not in seen and not item.get("link"), "Aliased or linked choice dependency.") + seen.add(location.casefold()) + require(isinstance(item.get("version"), str) and item["version"], "Missing choice dependency version.") + require(item.get("inBundle") or (item.get("resolved") and item.get("integrity")), "Choice dependency has no verified source.") + return raw, plan + + +def restore_choice_dependencies(plan, output, cache, deadline): + restored = [] + for location, name, item in plan: + destination = output.joinpath(*safe_parts(location)) + metadata_file = destination / "package.json" + archive = None + if not metadata_file.exists(): + require(item.get("resolved") and item.get("integrity"), "Missing bundled choice dependency has no pinned archive.") + archive = fetch({"url": item["resolved"], "integrity": item["integrity"]}, cache, deadline) + extract(archive["archive"], destination) + metadata = json.loads(metadata_file.read_text()) + require(metadata["name"] == name and metadata["version"] == item["version"], "Choice dependency identity differs from the canonical lock.") + restored.append({"path": location, "package": name, "version": item["version"], "archive": archive}) + return restored + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--cache", type=Path, required=True) + parser.add_argument("--lock", type=Path, default=Path(__file__).with_name("windows-app-build.lock.json")) + parser.add_argument("--portable-proof", action="store_true") + args = parser.parse_args() + require(os.name == "nt" or args.portable_proof, "Materialization is a Windows CI operation.") + require(not args.output.exists(), "A fresh build-input directory is required.") + lock = json.loads(args.lock.read_text()) + require(lock["schemaVersion"] == 1, "Unknown application build lock.") + dependency_lock_bytes, core_path, plan, requested = dependency_plan(lock, args.lock) + choice_lock_bytes, choice_plan = choice_dependency_plan(lock, args.lock, plan) + args.output.mkdir(parents=True) + args.cache.mkdir(parents=True, exist_ok=True) + deadline = time.monotonic() + 900 + source = fetch(lock["openclaw"], args.cache, deadline) + package = args.output.joinpath(*safe_parts(core_path)) + source_inventory = extract(source["archive"], package) + metadata = json.loads((package / "package.json").read_text()) + require(metadata["name"] == "openclaw" and metadata["version"] == lock["openclaw"]["version"], "Unexpected source package identity.") + del requested[lock["openclaw"]["url"]] + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as workers: + archives = list(workers.map(lambda item: fetch(item, args.cache, deadline), requested.values())) + by_url = {item["url"]: item for item in archives} + by_url[source["url"]] = source + dependencies = [] + for name, components, item in plan: + if name == core_path: + continue + inventory = extract(by_url[item["resolved"]]["archive"], args.output.joinpath(*components)) + dependencies.append({"path": name, "version": item["version"], "lifecycleScriptDeclared": item.get("hasInstallScript", False), **inventory}) + platform_package = "@esbuild/darwin-arm64" if args.portable_proof else "@esbuild/win32-arm64" + compiler = [] + for item in lock["compilerPackages"]: + if item["package"] not in ("esbuild", platform_package, "yaml"): + continue + archive = fetch(item, args.cache, deadline) + inventory = extract(archive["archive"], args.output / "tools" / "node_modules" / item["package"]) + compiler.append({**archive, "package": item["package"], **inventory}) + additional = [] + for item in lock.get("additionalPackages", []): + target = safe_parts(item["target"]) + require(target[:1] == ("plugins",), "Additional app inputs require the plugins namespace.") + archive = fetch(item, args.cache, deadline) + inventory = extract(archive["archive"], args.output.joinpath(*target)) + additional.append({**archive, "package": item["package"], "version": item["version"], "target": item["target"], **inventory}) + choice_dependencies = restore_choice_dependencies(choice_plan, args.output, args.cache, deadline) + choice_lock = None + if choice_lock_bytes is not None: + with (args.output / "choice-package-lock.json").open("xb") as choice_output: + choice_output.write(choice_lock_bytes) + choice_lock = {"path": "choice-package-lock.json", "sha256": hashlib.sha256(choice_lock_bytes).hexdigest()} + with (args.output / "runtime-package-lock.json").open("xb") as dependency_output: + dependency_output.write(dependency_lock_bytes) + receipt = {"schemaVersion": 1, "classification": "verified-application-build-inputs", "portableProof": args.portable_proof, "source": source, "sourceRoot": core_path, "sourceInventory": source_inventory, "dependencyLock": {"path": "runtime-package-lock.json", "sha256": hashlib.sha256(dependency_lock_bytes).hexdigest()}, "dependencyArchives": archives, "dependencies": dependencies, "compiler": compiler, "additionalPackages": additional, "lifecycleScriptsExecuted": False, "runtimeReady": False, "lockSha256": hashlib.sha256(args.lock.read_bytes()).hexdigest()} + receipt["choiceDependencyLock"] = choice_lock + receipt["choiceDependencies"] = choice_dependencies + (args.output / "materialization-receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") + print(json.dumps({"packages": len(dependencies), "sourceRoot": str(package), "toolRoot": str(args.output / "tools"), "runtimeReady": False})) + + +if __name__ == "__main__": + main() diff --git a/packaging/windows/app/native-model-catalog-build.mts b/packaging/windows/app/native-model-catalog-build.mts new file mode 100644 index 00000000000..facbc5159d0 --- /dev/null +++ b/packaging/windows/app/native-model-catalog-build.mts @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import path from "node:path"; + +/** Bind the packaged provider APIs; OpenClaw owns discovery and model metadata. */ +export function nativeModelCatalogSource(source: string) { + const entry = (relative: string) => + JSON.stringify(path.join(source, "dist", relative).replaceAll("\\", "/")); + return ` +export async function parseNativeConfiguration(text) { + __nemoPrepareAssetRoot(); + const { l: parseConfigJson5 } = await import(${entry("io.read-helpers-ZKp-UiGx.js")}); + const result = parseConfigJson5(text); + if (!result.ok || !result.parsed || typeof result.parsed !== "object" || Array.isArray(result.parsed)) + throw Error("The saved OpenClaw configuration is invalid; it has not been overwritten."); + return result.parsed; +} +export async function buildNativeModelCatalog(inference, baseUrl, apiKey) { + __nemoPrepareAssetRoot(); + const { t: modelKey } = await import(${entry("model-key-CMdQNkZf.js")}); + const { a: legacyModelKey } = await import(${entry("model-ref-shared-Dz7QU0Lx.js")}); + let provider = "nemoclawNative"; + let configuration; + if (inference === "nvidia") { + provider = "nvidia"; + const { buildSelectableLiveNvidiaProvider } = await import(${entry("extensions/nvidia/provider-catalog.js")}); + configuration = await buildSelectableLiveNvidiaProvider(); + } else if (inference === "openrouter") { + provider = "openrouter"; + const { buildOpenrouterLiveProvider } = await import(${entry("extensions/openrouter/provider-catalog.js")}); + configuration = await buildOpenrouterLiveProvider({ baseUrl, apiKey }); + } else if (inference === "compatible" || inference === "local") { + const { discoverOpenAICompatibleLocalModels } = await import(${entry("plugin-sdk/provider-setup.js")}); + configuration = { api: "openai-completions", models: await discoverOpenAICompatibleLocalModels({ + baseUrl, apiKey, label: "Configured provider", discoverRuntimeContext: false, + }) }; + } else throw Error("Unsupported native inference provider"); + return { + provider, + configuration: { ...configuration, baseUrl, apiKey, timeoutSeconds: 180 }, + references: Object.fromEntries(configuration.models.map(model => [model.id, modelKey(provider, model.id)])), + referenceAliases: Object.fromEntries(configuration.models.flatMap(model => { + const legacy = legacyModelKey(provider, model.id); + return legacy ? [[legacy, modelKey(provider, model.id)]] : []; + })), + }; +} +`; +} diff --git a/packaging/windows/app/native-model-catalog-build.test.mts b/packaging/windows/app/native-model-catalog-build.test.mts new file mode 100644 index 00000000000..8db04bda5f3 --- /dev/null +++ b/packaging/windows/app/native-model-catalog-build.test.mts @@ -0,0 +1,126 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import test from "node:test"; +import { runInNewContext } from "node:vm"; +import { build } from "esbuild"; +import { nativeModelCatalogSource } from "./native-model-catalog-build.mts"; +import type { NativeModelCatalog } from "../runtime/native-openclaw-models.mts"; + +test("the compiled adapter delegates provider discovery, metadata and references to pinned OpenClaw APIs", async () => { + const calls: { provider: string; parameters: unknown }[] = []; + const models = [ + { + id: "vendor/model", + name: "Native name", + reasoning: true, + contextWindow: 234567, + maxTokens: 7654, + compat: { requiresStringContent: true }, + }, + ]; + const modules: Record = { + "io.read-helpers-ZKp-UiGx.js": + "export function l(text) { return globalThis.nativeParse(text); }", + "model-key-CMdQNkZf.js": + 'export function t(provider, id) { return "native-reference:" + provider + ":" + id; }', + "model-ref-shared-Dz7QU0Lx.js": + 'export function a(provider, id) { return provider === "nvidia" ? "native-legacy:" + provider + ":" + id : null; }', + "extensions/nvidia/provider-catalog.js": + 'export async function buildSelectableLiveNvidiaProvider() { return globalThis.nativeProvider("nvidia"); }', + "extensions/openrouter/provider-catalog.js": + 'export async function buildOpenrouterLiveProvider(params) { return globalThis.nativeProvider("openrouter", params); }', + "plugin-sdk/provider-setup.js": + 'export async function discoverOpenAICompatibleLocalModels(params) { return globalThis.nativeProvider("compatible", params).models; }', + }; + const bundled = await build({ + stdin: { + contents: + "function __nemoPrepareAssetRoot() {}\n" + nativeModelCatalogSource("/pinned/openclaw"), + loader: "js", + }, + bundle: true, + write: false, + format: "cjs", + platform: "node", + plugins: [ + { + name: "native-api-contract", + setup(builder) { + builder.onResolve({ filter: /\/pinned\/openclaw\/dist\// }, (args) => ({ + path: args.path.split("/dist/")[1]!, + namespace: "fixture", + })); + builder.onLoad({ filter: /.*/, namespace: "fixture" }, (args) => { + assert(args.path in modules, "Only the pinned native APIs may be imported"); + return { contents: modules[args.path], loader: "js" }; + }); + }, + }, + ], + }); + const module = { + exports: {} as { + parseNativeConfiguration(text: string): Promise; + buildNativeModelCatalog( + provider: string, + url: string, + token: string, + ): Promise; + }, + }; + runInNewContext(bundled.outputFiles[0]!.text, { + module, + exports: module.exports, + nativeParse: (text: string) => ({ + ok: text !== "invalid", + parsed: text === "null" ? null : { native: text }, + }), + nativeProvider(provider: string, parameters: unknown) { + calls.push({ provider, parameters }); + return { + models, + api: "openai-completions", + apiKey: "upstream-placeholder", + baseUrl: "https://upstream.invalid", + }; + }, + }); + assert.equal( + ((await module.exports.parseNativeConfiguration("fixture")) as { native: string }).native, + "fixture", + ); + for (const invalid of ["invalid", "null"]) + await assert.rejects(module.exports.parseNativeConfiguration(invalid), /not been overwritten/); + for (const inference of ["nvidia", "openrouter", "compatible", "local"]) { + const result = await module.exports.buildNativeModelCatalog( + inference, + "http://127.0.0.1:18790/v1", + "guest-token", + ); + assert.equal(result.configuration.models, models); + assert.equal(result.configuration.baseUrl, "http://127.0.0.1:18790/v1"); + assert.equal(result.configuration.apiKey, "guest-token"); + assert.equal( + result.references[models[0]!.id], + `native-reference:${result.provider}:vendor/model`, + ); + assert.deepEqual( + Object.entries(result.referenceAliases ?? {}), + inference === "nvidia" + ? [["native-legacy:nvidia:vendor/model", "native-reference:nvidia:vendor/model"]] + : [], + ); + assert.equal( + result.provider, + ["nvidia", "openrouter"].includes(inference) ? inference : "nemoclawNative", + ); + assert.equal(calls.at(-1)!.provider, inference === "local" ? "compatible" : inference); + if (inference !== "nvidia") + assert.equal((calls.at(-1)!.parameters as { apiKey: string }).apiKey, "guest-token"); + } + await assert.rejects( + module.exports.buildNativeModelCatalog("unregistered", "https://other.invalid", "guest-token"), + /Unsupported/, + ); +}); diff --git a/packaging/windows/app/native-pipe-transport-build.mts b/packaging/windows/app/native-pipe-transport-build.mts new file mode 100644 index 00000000000..84832035177 --- /dev/null +++ b/packaging/windows/app/native-pipe-transport-build.mts @@ -0,0 +1,263 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import type ts from "typescript"; + +const listenerModule = "dist/server-start-yuOHTviK.js"; +const clientModule = "dist/client-I-RoP1Al.js"; +const providerModule = "dist/provider-transport-fetch-DGSx4u4m.js"; +const catalogModule = "dist/provider-catalog-live-runtime-EZZSw18v.js"; +const localCatalogModule = "dist/provider-setup-CQYNqo2d.js"; +const callModule = "dist/call-BWR5pPgw.js"; +const portHelper = String.raw` +function __nemoPipePort() { + const value = process.env.NEMOCLAW_MXC_GATEWAY_PIPE_PORT; + if (value === undefined) return undefined; + if (process.platform !== "win32" || !/^[1-9][0-9]{0,4}$/.test(value) || Number(value) > 65535) + throw Error("Invalid native gateway pipe port"); + return Number(value); +} +function __nemoPipeName(port) { return "\\\\.\\pipe\\LOCAL\\OpenShell-Loopback-" + port; } +`; +const listenerHelper = String.raw` +function __nemoListenGateway(httpServer, port, bindHost) { + const selected = __nemoPipePort(); + if (selected === undefined) return httpServer.listen(port, bindHost); + if (selected !== port || !["127.0.0.1", "::1"].includes(bindHost)) + throw Error("Native gateway pipe requires the declared loopback port"); + return httpServer.listen({ path: __nemoPipeName(port) }); +} +`; +const clientHelper = String.raw` +import { connect as __nemoConnectPipe } from "node:net"; +function __nemoGatewaySocketOptions(url, options) { + const selected = __nemoPipePort(); + if (selected === undefined) return options; + const target = new URL(url); + if (!["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || Number(target.port) !== selected) + return options; + if (target.protocol !== "ws:") throw Error("Native gateway pipe requires local ws transport"); + return { ...options, createConnection: () => __nemoConnectPipe(__nemoPipeName(selected)) }; +} +`; +const providerHelper = String.raw` +import { request as __nemoProviderRequest } from "node:http"; +import { Readable as __nemoProviderReadable } from "node:stream"; +import { pipeline as __nemoProviderPipeline } from "node:stream/promises"; +function __nemoBrokerFetchOptions(model, options) { + const value = process.env.NEMOCLAW_MXC_BROKER_PIPE_PORT; + const provider = process.env.NEMOCLAW_MXC_MODEL_PROVIDER ?? "nemoclawNative"; + if (value === undefined || typeof model.provider !== "string" || model.provider.toLowerCase() !== provider.toLowerCase()) return options; + if (process.platform !== "win32" || !/^[1-9][0-9]{0,4}$/.test(value) || Number(value) > 65535) + throw Error("Invalid native broker pipe port"); + const base = new URL(model.baseUrl); + const origin = "http://127.0.0.1:" + value; + if (base.origin !== origin || base.username || base.password || base.pathname !== "/v1" || base.search || base.hash) + throw Error("Native broker requires its declared local origin"); + if (options.dispatcherPolicy || options.resolveDispatcherPolicy || options.fetchImpl || process.env.OPENCLAW_PROXY_ACTIVE === "1") + throw Error("Native broker has conflicting transport settings"); + const selected = { mode: "direct", connect: { socketPath: __nemoPipeName(Number(value)) } }; + const resolveDispatcherPolicy = (target) => { + if (target.origin !== origin || target.username || target.password || + !["/v1/models", "/v1/chat/completions"].includes(target.pathname) || target.search || target.hash) + throw Error("Native broker request escaped its declared endpoint"); + return selected; + }; + resolveDispatcherPolicy(new URL(options.url)); + // Keep native guarded fetch as the owner of policy, redirects and timeouts. + // Node's HTTP reader avoids the pinned fetch client's Windows pipe read hang. + const fetchImpl = async (url, init) => { + const target = new URL(url); + resolveDispatcherPolicy(target); + if (init?.redirect !== "manual") throw Error("Native broker requires guarded redirects"); + const request = new Request(url, init); + return await new Promise((resolve, reject) => { + const outgoing = __nemoProviderRequest({ + socketPath: selected.connect.socketPath, path: target.pathname, + method: request.method, headers: Object.fromEntries(request.headers), + signal: request.signal, agent: false, + }, incoming => { + try { + const headers = new Headers(); + for (let i = 0; i < incoming.rawHeaders.length; i += 2) + headers.append(incoming.rawHeaders[i], incoming.rawHeaders[i + 1]); + const status = incoming.statusCode; + const empty = request.method === "HEAD" || [204, 205, 304].includes(status); + resolve(new Response(empty ? null : __nemoProviderReadable.toWeb(incoming), { + status, statusText: incoming.statusMessage, headers, + })); + if (empty) incoming.resume(); + } catch (error) { incoming.destroy(); outgoing.destroy(); reject(error); } + }); + outgoing.once("error", reject); + if (request.body) { + void __nemoProviderPipeline(__nemoProviderReadable.fromWeb(request.body), outgoing).catch(reject); + } else outgoing.end(); + }); + }; + return { ...options, dispatcherPolicy: selected, resolveDispatcherPolicy, fetchImpl }; +} +`; +const catalogHelper = String.raw` +import { request as __nemoCatalogRequest } from "node:http"; +import { Readable as __nemoCatalogReadable } from "node:stream"; +async function __nemoCatalogFetch(params, options) { + const port = process.env.NEMOCLAW_MXC_BROKER_PIPE_PORT; + if (port === undefined) return params.fetchGuard(options); + const provider = process.env.NEMOCLAW_MXC_MODEL_PROVIDER; + const token = process.env.NEMOCLAW_MXC_MODEL_TOKEN; + if (process.platform !== "win32" || !/^[1-9][0-9]{0,4}$/.test(port) || Number(port) > 65535 || + !token || !/^[A-Za-z0-9_-]{32,128}$/.test(token)) throw Error("Invalid native catalog transport"); + const local = "http://127.0.0.1:" + port + "/v1/models"; + const endpoints = provider === "nvidia" + ? [local, "https://integrate.api.nvidia.com/v1/models"] + : provider === "openrouter" ? [local, "https://openrouter.ai/api/v1/models"] : [local]; + const featured = provider === "nvidia" && options.url === "https://assets.ngc.nvidia.com/products/api-catalog/featured-models.json"; + if (params.providerId !== provider || (!featured && !endpoints.includes(options.url))) + throw Error("Native catalog request escaped the selected provider"); + const signal = AbortSignal.any([...(options.signal ? [options.signal] : []), AbortSignal.timeout(options.timeoutMs ?? 10000)]); + const response = await new Promise((resolve, reject) => { + const request = __nemoCatalogRequest({ + socketPath: __nemoPipeName(Number(port)), method: "GET", + path: featured ? "/native/nvidia-featured-models" : "/v1/models", + headers: { authorization: "Bearer " + token, accept: "application/json" }, signal, + }, resolve); + request.once("error", reject); + request.end(); + }); + return { + response: new Response(__nemoCatalogReadable.toWeb(response), { status: response.statusCode, headers: { "content-type": response.headers["content-type"] ?? "application/json" } }), + finalUrl: options.url, + release: async () => { response.destroy(); }, + }; +} +`; +const identityHelper = String.raw` +function __nemoPipeRequiresIdentity(url) { + const selected = __nemoPipePort(); + if (selected === undefined) return false; + const target = new URL(url); + return ["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) && Number(target.port) === selected; +} +`; + +/** Change only the pinned gateway listener/client call sites, never Node prototypes. */ +export function compileNativePipeTransport(relative: string, text: string, syntax?: typeof ts) { + if ( + relative !== listenerModule && + relative !== clientModule && + relative !== providerModule && + relative !== catalogModule && + relative !== localCatalogModule && + relative !== callModule + ) + return text; + if (!syntax) throw new Error("Native gateway compilation requires the syntax parser."); + const file = syntax.createSourceFile( + relative, + text, + syntax.ScriptTarget.Latest, + true, + syntax.ScriptKind.JS, + ); + const edits: { start: number; end: number; replacement: string }[] = []; + const visit = (node: ts.Node) => { + if ( + relative === localCatalogModule && + syntax.isCallExpression(node) && + node.expression.getText(file) === "fetchWithSsrFGuard" && + node.arguments.length === 1 + ) + edits.push({ + start: node.getStart(file), + end: node.end, + replacement: + "__nemoCatalogFetch({ ...params, providerId: process.env.NEMOCLAW_MXC_MODEL_PROVIDER, fetchGuard: fetchWithSsrFGuard }, " + + node.arguments[0]!.getText(file) + + ")", + }); + if ( + relative === catalogModule && + syntax.isCallExpression(node) && + node.expression.getText(file) === "params.fetchGuard" && + node.arguments.length === 1 + ) + edits.push({ + start: node.getStart(file), + end: node.end, + replacement: "__nemoCatalogFetch(params, " + node.arguments[0]!.getText(file) + ")", + }); + if ( + relative === callModule && + syntax.isFunctionDeclaration(node) && + node.name?.text === "shouldOmitDeviceIdentityForGatewayCall" && + node.body && + node.parameters.length === 1 && + node.parameters[0]?.name.getText(file) === "params" + ) + edits.push({ + start: node.body.getStart(file) + 1, + end: node.body.getStart(file) + 1, + replacement: "\nif (__nemoPipeRequiresIdentity(params.url)) return false;\n", + }); + if ( + relative === listenerModule && + syntax.isCallExpression(node) && + syntax.isPropertyAccessExpression(node.expression) && + node.expression.expression.getText(file) === "httpServer" && + node.expression.name.text === "listen" && + node.arguments.length === 2 && + node.arguments[0]?.getText(file) === "port" && + node.arguments[1]?.getText(file) === "bindHost" + ) + edits.push({ + start: node.getStart(file), + end: node.end, + replacement: "__nemoListenGateway(httpServer, port, bindHost)", + }); + if ( + relative === clientModule && + syntax.isNewExpression(node) && + node.expression.getText(file) === "WebSocket" && + node.arguments?.length === 2 && + node.arguments[0]?.getText(file) === "url" && + node.arguments[1]?.getText(file) === "transport.options" + ) + edits.push({ + start: node.arguments[1].getStart(file), + end: node.arguments[1].end, + replacement: "__nemoGatewaySocketOptions(url, transport.options)", + }); + if ( + relative === providerModule && + syntax.isCallExpression(node) && + node.expression.getText(file) === "fetchWithSsrFGuard" && + node.arguments.length === 1 && + node.arguments[0]?.getText(file) === + "useEnvProxy ? withTrustedEnvProxyGuardedFetchMode(guardedFetchOptions) : guardedFetchOptions" + ) + edits.push({ + start: node.arguments[0].getStart(file), + end: node.arguments[0].end, + replacement: "__nemoBrokerFetchOptions(model, " + node.arguments[0].getText(file) + ")", + }); + syntax.forEachChild(node, visit); + }; + visit(file); + if (edits.length !== 1) throw new Error(`Pinned native gateway call site changed: ${relative}`); + const edit = edits[0]!; + return ( + portHelper + + (relative === listenerModule + ? listenerHelper + : relative === clientModule + ? clientHelper + : relative === callModule + ? identityHelper + : relative === catalogModule || relative === localCatalogModule + ? catalogHelper + : providerHelper) + + text.slice(0, edit.start) + + edit.replacement + + text.slice(edit.end) + ); +} diff --git a/packaging/windows/app/native-pipe-transport-build.test.mts b/packaging/windows/app/native-pipe-transport-build.test.mts new file mode 100644 index 00000000000..7c2117f43e4 --- /dev/null +++ b/packaging/windows/app/native-pipe-transport-build.test.mts @@ -0,0 +1,432 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import test from "node:test"; +import vm from "node:vm"; +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import { randomBytes, randomInt } from "node:crypto"; +import { buffer } from "node:stream/consumers"; +import { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { EventEmitter } from "node:events"; +import syntax from "typescript"; +import { transformSync } from "esbuild"; +import { compileNativePipeTransport } from "./native-pipe-transport-build.mts"; +import { createBrokerRelayPeer } from "../runtime/native-broker-relay-protocol.mts"; +import { containedBrokerRelayFiles } from "../runtime/native-broker-tunnel.mts"; + +const listenerPath = "dist/server-start-yuOHTviK.js"; +const listener = + "module.exports = function(httpServer, port, bindHost) { return httpServer.listen(port, bindHost); };"; +const clientPath = "dist/client-I-RoP1Al.js"; +const client = + "module.exports = function(url, transport) { return new WebSocket(url, transport.options); };"; +const providerPath = "dist/provider-transport-fetch-DGSx4u4m.js"; +const provider = + "module.exports = function(model, guardedFetchOptions, useEnvProxy) { return fetchWithSsrFGuard(useEnvProxy ? withTrustedEnvProxyGuardedFetchMode(guardedFetchOptions) : guardedFetchOptions); };"; +const callPath = "dist/call-BWR5pPgw.js"; +const catalogPath = "dist/provider-catalog-live-runtime-EZZSw18v.js"; +const catalog = + "module.exports = async function(params, options) { return await params.fetchGuard(options); };"; +const localCatalogPath = "dist/provider-setup-CQYNqo2d.js"; +const localCatalog = + "module.exports = async function(params) { return await fetchWithSsrFGuard({ url: params.url }); };"; +const call = + "function shouldOmitDeviceIdentityForGatewayCall(params) { return params.original; } module.exports = shouldOmitDeviceIdentityForGatewayCall;"; +function load( + relative: string, + text: string, + selected?: string, + platform = "win32", + broker?: string, + environment: Record = {}, + modules: Record = {}, +) { + const code = transformSync(compileNativePipeTransport(relative, text, syntax), { + format: "cjs", + }).code; + const context = { + module: { exports: undefined as unknown }, + process: { + platform, + env: { + ...environment, + ...(selected === undefined ? {} : { NEMOCLAW_MXC_GATEWAY_PIPE_PORT: selected }), + ...(broker === undefined ? {} : { NEMOCLAW_MXC_BROKER_PIPE_PORT: broker }), + }, + }, + fetchWithSsrFGuard: (options: unknown) => options, + withTrustedEnvProxyGuardedFetchMode: (options: object) => ({ + ...options, + mode: "trusted_env_proxy", + }), + URL, + Response, + Request, + Headers, + AbortSignal, + require: (name: string) => { + if (name in modules) return modules[name]; + if (name === "node:stream") return { Readable }; + if (name === "node:stream/promises") return { pipeline }; + if (name === "node:http") return { request: () => assert.fail("Unexpected HTTP request") }; + assert.equal(name, "node:net"); + return { connect: (pipe: string) => ({ pipe }) }; + }, + WebSocket: function (url: string, options: Record) { + return { url, options }; + }, + }; + vm.runInNewContext(code, context); + return context.module.exports as (...args: unknown[]) => unknown; +} + +test("declared gateway listener uses only its sandbox-local pipe", () => { + const listen = load(listenerPath, listener, "18789"); + const server = { listen: (...args: unknown[]) => args }; + const [options] = listen(server, 18789, "127.0.0.1") as { path: string }[]; + assert.equal(options?.path, String.raw`\\.\pipe\LOCAL\OpenShell-Loopback-18789`); + assert.equal((listen(server, 18789, "::1") as { path: string }[])[0]?.path, options?.path); + assert.throws(() => listen(server, 18790, "127.0.0.1"), /declared loopback port/); + assert.throws(() => listen(server, 18789, "0.0.0.0"), /declared loopback port/); + assert.deepEqual(load(listenerPath, listener)(server, 18789, "127.0.0.1"), [18789, "127.0.0.1"]); +}); + +test("native provider identities use only their selected broker transport", () => { + for (const providerId of ["nvidia", "openrouter"]) { + const fetch = load(providerPath, provider, undefined, "win32", "18790", { + NEMOCLAW_MXC_MODEL_PROVIDER: providerId, + }); + const options = { url: "http://127.0.0.1:18790/v1/chat/completions" }; + const guarded = fetch( + { provider: providerId, baseUrl: "http://127.0.0.1:18790/v1" }, + options, + ) as { dispatcherPolicy: unknown }; + assert(guarded.dispatcherPolicy); + assert.equal( + fetch({ provider: "foreign", baseUrl: "https://foreign.invalid" }, options), + options, + ); + } +}); + +test("native catalog parsing receives the provider response over the authenticated private pipe", async () => { + const requests: Record[] = []; + const modules = { + "node:stream": { Readable }, + "node:http": { + request(options: Record, callback: (response: Readable) => void) { + requests.push(options); + const request = new EventEmitter() as EventEmitter & { end(): void }; + request.end = () => + callback( + Object.assign(Readable.from([Buffer.from('{"data":[{"id":"fixture"}]}')]), { + statusCode: 200, + headers: {}, + }), + ); + return request; + }, + }, + }; + const environment = { + NEMOCLAW_MXC_MODEL_PROVIDER: "nvidia", + NEMOCLAW_MXC_MODEL_TOKEN: "fixture-token_".repeat(4), + }; + const fetch = load(catalogPath, catalog, undefined, "win32", "18790", environment, modules); + const params = { + providerId: "nvidia", + fetchGuard: () => assert.fail("Direct network must not run"), + }; + const url = "https://integrate.api.nvidia.com/v1/models"; + const result = (await fetch(params, { + url, + timeoutMs: 2000, + init: { headers: { authorization: "untrusted-header" } }, + })) as { response: Response; finalUrl: string; release(): Promise }; + assert.deepEqual(await result.response.json(), { data: [{ id: "fixture" }] }); + assert.equal(result.finalUrl, url); + await result.release(); + assert.equal(requests[0]?.socketPath, String.raw`\\.\pipe\LOCAL\OpenShell-Loopback-18790`); + assert.equal(requests[0]?.path, "/v1/models"); + assert.equal( + requests[0]?.headers.authorization, + "Bearer " + environment.NEMOCLAW_MXC_MODEL_TOKEN, + ); + assert.equal(requests[0]?.method, "GET"); + const featured = (await fetch(params, { + url: "https://assets.ngc.nvidia.com/products/api-catalog/featured-models.json", + })) as typeof result; + await featured.release(); + assert.equal(requests[1]?.path, "/native/nvidia-featured-models"); + for (const target of [ + url + "?next=other", + url + "#fragment", + "https://other.invalid/v1/models", + "http://127.0.0.1:18791/v1/models", + "http://127.0.0.1:18790/v1/chat/completions", + ]) { + await assert.rejects(async () => fetch(params, { url: target }), /escaped/); + } + await assert.rejects( + async () => fetch({ ...params, providerId: "openrouter" }, { url }), + /escaped/, + ); + assert.equal(requests.length, 2); + const unmodified = load(catalogPath, catalog, undefined, "linux", undefined, {}, modules); + assert.equal(await unmodified({ fetchGuard: () => "native-fetch" }, { url }), "native-fetch"); + const local = load( + localCatalogPath, + localCatalog, + undefined, + "win32", + "18790", + { ...environment, NEMOCLAW_MXC_MODEL_PROVIDER: "nemoclawNative" }, + modules, + ); + const localResult = (await local({ url: "http://127.0.0.1:18790/v1/models" })) as typeof result; + await localResult.release(); + assert.equal(requests[2]?.path, "/v1/models"); +}); + +test("provider pipe retains guarded fetch and refuses origin or transport changes", () => { + const fetch = load(providerPath, provider, undefined, "win32", "18790"); + const model = { provider: "nemoclawNative", baseUrl: "http://127.0.0.1:18790/v1" }; + const policy = { allowedOrigins: [model.baseUrl] }; + const init = { method: "POST", headers: { authorization: "fixture" } }; + const options = { url: model.baseUrl + "/chat/completions", timeoutMs: 10000, policy, init }; + const guarded = fetch(model, options, true) as typeof options & { + dispatcherPolicy: { connect: { socketPath: string } }; + resolveDispatcherPolicy(url: URL): unknown; + }; + assert.equal(guarded.policy, policy); + assert.equal(guarded.init, init); + assert.equal(guarded.timeoutMs, options.timeoutMs); + assert.equal( + guarded.dispatcherPolicy.connect.socketPath, + String.raw`\\.\pipe\LOCAL\OpenShell-Loopback-18790`, + ); + assert.equal( + guarded.resolveDispatcherPolicy(new URL(model.baseUrl + "/models")), + guarded.dispatcherPolicy, + ); + for (const url of [ + "http://example.invalid:18790/v1/models", + "http://127.0.0.1:18791/v1/models", + "http://127.0.0.1:18790/private", + "https://127.0.0.1:18790/v1/models", + model.baseUrl + "/models?key=other", + ]) + assert.throws(() => guarded.resolveDispatcherPolicy(new URL(url)), /escaped/); + assert.throws(() => fetch(model, { ...options, dispatcherPolicy: {} }), /conflicting/); + assert.throws(() => fetch(model, { ...options, fetchImpl: () => {} }), /conflicting/); + assert.throws( + () => fetch({ ...model, baseUrl: "https://127.0.0.1:18790/v1" }, options), + /declared local origin/, + ); + assert.throws( + () => load(providerPath, provider, undefined, "win32", "018790")(model, options), + /Invalid native broker/, + ); + assert.equal(fetch({ ...model, provider: "other" }, options), options); + assert.equal(load(providerPath, provider)(model, options), options); +}); + +test( + "Windows guarded provider pipe streams repeated responses and propagates cancellation", + { + skip: process.platform !== "win32", + timeout: 30000, + }, + async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "native-provider-pipe-")); + const slots = Array.from({ length: 32 }, () => `stream-${randomBytes(8).toString("hex")}`); + for (const slot of slots) fs.mkdirSync(path.join(root, slot)); + const payload = Buffer.from("data: " + "a".repeat(96 * 1024) + "\n\ndata: [DONE]\n\n"); + let received = 0; + const server = http.createServer(async (request, response) => { + const body = await buffer(request); + received++; + response.setHeader("content-type", "text/event-stream"); + if (body.toString() === "wait") { + response.flushHeaders(); + return; + } + if ( + request.headers.authorization !== "Bearer fixture" || + body.toString() !== "fixture request" + ) { + response.writeHead(400).end(); + return; + } + response.end(payload); + }); + let host: Awaited> | undefined; + let sandbox: typeof host; + try { + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const options = { + files: containedBrokerRelayFiles(root), + token: randomBytes(32).toString("base64url"), + slots, + }; + const pipePort = randomInt(20000, 60000); + host = await createBrokerRelayPeer({ + ...options, + side: "host", + brokerPort: (server.address() as { port: number }).port, + }); + sandbox = await createBrokerRelayPeer({ + ...options, + side: "sandbox", + sandboxPipePort: pipePort, + }); + const url = `http://127.0.0.1:${pipePort}/v1/chat/completions`; + const adapt = load( + providerPath, + provider, + undefined, + "win32", + String(pipePort), + {}, + { "node:http": http }, + ); + const guarded = adapt( + { provider: "nemoclawNative", baseUrl: `http://127.0.0.1:${pipePort}/v1` }, + { url }, + ) as { + fetchImpl(url: string, init: RequestInit): Promise; + }; + for (let turn = 0; turn < 36; turn++) { + const request = new Request(url, { + method: "POST", + headers: { authorization: "Bearer fixture" }, + body: "fixture request", + }); + const response = await guarded.fetchImpl(url, { + method: request.method, + headers: request.headers, + body: request.body, + redirect: "manual", + signal: AbortSignal.timeout(5000), + ...{ duplex: "half" }, + }); + assert.equal(response.status, 200); + assert.equal(response.headers.get("content-type"), "text/event-stream"); + assert.deepEqual(Buffer.from(await response.arrayBuffer()), payload); + } + const beforeRejected = received; + await assert.rejects( + guarded.fetchImpl("http://127.0.0.1:1/v1/models", { redirect: "manual" }), + /escaped/, + ); + await assert.rejects(guarded.fetchImpl(url, { redirect: "follow" }), /guarded redirects/); + assert.equal(received, beforeRejected); + const controller = new AbortController(); + const pending = await guarded.fetchImpl(url, { + method: "POST", + body: "wait", + redirect: "manual", + signal: controller.signal, + }); + controller.abort(); + await assert.rejects(pending.text()); + const cancelled = await guarded.fetchImpl(url, { + method: "POST", + body: "wait", + redirect: "manual", + }); + await cancelled.body!.cancel(); + await sandbox.close(); + await host.close(); + assert.equal(host.diagnostics().activeConnections, 0); + assert.equal(sandbox.diagnostics().activeConnections, 0); + } finally { + try { + await sandbox?.close(); + } finally { + try { + await host?.close(); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + fs.rmSync(root, { recursive: true, force: true }); + } + } + } + }, +); + +test("pipe activation rejects invalid ports and non-Windows execution", () => { + const server = { listen: () => assert.fail("Invalid configuration reached listen") }; + for (const port of ["", "0", "018789", "65536", "-1", "18789/other", " 18789"]) + assert.throws( + () => load(listenerPath, listener, port)(server, 18789, "127.0.0.1"), + /Invalid native gateway pipe port/, + ); + assert.throws( + () => load(listenerPath, listener, "18789", "linux")(server, 18789, "127.0.0.1"), + /Invalid native gateway pipe port/, + ); +}); + +test("normal gateway client retains options and uses the declared pipe only", () => { + const connect = load(clientPath, client, "18789"); + const options = { handshakeTimeout: 3000, headers: { authorization: "fixture-token" } }; + for (const host of ["127.0.0.1", "localhost", "[::1]"]) { + const socket = connect(`ws://${host}:18789`, { options }) as { + options: typeof options & { createConnection(): { pipe: string } }; + }; + assert.equal(socket.options.headers, options.headers); + assert.equal(socket.options.handshakeTimeout, options.handshakeTimeout); + assert.equal( + socket.options.createConnection().pipe, + String.raw`\\.\pipe\LOCAL\OpenShell-Loopback-18789`, + ); + } + for (const url of ["ws://example.invalid:18789", "ws://127.0.0.1:12345"]) + assert.equal((connect(url, { options }) as { options: unknown }).options, options); + assert.equal( + (load(clientPath, client)("ws://127.0.0.1:18789", { options }) as { options: unknown }).options, + options, + ); + assert.throws(() => connect("wss://127.0.0.1:18789", { options }), /requires local ws transport/); +}); + +test("pipe clients retain device identity instead of assuming TCP loopback trust", () => { + const omit = load(callPath, call, "18789"); + for (const host of ["127.0.0.1", "localhost", "[::1]"]) + assert.equal(omit({ url: `ws://${host}:18789`, original: true }), false); + for (const url of ["ws://example.invalid:18789", "ws://127.0.0.1:12345"]) + assert.equal(omit({ url, original: true }), true); + assert.equal(load(callPath, call)({ url: "ws://127.0.0.1:18789", original: true }), true); + assert.throws( + () => load(callPath, call, "0")({ url: "ws://127.0.0.1:18789" }), + /Invalid native gateway/, + ); +}); + +test("compiler rejects missing or duplicated pinned transport sites", () => { + assert.equal(compileNativePipeTransport("unrelated.js", listener), listener); + assert.throws(() => compileNativePipeTransport(listenerPath, listener), /syntax parser/); + for (const [relative, code] of [ + [listenerPath, listener], + [clientPath, client], + [providerPath, provider], + [callPath, call], + [catalogPath, catalog], + [localCatalogPath, localCatalog], + ]) { + assert.throws( + () => compileNativePipeTransport(relative!, "unrelated();", syntax), + /call site changed/, + ); + assert.throws( + () => compileNativePipeTransport(relative!, code! + code!, syntax), + /call site changed/, + ); + } +}); diff --git a/packaging/windows/app/openclaw-app-resources.mts b/packaging/windows/app/openclaw-app-resources.mts new file mode 100644 index 00000000000..7dc53363132 --- /dev/null +++ b/packaging/windows/app/openclaw-app-resources.mts @@ -0,0 +1,846 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// CI-only composition of the pinned package's prebuilt runtime. No dependency scripts run here. +import fs from "node:fs"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import { createRequire } from "node:module"; +import type { Plugin, TransformOptions, TransformResult } from "esbuild"; +import type ts from "typescript"; +import { compilePrivateDirectoryRuntime } from "./sqlite-private-directory-build.mts"; +import { compileNativePipeTransport } from "./native-pipe-transport-build.mts"; +import { + compileSqliteCanonicalRuntime, + registerSqliteCanonicalModule, +} from "./sqlite-canonical-path-build.mts"; + +type Syntax = typeof ts; +type Transformer = { + transform(input: string, options: TransformOptions): Promise; +}; +type Entry = { path: string; exports: string[]; sourceSha256: string; processEntry?: boolean }; +type Role = + | "metadata" + | "control-ui" + | "plugin-facade" + | "worker" + | "native-sidecar" + | "runtime-sidecar" + | "license"; +export type ResourceFile = { path: string; bytes: number; sha256: string; role: Role }; +type PackageMetadata = { + name: string; + version: string; + dependencies?: Record; + optionalDependencies?: Record; + os?: string[]; + cpu?: string[]; +}; +export const sha256 = (bytes: Uint8Array | string) => + createHash("sha256").update(bytes).digest("hex"); +const portablePath = (file: string) => file.split(path.sep).join("/"); +function javascriptStringLiteral(value: string) { + return JSON.stringify(value).replace( + /[<>/\u2028\u2029]/gu, + (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`, + ); +} +function readOpenedResource(file: string) { + const descriptor = fs.openSync(file, "r"); + try { + const opened = fs.fstatSync(descriptor); + const named = fs.lstatSync(file); + if ( + !opened.isFile() || + !named.isFile() || + named.isSymbolicLink() || + named.dev !== opened.dev || + named.ino !== opened.ino + ) + throw new Error("Runtime resource output is not an ordinary exact file."); + return fs.readFileSync(descriptor); + } finally { + fs.closeSync(descriptor); + } +} +function regular(file: string) { + const stat = fs.lstatSync(file); + if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) + throw new Error("Runtime composition requires ordinary, single-link input files."); + return stat; +} +function packageName(name: string) { + if (!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i.test(name)) + throw new Error("Invalid runtime dependency name."); + return name; +} +function filesBelow(root: string): string[] { + const result: string[] = []; + for (const item of fs.readdirSync(root, { withFileTypes: true })) { + if (item.isSymbolicLink()) + throw new Error("Runtime resource links require separate admission."); + const file = path.join(root, item.name); + if (item.isDirectory()) result.push(...filesBelow(file)); + else { + regular(file); + result.push(file); + } + } + return result.sort(); +} +function copyExact(source: string, target: string, transform?: (bytes: Buffer) => Buffer) { + regular(source); + const original = fs.readFileSync(source); + const content = transform ? transform(original) : original; + fs.mkdirSync(path.dirname(target), { recursive: true }); + try { + fs.writeFileSync(target, content, { flag: "wx" }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + if (!readOpenedResource(target).equals(content)) + throw new Error("Conflicting runtime resource output."); + } +} +function exportNames(syntax: Syntax, file: string, text: string) { + const parsed = syntax.createSourceFile( + file, + text, + syntax.ScriptTarget.Latest, + true, + syntax.ScriptKind.JS, + ); + const names: string[] = []; + for (const statement of parsed.statements) { + if (!syntax.isExportDeclaration(statement)) continue; + if (!statement.exportClause || !syntax.isNamedExports(statement.exportClause)) + throw new Error("A compiled plugin entry requires explicit reviewed exports."); + for (const entry of statement.exportClause.elements) names.push(entry.name.text); + } + return names; +} +export function guardWindowsInstallerUpdate(relative: string, text: string) { + if (relative !== "dist/update-BxCRjwo_.js") return text; + if (sha256(text) !== "0034e0fcbb4e77b9d64985e46feba51bfc7afa450d6988ef648d6d12a451148d") + throw new Error("The reviewed gateway update handler changed."); + const validation = + 'if (!assertValidParams(params, validateUpdateRunParams, "update.run", respond)) return;'; + if (text.split(validation).length !== 2) + throw new Error("The gateway update admission seam changed."); + const refusal = + 'if (process.platform === "win32") { respond(false, void 0, __nemoUpdateErrorShape(__nemoUpdateErrorCodes.UNAVAILABLE, "This Windows application is managed by the NemoClaw installer. Use the NemoClaw installer to update or repair it.")); return; }'; + return ( + 'import { d as __nemoUpdateErrorShape } from "./error-codes-Bo8q2D1o.js";\n' + + 'import { t as __nemoUpdateErrorCodes } from "./gateway-error-details-w0nAGBBp.js";\n' + + text.replace(validation, validation + "\n" + refusal) + ); +} +export function compileEagerOllamaRuntime(relative: string, text: string) { + if (relative !== "dist/stream-api-DUG3zQPW.js") return text; + if (sha256(text) !== "998ecb135564b06544ef39ef048123bbf0cd8757c344cf93e4b7fe08022e8ebb") + throw new Error("The reviewed eager Ollama runtime changed."); + // Upstream immediately awaits this one-use loader before copying its exports. + // A static import preserves that eager initialization and the same module graph + // without introducing top-level await into the synchronous compiled registry. + return text + .replace('import { r as createLazyRuntimeModule } from "./lazy-runtime-CgCh8H_K.js";\n', "") + .replace( + 'const ollamaStreamRuntime = await createLazyRuntimeModule(() => import("./stream.runtime.js"))();', + 'import * as ollamaStreamRuntime from "./stream.runtime.js";', + ); +} +export function compileAsyncProcessEntry(relative: string, text: string) { + if (relative === "dist/system-agent/setup-inference-detection.worker.js") { + if (sha256(text) !== "37aae8bde397c2dde8eda0514229022155250ea5c14ae1eca125f976f5f3e1b2") + throw new Error("The reviewed asynchronous setup worker changed."); + const start = "try {"; + const end = "//#endregion\nexport {};"; + if (text.split(start).length !== 2 || text.split(end).length !== 2) + throw new Error("The setup worker entry boundary changed."); + // Keep detection, error reporting, and port closure in their original order. + // The process facade awaits completion before finishing ESM evaluation. + return text + .replace(start, "const __nemoWorkerCompletion = (async () => {\n" + start) + .replace(end, "})();\nexport { __nemoWorkerCompletion };\n" + end); + } + if (relative !== "dist/config/sessions/session-accessor.sqlite-archive.worker.js") return text; + if (sha256(text) !== "1bac9789df2f1a57538459e4c2c7878ead9bbc280a1218a6e1f116f9cff18158") + throw new Error("The reviewed asynchronous archive worker changed."); + const start = "if (isSqliteTranscriptArchiveWorkerData(workerData)) {"; + const end = + "//#endregion\nexport { materializeTranscriptArchiveInWorker, publishTranscriptArchiveInWorker };"; + if (text.split(start).length !== 2 || text.split(end).length !== 2) + throw new Error("The archive worker entry boundary changed."); + // Only this standalone entry's final dispatch uses top-level await. Its facade + // awaits the same completion before finishing ESM evaluation; failures propagate. + return text + .replace(start, "const __nemoWorkerCompletion = (async () => {\n" + start) + .replace(end, "})();\nexport { __nemoWorkerCompletion };\n" + end); +} +export const PREBUILT_CHOICE_PLUGINS = { + brave: { + package: "@openclaw/brave-plugin", + sha256: "40c0cf23e8373f2285034b8f0a575cc51ec1ed53d081b0e1592d219dd411e54d", + }, + discord: { + package: "@openclaw/discord", + sha256: "358b88763e7697e29eb1807240ab5cdc04e38662462fb93c14e2b563ca7521d6", + }, + slack: { + package: "@openclaw/slack", + sha256: "79ad40233b041c2081408efe59c93c2d38ca508429e016dd9843cccffc8cf49a", + }, + tavily: { + package: "@openclaw/tavily-plugin", + sha256: "c5d65ff201a8178ec914736887802c38d33628c667be5b2453b890fe44086984", + }, +} as const; +function choiceRoots(source: string) { + return Object.keys(PREBUILT_CHOICE_PLUGINS).map((id) => ({ + id, + root: path.join(runtimeInputRoot(source), "plugins", id), + })); +} +export function runtimeInputRoot(source: string) { + const resolved = path.resolve(source); + if ( + path.basename(resolved) !== "openclaw" || + path.basename(path.dirname(resolved)) !== "node_modules" + ) + throw new Error("The canonical OpenClaw wrapper layout is required."); + return path.dirname(path.dirname(resolved)); +} +function inputRelativePath(source: string, file: string) { + const relative = path.relative(runtimeInputRoot(source), file); + if ( + !relative || + relative === ".." || + relative.startsWith(".." + path.sep) || + path.isAbsolute(relative) + ) + throw new Error("A runtime dependency escaped the verified input root."); + return portablePath(relative); +} +export function runtimeExternalPlugin(source: string, externalPackages: readonly string[]): Plugin { + return { + name: "pinned-openclaw-runtime-dependencies", + setup(build) { + build.onResolve({ filter: /^[^./]/ }, async (args) => { + if (args.pluginData?.resolvingRuntimeExternal) return; + const selected = externalPackages.find( + (name) => args.path === name || args.path.startsWith(name + "/"), + ); + if (!selected) return; + // The optional tracing peer remains absent, as in the approved source graph. + if (selected === "@opentelemetry/api") return { path: args.path, external: true }; + const resolved = await build.resolve(args.path, { + importer: args.importer, + resolveDir: args.resolveDir, + namespace: args.namespace, + kind: args.kind, + pluginData: { resolvingRuntimeExternal: true }, + }); + if (resolved.errors.length) return { errors: resolved.errors }; + if (resolved.external || !resolved.path) + throw new Error("A pinned sidecar did not resolve to a verified input file."); + return { path: "./" + inputRelativePath(source, resolved.path), external: true }; + }); + }, + }; +} +export function guardWindowsConfiguredPluginInstall(relative: string, text: string) { + if (relative !== "dist/missing-configured-plugin-install-B3eZm5tD.js") return text; + if (sha256(text) !== "e41ae67723c77d09d21ccc38658a9376481d5d34054a589795efddc44a726e87") + throw new Error("The reviewed configured-plugin repair source changed."); + const refusal = + 'if (process.platform === "win32") throw new Error("A configured plugin is missing or incomplete in this installer-managed Windows application. Repair or update NemoClaw with its installer; runtime plugin downloads are disabled.");'; + for (const marker of [ + "if (missingRecordedPluginIds.length > 0) {", + "const installed = await installCandidate({", + ]) + if (text.split(marker).length !== 2) + throw new Error("The configured-plugin repair admission seam changed."); + return text + .replace( + "if (missingRecordedPluginIds.length > 0) {", + "if (missingRecordedPluginIds.length > 0) {\n" + refusal, + ) + .replace( + "const installed = await installCandidate({", + refusal + "\nconst installed = await installCandidate({", + ); +} +export function prebuiltPluginRegistrationSource(source: string) { + const records = "dist/installed-plugin-index-records-C06Xozeq.js"; + const reader = "dist/installed-plugin-index-record-reader-SXWwf_BU.js"; + for (const [file, expected] of [ + [records, "46f3119398f4ee3a5acb4c51d49e049be6e1d5a3034804ccbc8dc1134c841ff9"], + [reader, "6d1cff63b25360188af688f92856df69c1708bc68e1b37b4f5adccf2493db173"], + ]) + if (sha256(fs.readFileSync(path.join(source, file))) !== expected) + throw new Error("The reviewed plugin record API changed."); + return `export async function registerPrebuiltPlugins(config) { + __nemoPrepareAssetRoot(); + const fs = require("node:fs"), path = require("node:path"); + const packages = ${JSON.stringify(Object.fromEntries(Object.entries(PREBUILT_CHOICE_PLUGINS).map(([id, item]) => [id, item.package])))}; + const ids = Object.keys(packages).filter(id=>config.plugins?.entries?.[id]?.enabled === true); + if (!ids.length) return {schemaVersion:1,registered:[]}; + // Bind consent to this compiled artifact, including its packaged resources. + const integrity="sha256-"+require("node:crypto").createHash("sha256").update(fs.readFileSync(path.join(__nemoAssetDir,"openclaw-resource-closure.json"))).digest("base64"); + const selected = ids.map(id=>{ + const directory = path.join(__nemoAssetDir,"plugins",id); + const metadata = JSON.parse(fs.readFileSync(path.join(directory,"package.json"),"utf8")); + if(metadata.name!==packages[id]||metadata.version!=="2026.9.2") throw new Error("The prebuilt plugin is missing or differs from this application; repair NemoClaw with its installer."); + const entries=metadata.openclaw?.runtimeExtensions??metadata.openclaw?.extensions; + if(!Array.isArray(entries)||!entries.length)throw new Error("The prebuilt plugin runtime is incomplete; repair NemoClaw with its installer."); + for(const entry of entries) { + if(typeof entry!=="string"||!entry.startsWith("./dist/")||entry.includes("..")||entry.includes("\\\\")) throw new Error("The prebuilt plugin runtime entry is invalid."); + const info=fs.lstatSync(path.join(directory,entry)); + if(!info.isFile()||info.isSymbolicLink())throw new Error("The prebuilt plugin runtime entry is unavailable; repair NemoClaw with its installer."); + } + return {pluginId:id,source:"path",sourcePath:directory,installPath:directory,version:metadata.version,integrity}; + }); + // Called before runCli or runtime loader initialization. These canonical APIs + // update only the guest state's SQLite record/index and their metadata caches. + const {r:loadRecords}=await import(${JSON.stringify(path.join(source, reader))}); + const {n:recordPluginInstallInRecords,s:writeRecords}=await import(${JSON.stringify(path.join(source, records))}); + let records=await loadRecords({env:process.env}); + for(const update of selected) { + const previous=Object.hasOwn(records,update.pluginId)?records[update.pluginId]:undefined; + if(previous && ["source","sourcePath","installPath","version","integrity"].every(key=>previous[key]===update[key])) continue; + records=recordPluginInstallInRecords(records,update); + } + await writeRecords(records,{config,env:process.env}); + return {schemaVersion:1,registered:ids}; +}\n`; +} + +export function compiledPluginPlan(source: string, syntax: Syntax, compiler: Transformer) { + const processRegistry = fs.readFileSync( + path.join(source, "dist/runtime-process-entrypoints-CEMkwAJ_.js"), + "utf8", + ); + if ( + sha256(processRegistry) !== "357ec4f9cf1238a8c61afc35f9b783017d8d125b97d7173c5e1627776d814440" + ) + throw new Error("The reviewed runtime process entrypoints changed."); + // These modules are launched by filename, not imported by the parent graph. + // Keep all sibling entrypoints from the exact upstream registry in the bundle. + const processEntries = new Set( + [...processRegistry.matchAll(/distWorkerPath: "([a-zA-Z0-9/_.-]+\.js)"/g)].map((match) => + path.join(source, "dist", match[1]), + ), + ); + if (processEntries.size !== 11) + throw new Error("The runtime process entrypoint inventory changed."); + // The central registry omits workers owned by individual subsystems. These + // filename-launched modules also need a registry in their new process. + for (const [relative, expected] of Object.entries({ + "agents/code-mode.worker.js": + "d26f55f9e06c00c5c73bfad0c0aeb55a17b48520454371bb6b14d85b6c773991", + "agents/compaction-planning.worker.js": + "743208e555c08e977a5be25b65629a9754325fbc57395b97c6b9937f0fad0b57", + "agents/model-provider-auth.worker.js": + "acc15b2a308497a82f85b591462946e8e113e7ed0a877c659039dabe7ed99325", + "agents/prepared-model-catalog.worker.js": + "a82707371e3cf477446023b4ea836e89b760646bbd20d5720d9925c60d255017", + "config/sessions/disk-budget.worker.js": + "2a330cb989426a3b2056f1cb34939df8a4b2bc33f3a85c77e8c53c0147e4f8eb", + "config/sessions/session-model-context.worker.js": + "5207534e3a19431b783cd8b591aaf3fd65b1071357ee54d45c341264859d95cd", + "system-agent/setup-inference-detection.worker.js": + "37aae8bde397c2dde8eda0514229022155250ea5c14ae1eca125f976f5f3e1b2", + "extensions/memory-core/memory-search-knn.child.js": + "4dea70100d79859e7a0e17577acb91cc5231192c5a5c7c957b57313de8082e78", + "telegram-ingress-worker.runtime.js": + "44ea3ff5063d74a524bf2adeaf8c54902fc019f9f392bcf03cb1cadbe9dee358", + })) { + const file = path.join(source, "dist", relative); + if (sha256(fs.readFileSync(file)) !== expected) + throw new Error(`The reviewed subsystem process entry changed: ${relative}`); + processEntries.add(file); + } + const auditRecorder = path.join(source, "dist/audit-recorder-BCaTSxYZ.js"); + if ( + sha256(fs.readFileSync(auditRecorder)) !== + "74d8649501180770ba7df5fa0f5caad9920b64ffc7e44bc7c10db4f3fef3b484" + ) + throw new Error("The reviewed process-owned audit recorder changed."); + const entryFiles = filesBelow(path.join(source, "dist", "extensions")).filter( + (file) => + file.endsWith(".js") && + path.relative(path.join(source, "dist", "extensions"), file).split(path.sep).length === 2, + ); + entryFiles.push(path.join(source, "dist", "plugins", "runtime", "index.js")); + // The package control exercises the same compiled recorder used by the gateway. + entryFiles.push(auditRecorder); + entryFiles.push(...[...processEntries].filter((file) => !entryFiles.includes(file))); + for (const plugin of choiceRoots(source)) + entryFiles.push( + ...filesBelow(path.join(plugin.root, "dist")).filter((file) => file.endsWith(".js")), + ); + for (const name of [ + "plugin-entry", + "extension-shared", + "target-resolver-runtime", + "provider-web-search-config-contract", + "string-coerce-runtime", + "diagnostic-runtime", + "lazy-runtime", + "provider-http", + "provider-web-search", + "runtime-env", + "ssrf-runtime", + ]) + entryFiles.push(path.join(source, "dist", "plugin-sdk", `${name}.js`)); + const entries: Entry[] = entryFiles.map((file) => { + const text = fs.readFileSync(file, "utf8"); + return { + path: inputRelativePath(source, file), + exports: exportNames(syntax, file, text), + sourceSha256: sha256(text), + ...(processEntries.has(file) ? { processEntry: true } : {}), + }; + }); + const factories = entries + .map( + (entry) => + `${javascriptStringLiteral(entry.path)}:()=>require(${javascriptStringLiteral(entryFiles[entries.indexOf(entry)]!)})`, + ) + .join(",\n"); + const prelude = `const factories={${factories}}; +const registry=Object.freeze({load(key){if(!Object.hasOwn(factories,key))throw Error("Unknown compiled plugin entry");return factories[key]();}}); +Object.defineProperty(globalThis,Symbol.for("nemoclaw.compiled-openclaw.plugins.v1"),{value:registry});\n`; + const banner = ` +function __nemoModuleFilenameFor(relative){return require("node:path").join(__nemoAssetDir,relative);} +function __nemoModuleDirnameFor(relative){return require("node:path").dirname(__nemoModuleFilenameFor(relative));} +function __nemoModuleUrlFor(relative){return require("node:url").pathToFileURL(__nemoModuleFilenameFor(relative)).href;}`; + return { + entries, + prelude, + plugin: compiledModuleLocationPlugin(source, compiler, syntax), + banner, + }; +} +export function compiledModuleLocationPlugin( + source: string, + compiler: Transformer, + syntax?: Syntax, +): Plugin { + // Preserve each original module's resource location while compiling its code into one graph. + // This includes bundled dependencies, not just core/plugin files: their native + // createRequire(import.meta.url) calls need the same sealed package locations. + return { + name: "compiled-openclaw-module-locations", + setup(build) { + registerSqliteCanonicalModule(build, source); + const canonical = createRequire(path.join(source, "package.json")); + build.onResolve({ filter: /^openclaw(?:\/|$)/ }, (args) => ({ + path: canonical.resolve(args.path), + })); + build.onLoad({ filter: /\.[cm]?js$/ }, async (args) => { + const sourceRelative = inputRelativePath(source, args.path); + const original = fs.readFileSync(args.path, "utf8"); + const adaptationPath = args.path.startsWith(source + path.sep) + ? portablePath(path.relative(source, args.path)) + : sourceRelative; + const text = guardWindowsConfiguredPluginInstall( + adaptationPath, + guardWindowsInstallerUpdate( + adaptationPath, + compileEagerOllamaRuntime( + adaptationPath, + compileAsyncProcessEntry( + adaptationPath, + compileSqliteCanonicalRuntime( + adaptationPath, + compilePrivateDirectoryRuntime( + adaptationPath, + compileNativePipeTransport(adaptationPath, original, syntax), + ), + original, + ), + ), + ), + ), + ); + if ( + !text.includes("import.meta") && + !text.includes("__dirname") && + !text.includes("__filename") + ) + return text === original + ? undefined + : { contents: text, loader: "js", resolveDir: path.dirname(args.path) }; + const relative = JSON.stringify(sourceRelative); + const result = await compiler.transform(text, { + loader: "js", + sourcefile: args.path, + define: { + "import.meta.url": "__originalModuleUrl", + __dirname: "__originalDirname", + __filename: "__originalFilename", + }, + banner: `const __originalModuleUrl=__nemoModuleUrlFor(${relative});const __originalFilename=__nemoModuleFilenameFor(${relative});const __originalDirname=__nemoModuleDirnameFor(${relative});`, + }); + return { contents: result.code, loader: "js", resolveDir: path.dirname(args.path) }; + }); + }, + }; +} +export function publishPluginFacades(app: string, entries: Entry[]) { + for (const entry of entries) { + const owner = + "./" + + portablePath( + path.relative(path.dirname(path.join(app, entry.path)), path.join(app, "openclaw-app.cjs")), + ); + // A Worker may intentionally have env:{}. Derive only its asset root from + // the sealed owner; never copy the parent's environment into the Worker. + // Ordinary plugin facades still require an initialized owner. + const bootstrap = entry.processEntry + ? `import {createRequire} from "node:module";import {dirname,isAbsolute,relative} from "node:path"; +const requireOwner=createRequire(import.meta.url);const ownerPath=requireOwner.resolve(${JSON.stringify(owner)});const assetRoot=dirname(ownerPath); +const suppliedRoot=process.env.OPENCLAW_COMPILED_ASSET_ROOT; +if(suppliedRoot!==undefined&&(!isAbsolute(suppliedRoot)||relative(assetRoot,suppliedRoot)!==""))throw Error("The OpenClaw asset root does not match its compiled owner."); +process.env.OPENCLAW_COMPILED_ASSET_ROOT=assetRoot; +const owner=requireOwner(ownerPath);await owner.registerPrebuiltPlugins({});\n` + : ""; + const content = + bootstrap + + `const registry=globalThis[Symbol.for("nemoclaw.compiled-openclaw.plugins.v1")];if(!registry)throw Error("The compiled OpenClaw owner is unavailable");const original=registry.load(${JSON.stringify(entry.path)});\n` + + (entry.processEntry ? "await original.__nemoWorkerCompletion;\n" : "") + + entry.exports + .map( + (name, index) => + `const v${index}=original[${JSON.stringify(name)}];export{v${index} as ${JSON.stringify(name)}};`, + ) + .join("\n") + + "\n"; + const target = path.join(app, entry.path); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, content, { flag: "wx" }); + } +} +export function publishDynamicImportBridges(app: string) { + // Native SDK imports must resolve within the canonical wrapper, not the + // top-level package metadata used by the compiled application's launcher. + const bridge = + '"use strict"; module.exports = specifier => typeof specifier === "string" && specifier.startsWith("openclaw/plugin-sdk/") ? require("./node_modules/openclaw/nemoclaw-dynamic-import.cjs")(specifier) : import(specifier);\n'; + const sdkBridge = '"use strict"; module.exports = specifier => import(specifier);\n'; + fs.mkdirSync(path.join(app, "node_modules/openclaw"), { recursive: true }); + fs.writeFileSync(path.join(app, "openclaw-dynamic-import.cjs"), bridge, { flag: "wx" }); + fs.writeFileSync(path.join(app, "node_modules/openclaw/nemoclaw-dynamic-import.cjs"), sdkBridge, { + flag: "wx", + }); + return bridge; +} +function resolvePackage(source: string, importer: string, name: string) { + packageName(name); + let directory = importer; + const boundary = runtimeInputRoot(source); + if (importer !== boundary && !importer.startsWith(boundary + path.sep)) return undefined; + while (directory === boundary || directory.startsWith(boundary + path.sep)) { + const candidate = path.join(directory, "node_modules", name); + if (fs.existsSync(path.join(candidate, "package.json"))) return candidate; + directory = path.dirname(directory); + } + return undefined; +} +function targetMatches(values: string[] | undefined, target: string) { + return ( + !values || + (!values.includes(`!${target}`) && + (!values.some((value) => !value.startsWith("!")) || values.includes(target))) + ); +} +const sidecarRoots = [ + "koffi", + "@emnapi/core", + "@emnapi/runtime", + "@lydell/node-pty", + "@openclaw/fs-safe", + "@silvia-odwyer/photon-node", + "clawpdf", + "rastermill", + "quickjs-wasi", + "web-tree-sitter", + "tree-sitter-bash", + "playwright-core", + "typescript", + "jiti", + "@homebridge/ciao", + "undici", + "ws", +]; +export const CONTROL_UI_STARTUP_ENTRY = "dist/control-ui/assets/index-1fvEwqai.js"; +export const CONTROL_UI_SERVICE_WORKER = "dist/control-ui/sw.js"; +export function protectControlUiWorkerRecovery(original: Buffer) { + const source = original.toString("utf8"); + const signature = "async function navigateSuspendedClient(client) {"; + const start = source.indexOf(signature); + const end = source.indexOf("\n}\n", start) + 3; + if ( + start < 0 || + source.indexOf(signature, start + signature.length) !== -1 || + end <= start || + sha256(Buffer.from(source.slice(start, end))) !== + "afa90cafacc3b3dd0b6a190a98af31ce0a7b968d979fd72649b93e4d89a30f58" + ) + throw new Error("The reviewed Control UI worker recovery changed."); + // Temporary Windows packaging bridge: WindowClient.url can retain the original + // sign-in fragment after upstream removes it. A missed probe is not permission + // to interrupt a visible page or replay credentials. Remove after upstream fixes + // that recovery path; the installer maintainer owns this packaged adaptation. + const guard = ` + const canRecover = current => { + if (!current || current.visibilityState !== "hidden") return false; + const target = new URL(current.url); + const fragment = new URLSearchParams(target.hash.slice(1)); + return !["token", "bootstrapToken", "password", "gatewayUrl"].some( + key => target.searchParams.has(key) || fragment.has(key) + ); + }; + const current = await self.clients.get(client.id); + if (!canRecover(current)) return; + client = current;`; + const recheck = ` try { + const latest = await self.clients.get(client.id); + if (!canRecover(latest)) { + await reloadClaim.cache.delete(reloadClaim.guardRequest); + return; + } + client = latest; + } catch (error) { + await reloadClaim.cache.delete(reloadClaim.guardRequest).catch(() => undefined); + throw error; + } +`; + const recovery = source + .slice(start, end) + .replace(signature, signature + guard) + .replace(" // Navigation can stay pending", recheck + " // Navigation can stay pending"); + return Buffer.from(source.slice(0, start) + recovery + source.slice(end)); +} +export function deferControlUiStartup(original: Buffer) { + if (sha256(original) !== "76a9b487a03b82bb4355d7a9696c2a8c82c38739f29ebe54a71e50371ec5de3a") + throw new Error("The reviewed Control UI startup entry changed."); + // Edge can restore the initial navigation fragment after an early replaceState. + // Let that navigation finish before upstream captures and sanitizes its landing URL. + // Keep the upstream initializer, authentication and strict route comparison intact. + // Remove this bridge when the pinned upstream startup handles that ordering itself. + return Buffer.from( + original + .toString("utf8") + .replace( + ";e();", + ';if(document.readyState==="complete"){e();}else{window.addEventListener("load",()=>e(),{once:true});}', + ), + ); +} +export function stagePublishedResources(source: string, app: string, platform = "win32") { + const core = path.join(app, inputRelativePath(source, source)); + const entrySource = path.join(source, CONTROL_UI_STARTUP_ENTRY); + regular(entrySource); + const entryBytes = fs.readFileSync(entrySource); + const startup = deferControlUiStartup(entryBytes); + const workerSource = path.join(source, CONTROL_UI_SERVICE_WORKER); + regular(workerSource); + const workerBytes = fs.readFileSync(workerSource); + const worker = protectControlUiWorkerRecovery(workerBytes); + for (const suffix of [".br", ".gz"]) + if (fs.existsSync(workerSource + suffix)) + throw new Error("A compressed Control UI worker would bypass the reviewed adaptation."); + const startupPath = `dist/control-ui/assets/nemoclaw-start-${sha256(startup)}.js`; + const indexSource = path.join(source, "dist/control-ui/index.html"); + regular(indexSource); + const indexBytes = fs.readFileSync(indexSource); + const originalReference = `src="./assets/${path.basename(CONTROL_UI_STARTUP_ENTRY)}"`; + if (indexBytes.toString("utf8").split(originalReference).length !== 2) + throw new Error("The reviewed Control UI startup reference changed."); + const index = Buffer.from( + indexBytes + .toString("utf8") + .replace(originalReference, `src="./assets/${path.basename(startupPath)}"`), + ); + for (const name of ["package.json", "LICENSE", "THIRD_PARTY_NOTICES.md"]) + copyExact(path.join(source, name), path.join(core, name)); + copyExact(path.join(source, "package.json"), path.join(app, "package.json")); + // Keep upstream chunks, their compressed siblings and asset manifest byte-identical. + // A distinct entry URL prevents old immutable caches from bypassing the startup repair. + // No frontend code is compiled on the customer machine. + // Workspace creation reads the published templates from the canonical package root. + for (const directory of ["dist/control-ui", "skills", "docs/reference/templates"]) { + for (const file of filesBelow(path.join(source, directory))) { + const relative = path.relative(source, file); + copyExact( + file, + path.join(core, relative), + portablePath(relative) === "dist/control-ui/index.html" + ? () => index + : portablePath(relative) === CONTROL_UI_SERVICE_WORKER + ? () => worker + : undefined, + ); + } + } + fs.writeFileSync(path.join(core, startupPath), startup, { flag: "wx" }); + for (const file of filesBelow(path.join(source, "dist"))) { + const relative = portablePath(path.relative(source, file)); + if (relative.startsWith("dist/control-ui/")) continue; + // Preserve published data/licenses and nested extension resources. Development + // declarations/maps are not deleted from the source; the compiled profile does not use them. + const nestedExtension = + relative.startsWith("dist/extensions/") && relative.split("/").length > 4; + if ( + (!file.endsWith(".js") && !file.endsWith(".ts") && !file.endsWith(".map")) || + nestedExtension + ) + copyExact(file, path.join(core, relative)); + } + const pending = sidecarRoots.map((name) => { + const found = resolvePackage(source, source, name); + if (!found) throw new Error(`Missing pinned runtime sidecar: ${name}`); + return found; + }); + // The gateway resolves ws by package metadata; messaging plugins can select + // nested copies. Preserve every selected identity instead of bundling a second one. + for (const plugin of choiceRoots(source)) { + const websocket = resolvePackage(source, plugin.root, "ws"); + if (!websocket) throw new Error("Missing pinned WebSocket sidecar."); + pending.push(websocket); + } + for (const name of ["libopus-wasm", "@discordjs/voice"]) { + const found = resolvePackage( + source, + path.join(runtimeInputRoot(source), "plugins", "discord"), + name, + ); + if (!found) throw new Error(`Missing canonical Discord native/WASM sidecar: ${name}`); + pending.push(found); + } + const seen = new Set(); + const destinations = new Map(); + const packages: { name: string; version: string; path: string; packageSha256: string }[] = []; + while (pending.length) { + const folder = pending.shift()!; + if (seen.has(folder)) continue; + seen.add(folder); + const packageBytes = fs.readFileSync(path.join(folder, "package.json")); + const metadata = JSON.parse(packageBytes.toString("utf8")) as PackageMetadata; + if ( + !targetMatches(metadata.os, platform) || + (!targetMatches(metadata.cpu, "arm64") && metadata.name !== "@snazzah/davey-wasm32-wasi") + ) + continue; + const destination = inputRelativePath(source, folder); + const prior = destinations.get(destination); + if (prior) { + if (prior !== sha256(packageBytes)) + throw new Error("Conflicting pinned native sidecar dependency."); + } + destinations.set(destination, sha256(packageBytes)); + if (!prior) + packages.push({ + name: metadata.name, + version: metadata.version, + path: destination, + packageSha256: sha256(packageBytes), + }); + for (const file of filesBelow(folder)) { + if (path.relative(folder, file).split(path.sep).includes("node_modules")) continue; + copyExact(file, path.join(app, destination, path.relative(folder, file))); + } + for (const [name] of Object.entries({ + ...metadata.dependencies, + ...metadata.optionalDependencies, + })) { + const dependency = resolvePackage(source, folder, name); + if (!dependency) throw new Error(`Missing pinned transitive sidecar: ${name}`); + pending.push(dependency); + } + } + for (const plugin of choiceRoots(source)) { + const bytes = fs.readFileSync(path.join(plugin.root, "package.json")); + const metadata = JSON.parse(bytes.toString("utf8")) as PackageMetadata; + if ( + metadata.name !== + PREBUILT_CHOICE_PLUGINS[plugin.id as keyof typeof PREBUILT_CHOICE_PLUGINS].package || + metadata.version !== "2026.9.2" + ) + throw new Error("The reviewed complete choice plugin is required."); + const pluginFiles = filesBelow(plugin.root); + // The integrity-checked archive binds bundled dependency metadata; 9.2 no longer + // publishes a plugin shrinkwrap. Keep target filtering at each package root. + const dependencies = pluginFiles + .map((file) => ({ file, relative: portablePath(path.relative(plugin.root, file)) })) + .filter(({ relative }) => + /^(?:node_modules\/(?:@[^/]+\/)?[^/]+\/)+package\.json$/.test(relative), + ) + .map( + ({ file, relative }) => + [ + relative.slice(0, -"/package.json".length), + JSON.parse(fs.readFileSync(file, "utf8")) as PackageMetadata, + ] as const, + ) + .sort(([left], [right]) => right.length - left.length); + for (const file of pluginFiles) { + const relative = portablePath(path.relative(plugin.root, file)); + const dependency = dependencies.find(([name]) => relative.startsWith(name + "/")); + if ( + dependency && + (!targetMatches(dependency[1].os, platform) || + (!targetMatches(dependency[1].cpu, "arm64") && + !dependency[0].endsWith("/@snazzah/davey-wasm32-wasi"))) + ) + continue; + // Every plugin JS runtime entry has a compiled facade. Preserve its + // original non-code resources and the bundled dependency data/licenses. + if (/\.(?:[cm]?js|[cm]?ts|map)$/.test(file)) continue; + copyExact(file, path.join(app, "plugins", plugin.id, relative)); + } + packages.push({ + name: metadata.name, + version: metadata.version, + path: "plugins/" + plugin.id, + packageSha256: sha256(bytes), + }); + } + return { + packages: packages.sort((a, b) => a.path.localeCompare(b.path)), + controlUiServiceWorker: { + path: CONTROL_UI_SERVICE_WORKER, + sourceSha256: sha256(workerBytes), + stagedSha256: sha256(worker), + adaptation: "Do not force recovery navigation of visible pages or credential-bearing URLs.", + }, + controlUiStartup: { + originalEntry: CONTROL_UI_STARTUP_ENTRY, + sourceSha256: sha256(entryBytes), + stagedEntry: startupPath, + stagedSha256: sha256(startup), + originalIndexSha256: sha256(indexBytes), + stagedIndexSha256: sha256(index), + adaptation: + "Run the original UI initializer after initial document load; authentication and routing are unchanged.", + }, + }; +} +export function resourceInventory(app: string, facadePaths: string[]): ResourceFile[] { + const facades = new Set(facadePaths); + return filesBelow(app) + .filter((file) => !file.endsWith("openclaw-resource-closure.json")) + .map((file) => { + const relative = portablePath(path.relative(app, file)); + let role: Role = "metadata"; + if (relative.startsWith("node_modules/openclaw/dist/control-ui/")) role = "control-ui"; + else if (relative.startsWith("dist/audit/")) role = "worker"; + else if (facades.has(relative)) role = "plugin-facade"; + else if (/\.(?:node|dll|exe)$/i.test(file)) role = "native-sidecar"; + else if (/(?:LICENSE|NOTICE|COPYING)/i.test(path.basename(file))) role = "license"; + else if (relative.startsWith("node_modules/") || /\.[cm]?js$/.test(file)) + role = "runtime-sidecar"; + const bytes = fs.readFileSync(file); + return { path: relative, bytes: bytes.length, sha256: sha256(bytes), role }; + }); +} diff --git a/packaging/windows/app/prepare-app-node.ps1 b/packaging/windows/app/prepare-app-node.ps1 new file mode 100644 index 00000000000..33ba7b2bbd0 --- /dev/null +++ b/packaging/windows/app/prepare-app-node.ps1 @@ -0,0 +1,85 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# CI-only input preparation. This script is never part of the installed application. +[CmdletBinding()] +param( + [Parameter(Mandatory=$true)][string]$LockPath, + [Parameter(Mandatory=$true)][string]$OutputDirectory +) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +if ($env:GITHUB_ACTIONS -cne 'true' -or $env:OS -cne 'Windows_NT' -or + [Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -ne [Runtime.InteropServices.Architecture]::Arm64) { + throw 'Application compilation requires the native GitHub Windows ARM64 runner.' +} +$lock = Get-Content -LiteralPath $LockPath -Raw | ConvertFrom-Json +$artifacts = @($lock.artifacts | Where-Object { $_.file -ceq 'node-v22.23.2-win-arm64.zip' }) +if ($artifacts.Count -ne 1) { throw 'The canonical runtime lock must contain exactly one selected Node artifact.' } +$artifact = $artifacts[0] +if ($artifact.url -cne 'https://nodejs.org/dist/v22.23.2/node-v22.23.2-win-arm64.zip' -or + $artifact.sha256 -cne 'fec025a6da31757e3b6af84c5a1628e9d38442ca99a2161091d78f2fcfa35ef3' -or + $artifact.size -ne 31418167) { throw 'The selected Node distribution differs from the reviewed compilation input.' } +$output = [IO.Path]::GetFullPath($OutputDirectory) +if (Test-Path -LiteralPath $output) { throw 'Application Node preparation requires a fresh output directory.' } +$null = New-Item -ItemType Directory -Path $output +$archive = Join-Path $output $artifact.file +Invoke-WebRequest -Uri $artifact.url -OutFile $archive -UseBasicParsing -TimeoutSec 180 +if ((Get-Item -LiteralPath $archive).Length -ne $artifact.size -or + (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() -cne $artifact.sha256) { + throw 'The downloaded Node distribution failed its immutable size or SHA-256 check.' +} +Add-Type -AssemblyName System.IO.Compression.FileSystem +$zip = [IO.Compression.ZipFile]::OpenRead($archive) +try { + # npm is retained only as a pinned CI build tool for selected Node agents; + # prepare-finished-host copies only node.exe and LICENSE into the product. + foreach ($name in @('node.exe', 'LICENSE', 'npm.cmd')) { + $members = @($zip.Entries | Where-Object { $_.FullName -ceq "node-v22.23.2-win-arm64/$name" }) + if ($members.Count -ne 1) { throw 'The verified Node archive has an unexpected executable/license layout.' } + $stream = $members[0].Open() + try { + $destination = [IO.File]::Open((Join-Path $output $name), [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) + try { $stream.CopyTo($destination) } finally { $destination.Dispose() } + } finally { $stream.Dispose() } + } + $npmPrefix = 'node-v22.23.2-win-arm64/node_modules/npm/' + foreach ($member in @($zip.Entries | Where-Object { $_.FullName.StartsWith($npmPrefix, [StringComparison]::Ordinal) })) { + $relative = $member.FullName.Substring($npmPrefix.Length) + if ([string]::IsNullOrEmpty($relative)) { continue } + if ($relative.Contains('..') -or $relative.Contains(':') -or $relative.StartsWith('/')) { + throw 'The verified npm member has an unsafe path.' + } + $destination = Join-Path $output ('node_modules\npm\' + $relative.Replace('/', '\')) + if ($member.FullName.EndsWith('/')) { [IO.Directory]::CreateDirectory($destination) | Out-Null; continue } + [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($destination)) | Out-Null + $stream = $member.Open() + try { + $file = [IO.File]::Open($destination, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) + try { $stream.CopyTo($file) } finally { $file.Dispose() } + } finally { $stream.Dispose() } + } +} finally { $zip.Dispose() } +$node = Join-Path $output 'node.exe' +$version = & $node -p 'JSON.stringify({version:process.versions.node,platform:process.platform,architecture:process.arch})' +if ($LASTEXITCODE -ne 0) { throw 'The verified Node executable failed its native execution check.' } +$identity = $version | ConvertFrom-Json +if ($identity.version -cne '22.23.2' -or $identity.platform -cne 'win32' -or $identity.architecture -cne 'arm64') { + throw 'The selected compiler/runtime is not the pinned native Windows ARM64 Node.' +} +$signature = Get-AuthenticodeSignature -LiteralPath $node +$npmVersion = (& $node (Join-Path $output 'node_modules\npm\bin\npm-cli.js') --version | Out-String).Trim() +if ($LASTEXITCODE -ne 0 -or $npmVersion -cne '10.9.8') { throw 'The pinned Node archive npm tool is invalid.' } +$receipt = [ordered]@{ + schemaVersion = 1; classification = 'compiled-windows-app-node-input' + upstream = $artifact.url; archiveSha256 = $artifact.sha256 + nodeSha256 = (Get-FileHash -LiteralPath $node -Algorithm SHA256).Hash.ToLowerInvariant() + licenseSha256 = (Get-FileHash -LiteralPath (Join-Path $output 'LICENSE') -Algorithm SHA256).Hash.ToLowerInvariant() + runtime = $identity; signatureStatus = $signature.Status.ToString() + signer = if ($signature.SignerCertificate) { $signature.SignerCertificate.Subject } else { $null } + npmVersion = $npmVersion + controllerSource = $env:GITHUB_SHA + installedAcceptance = $false +} +[IO.File]::WriteAllText((Join-Path $output 'node-input.json'), (($receipt | ConvertTo-Json -Depth 6) + "`n"), [Text.UTF8Encoding]::new($false)) +Write-Host 'Pinned native Node application/compiler input is ready; no package manager was installed.' diff --git a/packaging/windows/app/runtime-external-packages.test.mts b/packaging/windows/app/runtime-external-packages.test.mts new file mode 100644 index 00000000000..6133c829eab --- /dev/null +++ b/packaging/windows/app/runtime-external-packages.test.mts @@ -0,0 +1,557 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createRequire } from "node:module"; +import { spawnSync } from "node:child_process"; +import test from "node:test"; +import { Worker } from "node:worker_threads"; +import { build, transform } from "esbuild"; +import { + compileAsyncProcessEntry, + compiledModuleLocationPlugin, + publishDynamicImportBridges, + publishPluginFacades, + runtimeExternalPlugin, + runtimeInputRoot, +} from "./openclaw-app-resources.mts"; + +function fixture(t: test.TestContext) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-sidecar-graph-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const inputs = path.join(root, "inputs"); + const source = path.join(inputs, "node_modules/openclaw"); + const app = path.join(root, "app"); + fs.mkdirSync(source, { recursive: true }); + fs.mkdirSync(app); + const write = (relative: string, content: string) => { + const file = path.join(root, relative); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content, { flag: "wx" }); + }; + return { root, inputs, source, app, write }; +} + +test("compiled imports retain nested versions and import/require export conditions", async (t) => { + const { inputs, source, app, write } = fixture(t); + write( + "inputs/node_modules/openclaw/package.json", + JSON.stringify({ name: "openclaw", type: "module" }), + ); + write( + "inputs/node_modules/openclaw/entry.mjs", + 'import {version} from "versioned"; import consumer from "consumer"; export const selected = [version, consumer];', + ); + write( + "inputs/node_modules/consumer/package.json", + JSON.stringify({ name: "consumer", main: "index.cjs" }), + ); + write("inputs/node_modules/consumer/index.cjs", 'module.exports = require("versioned").version;'); + for (const [folder, version] of [ + ["inputs/node_modules/versioned", "2"], + ["inputs/node_modules/openclaw/node_modules/versioned", "1"], + ]) { + write( + folder + "/package.json", + JSON.stringify({ + name: "versioned", + exports: { import: "./import.mjs", require: "./require.cjs" }, + }), + ); + write(folder + "/import.mjs", `export const version = "${version}.import";`); + write(folder + "/require.cjs", `exports.version = "${version}.require";`); + } + const output = path.join(app, "openclaw-app.cjs"); + const result = await build({ + entryPoints: [path.join(source, "entry.mjs")], + outfile: output, + bundle: true, + platform: "node", + format: "cjs", + metafile: true, + logLevel: "silent", + plugins: [runtimeExternalPlugin(source, ["versioned"])], + }); + fs.cpSync(path.join(inputs, "node_modules"), path.join(app, "node_modules"), { recursive: true }); + assert.deepEqual(createRequire(import.meta.url)(output).selected, ["1.import", "2.require"]); + const imports = Object.values(result.metafile!.outputs).flatMap((item) => item.imports); + assert( + imports.some( + (item) => + item.external && item.path === "./node_modules/openclaw/node_modules/versioned/import.mjs", + ), + ); + assert( + imports.some((item) => item.external && item.path === "./node_modules/versioned/require.cjs"), + ); + assert.equal(runtimeInputRoot(source), inputs); +}); + +test("sidecar resolution rejects packages outside verified build inputs", async (t) => { + const { source, app, write } = fixture(t); + write("inputs/node_modules/openclaw/entry.cjs", 'module.exports = require("outside");'); + write( + "node_modules/outside/package.json", + JSON.stringify({ name: "outside", main: "index.cjs" }), + ); + write("node_modules/outside/index.cjs", "module.exports = 'not an admitted input';"); + await assert.rejects( + build({ + entryPoints: [path.join(source, "entry.cjs")], + outfile: path.join(app, "bundle.cjs"), + bundle: true, + platform: "node", + format: "cjs", + logLevel: "silent", + plugins: [runtimeExternalPlugin(source, ["outside"])], + }), + /escaped the verified input root/, + ); +}); + +test("missing required sidecars fail while the approved absent tracing peer stays lazy", async (t) => { + const { source, app, write } = fixture(t); + write( + "inputs/node_modules/openclaw/missing.cjs", + 'module.exports = require("required-sidecar");', + ); + await assert.rejects( + build({ + entryPoints: [path.join(source, "missing.cjs")], + outfile: path.join(app, "missing.cjs"), + bundle: true, + platform: "node", + format: "cjs", + logLevel: "silent", + plugins: [runtimeExternalPlugin(source, ["required-sidecar"])], + }), + /Could not resolve/, + ); + write( + "inputs/node_modules/openclaw/tracing.cjs", + 'exports.load = () => import("@opentelemetry/api");', + ); + const result = await build({ + entryPoints: [path.join(source, "tracing.cjs")], + outfile: path.join(app, "tracing.cjs"), + bundle: true, + platform: "node", + format: "cjs", + metafile: true, + logLevel: "silent", + plugins: [runtimeExternalPlugin(source, ["@opentelemetry/api"])], + }); + assert( + Object.values(result.metafile!.outputs) + .flatMap((item) => item.imports) + .some((item) => item.path === "@opentelemetry/api" && item.external), + ); + assert.equal( + typeof createRequire(import.meta.url)(path.join(app, "tracing.cjs")).load, + "function", + ); +}); + +test("runtime source must use the canonical wrapper package location", () => { + assert.throws( + () => runtimeInputRoot(path.join(os.tmpdir(), "openclaw")), + /canonical OpenClaw wrapper layout/, + ); +}); + +test("dynamic SDK imports use the canonical wrapper and retain ESM export conditions", async (t) => { + const { app, write } = fixture(t); + write( + "app/package.json", + JSON.stringify({ + name: "openclaw", + exports: { "./plugin-sdk/extension-shared": "./missing.js" }, + }), + ); + write( + "app/node_modules/openclaw/package.json", + JSON.stringify({ + name: "openclaw", + exports: { + "./plugin-sdk/extension-shared": { import: "./import.mjs", require: "./require.cjs" }, + }, + }), + ); + write("app/node_modules/openclaw/import.mjs", 'export const owner="canonical-import";'); + write("app/node_modules/openclaw/require.cjs", 'exports.owner="wrong-require-condition";'); + write("app/other.mjs", 'export const owner="root-relative";'); + publishDynamicImportBridges(app); + const load = createRequire(import.meta.url)(path.join(app, "openclaw-dynamic-import.cjs")); + assert.equal((await load("openclaw/plugin-sdk/extension-shared")).owner, "canonical-import"); + assert.equal((await load("./other.mjs")).owner, "root-relative"); + await assert.rejects(load("openclaw/plugin-sdk/not-exported"), /not defined by "exports"/); +}); + +test("process facades initialize the compiled owner and load only the selected entry", (t) => { + const { app, write } = fixture(t); + const entry = "node_modules/openclaw/dist/infra/owned.worker.js"; + write("app/package.json", '{"type":"module"}'); + write( + "app/openclaw-app.cjs", + ` + exports.registerPrebuiltPlugins = async config => { + if (Object.keys(config).length) throw Error("Unexpected plugin configuration"); + await Promise.resolve(); + globalThis[Symbol.for("nemoclaw.compiled-openclaw.plugins.v1")] = { + load(key) { + if (key !== ${JSON.stringify(entry)}) throw Error("Wrong entry"); + process.stdout.write(JSON.stringify({key, args:process.argv.slice(2)})); + return {answer:42}; + } + }; + };`, + ); + publishPluginFacades(app, [ + { path: entry, exports: ["answer"], sourceSha256: "fixture", processEntry: true }, + ]); + const roots = [app, app + path.sep + "."]; + if (process.platform === "win32") roots.push(app.toUpperCase()); + for (const root of roots) { + const result = spawnSync( + process.execPath, + [path.join(app, entry), "owned-child", "path with spaces"], + { + env: { ...process.env, OPENCLAW_COMPILED_ASSET_ROOT: root }, + encoding: "utf8", + timeout: 10_000, + maxBuffer: 1024 * 1024, + windowsHide: true, + }, + ); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(JSON.parse(result.stdout), { + key: entry, + args: ["owned-child", "path with spaces"], + }); + } +}); + +test("process facades locate their sealed owner in an empty Worker environment", async (t) => { + const { app, write } = fixture(t); + const entry = "node_modules/openclaw/dist/state/owned.worker.js"; + write("app/package.json", '{"type":"module"}'); + write( + "app/openclaw-app.cjs", + ` + exports.registerPrebuiltPlugins = async () => { + if(process.env.OPENCLAW_COMPILED_ASSET_ROOT !== __dirname) + throw Error("The sealed OpenClaw asset root is required."); + globalThis[Symbol.for("nemoclaw.compiled-openclaw.plugins.v1")] = {load(key){ + if(key !== ${JSON.stringify(entry)}) throw Error("Wrong entry"); + require("node:worker_threads").parentPort.postMessage({ + assetRoot:process.env.OPENCLAW_COMPILED_ASSET_ROOT, + environmentKeys:Object.keys(process.env) + }); + return {}; + }}; + };`, + ); + publishPluginFacades(app, [ + { path: entry, exports: [], sourceSha256: "fixture", processEntry: true }, + ]); + const worker = new Worker(path.join(app, entry), { + env: {}, + execArgv: [], + stdout: true, + stderr: true, + }); + const messages: unknown[] = []; + worker.on("message", (message) => messages.push(message)); + let failure: Error | undefined; + worker.on("error", (error) => { + failure = error; + }); + const exited = new Promise((resolve) => worker.once("exit", resolve)); + let expired = false; + const timer = setTimeout(() => { + expired = true; + void worker.terminate(); + }, 10_000); + try { + assert.equal(await exited, 0, failure?.message); + assert.equal(expired, false); + assert.equal(failure, undefined); + assert.deepEqual(messages, [ + { assetRoot: app, environmentKeys: ["OPENCLAW_COMPILED_ASSET_ROOT"] }, + ]); + } finally { + clearTimeout(timer); + await worker.terminate(); + } +}); + +test("process facades reject a conflicting asset root before loading the owner", (t) => { + const { app, write } = fixture(t); + write("app/package.json", '{"type":"module"}'); + write("app/openclaw-app.cjs", 'throw Error("Owner must not load for a conflicting root");'); + publishPluginFacades(app, [ + { path: "worker.js", exports: [], sourceSha256: "fixture", processEntry: true }, + ]); + for (const root of ["relative-root", path.join(app, "other"), ""]) { + const result = spawnSync(process.execPath, [path.join(app, "worker.js")], { + env: { ...process.env, OPENCLAW_COMPILED_ASSET_ROOT: root }, + encoding: "utf8", + timeout: 10_000, + maxBuffer: 1024 * 1024, + windowsHide: true, + }); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, /asset root does not match its compiled owner/); + assert.doesNotMatch(result.stderr, /Owner must not load/); + assert.equal(result.stdout, ""); + } +}); + +test("ordinary plugin facades do not initialize an absent owner", (t) => { + const { app, write } = fixture(t); + write("app/package.json", '{"type":"module"}'); + write("app/openclaw-app.cjs", 'throw Error("Owner must not be loaded automatically");'); + publishPluginFacades(app, [{ path: "plugin.js", exports: [], sourceSha256: "fixture" }]); + const result = spawnSync(process.execPath, [path.join(app, "plugin.js")], { + encoding: "utf8", + timeout: 10_000, + maxBuffer: 1024 * 1024, + windowsHide: true, + }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /compiled OpenClaw owner is unavailable/); + assert.doesNotMatch(result.stderr, /Owner must not be loaded automatically/); +}); + +test("process facade initialization failure does not reach the worker", (t) => { + const { app, write } = fixture(t); + write("app/package.json", '{"type":"module"}'); + write( + "app/openclaw-app.cjs", + ` + globalThis[Symbol.for("nemoclaw.compiled-openclaw.plugins.v1")] = {load(){process.stdout.write("must-not-run");}}; + exports.registerPrebuiltPlugins = async () => {throw Error("owned-initialization-failure");};`, + ); + publishPluginFacades(app, [ + { path: "worker.js", exports: [], sourceSha256: "fixture", processEntry: true }, + ]); + const result = spawnSync(process.execPath, [path.join(app, "worker.js")], { + encoding: "utf8", + timeout: 10_000, + maxBuffer: 1024 * 1024, + windowsHide: true, + }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /owned-initialization-failure/); + assert.equal(result.stdout, ""); +}); + +test("process facades await asynchronous completion and propagate its rejection", (t) => { + const { app, write } = fixture(t); + write("app/package.json", '{"type":"module"}'); + write( + "app/openclaw-app.cjs", + ` + exports.registerPrebuiltPlugins = async () => { + globalThis[Symbol.for("nemoclaw.compiled-openclaw.plugins.v1")] = {load(){return { + __nemoWorkerCompletion:new Promise((resolve,reject)=>setTimeout(()=>{ + if(process.argv[2] === "fail") reject(Error("owned-worker-completion-failure")); + else {process.stdout.write("completed\\n");resolve();} + },20)) + };}}; + };`, + ); + publishPluginFacades(app, [ + { path: "worker.js", exports: [], sourceSha256: "fixture", processEntry: true }, + ]); + write("app/driver.mjs", 'await import("./worker.js");process.stdout.write("imported\\n");'); + for (const mode of ["pass", "fail"]) { + const result = spawnSync(process.execPath, [path.join(app, "driver.mjs"), mode], { + encoding: "utf8", + timeout: 10_000, + maxBuffer: 1024 * 1024, + windowsHide: true, + }); + assert.equal(result.status, mode === "pass" ? 0 : 1, result.stderr); + if (mode === "pass") assert.equal(result.stdout, "completed\nimported\n"); + else { + assert.match(result.stderr, /owned-worker-completion-failure/); + assert.equal(result.stdout, ""); + } + } +}); + +test("archive worker adaptation refuses source drift and leaves other modules unchanged", () => { + assert.equal(compileAsyncProcessEntry("dist/unrelated.js", "unchanged"), "unchanged"); + assert.throws( + () => + compileAsyncProcessEntry( + "dist/config/sessions/session-accessor.sqlite-archive.worker.js", + "changed", + ), + /reviewed asynchronous archive worker changed/, + ); +}); + +test("setup worker compilation preserves partial results, completion, and reported failures", async () => { + // Pinned upstream entry; only detection is replaced with a credential-free fixture. + const original = [ + 'import { t as detectSetupInference } from "../setup-inference-detect-QZ_aVC2Y.js";', + 'import { parentPort, workerData } from "node:worker_threads";', + "//#region src/system-agent/setup-inference-detection.worker.ts", + 'if (!parentPort) throw new Error("setup inference detection worker requires a parent port");', + "const port = parentPort;", + "try {", + '\tconst agentId = workerData && typeof workerData === "object" && typeof workerData.agentId === "string" ? workerData.agentId : void 0;', + "\tconst detection = await detectSetupInference({ onPartial: (partial) => port.postMessage({", + '\t\ttype: "partial",', + "\t\tdetection: partial", + "\t}) }, agentId);", + "\tport.postMessage({", + '\t\ttype: "result",', + "\t\tdetection", + "\t});", + "} catch (error) {", + "\tport.postMessage({", + "\t\tok: false,", + "\t\terror: error instanceof Error ? error.message : String(error)", + "\t});", + "} finally {", + "\tport.close();", + "}", + "//#endregion", + "export {};", + "", + ].join("\n"); + const relative = "dist/system-agent/setup-inference-detection.worker.js"; + const adapted = compileAsyncProcessEntry(relative, original); + assert.throws( + () => compileAsyncProcessEntry(relative, original + "\n"), + /reviewed asynchronous setup worker changed/, + ); + const compiled = await build({ + stdin: { contents: adapted, loader: "js" }, + bundle: true, + platform: "node", + format: "cjs", + write: false, + logLevel: "silent", + plugins: [ + { + name: "isolated-detection", + setup(builder) { + builder.onResolve({ filter: /setup-inference-detect-QZ_aVC2Y/ }, () => ({ + path: "detection", + namespace: "fixture", + })); + builder.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({ + contents: ` + export async function t({onPartial}, agentId) { + onPartial({agentId, complete:false}); + await new Promise(resolve=>setTimeout(resolve,10)); + if(agentId==="fail") throw Error("owned-detection-failure"); + return {agentId, complete:true}; + }`, + loader: "js", + })); + }, + }, + ], + }); + for (const agentId of ["main", "fail"]) { + const messages: unknown[] = []; + let failure: Error | undefined; + const worker = new Worker( + compiled.outputFiles[0].text + + '\nmodule.exports.__nemoWorkerCompletion.then(()=>console.log("completed"));', + { eval: true, workerData: { agentId }, execArgv: [], stdout: true, stderr: true }, + ); + let stdout = ""; + worker.stdout.on("data", (chunk) => { + stdout += chunk.toString(); + }); + worker.on("message", (message) => messages.push(message)); + worker.on("error", (error) => { + failure = error; + }); + const exited = new Promise((resolve) => worker.once("exit", resolve)); + let expired = false; + const timer = setTimeout(() => { + expired = true; + void worker.terminate(); + }, 10_000); + try { + assert.equal(await exited, 0, failure?.message); + assert.equal(expired, false); + assert.equal(failure, undefined); + assert.equal(stdout.trim(), "completed"); + assert.deepEqual(messages, [ + { type: "partial", detection: { agentId, complete: false } }, + agentId === "fail" + ? { ok: false, error: "owned-detection-failure" } + : { type: "result", detection: { agentId, complete: true } }, + ]); + } finally { + clearTimeout(timer); + await worker.terminate(); + } + } +}); + +test("bundled dependencies retain module URLs for native createRequire", async (t) => { + const { source, app, write } = fixture(t); + write("inputs/node_modules/openclaw/package.json", '{"name":"openclaw"}'); + write("inputs/node_modules/openclaw/entry.mjs", 'export {location, name} from "dependency";'); + write("inputs/node_modules/dependency/package.json", '{"name":"dependency","main":"index.mjs"}'); + write( + "inputs/node_modules/dependency/index.mjs", + ` + import {createRequire} from "node:module"; + export const location=import.meta.url; + export const name=createRequire(import.meta.url)("node:path").basename(__filename);`, + ); + const output = path.join(app, "bundle.cjs"); + await build({ + entryPoints: [path.join(source, "entry.mjs")], + outfile: output, + bundle: true, + platform: "node", + format: "cjs", + logLevel: "silent", + plugins: [compiledModuleLocationPlugin(source, { transform })], + banner: { + js: ` + function __nemoModuleFilenameFor(relative){return require("node:path").join(${JSON.stringify(app)},relative);} + function __nemoModuleDirnameFor(relative){return require("node:path").dirname(__nemoModuleFilenameFor(relative));} + function __nemoModuleUrlFor(relative){return require("node:url").pathToFileURL(__nemoModuleFilenameFor(relative)).href;}`, + }, + }); + const result = createRequire(import.meta.url)(output); + assert.equal(result.name, "index.mjs"); + assert.equal( + new URL(result.location).pathname.endsWith("/app/node_modules/dependency/index.mjs"), + true, + ); +}); + +test("module location adaptation refuses source outside verified inputs", async (t) => { + const { source, app, write } = fixture(t); + write("inputs/node_modules/openclaw/package.json", '{"name":"openclaw"}'); + write("inputs/node_modules/openclaw/entry.mjs", 'import "outside";'); + write("node_modules/outside/package.json", '{"name":"outside","main":"index.mjs"}'); + write("node_modules/outside/index.mjs", "export const location=import.meta.url;"); + await assert.rejects( + build({ + entryPoints: [path.join(source, "entry.mjs")], + outfile: path.join(app, "bundle.cjs"), + bundle: true, + platform: "node", + format: "cjs", + logLevel: "silent", + plugins: [compiledModuleLocationPlugin(source, { transform })], + }), + /escaped the verified input root/, + ); +}); diff --git a/packaging/windows/app/runtime-published-resources.test.mts b/packaging/windows/app/runtime-published-resources.test.mts new file mode 100644 index 00000000000..9f35799f21a --- /dev/null +++ b/packaging/windows/app/runtime-published-resources.test.mts @@ -0,0 +1,454 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { createHash } from "node:crypto"; +import vm from "node:vm"; +import { + CONTROL_UI_STARTUP_ENTRY, + CONTROL_UI_SERVICE_WORKER, + deferControlUiStartup, + protectControlUiWorkerRecovery, + resourceInventory, + stagePublishedResources, +} from "./openclaw-app-resources.mts"; + +const originalStartup = 'import{t as e}from"./control-ui-foundation-Cydpkyqa.js";e();'; +const originalWorkerRecovery = `async function navigateSuspendedClient(client) { + const reloadClaim = await markClientReload(client); + if (!reloadClaim) { + return; + } + // Navigation can stay pending for the lifetime of a suspended document, so + // it must not keep the replacement service worker's activation alive. + void client.navigate(client.url).catch(() => { + // A suspended WebKit document can reject navigation. Release ownership so + // the next activation can retry instead of stranding this build forever. + void reloadClaim.cache.delete(reloadClaim.guardRequest).catch(() => undefined); + }); +} +`; + +function fixture(t: test.TestContext) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-sidecar-graph-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const inputs = path.join(root, "inputs"); + const source = path.join(inputs, "node_modules/openclaw"); + const app = path.join(root, "app"); + fs.mkdirSync(source, { recursive: true }); + fs.mkdirSync(app); + const write = (relative: string, content: string) => { + const file = path.join(root, relative); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content, { flag: "wx" }); + }; + return { root, inputs, source, app, write }; +} + +function resourceFixture(t: test.TestContext) { + const result = fixture(t); + const { write } = result; + write( + "inputs/node_modules/openclaw/package.json", + JSON.stringify({ name: "openclaw", version: "2026.9.2" }), + ); + write("inputs/node_modules/openclaw/" + CONTROL_UI_STARTUP_ENTRY, originalStartup); + write("inputs/node_modules/openclaw/" + CONTROL_UI_SERVICE_WORKER, originalWorkerRecovery); + write( + "inputs/node_modules/openclaw/dist/control-ui/index.html", + '', + ); + for (const file of [ + "LICENSE", + "THIRD_PARTY_NOTICES.md", + "skills/fixture/SKILL.md", + "docs/reference/templates/AGENTS.md", + "docs/reference/templates/BOOTSTRAP.md", + "docs/not-a-runtime-input.md", + ]) + write("inputs/node_modules/openclaw/" + file, "published fixture: " + file); + for (const name of [ + "koffi", + "@emnapi/core", + "@emnapi/runtime", + "@lydell/node-pty", + "@openclaw/fs-safe", + "@silvia-odwyer/photon-node", + "clawpdf", + "rastermill", + "quickjs-wasi", + "web-tree-sitter", + "tree-sitter-bash", + "playwright-core", + "typescript", + "jiti", + "@homebridge/ciao", + "undici", + "ws", + "libopus-wasm", + "@discordjs/voice", + ]) + write( + "inputs/node_modules/" + name + "/package.json", + JSON.stringify({ name, version: "1.0.0" }), + ); + for (const [id, name] of [ + ["brave", "@openclaw/brave-plugin"], + ["discord", "@openclaw/discord"], + ["slack", "@openclaw/slack"], + ["tavily", "@openclaw/tavily-plugin"], + ]) + write("inputs/plugins/" + id + "/package.json", JSON.stringify({ name, version: "2026.9.2" })); + return result; +} + +test("published workspace templates retain their canonical paths, bytes and inventory identities", (t) => { + const { source, app } = resourceFixture(t); + stagePublishedResources(source, app); + const inventory = resourceInventory(app, []); + for (const name of ["AGENTS.md", "BOOTSTRAP.md"]) { + const relative = "node_modules/openclaw/docs/reference/templates/" + name; + const original = fs.readFileSync(path.join(source, "docs/reference/templates", name)); + assert.deepEqual(fs.readFileSync(path.join(app, relative)), original); + assert.deepEqual( + inventory.find((row) => row.path === relative), + { + path: relative, + bytes: original.length, + sha256: createHash("sha256").update(original).digest("hex"), + role: "runtime-sidecar", + }, + ); + } + assert.equal( + fs.existsSync(path.join(app, "node_modules/openclaw/docs/not-a-runtime-input.md")), + false, + ); +}); + +test("missing published workspace templates stop resource composition", (t) => { + const { source, app } = resourceFixture(t); + const templates = path.join(source, "docs/reference/templates"); + for (const name of ["AGENTS.md", "BOOTSTRAP.md"]) fs.unlinkSync(path.join(templates, name)); + fs.rmdirSync(templates); + assert.throws(() => stagePublishedResources(source, app), { code: "ENOENT" }); +}); + +test("linked workspace templates are rejected without copying or changing the linked data", (t) => { + const { root, source, app, write } = resourceFixture(t); + write("outside-template.txt", "must remain unchanged"); + const original = path.join(root, "outside-template.txt"); + fs.linkSync(original, path.join(source, "docs/reference/templates/linked.md")); + assert.throws(() => stagePublishedResources(source, app), /single-link input files/); + assert.equal(fs.readFileSync(original, "utf8"), "must remain unchanged"); + assert.equal( + fs.existsSync(path.join(app, "node_modules/openclaw/docs/reference/templates/linked.md")), + false, + ); +}); + +test("worker recovery leaves visible, missing and credential-bearing clients unchanged", async () => { + const source = protectControlUiWorkerRecovery(Buffer.from(originalWorkerRecovery)).toString( + "utf8", + ); + const protectedClients = [ + undefined, + { visibilityState: "visible", url: "http://fixture/chat" }, + { visibilityState: "unknown", url: "http://fixture/chat" }, + ...["token", "bootstrapToken", "password", "gatewayUrl"].flatMap((key) => + ["?", "#"].map((separator) => ({ + visibilityState: "hidden", + url: `http://fixture/chat${separator}${key}=owned-fixture`, + })), + ), + ]; + for (const current of protectedClients) { + let claims = 0; + await vm.runInNewContext(source + "navigateSuspendedClient(client)", { + URL, + URLSearchParams, + client: { id: "owned-client" }, + self: { + clients: { + get: async (id: string) => { + assert.equal(id, "owned-client"); + return current; + }, + }, + }, + markClientReload: async () => { + claims++; + throw new Error("Protected client was claimed."); + }, + }); + assert.equal(claims, 0); + } +}); + +test("worker recovery uses the refreshed hidden client and preserves reload claims and rejection cleanup", async () => { + const source = protectControlUiWorkerRecovery(Buffer.from(originalWorkerRecovery)).toString( + "utf8", + ); + for (const mode of ["claimed", "already-claimed", "rejected"] as const) { + let claims = 0; + let navigations = 0; + let releases = 0; + const current = { + visibilityState: "hidden", + url: "http://fixture/chat?session=owned-session", + navigate: async (url: string) => { + assert.equal(url, current.url); + navigations++; + if (mode === "rejected") throw new Error("Owned navigation rejection."); + }, + }; + const guardRequest = {}; + await vm.runInNewContext(source + "navigateSuspendedClient(client)", { + URL, + URLSearchParams, + client: { id: "owned-client", url: "http://fixture/chat#token=old-fixture" }, + self: { clients: { get: async () => current } }, + markClientReload: async (client: unknown) => { + assert.equal(client, current); + claims++; + return mode === "already-claimed" + ? null + : { + guardRequest, + cache: { + delete: async (request: unknown) => { + assert.equal(request, guardRequest); + releases++; + }, + }, + }; + }, + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(claims, 1); + assert.equal(navigations, mode === "already-claimed" ? 0 : 1); + assert.equal(releases, mode === "rejected" ? 1 : 0); + } +}); + +test("worker recovery releases its claim when the page changes or lookup fails during acquisition", async () => { + const source = protectControlUiWorkerRecovery(Buffer.from(originalWorkerRecovery)).toString( + "utf8", + ); + for (const mode of ["visible", "credentials", "closed", "lookup-failed"] as const) { + let reads = 0; + let releases = 0; + const initial = { id: "owned-client", visibilityState: "hidden", url: "http://fixture/chat" }; + const failure = new Error("Owned lookup failure."); + const completion = vm.runInNewContext(source + "navigateSuspendedClient(client)", { + URL, + URLSearchParams, + client: initial, + self: { + clients: { + get: async () => { + if (++reads === 1) return initial; + if (mode === "lookup-failed") throw failure; + if (mode === "closed") return undefined; + return { + ...initial, + visibilityState: mode === "visible" ? "visible" : "hidden", + url: mode === "credentials" ? "http://fixture/chat#token=owned-fixture" : initial.url, + }; + }, + }, + }, + markClientReload: async () => ({ + cache: { + delete: async () => { + releases++; + }, + }, + guardRequest: {}, + }), + }); + if (mode === "lookup-failed") await assert.rejects(completion, (error) => error === failure); + else await completion; + assert.equal(reads, 2); + assert.equal(releases, 1); + } +}); + +test("worker adaptation rejects changed recovery and seals transformed bytes without changing inputs", (t) => { + for (const source of [ + "", + originalWorkerRecovery.replace("client.url", "client.other"), + originalWorkerRecovery.repeat(2), + ]) + assert.throws( + () => protectControlUiWorkerRecovery(Buffer.from(source)), + /worker recovery changed/, + ); + const { source, app } = resourceFixture(t); + const { controlUiServiceWorker } = stagePublishedResources(source, app); + const relative = "node_modules/openclaw/" + CONTROL_UI_SERVICE_WORKER; + const staged = fs.readFileSync(path.join(app, relative)); + assert.equal( + fs.readFileSync(path.join(source, CONTROL_UI_SERVICE_WORKER), "utf8"), + originalWorkerRecovery, + ); + assert.deepEqual(staged, protectControlUiWorkerRecovery(Buffer.from(originalWorkerRecovery))); + assert.equal( + controlUiServiceWorker.sourceSha256, + createHash("sha256").update(originalWorkerRecovery).digest("hex"), + ); + assert.equal( + controlUiServiceWorker.stagedSha256, + createHash("sha256").update(staged).digest("hex"), + ); + assert.equal( + resourceInventory(app, []).find((entry) => entry.path === relative)?.sha256, + controlUiServiceWorker.stagedSha256, + ); +}); + +test("compressed workers cannot bypass the packaged recovery guard", (t) => { + for (const suffix of [".br", ".gz"]) { + const { source, app, write } = resourceFixture(t); + write( + "inputs/node_modules/openclaw/" + CONTROL_UI_SERVICE_WORKER + suffix, + "old compressed worker", + ); + assert.throws(() => stagePublishedResources(source, app), /compressed Control UI worker/); + assert.deepEqual(fs.readdirSync(app), []); + } +}); + +test("packaged UI startup waits for initial fragment navigation before capturing its landing URL", () => { + let hash = "#token=fixture"; + let landing: string | undefined; + let calls = 0; + const window = new EventTarget(); + const initialize = () => { + calls++; + hash = ""; + landing = hash; + }; + const entry = deferControlUiStartup(Buffer.from(originalStartup)).toString("utf8"); + vm.runInNewContext(entry.replace(/^import[^;]+;/u, "const e=initialize;"), { + document: { readyState: "interactive" }, + window, + initialize, + }); + assert.equal(calls, 0); + hash = "#token=fixture"; // Initial navigation completes before the load event. + window.dispatchEvent(new Event("load")); + assert.equal(calls, 1); + assert.equal(hash, ""); + assert.equal(landing, hash); + window.dispatchEvent(new Event("load")); + assert.equal(calls, 1); + hash = "#user-navigation"; + assert.notEqual(landing, hash); // Later navigation still differs from the captured landing. +}); + +test("an already loaded document starts the original UI immediately and propagates its failure", () => { + const entry = deferControlUiStartup(Buffer.from(originalStartup)) + .toString("utf8") + .replace(/^import[^;]+;/u, "const e=initialize;"); + let calls = 0; + const failure = new Error("upstream initializer failure"); + assert.throws( + () => + vm.runInNewContext(entry, { + document: { readyState: "complete" }, + window: { + addEventListener: () => assert.fail("No load listener after document completion."), + }, + initialize: () => { + calls++; + throw failure; + }, + }), + (error) => error === failure, + ); + assert.equal(calls, 1); +}); + +test("UI startup adaptation rejects changed source and inventories the staged bytes without modifying upstream", (t) => { + assert.throws( + () => deferControlUiStartup(Buffer.from(originalStartup + "e();")), + /entry changed/, + ); + const { source, app } = resourceFixture(t); + const { controlUiStartup } = stagePublishedResources(source, app); + const relative = "node_modules/openclaw/" + controlUiStartup.stagedEntry; + const staged = fs.readFileSync(path.join(app, relative)); + assert.deepEqual(staged, deferControlUiStartup(Buffer.from(originalStartup))); + assert.equal( + fs.readFileSync(path.join(source, CONTROL_UI_STARTUP_ENTRY), "utf8"), + originalStartup, + ); + assert.equal( + fs.readFileSync(path.join(app, "node_modules/openclaw", CONTROL_UI_STARTUP_ENTRY), "utf8"), + originalStartup, + ); + const index = fs.readFileSync( + path.join(app, "node_modules/openclaw/dist/control-ui/index.html"), + "utf8", + ); + assert.equal( + index, + ``, + ); + assert.equal(controlUiStartup.stagedSha256, createHash("sha256").update(staged).digest("hex")); + assert.ok(controlUiStartup.stagedEntry.includes(controlUiStartup.stagedSha256)); + assert.equal( + resourceInventory(app, []).find((row) => row.path === relative)?.sha256, + createHash("sha256").update(staged).digest("hex"), + ); +}); + +test("startup adaptation rejects missing and duplicated entry references before staging", (t) => { + const { source, app } = resourceFixture(t); + const index = path.join(source, "dist/control-ui/index.html"); + const original = fs.readFileSync(index); + fs.writeFileSync(index, ""); + assert.throws(() => stagePublishedResources(source, app), /startup reference changed/); + assert.deepEqual(fs.readdirSync(app), []); + fs.writeFileSync(index, Buffer.concat([original, original])); + assert.throws(() => stagePublishedResources(source, app), /startup reference changed/); + assert.deepEqual(fs.readdirSync(app), []); + fs.writeFileSync(index, original); + fs.unlinkSync(path.join(source, CONTROL_UI_STARTUP_ENTRY)); + assert.throws(() => stagePublishedResources(source, app), { code: "ENOENT" }); + assert.deepEqual(fs.readdirSync(app), []); +}); + +test("derived startup URL cannot select the original compressed script or change its manifest", (t) => { + const { source, app, write } = resourceFixture(t); + write( + "inputs/node_modules/openclaw/" + CONTROL_UI_STARTUP_ENTRY + ".br", + "original brotli fixture", + ); + write( + "inputs/node_modules/openclaw/" + CONTROL_UI_STARTUP_ENTRY + ".gz", + "original gzip fixture", + ); + const manifest = "dist/control-ui/asset-manifest.json"; + write( + "inputs/node_modules/openclaw/" + manifest, + JSON.stringify({ entry: CONTROL_UI_STARTUP_ENTRY }), + ); + const { controlUiStartup } = stagePublishedResources(source, app); + const core = path.join(app, "node_modules/openclaw"); + for (const relative of [ + CONTROL_UI_STARTUP_ENTRY + ".br", + CONTROL_UI_STARTUP_ENTRY + ".gz", + manifest, + ]) + assert.deepEqual( + fs.readFileSync(path.join(core, relative)), + fs.readFileSync(path.join(source, relative)), + ); + assert.equal(fs.existsSync(path.join(core, controlUiStartup.stagedEntry + ".br")), false); + assert.equal(fs.existsSync(path.join(core, controlUiStartup.stagedEntry + ".gz")), false); +}); diff --git a/packaging/windows/app/sqlite-canonical-path-build.mts b/packaging/windows/app/sqlite-canonical-path-build.mts new file mode 100644 index 00000000000..378820ba19e --- /dev/null +++ b/packaging/windows/app/sqlite-canonical-path-build.mts @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; +import { createHash } from "node:crypto"; +import type { PluginBuild } from "esbuild"; + +const sources: Record = { + "dist/builtin-openclaw-B_H1oNzF.js": { + hash: "18772e63fa42f6e774b692fee3e2ceb394870c03b9caaec02b155728bb75de77", + calls: 0, + workspace: true, + }, + "dist/openclaw-agent-db-maintenance-wTIy-jt-.js": { + hash: "cb74fbb66177d98bfd2ad3a01362a0973db5d77af440875ac402bd2cafdc4521", + calls: 2, + }, + "dist/sqlite-readonly-location-BC9PgENz.js": { + hash: "51b2e9d5e354d2f61546c87d90ae719f1d794545e06a5d9b944c03306a84808c", + calls: 3, + }, + "dist/openclaw-database-preflight-DmhpNBQv.js": { + hash: "7472b7e3f7db87580267e1b022936251942b9f44ff7eb2fd3b860f7da6046bab", + calls: 3, + }, +}; + +export function compileSqliteCanonicalRuntime(relative: string, text: string, original = text) { + const expected = sources[relative]; + if (!expected) return text; + if (createHash("sha256").update(original).digest("hex") !== expected.hash) + throw new Error("The reviewed SQLite canonical-path source changed."); + const expression = /\b(?:fs\.)?realpathSync\.native\(/gu; + if ([...text.matchAll(expression)].length !== expected.calls) + throw new Error("The SQLite canonical-path call boundary changed."); + let result = text.replace(expression, "__nemoSqliteCanonicalPath("); + if (expected.workspace) { + const workspaceLookup = "await fs$1.realpath(resolvedWorkspace)"; + if (result.split(workspaceLookup).length !== 2) + throw new Error("The workspace canonical-path call boundary changed."); + // File-tool guards require the handle-resolved root in the drive-letter namespace. + result = result.replace( + workspaceLookup, + '(process.platform === "win32" ? __nemoWorkspaceCanonicalPath(resolvedWorkspace) : await fs$1.realpath(resolvedWorkspace))', + ); + } + const marker = "function resolveDanglingSymlinkTargetPath(lexicalPath) {"; + if (relative === "dist/openclaw-agent-db-maintenance-wTIy-jt-.js") { + if (result.split(marker).length !== 2) + throw new Error("The SQLite missing-path boundary changed."); + result = result.replace( + marker, + marker + + '\n\tif (process.platform === "win32") return __nemoResolveMissingSqlitePath(lexicalPath);', + ); + } + return ( + `import { createRequire as __nemoSqliteRequire } from "node:module"; +import { createSqliteCanonicalPath, createWorkspaceCanonicalPath, resolveMissingSqlitePath as __nemoResolveMissingSqlitePath } from "nemoclaw:sqlite-canonical-path"; +const __nemoSqliteCanonicalPath = createSqliteCanonicalPath(() => __nemoSqliteRequire(import.meta.url)("koffi")); +const __nemoWorkspaceCanonicalPath = createWorkspaceCanonicalPath(() => __nemoSqliteRequire(import.meta.url)("koffi")); +` + result + ); +} + +export function registerSqliteCanonicalModule(build: PluginBuild, source: string) { + build.onResolve({ filter: /^nemoclaw:sqlite-canonical-path$/ }, () => ({ + path: "sqlite-canonical-path.mts", + namespace: "nemoclaw-sqlite", + })); + build.onLoad({ filter: /.*/, namespace: "nemoclaw-sqlite" }, () => ({ + contents: fs.readFileSync(new URL("./sqlite-canonical-path.mts", import.meta.url), "utf8"), + loader: "ts", + resolveDir: source, + })); +} diff --git a/packaging/windows/app/sqlite-canonical-path.mts b/packaging/windows/app/sqlite-canonical-path.mts new file mode 100644 index 00000000000..5ecc55b6f69 --- /dev/null +++ b/packaging/windows/app/sqlite-canonical-path.mts @@ -0,0 +1,171 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; +import path from "node:path"; + +type NativeFunction = (...args: unknown[]) => unknown; +type Koffi = { + load(name: string): { func(declaration: string): NativeFunction }; + address(pointer: unknown): bigint; +}; +export type CanonicalPathApi = { + open(pathname: string): unknown; + invalid(handle: unknown): boolean; + finalPath(handle: unknown, output: Buffer, volume?: number): number; + close(handle: unknown): boolean; + lastError(): number; +}; + +function windowsApi(koffi: Koffi): CanonicalPathApi { + const kernel = koffi.load("kernel32.dll"); + const open = kernel.func( + "void * __stdcall CreateFileW(str16 path, uint32_t access, uint32_t share, void *security, uint32_t creation, uint32_t flags, void *template)", + ); + const finalPath = kernel.func( + "uint32_t __stdcall GetFinalPathNameByHandleW(void *handle, _Out_ uint16_t *output, uint32_t length, uint32_t flags)", + ); + const close = kernel.func("int __stdcall CloseHandle(void *handle)"); + const lastError = kernel.func("uint32_t __stdcall GetLastError()"); + return { + open: (pathname) => open(pathname, 0, 7, null, 3, 0x02000080, null), + invalid: (handle) => + handle === null || [-1n, 0xffffffffffffffffn].includes(koffi.address(handle)), + finalPath: (handle, output, volume = 2) => + Number(finalPath(handle, output, output.length / 2, volume)), + close: (handle) => Boolean(close(handle)), + lastError: () => Number(lastError()), + }; +} + +function pathError(code: string, pathname: string, detail: string): NodeJS.ErrnoException { + return Object.assign(new Error(`${code}: ${detail}, realpath '${pathname}'`), { + code, + syscall: "realpath", + path: pathname, + }); +} + +function apiError(api: CanonicalPathApi, pathname: string): NodeJS.ErrnoException { + const status = api.lastError(); + const codes: Record = { + 2: "ENOENT", + 3: "ENOENT", + 5: "EPERM", + 15: "ENOENT", + 32: "EBUSY", + 87: "EINVAL", + 123: "EINVAL", + 206: "ENAMETOOLONG", + 1921: "ELOOP", + }; + return pathError(codes[status] ?? "EIO", pathname, `Windows path error ${status}`); +} + +export function canonicalPathFromHandle( + pathname: string, + api: CanonicalPathApi, + volume: "nt" | "relative" = "nt", +): string { + if (typeof pathname !== "string" || pathname.includes("\0")) + throw new TypeError("SQLite canonical paths must be strings without NUL characters."); + const handle = api.open(pathname); + if (api.invalid(handle)) throw apiError(api, pathname); + try { + const output = Buffer.alloc(65536); + const length = api.finalPath(handle, output, volume === "nt" ? 2 : 4); + if (length === 0) throw apiError(api, pathname); + if (!Number.isInteger(length) || length < 0 || length >= output.length / 2) + throw pathError("ENAMETOOLONG", pathname, "canonical path exceeds the Windows limit"); + const normalized = output.subarray(0, length * 2).toString("utf16le"); + if (volume === "relative") { + if (!/^\\(?!\\)/u.test(normalized) || normalized.includes("\0")) + throw pathError("EIO", pathname, "unexpected Windows volume-relative name"); + return normalized; + } + if (!normalized.startsWith("\\Device\\") || normalized.includes("\0")) + throw pathError("EIO", pathname, "unexpected Windows canonical namespace"); + // NT normalized names retain link resolution without consulting the mount manager. + return "\\\\?\\GLOBALROOT" + normalized; + } finally { + if (!api.close(handle)) throw apiError(api, pathname); + } +} + +export function createSqliteCanonicalPath(loadKoffi: () => Koffi) { + let api: CanonicalPathApi | undefined; + return (pathname: string): string => { + if (process.platform !== "win32") return fs.realpathSync.native(pathname); + api ??= windowsApi(loadKoffi()); + return canonicalPathFromHandle(pathname, api); + }; +} + +export function workspacePathFromHandle(pathname: string, api: CanonicalPathApi): string { + const canonical = canonicalPathFromHandle(pathname, api); + const relative = canonicalPathFromHandle(pathname, api, "relative"); + const preferred = /^(?:\\\\\?\\)?([a-z]:)\\/iu.exec(pathname)?.[1]?.toUpperCase(); + const drives = new Set([ + ...(preferred ? [preferred] : []), + ...Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZ", (letter) => `${letter}:`), + ]); + for (const drive of drives) { + const resolved = drive + relative; + try { + // A drive spelling is accepted only after its handle proves the same NT identity. + if (canonicalPathFromHandle(resolved, api) === canonical) return resolved; + } catch (error) { + if (!["ENOENT", "EPERM"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; + } + } + throw pathError("EIO", pathname, "canonical workspace has no accessible drive mapping"); +} + +export function createWorkspaceCanonicalPath(loadKoffi: () => Koffi) { + let api: CanonicalPathApi | undefined; + return (pathname: string): string => { + if (process.platform !== "win32") return fs.realpathSync.native(pathname); + api ??= windowsApi(loadKoffi()); + return workspacePathFromHandle(pathname, api); + }; +} + +export function resolveMissingSqlitePath( + pathname: string, + filesystem: Pick = fs, + paths: typeof path = path, +): { existingPath: string; unresolvedSegments: string[] } { + let current = pathname; + let suffix: string[] = []; + const visited = new Set(); + let hops = 0; + for (;;) { + let stat: fs.BigIntStats; + try { + stat = filesystem.lstatSync(current, { bigint: true }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + const parent = paths.dirname(current); + if (parent === current) throw error; + suffix.unshift(paths.basename(current)); + current = parent; + continue; + } + if (!stat.isSymbolicLink()) { + if (suffix.length && !stat.isDirectory()) + throw pathError("ENOTDIR", pathname, "missing path parent is not a directory"); + return { existingPath: current, unresolvedSegments: suffix }; + } + const state = `${stat.dev}:${stat.ino}:${current}\0${suffix.join(paths.sep)}`; + if (hops >= 64 || visited.has(state)) + throw pathError("ELOOP", pathname, "too many symbolic links"); + hops += 1; + visited.add(state); + const target = filesystem.readlinkSync(current); + // Do not normalize '..' across a link before the filesystem resolves it. + const absolute = paths.isAbsolute(target) + ? target + : paths.dirname(current) + paths.sep + target; + current = absolute + (suffix.length ? paths.sep + suffix.join(paths.sep) : ""); + suffix = []; + } +} diff --git a/packaging/windows/app/sqlite-canonical-path.test.mts b/packaging/windows/app/sqlite-canonical-path.test.mts new file mode 100644 index 00000000000..c3533b25a3a --- /dev/null +++ b/packaging/windows/app/sqlite-canonical-path.test.mts @@ -0,0 +1,225 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import { + canonicalPathFromHandle, + resolveMissingSqlitePath, + workspacePathFromHandle, + type CanonicalPathApi, +} from "./sqlite-canonical-path.mts"; +import { compileSqliteCanonicalRuntime } from "./sqlite-canonical-path-build.mts"; + +function nativeFixture(value = "\\Device\\HarddiskVolume4\\state\\agent.sqlite") { + let closed = 0; + let opened = 0; + const api: CanonicalPathApi = { + open: () => { + opened += 1; + return 42; + }, + invalid: () => false, + finalPath: (_handle, output, volume = 2) => { + const name = volume === 4 ? value.replace(/^\\Device\\[^\\]+/u, "") : value; + output.write(name, "utf16le"); + return name.length; + }, + close: () => { + closed += 1; + return true; + }, + lastError: () => 5, + }; + return { api, counts: () => ({ opened, closed }) }; +} + +test("SQLite canonical names retain the handle-resolved NT namespace and close the handle", () => { + const fixture = nativeFixture(); + assert.equal( + canonicalPathFromHandle("C:\\state\\agent.sqlite", fixture.api), + "\\\\?\\GLOBALROOT\\Device\\HarddiskVolume4\\state\\agent.sqlite", + ); + assert.deepEqual(fixture.counts(), { opened: 1, closed: 1 }); +}); + +test("SQLite canonical lookup preserves access denial and missing-path errors", () => { + for (const [status, code] of [ + [5, "EPERM"], + [2, "ENOENT"], + [3, "ENOENT"], + [1921, "ELOOP"], + [9999, "EIO"], + ] as const) { + const fixture = nativeFixture(); + fixture.api.invalid = () => true; + fixture.api.lastError = () => status; + assert.throws(() => canonicalPathFromHandle("C:\\state", fixture.api), { + code, + syscall: "realpath", + path: "C:\\state", + }); + assert.deepEqual(fixture.counts(), { opened: 1, closed: 0 }); + } +}); + +test("SQLite canonical lookup rejects incomplete output and unexpected namespaces", () => { + for (const result of [0, 32768, -1, 1.5]) { + const fixture = nativeFixture(); + fixture.api.finalPath = () => result; + assert.throws(() => canonicalPathFromHandle("C:\\state", fixture.api)); + assert.equal(fixture.counts().closed, 1); + } + for (const value of ["C:\\state", "\\Device\\volume\0tail"]) { + const fixture = nativeFixture(value); + assert.throws(() => canonicalPathFromHandle("C:\\state", fixture.api), { code: "EIO" }); + assert.equal(fixture.counts().closed, 1); + } + const fixture = nativeFixture(); + assert.throws(() => canonicalPathFromHandle("C:\\state\0tail", fixture.api), TypeError); + assert.deepEqual(fixture.counts(), { opened: 0, closed: 0 }); +}); + +test("SQLite canonical lookup reports a failed handle close", () => { + const fixture = nativeFixture(); + fixture.api.close = () => false; + assert.throws(() => canonicalPathFromHandle("C:\\state", fixture.api), { code: "EPERM" }); +}); + +test("missing SQLite paths resolve from the nearest existing directory without probing ancestors", () => { + const visited: string[] = []; + const root = "\\\\?\\GLOBALROOT\\Device\\HarddiskVolume4\\state"; + const filesystem = { + lstatSync: (value: string) => { + visited.push(value); + if (value !== root) throw Object.assign(new Error("missing"), { code: "ENOENT" }); + return { isDirectory: () => true, isSymbolicLink: () => false }; + }, + readlinkSync: () => { + throw new Error("No link read is expected"); + }, + } as unknown as Pick; + const target = path.win32.join(root, "imports", "archive.sqlite"); + assert.deepEqual(resolveMissingSqlitePath(target, filesystem, path.win32), { + existingPath: root, + unresolvedSegments: ["imports", "archive.sqlite"], + }); + assert.deepEqual(visited, [target, path.win32.join(root, "imports"), root]); +}); + +test("missing SQLite paths propagate forbidden ancestor access without a lexical fallback", () => { + const denied = Object.assign(new Error("denied"), { code: "EPERM" }); + const filesystem = { + lstatSync: () => { + throw denied; + }, + } as unknown as Pick; + assert.throws( + () => resolveMissingSqlitePath("C:\\state\\imports", filesystem, path.win32), + (error) => error === denied, + ); +}); + +test("missing SQLite path resolution preserves dangling links, suffixes and link cycles", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "sqlite-path-")); + try { + const state = path.join(root, "state"); + fs.mkdirSync(state); + assert.deepEqual(resolveMissingSqlitePath(path.join(state, "imports", "archive")), { + existingPath: state, + unresolvedSegments: ["imports", "archive"], + }); + if (process.platform !== "win32") { + fs.symlinkSync("state/missing", path.join(root, "dangling")); + assert.deepEqual(resolveMissingSqlitePath(path.join(root, "dangling", "archive")), { + existingPath: state, + unresolvedSegments: ["missing", "archive"], + }); + fs.symlinkSync("cycle-b", path.join(root, "cycle-a")); + fs.symlinkSync("cycle-a", path.join(root, "cycle-b")); + assert.throws(() => resolveMissingSqlitePath(path.join(root, "cycle-a", "archive")), { + code: "ELOOP", + }); + const dotted = state + "/missing/../archive"; + assert.deepEqual(resolveMissingSqlitePath(dotted), { + existingPath: state, + unresolvedSegments: ["missing", "..", "archive"], + }); + } + const file = path.join(state, "file"); + fs.writeFileSync(file, "retained"); + assert.throws(() => resolveMissingSqlitePath(path.join(file, "child"))); + assert.equal(fs.readFileSync(file, "utf8"), "retained"); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test("SQLite adaptation refuses a changed pinned source and leaves other modules untouched", () => { + assert.throws( + () => + compileSqliteCanonicalRuntime("dist/openclaw-agent-db-maintenance-wTIy-jt-.js", "changed"), + /reviewed SQLite/u, + ); + assert.equal(compileSqliteCanonicalRuntime("dist/unrelated.js", "unchanged"), "unchanged"); +}); + +test("workspace canonical adaptation refuses changed upstream permission-root code", () => { + assert.throws( + () => compileSqliteCanonicalRuntime("dist/builtin-openclaw-B_H1oNzF.js", "changed"), + /reviewed SQLite/u, + ); +}); + +test("workspace roots use volume-relative names only after verifying the drive handle", () => { + const fixture = nativeFixture("\\Device\\HarddiskVolume4\\workspace"); + assert.equal(workspacePathFromHandle("C:\\alias", fixture.api), "C:\\workspace"); + assert.deepEqual(fixture.counts(), { opened: 3, closed: 3 }); + fixture.api.open = (pathname) => pathname; + fixture.api.invalid = (handle) => handle !== "C:\\junction" && handle !== "D:\\workspace"; + assert.equal(workspacePathFromHandle("C:\\junction", fixture.api), "D:\\workspace"); +}); + +test("workspace roots propagate original access denial and reject inaccessible drive candidates", () => { + const fixture = nativeFixture(); + fixture.api.invalid = () => true; + assert.throws(() => workspacePathFromHandle("C:\\workspace", fixture.api), { code: "EPERM" }); + let opened = 0; + fixture.api.open = () => ++opened; + fixture.api.invalid = (handle) => Number(handle) > 2; + assert.throws(() => workspacePathFromHandle("C:\\workspace", fixture.api), { code: "EIO" }); + assert.equal(opened, 28); +}); + +test("workspace drive mapping rejects a changed target identity", () => { + const fixture = nativeFixture("\\Device\\HarddiskVolume4\\workspace"); + let calls = 0; + fixture.api.finalPath = (_handle, output, volume = 2) => { + calls += 1; + const value = + volume === 4 + ? "\\workspace" + : calls === 1 + ? "\\Device\\HarddiskVolume4\\workspace" + : "\\Device\\HarddiskVolume4\\elsewhere"; + output.write(value, "utf16le"); + return value.length; + }; + assert.throws(() => workspacePathFromHandle("C:\\workspace", fixture.api), { code: "EIO" }); + assert.deepEqual(fixture.counts(), { opened: 28, closed: 28 }); +}); + +test("volume-relative workspace names reject an unexpected namespace", () => { + const fixture = nativeFixture(); + const original = fixture.api.finalPath; + for (const value of ["C:\\workspace", "\\\\server\\workspace", "\\workspace\0tail"]) { + fixture.api.finalPath = (handle, output, volume) => { + if (volume !== 4) return original(handle, output, volume); + output.write(value, "utf16le"); + return value.length; + }; + assert.throws(() => workspacePathFromHandle("C:\\workspace", fixture.api), { code: "EIO" }); + } +}); diff --git a/packaging/windows/app/sqlite-private-directory-build.mts b/packaging/windows/app/sqlite-private-directory-build.mts new file mode 100644 index 00000000000..72d7e0bf548 --- /dev/null +++ b/packaging/windows/app/sqlite-private-directory-build.mts @@ -0,0 +1,132 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import { execFileSync } from "node:child_process"; + +export const SQLITE_PRIVATE_DIRECTORY_SOURCE = "dist/sqlite-readonly-location-BC9PgENz.js"; +export const SQLITE_PRIVATE_DIRECTORY_LIBRARY = + "node_modules/openclaw/dist/nemoclaw-sqlite-private-directory.dll"; +const sourceSha256 = "51b2e9d5e354d2f61546c87d90ae719f1d794545e06a5d9b944c03306a84808c"; +const digest = (value: Uint8Array | string) => createHash("sha256").update(value).digest("hex"); + +export function privateDirectoryNativeSource(text: string) { + if (digest(text) !== sourceSha256) + throw new Error("The reviewed SQLite private-directory source changed."); + const declaration = /const WINDOWS_PRIVATE_DIRECTORY_NATIVE_SOURCE = `([^`]*)`;/u.exec(text); + if (!declaration || declaration[1].includes("${")) + throw new Error("The SQLite private-directory native source is unavailable."); + return { declaration: declaration[0], source: declaration[1] }; +} + +export function compilePrivateDirectoryRuntime(relative: string, text: string) { + if (relative !== SQLITE_PRIVATE_DIRECTORY_SOURCE) return text; + const native = privateDirectoryNativeSource(text); + // Keep the upstream script's owner, protected DACL, atomic creation and errors. + // Compile native code in CI and load its PowerShell cmdlets from the OS module. + const replacements = [ + [native.declaration, ""], + [ + 'const encodedNativeSource = Buffer.from(WINDOWS_PRIVATE_DIRECTORY_NATIVE_SOURCE, "utf8").toString("base64");', + 'const encodedNativeLibrary = Buffer.from(__nemoPrivateDirectoryFilePath(new URL("./nemoclaw-sqlite-private-directory.dll", import.meta.url)), "utf8").toString("base64");', + ], + [ + "`$nativeSource = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedNativeSource}'))`", + "`$nativeLibrary = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedNativeLibrary}'))`", + ], + [ + '"Add-Type -TypeDefinition $nativeSource -Language CSharp"', + `"Import-Module -Name ([IO.Path]::Combine($PSHOME, 'Modules', 'Microsoft.PowerShell.Utility', 'Microsoft.PowerShell.Utility.psd1')) -ErrorAction Stop",\n\t\t"Add-Type -LiteralPath $nativeLibrary"`, + ], + ]; + for (const [before, after] of replacements) { + if (text.split(before).length !== 2) + throw new Error("The SQLite private-directory compilation boundary changed."); + text = text.replace(before, after); + } + return 'import { fileURLToPath as __nemoPrivateDirectoryFilePath } from "node:url";\n' + text; +} + +export function privateDirectoryBuildCommand(text: string, output: string) { + const native = privateDirectoryNativeSource(text); + const encode = (value: string) => Buffer.from(value, "utf8").toString("base64"); + return [ + "$ErrorActionPreference = 'Stop'", + `if ($PSVersionTable.PSEdition -ne 'Desktop' -or $PSVersionTable.PSVersion.Major -ne 5) { throw 'Windows PowerShell 5 is required for the packaged library.' }`, + `$source = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encode(native.source)}'))`, + `$output = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encode(output)}'))`, + "if (Test-Path -LiteralPath $output) { throw 'The private-directory library output already exists.' }", + "Add-Type -TypeDefinition $source -Language CSharp -OutputAssembly $output -OutputType Library", + ].join("; "); +} + +export function buildPrivateDirectoryLibrary(source: string, app: string) { + const text = fs.readFileSync(path.join(source, SQLITE_PRIVATE_DIRECTORY_SOURCE), "utf8"); + const native = privateDirectoryNativeSource(text); + if (process.platform !== "win32") + return { + built: false, + reason: "Portable proof does not compile or qualify the Windows library.", + }; + const systemRoot = process.env.SystemRoot; + if (!systemRoot || !path.isAbsolute(systemRoot)) + throw new Error( + "The Windows system directory is required to compile the private-directory library.", + ); + const powershell = path.join( + systemRoot, + "System32", + "WindowsPowerShell", + "v1.0", + "powershell.exe", + ); + const output = path.join(app, SQLITE_PRIVATE_DIRECTORY_LIBRARY); + if (fs.existsSync(output)) throw new Error("The private-directory library output must be fresh."); + fs.mkdirSync(path.dirname(output), { recursive: true }); + // This process runs only during compilation, before the resource inventory is sealed. + execFileSync( + powershell, + [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-EncodedCommand", + Buffer.from(privateDirectoryBuildCommand(text, output), "utf16le").toString("base64"), + ], + { timeout: 60_000, maxBuffer: 65_536, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }, + ); + return { + built: true, + path: SQLITE_PRIVATE_DIRECTORY_LIBRARY, + sourceSha256, + nativeSourceSha256: digest(native.source), + ...privateDirectoryLibraryIdentity(output), + runtimeCompilation: false, + windowsQualified: false, + }; +} + +export function privateDirectoryLibraryIdentity(output: string) { + const descriptor = fs.openSync(output, "r"); + try { + const opened = fs.fstatSync(descriptor, { bigint: true }); + const named = fs.lstatSync(output, { bigint: true }); + if ( + !opened.isFile() || + opened.nlink !== 1n || + opened.size === 0n || + !named.isFile() || + named.isSymbolicLink() || + named.dev !== opened.dev || + named.ino !== opened.ino + ) + throw new Error("The compiled private-directory library is not an ordinary nonempty file."); + const bytes = fs.readFileSync(descriptor); + if (BigInt(bytes.length) !== opened.size) + throw new Error("The compiled private-directory library changed size while reading."); + return { sha256: digest(bytes), bytes: bytes.length }; + } finally { + fs.closeSync(descriptor); + } +} diff --git a/packaging/windows/app/test-compiled-openclaw-gateway.mts b/packaging/windows/app/test-compiled-openclaw-gateway.mts new file mode 100644 index 00000000000..6da5bcd0218 --- /dev/null +++ b/packaging/windows/app/test-compiled-openclaw-gateway.mts @@ -0,0 +1,1032 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// Bounded gateway/browser controls with a local provider; no GPU/MXC qualification. +import fs from "node:fs"; +import path from "node:path"; +import net from "node:net"; +import http from "node:http"; +import assert from "node:assert/strict"; +import { execFile, spawn } from "node:child_process"; +import { promisify } from "node:util"; +import { setTimeout as delay } from "node:timers/promises"; +import { createHash } from "node:crypto"; +import { once } from "node:events"; +import { DatabaseSync } from "node:sqlite"; +import { createRequire } from "node:module"; +import { Worker } from "node:worker_threads"; +import { + gatewayBrowserConsoleFailure, + gatewayBrowserMajorVersion, + gatewayBrowserRoute, + installGatewayBrowserRouteTrace, + readGatewayBrowserRouteTrace, + summarizeGatewayBrowserRouteTrace, + summarizeGatewayHello, +} from "./gateway-control-browser-diagnostics.mts"; +import { + gatewayDecisionAsset, + gatewayDecisionLogpoints, + observeGatewayDecisions, + type DecisionPage, +} from "./gateway-control-route-decisions.mts"; +import { + gatewayControlModelProviders, + isGatewayControlDiscoveryRequest, +} from "./gateway-control-model-fixture.mts"; + +async function archiveWorkerControl(appRoot: string, environment: NodeJS.ProcessEnv) { + const outcomes = []; + for (const operation of ["materialize", "publish", "invalid"]) { + const worker = new Worker( + path.join( + appRoot, + "node_modules/openclaw/dist/config/sessions/session-accessor.sqlite-archive.worker.js", + ), + { + env: environment, + execArgv: [], + workerData: { type: "sqlite-transcript-archive-v2", operation, plans: [] }, + }, + ); + const messages: unknown[] = []; + let failure: Error | undefined; + worker.on("message", (message) => messages.push(message)); + worker.on("error", (error) => { + failure = error instanceof Error ? error : new Error(String(error)); + }); + const exited = new Promise((resolve) => worker.once("exit", resolve)); + let expired = false; + const timeout = setTimeout(() => { + expired = true; + void worker.terminate(); + }, 15_000); + try { + const code = await exited; + assert.equal(expired, false, "The archive worker must finish within its bound."); + assert.equal(code, operation === "invalid" ? 1 : 0, failure?.message); + assert.deepEqual( + messages, + operation === "publish" ? [{ type: "published", results: [] }] : [], + ); + if (operation === "invalid") + assert.match(failure?.message ?? "", /requires a supported operation/); + else assert.equal(failure, undefined); + outcomes.push({ operation, exitCode: code }); + } finally { + clearTimeout(timeout); + await worker.terminate(); + } + } + return { outcomes, userArchivesReadOrWritten: false }; +} + +async function auditRecorderControl( + appRoot: string, + stateDir: string, + environment: NodeJS.ProcessEnv, +) { + fs.mkdirSync(stateDir); + const source = ` + (async () => { + const api = require(${JSON.stringify(path.join(appRoot, "openclaw-app.cjs"))}); + await api.registerPrebuiltPlugins({}); + const registry = globalThis[Symbol.for("nemoclaw.compiled-openclaw.plugins.v1")]; + const { t: createRecorder } = registry.load("node_modules/openclaw/dist/audit-recorder-BCaTSxYZ.js"); + const recorder = createRecorder({ stateDir: process.env.OPENCLAW_STATE_DIR, messageMode: "off" }); + process.once("message", async message => { + try { + if (message !== "record-and-stop") throw Error("Unexpected audit control message"); + recorder.recordTool({ type: "tool.execution.completed", seq: 1, ts: Date.now(), + agentId: "main", runId: "owned-audit-recorder-control", toolCallId: "call-1", + toolName: "owned-local-control" }); + await recorder.stop(); + process.send({ type: "stopped" }, () => process.disconnect()); + } catch (error) { + console.error(error); process.exitCode = 1; process.disconnect(); + } + }); + process.send({ type: "ready" }); + })().catch(error => { console.error(error); process.exitCode = 1; process.disconnect(); });`; + const child = spawn(process.execPath, ["--input-type=commonjs", "-e", source], { + env: { ...environment, OPENCLAW_STATE_DIR: stateDir, OPENCLAW_COMPILED_ASSET_ROOT: appRoot }, + stdio: ["ignore", "pipe", "pipe", "ipc"], + windowsHide: true, + }); + let closed = false; + let diagnostic = ""; + child.stdout!.on("data", (chunk: Buffer) => { + diagnostic = (diagnostic + chunk.toString("utf8")).slice(-8192); + }); + child.stderr!.on("data", (chunk: Buffer) => { + diagnostic = (diagnostic + chunk.toString("utf8")).slice(-8192); + }); + child.once("error", (error) => { + diagnostic = error.message; + }); + const exit = new Promise((resolve) => + child.once("close", (code) => { + closed = true; + resolve(code); + }), + ); + const message = () => + Promise.race([ + once(child, "message", { signal: AbortSignal.timeout(15_000) }), + exit.then((code) => { + throw new Error(`Audit recorder exited ${code} before acknowledgement: ${diagnostic}`); + }), + ]); + let failed = false; + let primary: unknown; + try { + assert.deepEqual((await message())[0], { type: "ready" }); + const stopped = message(); + child.send("record-and-stop"); + assert.deepEqual((await stopped)[0], { type: "stopped" }); + assert.equal( + await Promise.race([ + exit, + delay(15_000, undefined, { ref: false }).then(() => { + throw new Error("Audit recorder process did not exit after Stop."); + }), + ]), + 0, + diagnostic, + ); + const database = new DatabaseSync(path.join(stateDir, "state/openclaw.sqlite"), { + readOnly: true, + }); + let row; + try { + row = database + .prepare( + "select source_sequence,kind,action,status,agent_id,run_id,tool_name,tool_call_id from audit_events", + ) + .all(); + } finally { + database.close(); + } + assert.deepEqual( + row.map((item) => ({ ...item })), + [ + { + source_sequence: 1, + kind: "tool_action", + action: "tool.action.finished", + status: "succeeded", + agent_id: "main", + run_id: "owned-audit-recorder-control", + tool_name: "owned-local-control", + tool_call_id: "sha256:" + createHash("sha256").update("call-1").digest("hex"), + }, + ], + ); + return { + ready: true, + recorded: true, + stopped: true, + exitCode: 0, + persistedMetadataMatched: true, + implementation: "process-owned-upstream-recorder", + }; + } catch (error) { + failed = true; + primary = error; + throw error; + } finally { + if (!closed) { + try { + child.kill(); + await Promise.race([ + exit, + delay(5000, undefined, { ref: false }).then(() => { + throw new Error("Audit recorder process remained after failure cleanup."); + }), + ]); + } catch (cleanup) { + if (failed) + throw new AggregateError([primary, cleanup], "Audit recorder and cleanup failed."); + throw cleanup; + } + } + } +} +type BrowserLocator = { + count(): Promise; + first(): BrowserLocator; + filter(options: { hasText: string }): BrowserLocator; + getByRole(role: "button", options: { name: string; exact: boolean }): BrowserLocator; + waitFor(options: { state: "visible" | "hidden"; timeout: number }): Promise; + isEnabled(): Promise; + click(options?: { timeout: number }): Promise; + textContent(): Promise; +}; +type BrowserPage = DecisionPage & { + addInitScript(script: () => void): Promise; + evaluate(script: () => T): Promise; + url(): string; + on(event: "pageerror", listener: () => void): void; + on(event: "console", listener: (message: { type(): string; text(): string }) => void): void; + goto(url: string, options: { waitUntil: "domcontentloaded"; timeout: number }): Promise; + on( + event: "websocket", + listener: (socket: { + on( + event: "framesent" | "framereceived", + listener: (frame: { payload: string | Buffer }) => void, + ): void; + }) => void, + ): void; + locator(selector: string): BrowserLocator; + screenshot(options: { path: string }): Promise; +}; +async function inspectBraveConsent(appRoot: string, environment: NodeJS.ProcessEnv) { + const entry = path.join(appRoot, "openclaw-app.cjs"); + const source = `const entry=${JSON.stringify(entry)};process.argv=[process.execPath,entry,"plugins","inspect","brave","--runtime","--json"];require(entry).runCli(process.argv).catch(error=>{console.error(error);process.exitCode=1;});`; + const { stdout } = await promisify(execFile)(process.execPath, ["-e", source], { + cwd: appRoot, + env: environment, + timeout: 30_000, + maxBuffer: 2 * 1024 * 1024, + windowsHide: true, + }); + return JSON.parse(stdout) as { + install: { + source: string; + acceptedSurface?: { contracts: string[] }; + acceptedSurfaceHash?: string; + }; + diagnostics: { message: string }[]; + }; +} +async function browserControl( + appRoot: string, + origin: string, + directory: string, + executablePath: string, + firstRun: boolean, + pluginConsent: boolean, + environment: NodeJS.ProcessEnv, +) { + const playwright = createRequire(path.join(appRoot, "openclaw-app.cjs"))("playwright-core") as { + chromium: { + launch(options: { headless: boolean; executablePath: string; timeout: number }): Promise<{ + newPage(options: { viewport: { width: number; height: number } }): Promise; + version(): string; + close(): Promise; + }>; + }; + }; + const browser = await playwright.chromium.launch({ + headless: true, + executablePath, + timeout: 30_000, + }); + let failed = false; + let page: BrowserPage | undefined; + let decisionObserver: Awaited> | undefined; + const diagnostics = { + schemaVersion: 1, + browserMajorVersion: null as number | null, + firstRun, + sockets: 0, + pageErrors: 0, + consoleFailures: { + "application-start": 0, + "initial-location": 0, + "route-navigation": 0, + "gateway-snapshot": 0, + other: 0, + }, + helloResponses: 0, + lastHello: null as ReturnType, + detectionRequests: 0, + detectionResponses: 0, + verificationRequests: 0, + verificationResponses: 0, + navigation: null as ReturnType | null, + decisions: null as Awaited< + ReturnType>["finish"]> + > | null, + }; + const captureNavigation = async () => { + try { + return page + ? summarizeGatewayBrowserRouteTrace(await page.evaluate(readGatewayBrowserRouteTrace)) + : null; + } catch { + return null; + } + }; + try { + diagnostics.browserMajorVersion = gatewayBrowserMajorVersion(browser.version()); + page = await browser.newPage({ viewport: { width: 1280, height: 800 } }); + await page.addInitScript(installGatewayBrowserRouteTrace); + if (firstRun) { + decisionObserver = await observeGatewayDecisions( + page, + gatewayDecisionLogpoints( + fs.readFileSync( + path.join( + appRoot, + "node_modules/openclaw/dist/control-ui/assets", + gatewayDecisionAsset, + ), + "utf8", + ), + ), + ); + } + page.on("pageerror", () => diagnostics.pageErrors++); + page.on("console", (message) => { + if (message.type() !== "error") return; + const category = gatewayBrowserConsoleFailure(message.text()); + diagnostics.consoleFailures[category] = Math.min( + 64, + diagnostics.consoleFailures[category] + 1, + ); + }); + let detectionId: string | undefined; + let detection: + | { ok?: boolean; payload?: { setupComplete?: boolean }; error?: unknown } + | undefined; + let verificationId: string | undefined; + let verification: { ok?: boolean; payload?: { ok?: boolean; modelRef?: string } } | undefined; + page.on("websocket", (socket) => { + diagnostics.sockets++; + socket.on("framesent", (frame) => { + const message = JSON.parse(String(frame.payload)); + if (message.type === "req" && message.method === "openclaw.setup.detect") { + diagnostics.detectionRequests++; + detectionId = message.id; + } + if (message.type === "req" && message.method === "openclaw.setup.verify") { + diagnostics.verificationRequests++; + verificationId = message.id; + } + }); + socket.on("framereceived", (frame) => { + const message = JSON.parse(String(frame.payload)); + const hello = summarizeGatewayHello(message); + if (hello) { + diagnostics.helloResponses++; + diagnostics.lastHello = hello; + } + if (message.type === "res" && detectionId && message.id === detectionId) { + diagnostics.detectionResponses++; + detection = message; + } + if (message.type === "res" && verificationId && message.id === verificationId) { + diagnostics.verificationResponses++; + verification = message; + } + }); + }); + const route = firstRun ? "/chat" : "/settings/model-setup?firstRun=1"; + await page.goto(origin + route + "#token=owned-compiled-gateway-control-token", { + waitUntil: "domcontentloaded", + timeout: 90_000, + }); + if (firstRun) { + // The real dashboard must receive a successful worker-backed detection. + // No model is configured in this fixture, so conversation readiness stays false. + const deadline = performance.now() + 45_000; + while (!detection && performance.now() < deadline) await delay(100); + assert.equal(detection?.ok, true, "The dashboard model-detection RPC must succeed."); + assert.equal(detection?.payload?.setupComplete, false); + await page + .locator(".model-setup__intro") + .first() + .waitFor({ state: "visible", timeout: 10_000 }); + await page + .locator(".model-setup__manual") + .first() + .waitFor({ state: "visible", timeout: 10_000 }); + assert.equal(await page.locator(".model-setup__failure").count(), 0); + assert.equal( + await page.locator(".agent-chat__composer-combobox > textarea:enabled").count(), + 0, + ); + await page.screenshot({ path: path.join(directory, "compiled-model-setup.png") }); + diagnostics.navigation = await captureNavigation(); + if (pluginConsent) { + // All mutations belong to this disposable, credential-free Brave fixture. + // Cancellation must leave it disabled before a separate explicit acceptance. + const before = await inspectBraveConsent(appRoot, environment); + assert.equal(before.install.source, "path"); + assert.equal(before.install.acceptedSurface, undefined); + assert.equal(before.diagnostics.length, 1); + assert.match(before.diagnostics[0].message, /requires capability consent/); + await page.goto(origin + "/settings/plugins", { + waitUntil: "domcontentloaded", + timeout: 30_000, + }); + const row = page.locator('article[data-plugin-id="brave"]'); + await row.waitFor({ state: "visible", timeout: 30_000 }); + await row.getByRole("button", { name: "Disable", exact: true }).click(); + const enable = row.getByRole("button", { name: "Enable", exact: true }); + await enable.waitFor({ state: "visible", timeout: 30_000 }); + await enable.click(); + const consent = page.locator('.plugins-consent[data-plugin-consent="enable"]'); + // The dialog opens before its capability inspection finishes. + await consent + .filter({ hasText: "webSearchProviders: brave" }) + .waitFor({ state: "visible", timeout: 30_000 }); + assert.match((await consent.textContent()) ?? "", /webSearchProviders: brave/); + await page.screenshot({ path: path.join(directory, "compiled-plugin-consent.png") }); + await consent.getByRole("button", { name: "Cancel", exact: true }).click(); + await consent.waitFor({ state: "hidden", timeout: 10_000 }); + await enable.waitFor({ state: "visible", timeout: 10_000 }); + assert.equal( + (await inspectBraveConsent(appRoot, environment)).install.acceptedSurface, + undefined, + ); + await enable.click(); + await consent.waitFor({ state: "visible", timeout: 30_000 }); + await consent.getByRole("button", { name: "Enable Brave", exact: true }).click(); + await consent.waitFor({ state: "hidden", timeout: 30_000 }); + await row + .getByRole("button", { name: "Disable", exact: true }) + .waitFor({ state: "visible", timeout: 30_000 }); + const after = await inspectBraveConsent(appRoot, environment); + assert.equal(after.install.source, "path"); + assert(after.install.acceptedSurface?.contracts.includes("webSearchProviders: brave")); + assert.match(after.install.acceptedSurfaceHash ?? "", /^[a-f0-9]{64}$/); + assert.deepEqual(after.diagnostics, []); + } + return { + modelDetectionSucceeded: true, + setupComplete: false, + enabledComposer: false, + modelRequestSent: false, + ...(pluginConsent + ? { + pluginConsent: { + plugin: "brave", + cancelledThenExplicitlyAccepted: true, + acceptancePersisted: true, + diagnostics: [], + liveSearchTested: false, + }, + } + : {}), + }; + } + const composer = page.locator(".agent-chat__composer-combobox > textarea").first(); + await composer.waitFor({ state: "visible", timeout: 90_000 }); + assert.equal(detection?.ok, true, "Configured model detection must succeed."); + assert.equal(detection?.payload?.setupComplete, true); + assert.equal(verification?.ok, true, "The actual dashboard verification RPC must succeed."); + assert.equal( + verification?.payload?.ok, + true, + "The compiled runtime must verify the local provider.", + ); + assert.equal(verification?.payload?.modelRef, "nemoclawnative/fixture"); + const deadline = performance.now() + 30_000; + while (!(await composer.isEnabled()) && performance.now() < deadline) await delay(100); + assert.equal( + await composer.isEnabled(), + true, + "The actual published dashboard composer must become enabled.", + ); + await page.screenshot({ path: path.join(directory, "compiled-dashboard.png") }); + return { + visibleComposer: true, + enabledComposer: true, + modelRequestSent: true, + localProvider: true, + externalModelRequest: false, + modelVerificationSucceeded: true, + }; + } catch (error) { + failed = true; + try { + await page?.screenshot({ path: path.join(directory, "compiled-dashboard-failed.png") }); + } catch { + /* Keep the primary startup error if the browser cannot capture a frame. */ + } + throw error; + } finally { + try { + diagnostics.navigation ??= await captureNavigation(); + diagnostics.decisions = (await decisionObserver?.finish()) ?? null; + try { + fs.writeFileSync( + path.join(directory, "browser-control.json"), + JSON.stringify({ + ...diagnostics, + finalRoute: gatewayBrowserRoute(page?.url() ?? ""), + failed, + }), + { flag: "wx" }, + ); + } catch (error) { + if (!failed) throw error; + } + } finally { + try { + await browser.close(); + } catch (error) { + if (!failed) + throw error; /* Preserve the primary browser failure; this path never reports browser success. */ + } + } + } +} +function argument(name: string) { + const index = process.argv.indexOf(name); + if (index < 0 || !process.argv[index + 1]) throw new Error(`Missing ${name}`); + return path.resolve(process.argv[index + 1]); +} +const app = argument("--app-root"); +const output = argument("--output"); +const portable = process.argv.includes("--portable-proof"); +const withBrave = process.argv.includes("--with-brave"); +const browserSetupControl = process.argv.includes("--browser-setup-control"); +const browserPluginConsentControl = process.argv.includes("--browser-plugin-consent-control"); +const browserExecutable = process.argv.includes("--browser-executable") + ? argument("--browser-executable") + : undefined; +if (browserSetupControl && !browserExecutable) + throw new Error("The browser setup control requires a browser executable."); +if (browserPluginConsentControl && (!browserSetupControl || !withBrave)) + throw new Error( + "The plugin consent control requires the browser setup control and Brave fixture.", + ); +if ( + !portable && + (process.platform !== "win32" || process.arch !== "arm64" || process.versions.node !== "22.23.2") +) + throw new Error("The gateway control requires canonical Windows ARM64 Node 22.23.2."); +if (fs.existsSync(output)) throw new Error("Gateway evidence requires a fresh output directory."); +fs.mkdirSync(output, { recursive: true }); +const state = path.join(output, "state"); +fs.mkdirSync(state); +const receipt = JSON.parse( + fs.readFileSync(path.join(app, "openclaw-resource-closure.json"), "utf8"), +) as { + compiler: { mainSha256: string }; + files: { path: string; bytes: number; sha256: string; role: string }[]; +}; +const hash = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex"); +assert.equal( + hash(fs.readFileSync(path.join(app, "openclaw-app.cjs"))), + receipt.compiler.mainSha256, +); +const allocator = net.createServer(); +await new Promise((resolve, reject) => { + allocator.once("error", reject); + allocator.listen(0, "127.0.0.1", resolve); +}); +const port = (allocator.address() as net.AddressInfo).port; +await new Promise((resolve, reject) => + allocator.close((error) => (error ? reject(error) : resolve())), +); +const origin = `http://127.0.0.1:${port}`; +// A configured model must pass OpenClaw's real first-run verification before chat. +// Only the model endpoint is a fixture; the browser, gateway and verification are real. +const configuredModelControl = Boolean(browserExecutable && !browserSetupControl); +const modelEndpointControl = Boolean(browserExecutable); +const modelAllocator = net.createServer(); +let modelPort = 0; +if (modelEndpointControl) { + await new Promise((resolve, reject) => { + modelAllocator.once("error", reject); + modelAllocator.listen(0, "127.0.0.1", resolve); + }); + modelPort = (modelAllocator.address() as net.AddressInfo).port; + await new Promise((resolve, reject) => + modelAllocator.close((error) => (error ? reject(error) : resolve())), + ); +} +let modelRequests = 0; +let discoveryRequests = 0; +let modelError: unknown; +const modelServer = http.createServer(async (request, response) => { + try { + if (isGatewayControlDiscoveryRequest(request.method, request.url)) { + discoveryRequests++; + response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }); + response.end(JSON.stringify({ models: [] })); + return; + } + assert(configuredModelControl); + assert.equal(request.method, "POST"); + assert.equal(request.url, "/v1/chat/completions"); + assert.equal(request.headers.authorization, "Bearer owned-local-model-control"); + const chunks: Buffer[] = []; + let bytes = 0; + for await (const chunk of request) { + bytes += chunk.length; + assert(bytes <= 1024 * 1024); + chunks.push(chunk); + } + const body = JSON.parse(Buffer.concat(chunks).toString("utf8")); + assert.equal(body.model, "fixture"); + assert.equal(body.stream, true); + assert( + JSON.stringify(body.messages).includes("Reply with the single word OK. Do not use tools."), + ); + assert(++modelRequests <= 3, "The bounded verification must not loop."); + response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store" }); + for (const [delta, finish_reason] of [ + [{ role: "assistant", content: "OK" }, null], + [{}, "stop"], + ]) { + response.write( + "data: " + + JSON.stringify({ + id: "owned-model-verification", + object: "chat.completion.chunk", + created: Math.floor(Date.now() / 1000), + model: "fixture", + choices: [{ index: 0, delta, finish_reason }], + }) + + "\n\n", + ); + } + response.end("data: [DONE]\n\n"); + } catch (error) { + modelError ??= error; + response.writeHead(500); + response.end("Controlled model rejected request"); + } +}); +modelServer.requestTimeout = 15_000; +const inherited: NodeJS.ProcessEnv = {}; +for (const name of [ + "SystemRoot", + "SystemDrive", + "WINDIR", + "ComSpec", + "PATH", + "PATHEXT", + "OS", + "PROCESSOR_ARCHITECTURE", + "ProgramFiles", + "ProgramFiles(x86)", + "ProgramW6432", + "LANG", + "LC_ALL", + "TMPDIR", + "TEMP", + "TMP", +]) { + const key = Object.keys(process.env).find((key) => key.toLowerCase() === name.toLowerCase()); + if (key) inherited[key] = process.env[key]; +} +const env: NodeJS.ProcessEnv = { + ...inherited, + HOME: state, + USERPROFILE: state, + LOCALAPPDATA: state, + APPDATA: state, + OPENCLAW_STATE_DIR: state, + OPENCLAW_HOME: state, + OPENCLAW_COMPILED_ASSET_ROOT: app, + OPENCLAW_NO_RESPAWN: "1", + NODE_DISABLE_COMPILE_CACHE: "1", + OPENCLAW_GATEWAY_STARTUP_TRACE: "1", +}; +const systemRoot = Object.entries(inherited).find( + ([name]) => name.toUpperCase() === "SYSTEMROOT", +)?.[1]; +if (process.platform === "win32" && !systemRoot) + throw new Error("Windows controls require the owned SystemRoot."); +env.PATH = [ + path.dirname(process.execPath), + ...(systemRoot ? [path.join(systemRoot, "System32"), systemRoot] : ["/usr/bin", "/bin"]), +].join(path.delimiter); +delete env.NODE_OPTIONS; +delete env.NODE_PATH; +fs.writeFileSync( + path.join(state, "openclaw.json"), + JSON.stringify({ + gateway: { + mode: "local", + bind: "loopback", + port, + auth: { mode: "token", token: "owned-compiled-gateway-control-token" }, + terminal: { enabled: false }, + controlUi: { + root: path.join(app, "node_modules/openclaw/dist/control-ui"), + allowedOrigins: [origin], + }, + }, + update: { checkOnStart: false, auto: { enabled: false } }, + agents: { + list: [{ id: "main", default: true }], + defaults: { + skipBootstrap: true, + workspace: path.join(output, "workspace"), + ...(configuredModelControl + ? { model: { primary: "nemoclawnative/fixture" }, thinkingDefault: "off" } + : {}), + }, + }, + ...(modelEndpointControl + ? { + models: { + mode: "merge", + providers: gatewayControlModelProviders(modelPort, configuredModelControl), + }, + } + : {}), + ...(withBrave + ? { + plugins: { + load: { paths: [path.join(app, "plugins/brave")] }, + entries: { brave: { enabled: true } }, + }, + } + : {}), + logging: { file: path.join(output, "gateway.jsonl") }, + }), + { flag: "wx" }, +); +const started = performance.now(); +// Owned CI supervisor calls the public compiled API. IPC delivers the same in-process +// shutdown signal on Windows, where ChildProcess.kill cannot run JS signal cleanup. +const driver = path.join(output, "gateway-driver.cjs"); +fs.writeFileSync( + driver, + `const entry=process.argv[2];process.argv=[process.execPath,entry,...process.argv.slice(3)]; +process.on("message",message=>{if(message==="owned-gateway-stop")process.emit("SIGTERM");}); +const api=require(entry);Promise.resolve(${withBrave ? 'api.registerPrebuiltPlugins(JSON.parse(require("node:fs").readFileSync(require("node:path").join(process.env.OPENCLAW_STATE_DIR,"openclaw.json"),"utf8")))' : "undefined"}).then(()=>api.runCli(process.argv)).catch(error=>{console.error(error);process.exitCode=1;});\n`, + { flag: "wx" }, +); +const child = spawn( + process.execPath, + [ + driver, + path.join(app, "openclaw-app.cjs"), + "gateway", + "run", + "--allow-unconfigured", + "--bind", + "loopback", + "--port", + String(port), + ], + { cwd: app, env, stdio: ["ignore", "pipe", "pipe", "ipc"] }, +); +let stdout = "", + stderr = "", + closed = false, + spawnError: Error | undefined; +const exit = new Promise((resolve) => { + child.once("error", (error) => { + spawnError = error; + }); + child.once("close", (code) => { + closed = true; + resolve(code); + }); +}); +assert.ok(child.stdout && child.stderr, "Owned gateway output pipes must be present."); +child.stdout.on("data", (bytes: Buffer) => { + stdout = (stdout + bytes.toString("utf8")).slice(-2 * 1024 * 1024); +}); +child.stderr.on("data", (bytes: Buffer) => { + stderr = (stderr + bytes.toString("utf8")).slice(-2 * 1024 * 1024); +}); +const result: Record = { + schemaVersion: 1, + classification: "compiled-openclaw-gateway-resource-control", + platform: process.platform, + architecture: process.arch, + nodeVersion: process.versions.node, + portableProof: portable, + codeSha256: receipt.compiler.mainSha256, + modelRequestSent: false, + browserObserved: false, + windowsQualified: false, +}; +let primary: unknown; +let failed = false; +try { + if (modelEndpointControl) + await new Promise((resolve, reject) => { + modelServer.once("error", reject); + modelServer.listen(modelPort, "127.0.0.1", resolve); + }); + let healthy = false; + while (!closed && performance.now() - started < 45_000) { + try { + const response = await fetch(`${origin}/health`, { signal: AbortSignal.timeout(1_000) }); + if (response.status === 200) { + assert.equal(((await response.json()) as { ok: boolean }).ok, true); + healthy = true; + break; + } + } catch { + /* The real listener is not present during bounded startup. */ + } + await delay(100); + } + if (spawnError) throw spawnError; + assert.equal(healthy, true, "The compiled gateway must become healthy within the control bound."); + result.healthMs = performance.now() - started; + const page = await fetch(`${origin}/chat`, { + headers: { Accept: "text/html" }, + signal: AbortSignal.timeout(5_000), + }); + assert.equal(page.status, 200); + const html = await page.text(); + assert.match(html, / file.role === "control-ui"); + assert.ok(ui.length > 100, "The canonical published frontend resources must be inventoried."); + let resourceBytes = 0; + const resourceProgress = { + files: ui.length, + completed: 0, + resource: "", + expectedBytes: 0, + stage: "fetch", + }; + result.uiResourceProgress = resourceProgress; + for (const file of ui) { + assert(file.path.startsWith("node_modules/openclaw/dist/control-ui/")); + const relative = file.path.slice("node_modules/openclaw/dist/control-ui/".length); + resourceProgress.resource = relative; + resourceProgress.expectedBytes = file.bytes; + resourceProgress.stage = "fetch"; + const response = await fetch( + `${origin}/${relative.split("/").map(encodeURIComponent).join("/")}`, + { signal: AbortSignal.timeout(5_000) }, + ); + assert.equal(response.status, 200, `Published UI resource must be served: ${relative}`); + resourceProgress.stage = "body"; + const content = Buffer.from(await response.arrayBuffer()); + resourceProgress.stage = "integrity"; + if (relative === "index.html") { + const original = fs.readFileSync(path.join(app, file.path)); + assert.equal(hash(original), file.sha256); + // 9.2 anchors asset links and replaces document settings. This fixture uses + // an explicit root (not a bundled root), no base path/environment, and no terminal. + let expected = original + .toString("utf8") + .replaceAll('src="./assets/', 'src="/assets/') + .replaceAll('href="./assets/', 'href="/assets/'); + for (const asset of [ + "apple-touch-icon.png", + "favicon-32.png", + "favicon.ico", + "favicon.svg", + "manifest.webmanifest", + "sw.js", + ]) + expected = expected.replaceAll(`href="./${asset}"`, `href="/${asset}"`); + expected = expected.replace(/]*>/i, (tag) => + tag + .replace(/\sdata-openclaw-control-ui-build-id="[^"]*"/g, "") + .replace( + / line.includes("http server listening (") && line.includes(" plugins:")); + assert.ok(pluginLine, "Actual plugin registration must be reported."); + const match = /\((\d+) plugins: ([^;]+);/.exec(pluginLine); + assert.ok(match); + const plugins = match[2].split(", "); + for (const required of [ + "browser", + "canvas", + "cua-computer", + "device-pair", + "file-transfer", + "geolocation", + "linux-node", + "memory-core", + "ollama", + "talk-voice", + ]) + assert.ok(plugins.includes(required), `Canonical active plugin required: ${required}`); + if (withBrave) { + // 9.2 defers Brave until use. test-prebuilt-choice-plugins.mts owns actual + // runtime registration, persisted installation and fresh-process convergence. + const manifest = JSON.parse( + fs.readFileSync(path.join(app, "plugins/brave/openclaw.plugin.json"), "utf8"), + ); + assert.equal(manifest.activation.onStartup, false); + assert.equal( + plugins.includes("brave"), + false, + "Brave must retain upstream deferred activation.", + ); + } + result.brave = { + requested: withBrave, + observed: plugins.includes("brave"), + liveSearchTested: false, + }; + result.plugins = plugins; + assert.doesNotMatch( + stdout + stderr, + /failed to load plugin|failed to start audit|Cannot find (?:module|package)|Control UI assets are missing|building.*Control UI/i, + ); + const trace = fs + .readFileSync(path.join(output, "gateway.jsonl"), "utf8") + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as { message?: string }) + .map((line) => line.message ?? "") + .find((line) => line.startsWith("startup trace: plugins.gateway-load ")); + assert.ok(trace, "The actual canonical plugin loader counters must be retained."); + assert.match(trace, /loaderNativeMissesCount=0\.0(?: |$)/); + assert.match(trace, /loaderSourceTransformForcedCount=0\.0(?: |$)/); + assert.match(trace, /loaderSourceTransformFallbacksCount=0\.0(?: |$)/); + result.pluginLoaderTrace = trace; + result.auditRecorder = await auditRecorderControl( + app, + path.join(output, "audit-recorder-state"), + env, + ); + result.archiveWorker = await archiveWorkerControl(app, env); + if (browserExecutable) { + result.browser = await browserControl( + app, + origin, + output, + browserExecutable, + browserSetupControl, + browserPluginConsentControl, + env, + ); + result.browserObserved = true; + if (modelError) throw modelError; + if (configuredModelControl) { + assert(modelRequests > 0, "Browser readiness requires an actual local model request."); + result.modelRequestSent = true; + } + } + result.gatewayObserved = true; +} catch (error) { + failed = true; + primary = error; +} finally { + modelServer.closeAllConnections(); + if (modelServer.listening) + await new Promise((resolve) => modelServer.close(() => resolve())); + result.localModelVerificationRequests = modelRequests; + result.localModelDiscoveryRequests = discoveryRequests; + result.modelRequestSent = modelRequests > 0; + result.externalModelRequest = false; + if (modelError) + result.localModelError = modelError instanceof Error ? modelError.message : String(modelError); + if (!closed && child.connected) + child.send("owned-gateway-stop", (error) => { + if (error && !closed) child.kill(); + }); + let forced = false; + const force = setTimeout(() => { + if (!closed) { + forced = true; + child.kill("SIGKILL"); + } + }, 10_000); + result.exitCode = await exit; + clearTimeout(force); + result.cleanup = { ownedProcessExited: closed, forced }; + result.elapsedMs = performance.now() - started; + result.passed = !failed && result.exitCode === 0 && !forced; + if (failed) + result.primaryError = + primary instanceof Error ? primary.message : "Gateway control threw a non-Error value."; + fs.writeFileSync(path.join(output, "stdout.log"), stdout, { flag: "wx" }); + fs.writeFileSync(path.join(output, "stderr.log"), stderr, { flag: "wx" }); + fs.writeFileSync( + path.join(output, "gateway-control.json"), + JSON.stringify(result, null, 2) + "\n", + { flag: "wx" }, + ); +} +if (failed) throw primary; +assert.equal(result.passed, true, "Gateway control and owned graceful exit must both pass."); +console.log(JSON.stringify(result)); diff --git a/packaging/windows/app/test-compiled-openclaw-migration.mts b/packaging/windows/app/test-compiled-openclaw-migration.mts new file mode 100644 index 00000000000..e84c0a9d9a4 --- /dev/null +++ b/packaging/windows/app/test-compiled-openclaw-migration.mts @@ -0,0 +1,184 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { migrateNativeOpenClawSessions } from "../runtime/native-openclaw-migration.mts"; + +function argument(name: string) { + const index = process.argv.indexOf(name); + if (index < 0 || !process.argv[index + 1]) throw new Error(`Missing ${name}`); + return path.resolve(process.argv[index + 1]); +} +const app = argument("--app-root"); +const runtimeRoot = argument("--runtime-root"); +const output = argument("--output"); +const portable = process.argv.includes("--portable-proof"); +if ( + !portable && + (process.platform !== "win32" || process.arch !== "arm64" || process.versions.node !== "22.23.2") +) + throw new Error("Compiled migration controls require the canonical Windows ARM64 Node."); +assert.equal(fs.existsSync(output), false, "Migration control output must be fresh."); +const home = path.join(output, "synthetic-home"); +const sessions = path.join(home, ".openclaw", "agents", "main", "sessions"); +const entry = path.join(app, "openclaw-app.cjs"); +const worker = path.join(runtimeRoot, "workers", "openclaw-migrate.cjs"); +const hash = (file: string) => createHash("sha256").update(fs.readFileSync(file)).digest("hex"); +const appSha256 = hash(entry); +const workerSha256 = hash(worker); +const sessionId = "compiled-migration-history"; +const sessionKey = "agent:main:main"; +const timestamp = "2026-10-11T12:00:00.000Z"; +const transcript = path.join(sessions, `${sessionId}.jsonl`); +const store = path.join(sessions, "sessions.json"); +const events = [ + { type: "session", version: 3, id: sessionId, timestamp, cwd: home }, + { + type: "message", + id: "user-1", + parentId: null, + timestamp, + message: { + role: "user", + content: [{ type: "text", text: "retained user turn" }], + timestamp: Date.parse(timestamp), + }, + }, + { + type: "message", + id: "assistant-1", + parentId: "user-1", + timestamp, + message: { + role: "assistant", + content: [{ type: "text", text: "retained assistant turn" }], + api: "openai-completions", + provider: "synthetic", + model: "synthetic", + stopReason: "stop", + timestamp: Date.parse(timestamp), + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + }, + }, +]; +const originalTranscript = events.map((event) => JSON.stringify(event)).join("\n") + "\n"; +const originalStore = JSON.stringify({ + [sessionKey]: { sessionId, sessionFile: transcript, updatedAt: Date.parse(timestamp) }, +}); + +function filesBelow(directory: string): string[] { + return fs.readdirSync(directory, { withFileTypes: true }).flatMap((item) => { + assert.equal(item.isSymbolicLink(), false); + const file = path.join(directory, item.name); + if (item.isDirectory()) return filesBelow(file); + assert(item.isFile()); + return [file]; + }); +} + +const result = { + schemaVersion: 1, + classification: "compiled-openclaw-session-migration-controls", + platform: process.platform, + architecture: process.arch, + nodeVersion: process.version, + portableProof: portable, + appSha256, + workerSha256, + passed: false, + originalArchivesPreserved: false, + importedEvents: 0, + repeatSkipped: false, + syntheticStateRemoved: false, + // The caller owns this fresh fixture. Named-mutex and installed acceptance + // remain separate Windows tests; this check exercises the actual importer. + installedAcceptance: false, + nativeStateOwnershipProven: false, +}; +fs.mkdirSync(output, { recursive: true }); +try { + fs.mkdirSync(sessions, { recursive: true }); + fs.writeFileSync(transcript, originalTranscript, { flag: "wx" }); + fs.writeFileSync(store, originalStore, { flag: "wx" }); + const options = { home, entry, runtimeRoot, node: process.execPath, assertHeld() {} }; + assert.equal(await migrateNativeOpenClawSessions(options), true); + assert.equal(fs.existsSync(store), false); + assert.equal(fs.existsSync(transcript), false); + const archives = filesBelow(path.join(path.dirname(sessions), "session-sqlite-import-archive")); + const stores = archives.filter((file) => + path.basename(file).startsWith("legacy-store.sessions.json.imported-"), + ); + assert.equal(stores.length, 1); + assert.equal(fs.readFileSync(stores[0], "utf8"), originalStore); + assert.equal( + archives.filter((file) => fs.readFileSync(file, "utf8") === originalTranscript).length, + 1, + ); + result.originalArchivesPreserved = true; + const agentDatabases = filesBelow(path.join(home, ".openclaw")).filter((file) => { + if (!file.endsWith(".sqlite")) return false; + const db = new DatabaseSync(file, { readOnly: true }); + try { + return Boolean( + db + .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='session_nodes'") + .get(), + ); + } finally { + db.close(); + } + }); + assert.equal(agentDatabases.length, 1); + const db = new DatabaseSync(agentDatabases[0], { readOnly: true }); + try { + assert.equal( + db + .prepare("SELECT current_session_id FROM session_nodes WHERE session_key = ?") + .get(sessionKey)?.current_session_id, + sessionId, + ); + const imported = db + .prepare("SELECT event_json FROM transcript_events WHERE session_id = ? ORDER BY seq") + .all(sessionId) + .map((row) => JSON.parse(String(row.event_json))); + assert.deepEqual(imported, events); + result.importedEvents = imported.length; + assert.equal(Object.values(db.prepare("PRAGMA integrity_check").get()!)[0], "ok"); + } finally { + db.close(); + } + assert.equal(await migrateNativeOpenClawSessions(options), false); + result.repeatSkipped = true; + assert.equal(hash(entry), appSha256); + assert.equal(hash(worker), workerSha256); + result.passed = true; +} finally { + try { + fs.rmSync(home, { recursive: true, force: true }); + assert.equal(fs.existsSync(home), false); + result.syntheticStateRemoved = true; + } catch (error) { + result.passed = false; + throw error; + } finally { + fs.writeFileSync( + path.join(output, "migration-controls.json"), + JSON.stringify(result, null, 2) + "\n", + { flag: "wx" }, + ); + } +} +console.log( + "PASS: compiled importer preserves chat history and original archives, then skips repeated migration.", +); diff --git a/packaging/windows/app/test-compiled-openclaw-model-tools.mts b/packaging/windows/app/test-compiled-openclaw-model-tools.mts new file mode 100644 index 00000000000..198d8131749 --- /dev/null +++ b/packaging/windows/app/test-compiled-openclaw-model-tools.mts @@ -0,0 +1,316 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// CI-only dependency/transport smoke. Local deterministic provider; no external key/service. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import fs from "node:fs"; +import http from "node:http"; +import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; +function javascriptStringLiteral(value: string) { + return JSON.stringify(value).replace( + /[<>/\u2028\u2029]/gu, + (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`, + ); +} +function argument(name: string) { + const offset = process.argv.indexOf(name); + assert(offset >= 0 && process.argv[offset + 1]); + return path.resolve(process.argv[offset + 1]); +} +const app = argument("--app-root"), + output = argument("--output"); +assert(!fs.existsSync(output)); +fs.mkdirSync(output, { recursive: true }); +const state = path.join(output, "state"), + workspace = path.join(output, "workspace"); +fs.mkdirSync(state); +fs.mkdirSync(workspace); +const nonce = randomBytes(10).toString("hex"), + marker = "COMPILED_TRANSPORT_" + nonce, + token = "owned-local-provider-" + nonce; +const file = path.join(workspace, "controlled.txt"); +const shellCommand = + process.platform === "win32" ? `Write-Output 'SHELL_${nonce}'` : `printf '%s' 'SHELL_${nonce}'`; +const codeCommand = + process.platform === "win32" + ? `& '${process.execPath.replaceAll("'", "''")}' -e "process.stdout.write('CODE_${nonce}:'+String(6*7))"` + : `'${process.execPath.replaceAll("'", "'\\''")}' -e 'process.stdout.write("CODE_${nonce}:"+String(6*7))'`; +const calls = [ + { name: "write", args: { path: file, content: nonce }, expect: "" }, + { name: "read", args: { path: file }, expect: nonce }, + { name: "exec", args: { command: shellCommand, timeoutSeconds: 10 }, expect: "SHELL_" + nonce }, + { + name: "exec", + args: { command: codeCommand, timeoutSeconds: 10 }, + expect: "CODE_" + nonce + ":42", + }, +]; +const observations: { path: string; model: string; toolResults: unknown[] }[] = []; +let serverError: unknown; +const server = http.createServer(async (request, response) => { + try { + const chunks: Buffer[] = []; + let bytes = 0; + for await (const chunk of request) { + bytes += chunk.length; + assert(bytes <= 1024 * 1024); + chunks.push(chunk); + } + assert.equal(request.url, "/v1/chat/completions"); + assert.equal(request.headers.authorization, "Bearer " + token); + const body = JSON.parse(Buffer.concat(chunks).toString()); + assert.equal(body.model, "fixture"); + assert.equal(body.stream, true); + const results = body.messages.filter((message: { role: string }) => message.role === "tool"); + observations.push({ path: request.url!, model: body.model, toolResults: results }); + assert(observations.length <= 5); + if (results.length) { + const prior = calls[results.length - 1]; + assert(prior); + const text = JSON.stringify(results.at(-1)); + assert(!/"isError"\s*:\s*true/.test(text)); + if (prior.expect) + assert(text.includes(prior.expect), "The actual tool output differs: " + prior.name); + } + const next = calls[results.length]; + const delta = next + ? { + role: "assistant", + tool_calls: [ + { + index: 0, + id: "call_" + results.length, + type: "function", + function: { name: next.name, arguments: JSON.stringify(next.args) }, + }, + ], + } + : { role: "assistant", content: marker }; + response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store" }); + for (const [payload, finish] of [ + [delta, null], + [{}, next ? "tool_calls" : "stop"], + ] as const) + response.write( + "data: " + + JSON.stringify({ + id: "chatcmpl-" + nonce, + object: "chat.completion.chunk", + created: Math.floor(Date.now() / 1000), + model: "fixture", + choices: [{ index: 0, delta: payload, finish_reason: finish }], + }) + + "\n\n", + ); + response.end("data: [DONE]\n\n"); + } catch (error) { + serverError ??= error; + response.writeHead(500); + response.end("controlled provider rejected request"); + } +}); +await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); +const port = (server.address() as { port: number }).port; +const config = { + update: { checkOnStart: false, auto: { enabled: false } }, + models: { + mode: "merge", + providers: { + nemoclawNative: { + baseUrl: `http://127.0.0.1:${port}/v1`, + apiKey: token, + api: "openai-completions", + models: [ + { + id: "fixture", + name: "fixture", + reasoning: false, + input: ["text"], + contextWindow: 131072, + maxTokens: 4096, + }, + ], + }, + }, + }, + agents: { + defaults: { + workspace, + // Fresh workspace bootstrap must consume the packaged templates. + skipBootstrap: false, + model: { primary: "nemoclawNative/fixture" }, + thinkingDefault: "off", + }, + list: [{ id: "main", default: true }], + }, + tools: { exec: { security: "full", ask: "off" } }, + gateway: { mode: "local" }, +}; +fs.writeFileSync(path.join(state, "openclaw.json"), JSON.stringify(config)); +const entry = path.join(app, "openclaw-app.cjs"), + driver = path.join(output, "driver.cjs"); +fs.writeFileSync( + driver, + `const cp=require("node:child_process"),fs=require("node:fs"),Module=require("node:module");const loaded=new Set();const originalLoad=Module._load;Module._load=function(request,...rest){const value=originalLoad.call(this,request,...rest);if(request==="undici")loaded.add(value);return value;};for(const name of ["spawn","spawnSync","execFile","execFileSync"]){const original=cp[name];cp[name]=function(...args){if(/(?:npm|npx|pnpm|yarn|pip)(?:\\b|[-.])/i.test(JSON.stringify(args.slice(0,2)))){fs.writeFileSync(${javascriptStringLiteral(path.join(output, "package-manager-attempt"))},name);throw Error("Unexpected package-manager invocation");}return original.apply(this,args);};}Module.syncBuiltinESMExports();process.on("exit",()=>fs.writeFileSync(${javascriptStringLiteral(path.join(output, "undici-instances.json"))},JSON.stringify({instances:loaded.size})));const entry=${javascriptStringLiteral(entry)};process.argv=[process.execPath,entry,"agent","--local","--agent","main","--session-id",${javascriptStringLiteral(nonce)},"--message",${javascriptStringLiteral("Run the controlled test tools then reply " + marker)},"--json"];require(entry).runCli(process.argv).catch(error=>{console.error(error);process.exitCode=1;});`, +); +const env: NodeJS.ProcessEnv = {}; +for (const [key, value] of Object.entries(process.env)) + if ( + [ + "systemroot", + "windir", + "systemdrive", + "comspec", + "path", + "pathext", + "temp", + "tmp", + "programfiles", + "programfiles(x86)", + "os", + "processor_architecture", + "lang", + "lc_all", + "tmpdir", + ].includes(key.toLowerCase()) + ) + env[key] = value; +Object.assign(env, { + HOME: state, + USERPROFILE: state, + LOCALAPPDATA: state, + APPDATA: state, + OPENCLAW_STATE_DIR: state, + OPENCLAW_HOME: state, + OPENCLAW_COMPILED_ASSET_ROOT: app, + OPENCLAW_NO_RESPAWN: "1", + OPENCLAW_SKIP_CHANNELS: "1", + OPENCLAW_NO_AUTO_UPDATE: "1", + NODE_DISABLE_COMPILE_CACHE: "1", +}); +const systemRoot = Object.entries(env).find(([name]) => name.toUpperCase() === "SYSTEMROOT")?.[1]; +env.PATH = [ + path.dirname(process.execPath), + ...(systemRoot ? [path.join(systemRoot, "System32"), systemRoot] : ["/usr/bin", "/bin"]), +].join(path.delimiter); +const child = spawn(process.execPath, [driver], { + cwd: workspace, + env, + stdio: ["ignore", "pipe", "pipe"], +}); +let stdout = "", + stderr = "", + closed = false; +const completion = new Promise((resolve) => + child.once("close", (code) => { + closed = true; + resolve(code); + }), +); +child.stdout!.on("data", (chunk) => { + stdout += chunk; + if (stdout.length > 2 * 1024 * 1024) child.kill(); +}); +child.stderr!.on("data", (chunk) => { + stderr += chunk; + if (stderr.length > 2 * 1024 * 1024) child.kill(); +}); +const timer = setTimeout(() => child.kill(), 90000); +let primary: unknown; +let code: number | null = null; +try { + code = await completion; + assert.equal(code, 0); + if (serverError) throw serverError; + assert.equal(observations.length, 5); + const reply = JSON.parse(stdout); + assert.equal(reply.payloads?.[0]?.text, marker); + for (const name of ["AGENTS.md", "SOUL.md", "IDENTITY.md", "USER.md"]) { + const template = fs.statSync(path.join(workspace, name)); + assert(template.isFile() && template.size > 0, "Workspace bootstrap must publish " + name); + } + // Read the actual persisted transcript, not the provider's copy of tool output. + // OpenClaw 2026.9.2 stores agent transcripts in SQLite instead of JSONL. + const database = new DatabaseSync( + path.join(state, "agents", "main", "agent", "openclaw-agent.sqlite"), + { readOnly: true, allowExtension: false }, + ); + let transcript; + try { + const rows = database + .prepare("SELECT seq, event_json FROM transcript_events WHERE session_id = ? ORDER BY seq") + .all(nonce); + assert(rows.length > 0, "The controlled session must have a persisted transcript."); + const events = rows.map((row, index) => { + assert.equal(row.seq, index, "The transcript must have no missing or reordered events."); + assert.equal(typeof row.event_json, "string"); + return JSON.parse(row.event_json as string); + }); + assert.equal(events[0].type, "session"); + assert.equal(events[0].id, nonce); + transcript = events.map((event) => event.message).filter(Boolean); + } finally { + database.close(); + } + const results = transcript.filter((message) => message.role === "toolResult"); + assert.equal(results.length, calls.length); + for (const [index, result] of results.entries()) { + assert.equal(result.toolName, calls[index].name); + assert.equal(result.isError, false); + if (calls[index].name === "exec") { + assert.equal(result.details?.status, "completed"); + assert.equal(result.details?.exitCode, 0); + } + if (calls[index].expect) assert(JSON.stringify(result.content).includes(calls[index].expect)); + } + assert.equal(fs.readFileSync(file, "utf8"), nonce); + assert(!fs.existsSync(path.join(output, "package-manager-attempt"))); + assert.equal( + JSON.parse(fs.readFileSync(path.join(output, "undici-instances.json"), "utf8")).instances, + 1, + ); +} catch (error) { + primary = error; +} finally { + clearTimeout(timer); + if (!closed) { + child.kill(); + await completion; + } + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + fs.writeFileSync(path.join(output, "stdout.log"), stdout.split(token).join("[REDACTED]")); + fs.writeFileSync(path.join(output, "stderr.log"), stderr.split(token).join("[REDACTED]")); + fs.writeFileSync( + path.join(output, "result.json"), + JSON.stringify( + { + schemaVersion: 1, + classification: "compiled-openclaw-local-provider-tool-control", + verdict: primary ? "fail" : "pass", + exitCode: code, + requests: observations.length, + tools: ["write", "read", "shell", "node-code"], + workspaceBootstrapRequired: true, + transcriptStorage: "agent-sqlite", + singleUndiciInstance: fs.existsSync(path.join(output, "undici-instances.json")) + ? JSON.parse(fs.readFileSync(path.join(output, "undici-instances.json"), "utf8")) + : null, + error: primary instanceof Error ? primary.message : null, + localProvider: true, + externalModelRequest: false, + fixtureExecAuthorized: true, + shippingPolicyQualified: false, + containedWindowsQualified: false, + }, + null, + 2, + ) + "\n", + ); +} +if (primary) throw primary; +console.log( + "PASS actual compiled local inference, file read/write, shell and Node code; one Undici instance.", +); diff --git a/packaging/windows/app/test-compiled-openclaw.mts b/packaging/windows/app/test-compiled-openclaw.mts new file mode 100644 index 00000000000..94c7dbbdd5f --- /dev/null +++ b/packaging/windows/app/test-compiled-openclaw.mts @@ -0,0 +1,222 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { Worker } from "node:worker_threads"; +function argument(name: string) { + const index = process.argv.indexOf(name); + if (index < 0 || !process.argv[index + 1]) throw new Error(`Missing ${name}`); + return path.resolve(process.argv[index + 1]); +} +function readSealedFile(file: string, expectedBytes: number) { + const descriptor = fs.openSync(file, "r"); + try { + const opened = fs.fstatSync(descriptor); + const named = fs.lstatSync(file); + assert( + opened.isFile() && + opened.nlink === 1 && + named.isFile() && + !named.isSymbolicLink() && + named.dev === opened.dev && + named.ino === opened.ino && + opened.size === expectedBytes, + ); + return fs.readFileSync(descriptor); + } finally { + fs.closeSync(descriptor); + } +} +const inputApp = argument("--app-root"); +const output = argument("--output"); +const portable = process.argv.includes("--portable-proof"); +if ( + !portable && + (process.platform !== "win32" || process.arch !== "arm64" || process.versions.node !== "22.23.2") +) + throw new Error("Compiled app controls require the canonical Windows ARM64 Node."); +assert.equal(fs.existsSync(output), false, "Control output must be fresh."); +fs.mkdirSync(output, { recursive: true }); +const app = path.join(output, "isolated-code-unit"); +fs.mkdirSync(app); +const receipt = JSON.parse( + fs.readFileSync(path.join(inputApp, "openclaw-resource-closure.json"), "utf8"), +) as { + files: { path: string; bytes: number; sha256: string }[]; +}; +const selected = receipt.files.filter( + (row) => + ["openclaw-app.cjs", "openclaw-dynamic-import.cjs"].includes(row.path) || + row.path.startsWith("node_modules/undici/") || + row.path.startsWith("node_modules/ws/") || + row.path.startsWith("node_modules/@openclaw/fs-safe/"), +); +assert(selected.some((row) => row.path === "node_modules/undici/package.json")); +assert(selected.some((row) => row.path === "node_modules/ws/package.json")); +// 9.2 initializes fs-safe/config before the CLI. Keep its state shared with the +// remaining external fs-safe modules; bundling only config would split that state. +assert(selected.some((row) => row.path === "node_modules/@openclaw/fs-safe/package.json")); +for (const row of selected) { + assert( + !row.path.includes("\\") && + !row.path.includes(":") && + row.path.split("/").every((part) => part && part !== "." && part !== ".."), + ); + const source = path.join(inputApp, row.path), + target = path.join(app, row.path); + const bytes = readSealedFile(source, row.bytes); + assert.equal(createHash("sha256").update(bytes).digest("hex"), row.sha256); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, bytes, { flag: "wx" }); +} +assert.deepEqual(fs.readdirSync(path.join(app, "node_modules")).sort(), [ + "@openclaw", + "undici", + "ws", +]); +assert.deepEqual(fs.readdirSync(path.join(app, "node_modules", "@openclaw")), ["fs-safe"]); +const state = path.join(output, "state"); +fs.mkdirSync(state); +const entry = path.join(app, "openclaw-app.cjs"); +const env: NodeJS.ProcessEnv = {}; +for (const name of [ + "SystemRoot", + "SystemDrive", + "WINDIR", + "ComSpec", + "PATH", + "PATHEXT", + "OS", + "PROCESSOR_ARCHITECTURE", + "ProgramFiles", + "ProgramFiles(x86)", + "ProgramW6432", + "LANG", + "LC_ALL", + "TMPDIR", + "TEMP", + "TMP", +]) { + const key = Object.keys(process.env).find((key) => key.toLowerCase() === name.toLowerCase()); + if (key) env[key] = process.env[key]; +} +Object.assign(env, { + HOME: state, + USERPROFILE: state, + LOCALAPPDATA: state, + APPDATA: state, + OPENCLAW_STATE_DIR: state, + OPENCLAW_HOME: state, + OPENCLAW_COMPILED_ASSET_ROOT: app, + NODE_DISABLE_COMPILE_CACHE: "1", + OPENCLAW_NO_RESPAWN: "1", +}); +const results: { control: string; passed: boolean; stdout: string }[] = []; +const direct = spawnSync(process.execPath, [entry, "--version"], { + cwd: app, + env, + encoding: "utf8", + timeout: 30000, + maxBuffer: 1024 * 1024, +}); +fs.writeFileSync( + path.join(output, "direct-version.log"), + (direct.stdout ?? "") + (direct.stderr ?? ""), +); +assert.equal(direct.status, 0, direct.stderr); +assert.match(direct.stdout, /OpenClaw 2026\.9\.2/); +results.push({ + control: "direct-version-with-declared-startup-sidecars", + passed: true, + stdout: direct.stdout.trim(), +}); +const worker = new Worker( + `const {workerData}=require("node:worker_threads"); +process.argv=[process.execPath,workerData,"--version"]; +const api=require(workerData); +if(typeof api.runCli!=="function"||typeof api.runOpenClaw!=="function")throw Error("Missing compiled API"); +api.runOpenClaw(process.argv).catch(error=>{console.error(error);process.exitCode=1;});`, + { eval: true, workerData: entry, env, stdout: true, stderr: true, execArgv: [] }, +); +let stdout = ""; +let stderr = ""; +worker.stdout.on("data", (bytes: Buffer) => { + stdout = (stdout + bytes.toString("utf8")).slice(-65536); +}); +worker.stderr.on("data", (bytes: Buffer) => { + stderr = (stderr + bytes.toString("utf8")).slice(-65536); +}); +const timeout = setTimeout(() => void worker.terminate(), 30000); +let exitCode: number; +try { + exitCode = await new Promise((resolve, reject) => { + worker.once("exit", resolve); + worker.once("error", reject); + }); +} finally { + clearTimeout(timeout); +} +fs.writeFileSync(path.join(output, "worker-version.log"), stdout + stderr); +assert.equal(exitCode, 0, stderr); +assert.match(stdout, /OpenClaw 2026\.9\.2/); +results.push({ + control: "owned-worker-import-and-explicit-api-with-declared-startup-sidecars", + passed: true, + stdout: stdout.trim(), +}); +fs.writeFileSync( + path.join(state, "openclaw.json"), + JSON.stringify({ + gateway: { + mode: "local", + bind: "loopback", + auth: { mode: "token", token: "owned-compiler-control-token" }, + }, + }), +); +const config = spawnSync(process.execPath, [entry, "config", "validate", "--json"], { + cwd: app, + env, + encoding: "utf8", + timeout: 45000, + maxBuffer: 1024 * 1024, +}); +fs.writeFileSync( + path.join(output, "config-validate.log"), + (config.stdout ?? "") + (config.stderr ?? ""), +); +assert.equal(config.status, 0, config.stderr); +assert.equal((JSON.parse(config.stdout) as { valid?: boolean }).valid, true); +results.push({ + control: "actual-config-validation-with-declared-startup-sidecars", + passed: true, + stdout: config.stdout.trim(), +}); +fs.writeFileSync( + path.join(output, "compiled-controls.json"), + JSON.stringify( + { + schemaVersion: 1, + classification: "actual-compiled-code-controls", + platform: process.platform, + architecture: process.arch, + nodeVersion: process.version, + portableProof: portable, + neighboringDependencyTreeAbsent: false, + declaredSidecars: ["undici", "@openclaw/fs-safe"], + unrelatedNeighboringDependenciesAbsent: true, + sourceTreeIsolationVerified: false, + originalBuildTreeAccess: + "Not asserted by this script; a separate OS-denied control records that boundary.", + controls: results, + runtimeClosureProven: false, + agentResponseQualified: false, + }, + null, + 2, + ) + "\n", +); +console.log("PASS: compiled CLI, owned Worker API, and configuration validation."); diff --git a/packaging/windows/app/test-prebuilt-choice-plugins.mts b/packaging/windows/app/test-prebuilt-choice-plugins.mts new file mode 100644 index 00000000000..f11086cbacf --- /dev/null +++ b/packaging/windows/app/test-prebuilt-choice-plugins.mts @@ -0,0 +1,391 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// Real compiled registry/gateway control. External channel/search activity is deliberately disabled. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import net from "node:net"; +import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { choiceInspectChildDiagnostics } from "./choice-inspect-diagnostics.mts"; +import { + nativeOpenClawOptions, + normalizeNativeOptions, + type NativeOptions, +} from "../runtime/native-options.mts"; +function javascriptStringLiteral(value: string) { + return JSON.stringify(value).replace( + /[<>/\u2028\u2029]/gu, + (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`, + ); +} +const argument = (name: string) => { + const i = process.argv.indexOf(name); + assert(i >= 0 && process.argv[i + 1]); + return process.argv[i + 1]; +}; +const app = path.resolve(argument("--app-root")), + output = path.resolve(argument("--output")), + choice = argument("--choice"); +assert(["brave", "slack", "tavily"].includes(choice)); +if (!process.argv.includes("--portable-proof")) { + assert.equal(process.platform, "win32"); + assert.equal(process.arch, "arm64"); + assert.equal(process.version, "v22.23.2"); +} +assert(!fs.existsSync(output)); +fs.mkdirSync(output, { recursive: true }); +const state = path.join(output, "state"); +fs.mkdirSync(state); +const code = path.join(app, "openclaw-app.cjs"), + codeHash = createHash("sha256").update(fs.readFileSync(code)).digest("hex"); +assert.equal( + codeHash, + JSON.parse(fs.readFileSync(path.join(app, "openclaw-resource-closure.json"), "utf8")).compiler + .mainSha256, +); +const options: NativeOptions = + choice === "brave" || choice === "tavily" + ? { search: { provider: choice, credentialStored: true } } + : { + messaging: { + [choice]: { + credentialStored: true, + allowedUsers: [], + ...(choice === "slack" ? { appCredentialStored: true } : {}), + }, + }, + }; +const selected = nativeOpenClawOptions(normalizeNativeOptions("openclaw", options)); +const config = { + ...selected, + plugins: { ...selected.plugins, load: { paths: [path.join(app, "plugins", choice)] } }, + update: { checkOnStart: false, auto: { enabled: false } }, + // Plugin convergence does not exercise inference or the mutable public catalog. + // Keep the installed product's native catalog-refresh default unchanged. + models: { catalogRefresh: { enabled: false } }, + agents: { list: [{ id: "main", default: true }], defaults: { skipBootstrap: true } }, +}; +const env: NodeJS.ProcessEnv = {}; +for (const [key, value] of Object.entries(process.env)) + if ( + [ + "systemroot", + "windir", + "systemdrive", + "comspec", + "path", + "pathext", + "temp", + "tmp", + "programfiles", + "programfiles(x86)", + "os", + "processor_architecture", + "lang", + "lc_all", + "tmpdir", + ].includes(key.toLowerCase()) + ) + env[key] = value; +Object.assign(env, { + HOME: state, + USERPROFILE: state, + LOCALAPPDATA: state, + APPDATA: state, + OPENCLAW_STATE_DIR: state, + OPENCLAW_HOME: state, + OPENCLAW_COMPILED_ASSET_ROOT: app, + OPENCLAW_NO_RESPAWN: "1", + OPENCLAW_SKIP_CHANNELS: "1", + OPENCLAW_NO_AUTO_UPDATE: "1", + OPENCLAW_GATEWAY_STARTUP_TRACE: "1", + // Gateway startup tracing does not cover `plugins inspect`. Keep the pinned + // runtime's plugin phase timings in the existing bounded stderr evidence. + OPENCLAW_PLUGIN_LIFECYCLE_TRACE: "1", + NODE_DISABLE_COMPILE_CACHE: "1", +}); +const systemRoot = Object.entries(env).find(([name]) => name.toUpperCase() === "SYSTEMROOT")?.[1]; +env.PATH = [ + path.dirname(process.execPath), + ...(systemRoot ? [path.join(systemRoot, "System32"), systemRoot] : ["/usr/bin", "/bin"]), +].join(path.delimiter); +const attempts = path.join(output, "package-manager-attempt"); +const trap = `const cp=require("node:child_process"),fs=require("node:fs");for(const name of ["spawn","spawnSync","execFile","execFileSync"]){const original=cp[name];cp[name]=function(...args){if(/(?:npm|npx|pnpm|yarn|pip)(?:\\b|[-.])/i.test(JSON.stringify(args.slice(0,2)))){fs.appendFileSync(${javascriptStringLiteral(attempts)},name+"\\n");throw Error("Unexpected package-manager invocation");}return original.apply(this,args);};}require("node:module").syncBuiltinESMExports();`; +function start(label: string, source: string) { + const file = path.join(output, label + ".cjs"); + fs.writeFileSync( + file, + trap + (label === "inspect" ? choiceInspectChildDiagnostics : "") + source, + { flag: "wx" }, + ); + const child = spawn(process.execPath, [file], { + cwd: app, + env: + label === "inspect" + ? { + ...env, + // The Windows failure enters the CLI but does not finish it. Upstream + // start/end spans locate the pending bootstrap operation in this + // synthetic, credential-free fixture without changing its deadline. + OPENCLAW_DIAGNOSTICS: "1", + OPENCLAW_DIAGNOSTICS_TIMELINE_PATH: path.join(output, "inspect.timeline.log"), + } + : env, + stdio: ["ignore", "pipe", "pipe", "ipc"], + }); + let stdout = "", + stderr = ""; + child.once("error", (error) => { + stderr += error.message; + }); + child.stdout!.on("data", (data) => { + stdout += data; + if (stdout.length > 2 * 1024 * 1024) child.kill(); + }); + child.stderr!.on("data", (data) => { + stderr += data; + if (stderr.length > 2 * 1024 * 1024) child.kill(); + }); + let closed = false; + const completion = new Promise((resolve) => + child.once("close", (code) => { + closed = true; + resolve(code); + }), + ); + return { + child, + completion, + isClosed: () => closed, + stdout: () => stdout, + stderr: () => stderr, + save: () => { + fs.writeFileSync(path.join(output, label + ".stdout.log"), stdout); + fs.writeFileSync(path.join(output, label + ".stderr.log"), stderr); + }, + }; +} +async function finish(child: ReturnType, milliseconds: number) { + const timer = setTimeout(() => child.child.kill(), milliseconds); + try { + return await child.completion; + } finally { + clearTimeout(timer); + child.save(); + } +} +function command(label: string, args: string[]) { + return start( + label, + `const entry=${JSON.stringify(code)};process.argv=[process.execPath,entry,...${JSON.stringify(args)}];require(entry).runCli(process.argv).catch(error=>{console.error(error);process.exitCode=1;});`, + ); +} +async function observeRecurringHealth(_origin: string) { + const samples: { ts: number; observedAtMs: number; ok: boolean }[] = []; + for (const index of [0, 1]) { + if (index) await delay(65000); // Cross the unchanged 60s background health interval. + const probe = start( + "health-" + index, + `const entry=${JSON.stringify(code)};process.argv=[process.execPath,entry,"health","--json","--timeout","15000"];require(entry).runCli(process.argv).catch(error=>{console.error(error);process.exitCode=1;});`, + ); + assert.equal(await finish(probe, 30000), 0, "The actual gateway health RPC failed."); + const response = JSON.parse(probe.stdout()); + assert.equal(response.ok, true); + assert(Number.isFinite(response.ts)); + samples.push({ ts: response.ts, observedAtMs: Date.now(), ok: true }); + } + assert(samples[1].ts > samples[0].ts, "The configured health snapshot did not refresh."); + return { + samples, + naturalIntervalWaitMs: 65000, + healthRpcRequestsSent: 2, + observation: + "successful repeated canonical health RPC plus no background refresh errors across the unchanged timer interval; not a passive timer-only measurement", + }; +} + +let primary: unknown; +let gateway: ReturnType | undefined; +const result: Record = { + schemaVersion: 1, + classification: "compiled-prebuilt-choice-convergence", + choice, + codeSha256: codeHash, + channelConnectionsStarted: false, + liveSearchTested: false, + modelTested: false, + remoteModelCatalogTested: false, + windowsQualified: false, +}; +try { + fs.writeFileSync(path.join(state, "openclaw.json"), JSON.stringify(config)); + const registered = path.join(output, "registered.json"); + const inspect = start( + "inspect", + // Fixed stage names and elapsed times distinguish a blocked CLI from a child + // that finished its work but did not exit. Do not print configuration values. + `const started=performance.now(),mark=stage=>console.error("[nemoclaw-choice-inspect] "+stage+" elapsedMs="+Math.round(performance.now()-started));mark("load-start");const entry=${JSON.stringify(code)},api=require(entry);mark("load-finished");process.argv=[process.execPath,entry,"plugins","inspect",${JSON.stringify(choice)},"--runtime","--json"];api.registerPrebuiltPlugins(${JSON.stringify(config)}).then(result=>{fs.writeFileSync(${JSON.stringify(registered)},JSON.stringify(result));mark("registration-finished");mark("cli-start");return api.runCli(process.argv);}).then(()=>mark("cli-finished")).catch(error=>{mark("failed");console.error(error);process.exitCode=1;});`, + ); + assert.equal(await finish(inspect, 30000), 0, inspect.stderr()); + assert.deepEqual(JSON.parse(fs.readFileSync(registered, "utf8")).registered, [choice]); + let report = JSON.parse(inspect.stdout()); + assert.equal(report.plugin?.id, choice); + assert.equal(report.plugin?.status, "loaded"); + assert.equal(report.plugin?.imported, true); + assert.equal(report.install?.source, "path"); + assert.equal(report.install?.installPath, path.join(app, "plugins", choice)); + assert.equal(report.install?.sourcePath, report.install.installPath); + assert.equal(report.install?.version, "2026.9.2"); + assert.equal(report.install.acceptedSurface, undefined); + assert.equal(report.diagnostics.length, 1); + assert.match(report.diagnostics[0].message, /requires capability consent/); + // Explicit fixture approval, not installer behavior. The browser control owns + // the user-facing Cancel/Accept path; this control covers each packaged choice. + const disabled = command("disable", ["plugins", "disable", choice]); + assert.equal(await finish(disabled, 30000), 0, disabled.stderr()); + const denied = command("enable-without-consent", ["plugins", "enable", choice]); + assert.equal(await finish(denied, 30000), 1, denied.stderr()); + assert.match(denied.stderr(), /requires capability consent/); + assert.equal( + JSON.parse(fs.readFileSync(path.join(state, "openclaw.json"), "utf8")).plugins.entries[choice] + .enabled, + false, + ); + const accepted = command("enable-with-consent", [ + "plugins", + "enable", + choice, + "--accept-capabilities", + ]); + assert.equal(await finish(accepted, 30000), 0, accepted.stderr()); + const verified = command("inspect-after-consent", [ + "plugins", + "inspect", + choice, + "--runtime", + "--json", + ]); + assert.equal(await finish(verified, 30000), 0, verified.stderr()); + report = JSON.parse(verified.stdout()); + assert.equal(report.plugin?.status, "loaded"); + assert.equal(report.plugin?.imported, true); + assert.equal(report.install.source, "path"); + assert(report.install.acceptedSurface); + assert.match(report.install.acceptedSurfaceHash, /^[a-f0-9]{64}$/); + assert.deepEqual(report.diagnostics, []); + const acceptedSurfaceHash = report.install.acceptedSurfaceHash; + const acceptedSurfaceIntegrity = report.install.acceptedSurfaceIntegrity; + assert.equal(acceptedSurfaceIntegrity, report.install.integrity); + assert.match(acceptedSurfaceIntegrity, /^sha256-[A-Za-z0-9+/]{43}=$/); + const registeredAgain = start( + "register-after-consent", + `const entry=${JSON.stringify(code)};require(entry).registerPrebuiltPlugins(${JSON.stringify(config)}).catch(error=>{console.error(error);process.exitCode=1;});`, + ); + assert.equal(await finish(registeredAgain, 30000), 0, registeredAgain.stderr()); + const persisted = command("inspect-after-registration", [ + "plugins", + "inspect", + choice, + "--runtime", + "--json", + ]); + assert.equal(await finish(persisted, 30000), 0, persisted.stderr()); + const afterRegistration = JSON.parse(persisted.stdout()); + assert.equal(afterRegistration.install.acceptedSurfaceHash, acceptedSurfaceHash); + assert.equal(afterRegistration.install.acceptedSurfaceIntegrity, acceptedSurfaceIntegrity); + assert.deepEqual(afterRegistration.diagnostics, []); + result.capabilityConsent = { + missingConsentDenied: true, + explicitlyAccepted: true, + acceptancePersisted: true, + }; + result.runtimeInspection = { + status: report.plugin.status, + capabilities: report.capabilities, + install: report.install, + }; + const allocator = net.createServer(); + await new Promise((r) => allocator.listen(0, "127.0.0.1", r)); + const port = (allocator.address() as net.AddressInfo).port; + await new Promise((r) => allocator.close(() => r())); + const origin = "http://127.0.0.1:" + port; + const gatewayConfig = { + ...config, + gateway: { + mode: "local", + bind: "loopback", + port, + auth: { mode: "none" }, + controlUi: { + root: path.join(app, "node_modules/openclaw/dist/control-ui"), + allowedOrigins: [origin], + }, + }, + logging: { file: path.join(output, "gateway.jsonl") }, + }; + fs.writeFileSync(path.join(state, "openclaw.json"), JSON.stringify(gatewayConfig)); + // A new process must converge from the actual persisted metadata, without + // running the registration API again or inheriting a prior CLI checkpoint. + gateway = start( + "gateway", + `const entry=${JSON.stringify(code)};process.argv=[process.execPath,entry,"gateway","run","--allow-unconfigured","--port",${JSON.stringify(String(port))},"--bind","loopback","--auth","none"];process.on("message",message=>{if(message==="stop")process.emit("SIGINT");});require(entry).runCli(process.argv).catch(error=>{console.error(error);process.exitCode=1;});`, + ); + const started = performance.now(); + let healthy = false; + while (!gateway.isClosed() && performance.now() - started < 45000) { + try { + const response = await fetch(origin + "/healthz", { signal: AbortSignal.timeout(500) }); + if (response.ok) { + healthy = true; + break; + } + } catch {} + await delay(100); + } + assert(healthy, "The configured compiled gateway did not become healthy."); + result.recurringHealth = await observeRecurringHealth(origin); + assert.equal(gateway.isClosed(), false); + const trace = fs + .readFileSync(path.join(output, "gateway.jsonl"), "utf8") + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line).message) + .find( + (line: unknown) => + typeof line === "string" && line.startsWith("startup trace: plugins.gateway-load "), + ); + assert.equal(typeof trace, "string"); + for (const metric of [ + "loaderNativeMissesCount", + "loaderSourceTransformForcedCount", + "loaderSourceTransformFallbacksCount", + ]) + assert.match(trace, new RegExp(metric + "=0\\.0(?: |$)")); + result.loaderTrace = trace; + assert.doesNotMatch( + gateway.stdout() + gateway.stderr(), + /Cannot find (?:module|package)|failed to load plugin|(?:initial |background )?refresh failed|building.*Control UI|runtime plugin downloads are disabled/i, + ); + assert(!fs.existsSync(attempts)); + result.packageManagerInvocations = 0; +} catch (error) { + primary = error; +} finally { + if (gateway) { + if (!gateway.isClosed()) gateway.child.send("stop"); + const code = await finish(gateway, 30000); + if (code !== 0) primary ??= new Error("The configured gateway did not close successfully."); + result.gatewayExitCode = code; + } + result.verdict = primary ? "fail" : "pass"; + result.error = primary instanceof Error ? primary.message : null; + fs.writeFileSync(path.join(output, "result.json"), JSON.stringify(result, null, 2) + "\n"); +} +if (primary) throw primary; +console.log( + "PASS prebuilt " + + choice + + " registration, fresh convergence and real recurring health; no package manager or channel/search request.", +); diff --git a/packaging/windows/app/test-prebuilt-plugin-consent-records.mts b/packaging/windows/app/test-prebuilt-plugin-consent-records.mts new file mode 100644 index 00000000000..7f58ba868e3 --- /dev/null +++ b/packaging/windows/app/test-prebuilt-plugin-consent-records.mts @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createRequire } from "node:module"; +import { prebuiltPluginRegistrationSource } from "./openclaw-app-resources.mts"; + +const argument = (name: string) => { + const index = process.argv.indexOf(name); + assert(index >= 0 && process.argv[index + 1]); + return path.resolve(process.argv[index + 1]); +}; +const source = argument("--source-root"); +const toolRoot = argument("--tool-root"); +const require = createRequire(import.meta.url); +const compiler = require(path.join(toolRoot, "node_modules/esbuild")) as typeof import("esbuild"); +assert.equal(compiler.version, "0.27.4"); +const root = fs.mkdtempSync(path.join(os.tmpdir(), "prebuilt-consent-records-")); +try { + const plugin = path.join(root, "plugins/brave"); + fs.mkdirSync(path.join(plugin, "dist"), { recursive: true }); + fs.writeFileSync( + path.join(plugin, "package.json"), + JSON.stringify({ + name: "@openclaw/brave-plugin", + version: "2026.9.2", + openclaw: { runtimeExtensions: ["./dist/index.js"] }, + }), + ); + fs.writeFileSync(path.join(plugin, "dist/index.js"), "// Fixture; never executed.\n"); + const closure = path.join(root, "openclaw-resource-closure.json"); + fs.writeFileSync(closure, '{"fixtureArtifact":"first"}\n'); + const recordsModule = ` + export let records={}; + export function setRecords(value){records=value;} + export async function r(){return records;} + export function n(current,update){const {pluginId,...record}=update;return {...current,[pluginId]:record};} + export async function s(value){records=value;}`; + // The fixture replaces storage only. The generated registration logic and + // artifact identity calculation are the same code compiled into the app. + const built = await compiler.build({ + stdin: { + contents: + prebuiltPluginRegistrationSource(source) + + '\nexport {records,setRecords} from "fixture-records";', + loader: "js", + }, + bundle: true, + platform: "node", + format: "cjs", + write: false, + logLevel: "silent", + banner: { + js: `const __nemoAssetDir=${JSON.stringify(root)};function __nemoPrepareAssetRoot(){}`, + }, + plugins: [ + { + name: "owned-record-store", + setup(builder) { + builder.onResolve( + { + filter: + /fixture-records|installed-plugin-index-records-C06Xozeq|installed-plugin-index-record-reader-SXWwf_BU/, + }, + () => ({ path: "records", namespace: "fixture" }), + ); + builder.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({ + contents: recordsModule, + loader: "js", + })); + }, + }, + ], + }); + const file = path.join(root, "registration.cjs"); + fs.writeFileSync(file, built.outputFiles[0].contents); + const api = require(file) as { + records: Record>; + setRecords(records: Record>): void; + registerPrebuiltPlugins(config: unknown): Promise<{ registered: string[] }>; + }; + const config = { plugins: { entries: { brave: { enabled: true } } } }; + assert.deepEqual((await api.registerPrebuiltPlugins(config)).registered, ["brave"]); + const first = { ...api.records.brave }; + assert.equal(first.source, "path"); + assert.match(String(first.integrity), /^sha256-[A-Za-z0-9+/]{43}=$/); + const approved = { + ...first, + acceptedSurface: { contracts: ["webSearchProviders: brave"] }, + acceptedSurfaceHash: "owned-consent-hash", + acceptedSurfaceIntegrity: first.integrity, + }; + api.setRecords({ brave: approved }); + await api.registerPrebuiltPlugins(config); + assert.deepEqual(api.records.brave, approved); + for (const field of ["source", "sourcePath", "installPath", "version", "integrity"]) { + api.setRecords({ brave: { ...approved, [field]: "changed" } }); + await api.registerPrebuiltPlugins(config); + assert.deepEqual(api.records.brave, first, field + " must invalidate prior consent"); + } + api.setRecords({ brave: approved }); + fs.writeFileSync(closure, '{"fixtureArtifact":"second"}\n'); + await api.registerPrebuiltPlugins(config); + assert.notEqual(api.records.brave.integrity, first.integrity); + assert.equal(api.records.brave.acceptedSurface, undefined); + api.setRecords({ brave: approved }); + await api.registerPrebuiltPlugins({ plugins: { entries: { brave: { enabled: false } } } }); + assert.deepEqual(api.records.brave, approved); + console.log( + JSON.stringify({ + passed: true, + sameArtifactConsentRetained: true, + changedIdentityCases: 5, + changedArtifactConsentCleared: true, + disabledPluginUntouched: true, + }), + ); +} finally { + fs.rmSync(root, { recursive: true, force: true }); +} diff --git a/packaging/windows/app/test-windows-configured-plugin-install.mts b/packaging/windows/app/test-windows-configured-plugin-install.mts new file mode 100644 index 00000000000..e301cd0ebc7 --- /dev/null +++ b/packaging/windows/app/test-windows-configured-plugin-install.mts @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { createRequire } from "node:module"; +import { guardWindowsConfiguredPluginInstall } from "./openclaw-app-resources.mts"; + +const source = path.resolve(process.argv[process.argv.indexOf("--source-root") + 1] ?? ""); +const relative = "dist/missing-configured-plugin-install-B3eZm5tD.js"; +const original = fs.readFileSync(path.join(source, relative), "utf8"); +const patched = guardWindowsConfiguredPluginInstall(relative, original); +const syntax = createRequire(import.meta.url)( + path.join(source, "node_modules/typescript"), +) as typeof import("typescript"); +function body(text: string) { + const tree = syntax.createSourceFile( + "repair.js", + text, + syntax.ScriptTarget.Latest, + true, + syntax.ScriptKind.JS, + ); + const names = new Set([ + "resolveConfiguredPluginInstallContext", + "repairMissingPluginInstalls", + "repairMissingPluginInstallsWithLease", + ]); + const functions = tree.statements + .filter(syntax.isFunctionDeclaration) + .filter((node) => node.name && names.has(node.name.text)); + assert.equal(functions.length, names.size); + return ( + functions.map((node) => node.getText(tree)).join("\n") + "\nreturn repairMissingPluginInstalls;" + ); +} +async function control(text: string, platform: string, mode: "new" | "recorded" | "healthy") { + const calls: string[] = []; + const records: Record = + mode === "new" + ? {} + : { + discord: { source: "path", healthy: mode === "healthy", installPath: "/plugins/discord" }, + }; + let leases = 0; + const bindings = { + process: { platform, env: {} }, + VERSION: "2026.9.2", + path, + safeRealpathSync: (value: string) => value, + resolveUserPath: (value: string) => value, + withPluginLifecycleLease: async (_options: unknown, action: () => Promise) => { + leases++; + return await action(); + }, + normalizePluginsConfig: (value: unknown) => value, + loadManifestMetadataSnapshot: () => ({ + plugins: + mode === "healthy" + ? [{ id: "discord", origin: "config", rootDir: "/plugins/discord" }] + : [], + }), + loadInstalledPluginIndex: () => ({ plugins: [] }), + collectEffectiveConfiguredChannelOwnerPluginIds: () => new Map(), + collectConfiguredPluginIdsWithMissingChannelConfigDescriptors: () => new Set(), + loadInstalledPluginIndexInstallRecords: async () => records, + resolveRegistryUpdateChannel: () => "stable", + normalizeUpdateChannel: () => undefined, + collectInstalledPluginIdsWithRepairablePackageDiagnostics: () => new Set(), + collectInstalledPluginIdsWithStaleVersionBoundRuntimePackages: () => new Set(), + collectOfficialReplacementInstallCandidates: () => new Map(), + isLegacyPackageUpdateDoctorPass: () => false, + shouldDeferConfiguredPluginInstallRepair: () => false, + isPayloadMissing: () => mode !== "healthy", + forceNpmInstallRecordRepair: (record: unknown) => record, + resolveCompatibilityHostVersion: () => "2026.9.2", + updateNpmInstalledPlugins: async () => { + calls.push("package-manager-repair"); + return { + config: { plugins: { installs: { discord: { source: "path", healthy: true } } } }, + outcomes: [], + }; + }, + collectDownloadableInstallCandidates: () => [ + { pluginId: "discord", label: "Discord", npmSpec: "@openclaw/discord" }, + ], + installCandidate: async () => { + calls.push("package-manager-install"); + return { + records: { discord: { source: "path", healthy: true } }, + changes: [], + notices: [], + warnings: [], + }; + }, + writePersistedInstalledPluginIndexInstallRecords: async () => { + calls.push("persist-records"); + }, + }; + const params = { + cfg: { plugins: { entries: { discord: { enabled: true } } } }, + env: {}, + pluginIds: new Set(["discord"]), + channelIds: new Set(["discord"]), + blockedPluginIds: new Set(), + }; + // Execute the actual source function with install APIs replaced by observation + // boundaries. No package manager, filesystem writer or network client runs. + const invoke = new Function(...Object.keys(bindings), body(text))(...Object.values(bindings)); + try { + const result = await invoke(params); + assert.equal(leases, 1, "The upstream lifecycle lease must still wrap repair."); + return { calls, result, error: null }; + } catch (error) { + assert.equal(leases, 1, "The upstream lifecycle lease must still wrap refusal."); + return { calls, result: null, error }; + } +} +let controls = 0; +for (const mode of ["new", "recorded"] as const) { + const before = await control(original, "win32", mode); + assert.equal(before.error, null); + assert(before.calls.some((name) => name.startsWith("package-manager-"))); + const denied = await control(patched, "win32", mode); + assert(denied.error instanceof Error); + assert.match( + denied.error.message, + /Repair or update NemoClaw.*runtime plugin downloads are disabled/u, + ); + assert.deepEqual(denied.calls, []); + const portable = await control(patched, "linux", mode); + assert.equal(portable.error, null); + assert(portable.calls.some((name) => name.startsWith("package-manager-"))); + controls += 3; +} +const healthy = await control(patched, "win32", "healthy"); +assert.equal(healthy.error, null); +assert.deepEqual(healthy.calls, []); +controls++; +assert.throws( + () => guardWindowsConfiguredPluginInstall(relative, original + "\n"), + /source changed/u, +); +controls++; +console.log( + JSON.stringify({ + controls, + actualSourceFunction: true, + packageManagerExecuted: false, + platformClaim: "controlled function branches; full Windows gateway checked separately", + }), +); diff --git a/packaging/windows/app/test-windows-eager-ollama.mts b/packaging/windows/app/test-windows-eager-ollama.mts new file mode 100644 index 00000000000..78f4d69b7f5 --- /dev/null +++ b/packaging/windows/app/test-windows-eager-ollama.mts @@ -0,0 +1,134 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import { createRequire } from "node:module"; +import { pathToFileURL } from "node:url"; +import { compileEagerOllamaRuntime } from "./openclaw-app-resources.mts"; + +function argument(name: string) { + const index = process.argv.indexOf(name); + if (index < 0 || !process.argv[index + 1]) throw new Error(`Missing ${name}`); + return path.resolve(process.argv[index + 1]); +} +const source = argument("--source-root"); +const tools = argument("--tool-root"); +const relative = "dist/stream-api-DUG3zQPW.js"; +const original = fs.readFileSync(path.join(source, relative), "utf8"); +const adapted = compileEagerOllamaRuntime(relative, original); +const require = createRequire(import.meta.url); +const compiler = require(path.join(tools, "node_modules/esbuild")) as typeof import("esbuild"); +assert.equal(compiler.version, "0.27.4"); +assert.equal(compileEagerOllamaRuntime("dist/unrelated.js", original), original); +assert.throws(() => compileEagerOllamaRuntime(relative, original + "\n"), /reviewed eager Ollama/); + +// Both modules reference the same real, integrity-checked upstream runtime. +// No export implementation is replaced for this comparison. +const moduleUrl = pathToFileURL(path.join(source, relative)); +const absoluteAdapted = adapted.replace(/"(\.\/[^"\n]+)"/g, (_match, specifier: string) => + JSON.stringify(new URL(specifier, moduleUrl).href), +); +const baseline = await import(moduleUrl.href); +const candidate = await import( + "data:text/javascript;base64," + Buffer.from(absoluteAdapted).toString("base64") +); +assert.deepEqual(Object.keys(candidate), ["a", "c", "i", "n", "o", "r", "s", "t"]); +assert.deepEqual(Object.keys(candidate), Object.keys(baseline)); +for (const name of Object.keys(baseline)) assert.equal(candidate[name], baseline[name], name); + +// Fixture boundaries exercise eager initialization order, all exported bindings, +// failure propagation and the real compiler's synchronous CJS output. +const root = fs.mkdtempSync(path.join(os.tmpdir(), "ollama-eager-control-")); +const exports = [ + "OLLAMA_NATIVE_BASE_URL", + "resolveOllamaBaseUrlForRun", + "buildOllamaChatRequest", + "convertToOllamaMessages", + "buildAssistantMessage", + "parseNdjsonStream", + "createOllamaStreamFn", + "createConfiguredOllamaStreamFn", +]; +const marker = "nemoclaw.ollama-eager.control"; +const observations = globalThis as typeof globalThis & { [marker]?: string[] }; +try { + fs.writeFileSync(path.join(root, "package.json"), '{"type":"module"}\n'); + for (const name of ["lazy-runtime-CgCh8H_K.js", "lazy-promise-DGqyc4Y4.js"]) + fs.copyFileSync(path.join(source, "dist", name), path.join(root, name)); + fs.writeFileSync( + path.join(root, "stream-compat-DSz3ALUi.js"), + `globalThis[${JSON.stringify(marker)}].push("compat");\n`, + ); + const body = + `globalThis[${JSON.stringify(marker)}].push("runtime");\n` + + exports.map((name) => `export const ${name}=${JSON.stringify(name)};`).join("\n"); + fs.writeFileSync(path.join(root, "stream.runtime.js"), body); + fs.writeFileSync(path.join(root, "adapted.js"), adapted); + const compiled = await compiler.build({ + entryPoints: [path.join(root, "adapted.js")], + bundle: true, + platform: "node", + format: "cjs", + target: "node22.23", + write: false, + }); + const output = path.join(root, "compiled.cjs"); + fs.writeFileSync(output, compiled.outputFiles[0].contents); + observations[marker] = []; + const loaded = require(output) as Record; + assert.deepEqual(observations[marker], ["compat", "runtime"]); + assert.deepEqual(Object.keys(loaded).sort(), Object.keys(baseline).sort()); + assert.deepEqual(Object.values(loaded).sort(), exports.toSorted()); + assert.equal(require(output), loaded, "Repeated loads share the same module instance."); + assert.deepEqual(observations[marker], ["compat", "runtime"]); + + for (const [label, code] of [ + ["upstream", original], + ["adapted", adapted], + ]) { + const directory = path.join(root, label); + fs.mkdirSync(directory); + for (const name of [ + "lazy-runtime-CgCh8H_K.js", + "lazy-promise-DGqyc4Y4.js", + "stream-compat-DSz3ALUi.js", + ]) + fs.copyFileSync(path.join(root, name), path.join(directory, name)); + fs.writeFileSync( + path.join(directory, "stream.runtime.js"), + 'throw new Error("owned-runtime-init-failure");\n' + + exports.map((name) => `export const ${name}=null;`).join("\n"), + ); + const entry = path.join(directory, "entry.js"); + fs.writeFileSync(entry, code); + await assert.rejects(import(pathToFileURL(entry).href), /owned-runtime-init-failure/); + if (label === "adapted") { + const failedBuild = await compiler.build({ + entryPoints: [entry], + bundle: true, + platform: "node", + format: "cjs", + target: "node22.23", + write: false, + }); + const failedOutput = path.join(directory, "compiled.cjs"); + fs.writeFileSync(failedOutput, failedBuild.outputFiles[0].contents); + assert.throws(() => require(failedOutput), /owned-runtime-init-failure/); + } + } + console.log( + JSON.stringify({ + passed: true, + canonicalExports: Object.keys(baseline), + cjsEagerOrder: true, + cachedModuleIdentity: true, + initializationFailurePropagates: true, + hashDriftRejected: true, + }), + ); +} finally { + delete observations[marker]; + fs.rmSync(root, { recursive: true, force: true }); +} diff --git a/packaging/windows/app/test-windows-plugin-file-url.mts b/packaging/windows/app/test-windows-plugin-file-url.mts new file mode 100644 index 00000000000..036a674f026 --- /dev/null +++ b/packaging/windows/app/test-windows-plugin-file-url.mts @@ -0,0 +1,134 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import Module, { createRequire } from "node:module"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { createHash } from "node:crypto"; + +const index = process.argv.indexOf("--source-root"); +if (index < 0 || !process.argv[index + 1]) + throw new Error("The pinned materialized source root is required."); +const source = path.resolve(process.argv[index + 1]); +const relative = "dist/sdk-alias-BMTmaiMP.js"; +const original = fs.readFileSync(path.join(source, relative), "utf8"); +assert.equal( + createHash("sha256").update(original).digest("hex"), + "3644b7cef6e4b4059f6d824d0aac457b4e656ed8d9b40a9319de1954c036ac62", + "The reviewed upstream native loader must match the pinned source.", +); +const syntax = createRequire(import.meta.url)( + path.join(source, "node_modules/typescript"), +) as typeof import("typescript"); +const names = new Set([ + "isPluginSourceModulePath", + "isJavaScriptModulePath", + "isMissingTargetModuleError", + "isSourceTransformFallbackError", + "tryNativeRequireJavaScriptModule", + "tryNativeRequireModule", + "toNativeRequirePath", + "withNativeRequireAliases", +]); +type Result = { ok: boolean; moduleExport?: { identity?: string } }; +function actualLoader(text: string, platform: string) { + const parsed = syntax.createSourceFile( + "loader.js", + text, + syntax.ScriptTarget.Latest, + true, + syntax.ScriptKind.JS, + ); + const functions = parsed.statements.filter( + (statement) => + syntax.isFunctionDeclaration(statement) && statement.name && names.has(statement.name.text), + ); + assert.equal( + functions.length, + names.size, + "The exact native loader functions must be extracted.", + ); + return new Function( + "process", + "path", + "nodeRequire", + "fileURLToPath", + "pathToFileURL", + "moduleWithResolver", + "createRequire", + "nativeModuleLoadFailures", + "PLUGIN_SOURCE_MODULE_EXTENSIONS", + functions + .map((item) => item.getText(parsed)) + .join("\n") + .replaceAll("import.meta.url", JSON.stringify(import.meta.url)) + + "\nreturn tryNativeRequireJavaScriptModule;", + )( + { platform, features: process.features }, + path, + createRequire(import.meta.url), + fileURLToPath, + pathToFileURL, + Module, + createRequire, + new Map(), + [".ts", ".tsx", ".mts", ".cts", ".mtsx", ".ctsx"], + ) as (file: string, options: Record) => Result; +} +const root = fs.mkdtempSync(path.join(os.tmpdir(), "native plugin URL ü ")); +const options = { + allowWindows: true, + fallbackOnMissingDependency: true, + fallbackOnNativeError: true, +}; +const results: string[] = []; +try { + fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ type: "module" })); + const entry = path.join(root, "entry space ü.js"); + fs.writeFileSync(entry, 'export const identity="native-entry";\n'); + const url = pathToFileURL(entry).href; + const loader = actualLoader(original, "win32"); + assert.equal(loader(url, options).moduleExport?.identity, "native-entry"); + results.push("windows-file-url-native-esm-hit"); + assert.equal(loader(entry, options).moduleExport?.identity, "native-entry"); + results.push("plain-path-native-hit-preserved"); + assert.equal( + actualLoader(original, "darwin")(url, options).moduleExport?.identity, + "native-entry", + ); + results.push("upstream-file-url-loading-on-other-platforms"); + assert.equal(loader(url, { ...options, allowWindows: false }).ok, false); + results.push("windows-loading-requires-explicit-admission"); + for (const target of [ + pathToFileURL(path.join(root, "missing.js")).href, + "https://invalid.example/entry.js", + "file:///invalid%2Fencoded.js", + ]) + assert.equal(loader(target, options).ok, false); + results.push("missing-nonfile-malformed-targets-not-admitted"); + const alias = path.join(root, "alias.js"); + fs.writeFileSync(alias, 'export {identity} from "reviewed-alias";\n'); + const resolver = (Module as unknown as { _resolveFilename: unknown })._resolveFilename; + assert.equal( + loader(pathToFileURL(alias).href, { ...options, aliasMap: { "reviewed-alias": entry } }) + .moduleExport?.identity, + "native-entry", + ); + assert.equal((Module as unknown as { _resolveFilename: unknown })._resolveFilename, resolver); + results.push("existing-native-aliases-and-restoration-preserved"); + console.log( + JSON.stringify({ + passed: true, + controls: results, + nativePlatform: process.platform, + branchExercised: "win32", + realNodeRequire: true, + upstreamLoaderUnmodified: true, + windowsExecutionObserved: process.platform === "win32", + }), + ); +} finally { + fs.rmSync(root, { recursive: true, force: true }); +} diff --git a/packaging/windows/app/test-windows-private-directory-library.mts b/packaging/windows/app/test-windows-private-directory-library.mts new file mode 100644 index 00000000000..9884ce502b3 --- /dev/null +++ b/packaging/windows/app/test-windows-private-directory-library.mts @@ -0,0 +1,252 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import { execFile, execFileSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { privateDirectoryDiagnosticCommand } from "./choice-inspect-diagnostics.mts"; +import { + SQLITE_PRIVATE_DIRECTORY_SOURCE, + SQLITE_PRIVATE_DIRECTORY_LIBRARY, + compilePrivateDirectoryRuntime, + privateDirectoryNativeSource, + privateDirectoryBuildCommand, +} from "./sqlite-private-directory-build.mts"; + +function argument(name: string) { + const index = process.argv.indexOf(name); + if (index < 0 || !process.argv[index + 1]) throw new Error(`Missing ${name}`); + return path.resolve(process.argv[index + 1]); +} +const source = argument("--source-root"); +const app = argument("--app-root"); +const portable = process.argv.includes("--portable-proof"); +if (!portable) { + assert.equal(process.platform, "win32"); + assert.equal(process.arch, "arm64"); + assert.equal(process.versions.node, "22.23.2"); +} +const original = fs.readFileSync(path.join(source, SQLITE_PRIVATE_DIRECTORY_SOURCE), "utf8"); +const adapted = compilePrivateDirectoryRuntime(SQLITE_PRIVATE_DIRECTORY_SOURCE, original); +assert.equal(compilePrivateDirectoryRuntime("dist/unrelated.js", original), original); +assert.throws( + () => compilePrivateDirectoryRuntime(SQLITE_PRIVATE_DIRECTORY_SOURCE, original + "\n"), + /reviewed SQLite/, +); +assert.throws(() => privateDirectoryBuildCommand(original + "\n", "unused"), /reviewed SQLite/); + +type DirectoryRuntime = { + resolvePrivateDirectoryPowerShell(directory: string): { powershell: string; args: string[] }; + createPrivateSqliteDirectory(directory: string): Promise; + createPrivateSqliteDirectorySync(directory: string): void; +}; +const powershell = path.join( + process.env.SystemRoot ?? "C:\\Windows", + "System32", + "WindowsPowerShell", + "v1.0", + "powershell.exe", +); +function runtime(text: string, assetRoot = app): DirectoryRuntime { + // Evaluate the pinned implementation, not a second implementation of its policy. + // Only unrelated imports and system-program lookup are supplied by this harness. + const start = text.indexOf("//#region src/infra/windows-powershell-spawn.ts"); + const end = text.indexOf("//#region src/infra/sqlite-readonly-location.ts"); + assert(start >= 0 && end > start); + const moduleUrl = pathToFileURL( + path.join(assetRoot, "node_modules/openclaw", SQLITE_PRIVATE_DIRECTORY_SOURCE), + ).href; + const body = text.slice(start, end).replaceAll("import.meta.url", JSON.stringify(moduleUrl)); + const factory = new Function( + "path", + "fs", + "fs$1", + "execFile", + "execFileSync", + "resolveSystemBin", + "decodeWindowsOutputBuffer", + "truncateUtf16Safe", + "__nemoPrivateDirectoryFilePath", + body + + "\nreturn {resolvePrivateDirectoryPowerShell,createPrivateSqliteDirectory,createPrivateSqliteDirectorySync};", + ); + return factory( + path, + fs, + fs.promises, + execFile, + execFileSync, + () => powershell, + ({ buffer }: { buffer: Buffer }) => buffer.toString("utf8"), + (text: string, limit: number) => text.slice(0, limit), + fileURLToPath, + ) as DirectoryRuntime; +} +const baseline = runtime(original); +const candidate = runtime(adapted); +const command = (value: { args: string[] }) => + Buffer.from(value.args.at(-1)!, "base64").toString("utf16le"); +const unchangedPolicy = (script: string) => + script + .split("; ") + .filter( + (part) => + !part.startsWith("$nativeSource =") && + !part.startsWith("$nativeLibrary =") && + !part.startsWith("Import-Module ") && + !part.startsWith("Add-Type "), + ) + .join("; "); +for (const directory of ["plain", "spaces and 'quotes'", "[brackets]-é-雪"]) { + const target = path.join(app, directory); + const before = baseline.resolvePrivateDirectoryPowerShell(target); + const after = candidate.resolvePrivateDirectoryPowerShell(target); + assert.equal(before.powershell, after.powershell); + assert.deepEqual(before.args.slice(0, -1), after.args.slice(0, -1)); + assert.equal(unchangedPolicy(command(after)), unchangedPolicy(command(before))); + assert(privateDirectoryDiagnosticCommand(command(after))); + assert.deepEqual( + command(after) + .split("; ") + .filter((part) => part.startsWith("Import-Module ")), + [ + "Import-Module -Name ([IO.Path]::Combine($PSHOME, 'Modules', 'Microsoft.PowerShell.Utility', 'Microsoft.PowerShell.Utility.psd1')) -ErrorAction Stop", + ], + ); + assert(command(after).indexOf("Import-Module ") < command(after).indexOf("Add-Type ")); + assert.equal( + command(after) + .split("; ") + .find((part) => part.startsWith("Add-Type ")), + "Add-Type -LiteralPath $nativeLibrary", + ); + const encoded = /\$nativeLibrary = [^;]*FromBase64String\('([^']+)'\)/u.exec(command(after)); + assert(encoded); + assert.equal( + Buffer.from(encoded[1], "base64").toString("utf8"), + path.join(app, SQLITE_PRIVATE_DIRECTORY_LIBRARY), + ); +} +const buildCommand = privateDirectoryBuildCommand( + original, + path.join(app, SQLITE_PRIVATE_DIRECTORY_LIBRARY), +); +const encodedSource = /\$source = [^;]*FromBase64String\('([^']+)'\)/u.exec(buildCommand); +assert(encodedSource); +assert.equal( + Buffer.from(encodedSource[1], "base64").toString("utf8"), + privateDirectoryNativeSource(original).source, +); + +if (portable) { + console.log( + JSON.stringify({ + passed: true, + commandPolicyPreserved: true, + hashDriftRejected: true, + windowsQualified: false, + }), + ); +} else { + const library = path.join(app, SQLITE_PRIVATE_DIRECTORY_LIBRARY); + assert(fs.statSync(library).isFile()); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "sqlite-library-controls-")); + const priorModulePath = process.env.PSModulePath; + try { + // An ambient module with the same name must not supply the native helper's cmdlets. + const modules = path.join(root, "ambient-modules"); + const shadow = path.join(modules, "Microsoft.PowerShell.Utility"); + fs.mkdirSync(shadow, { recursive: true }); + fs.writeFileSync( + path.join(shadow, "Microsoft.PowerShell.Utility.psd1"), + "@{ RootModule='Microsoft.PowerShell.Utility.psm1'; ModuleVersion='99.0.0'; FunctionsToExport=@('Add-Type','New-Object'); CmdletsToExport=@() }", + { flag: "wx" }, + ); + fs.writeFileSync( + path.join(shadow, "Microsoft.PowerShell.Utility.psm1"), + "throw 'Ambient PowerShell utility module must not load.'", + { flag: "wx" }, + ); + process.env.PSModulePath = modules; + for (const variant of ["async", "sync"] as const) { + const directory = path.join(root, variant + "-'[é]'"); + if (variant === "async") await candidate.createPrivateSqliteDirectory(directory); + else candidate.createPrivateSqliteDirectorySync(directory); + const marker = path.join(directory, "retained.txt"); + fs.writeFileSync(marker, "retained", { flag: "wx" }); + const encoded = Buffer.from(directory, "utf8").toString("base64"); + const inspect = [ + "$ErrorActionPreference = 'Stop'", + // Node inherits pwsh's module paths; this child needs Windows PowerShell's modules. + "$env:PSModulePath = [IO.Path]::Combine($PSHOME, 'Modules')", + `$path = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded}'))`, + "$acl = Get-Acl -LiteralPath $path", + "$sid = [System.Security.Principal.SecurityIdentifier]", + "$current = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value", + "[pscustomobject]@{ owner=$acl.GetOwner($sid).Value; current=$current; protected=$acl.AreAccessRulesProtected; rules=@($acl.GetAccessRules($true,$true,$sid) | ForEach-Object { [pscustomobject]@{sid=$_.IdentityReference.Value;allow=($_.AccessControlType -eq 'Allow');full=($_.FileSystemRights -eq [System.Security.AccessControl.FileSystemRights]::FullControl);inheritance=[int]$_.InheritanceFlags;propagation=[int]$_.PropagationFlags} }) } | ConvertTo-Json -Depth 4 -Compress", + ].join("; "); + const inspectAcl = () => + JSON.parse( + execFileSync( + powershell, + [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-EncodedCommand", + Buffer.from(inspect, "utf16le").toString("base64"), + ], + { encoding: "utf8", timeout: 30_000, maxBuffer: 65_536, windowsHide: true }, + ).trim(), + ); + const acl = inspectAcl(); + assert.equal(acl.owner, acl.current); + assert.equal(acl.protected, true); + assert.deepEqual( + acl.rules.map((rule: { sid: string }) => rule.sid).sort(), + [...new Set([acl.current, "S-1-5-18", "S-1-5-32-544"])].sort(), + ); + for (const rule of acl.rules) { + assert.equal(rule.allow, true); + assert.equal(rule.full, true); + assert.equal(rule.inheritance, 3); + assert.equal(rule.propagation, 0); + } + if (variant === "async") + await assert.rejects(candidate.createPrivateSqliteDirectory(directory), { code: "EEXIST" }); + else + assert.throws(() => candidate.createPrivateSqliteDirectorySync(directory), { + code: "EEXIST", + }); + assert.equal(fs.readFileSync(marker, "utf8"), "retained"); + assert.deepEqual(inspectAcl(), acl); + } + // An absent library must not trigger runtime compilation or create staging state. + const missing = runtime(adapted, path.join(root, "missing-runtime")); + const absent = path.join(root, "must-not-exist"); + await assert.rejects(missing.createPrivateSqliteDirectory(absent), /Unable to create private/); + assert.throws( + () => missing.createPrivateSqliteDirectorySync(absent), + /Unable to create private/, + ); + assert.equal(fs.existsSync(absent), false); + } finally { + if (priorModulePath === undefined) delete process.env.PSModulePath; + else process.env.PSModulePath = priorModulePath; + fs.rmSync(root, { recursive: true, force: true }); + } + assert.equal(fs.existsSync(root), false); + console.log( + JSON.stringify({ + passed: true, + protectedDacl: true, + existingTargetRefused: true, + ambientModuleIgnored: true, + asyncAndSync: true, + cleanup: true, + installedAcceptance: false, + }), + ); +} diff --git a/packaging/windows/app/test-windows-update-owner.mts b/packaging/windows/app/test-windows-update-owner.mts new file mode 100644 index 00000000000..1d74354042a --- /dev/null +++ b/packaging/windows/app/test-windows-update-owner.mts @@ -0,0 +1,237 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { createRequire } from "node:module"; +import { guardWindowsInstallerUpdate } from "./openclaw-app-resources.mts"; + +const position = process.argv.indexOf("--source-root"); +if (position < 0 || !process.argv[position + 1]) + throw new Error("The pinned materialized source root is required."); +const source = path.resolve(process.argv[position + 1]); +const relative = "dist/update-BxCRjwo_.js"; +const original = fs.readFileSync(path.join(source, relative), "utf8"); +const patched = guardWindowsInstallerUpdate(relative, original); +const syntax = createRequire(import.meta.url)( + path.join(source, "node_modules/typescript"), +) as typeof import("typescript"); +const parse = (name: string, text: string) => + syntax.createSourceFile(name, text, syntax.ScriptTarget.Latest, true, syntax.ScriptKind.JS); +function declaration(file: string, name: string) { + const tree = parse(file, fs.readFileSync(path.join(source, "dist", file), "utf8")); + const found = tree.statements.find( + (statement) => + (syntax.isFunctionDeclaration(statement) && statement.name?.text === name) || + (syntax.isVariableStatement(statement) && + statement.declarationList.declarations.some((item) => item.name.getText(tree) === name)), + ); + assert.ok(found, `The actual pinned declaration must exist: ${name}`); + return found.getText(tree); +} +const protocol = new Function( + declaration("gateway-error-details-w0nAGBBp.js", "ErrorCodes") + + "\n" + + declaration("error-codes-Bo8q2D1o.js", "errorShape") + + "\nreturn {ErrorCodes,errorShape};", +)() as { + ErrorCodes: { UNAVAILABLE: string; INVALID_REQUEST: string }; + errorShape: (code: string, message: string) => Record; +}; +const validation = new Function( + "ErrorCodes", + "errorShape", + "formatValidationErrors", + declaration("validation-pzrlzFvo.js", "validateGatewayMethodParams") + + "\n" + + declaration("validation-pzrlzFvo.js", "assertValidParams") + + "\nreturn assertValidParams;", +)(protocol.ErrorCodes, protocol.errorShape, () => "controlled invalid request") as ( + ...args: unknown[] +) => boolean; +type Input = { + params: unknown; + respond: (...args: unknown[]) => void; + client: unknown; + context: unknown; +}; +function handler(text: string, platform: string, valid: boolean) { + const tree = parse("update.js", text); + const statement = tree.statements.find( + (node) => + syntax.isVariableStatement(node) && + node.declarationList.declarations.some( + (item) => item.name.getText(tree) === "updateHandlers", + ), + ); + assert.ok(statement && syntax.isVariableStatement(statement)); + const initializer = statement.declarationList.declarations.find( + (item) => item.name.getText(tree) === "updateHandlers", + )?.initializer; + assert.ok(initializer && syntax.isObjectLiteralExpression(initializer)); + const member = initializer.properties.find( + (item) => syntax.isPropertyAssignment(item) && item.name.getText(tree) === '"update.run"', + ); + assert.ok(member && syntax.isPropertyAssignment(member)); + const calls: string[] = []; + let validations = 0; + const context = { + getRuntimeConfig: () => ({ update: {} }), + logGateway: { info() {}, warn() {} }, + }; + const dependencies: Record = { + process: { platform, env: {}, argv: ["node", "owned-entry"] }, + assertValidParams: (...args: unknown[]) => { + validations++; + return validation(...args); + }, + validateUpdateRunParams: () => valid, + __nemoUpdateErrorShape: protocol.errorShape, + __nemoUpdateErrorCodes: protocol.ErrorCodes, + VERSION: "2026.9.2", + resolveControlPlaneActor: () => ({ actor: "owned-control" }), + parseRestartRequestParams: () => ({}), + normalizeGatewayRestartDelayMs: () => 0, + extractDeliveryInfo: () => ({}), + mergeDeliveryContext: () => undefined, + isBrowserOperatorUiClient: () => false, + resolveUpdateRunNoticeTarget: () => ({ kind: "none" }), + formatDoctorNonInteractiveHint: () => "controlled update hint", + createUpdateRun: () => { + calls.push("ledger-create"); + return { runId: "controlled-run" }; + }, + recordUpdateRunVerification: () => calls.push("ledger-verification"), + wakeUpdateRunWatcher: () => calls.push("update-watcher"), + loadUpdateRunNotifier: async () => { + calls.push("notifier-load"); + return { createUpdateRunNotifier: () => async () => ({ delivered: false, owned: false }) }; + }, + initializeGatewayUpdateStatus: async () => { + calls.push("package-root-probe"); + return { root: "owned-root", status: { installKind: "package" } }; + }, + resolveEffectiveUpdateChannel: () => ({ channel: "stable" }), + isRecord: (value: unknown) => value !== null && typeof value === "object", + gatewayUpdateCampaign: { adopt: () => undefined }, + recordUpdateRunPhase: () => { + calls.push("ledger-phase"); + return { runId: "controlled-run" }; + }, + isGatewayExternallySupervised: () => false, + readPackageVersion: async () => "2026.9.2", + getUpdateAvailable: () => undefined, + renderUpdateRunNotice: () => undefined, + normalizeControlPlaneUpdateResult: (result: unknown) => result, + normalizeUpdateChannel: () => undefined, + resolveUpdateInstallSurface: async () => { + calls.push("install-surface-probe"); + return { kind: "package", mode: "npm", root: "owned-root" }; + }, + detectRespawnSupervisor: () => null, + isRestartEnabled: () => true, + runGatewayUpdate: async () => { + calls.push("update-mutation"); + return { status: "ok", mode: "npm", steps: [], durationMs: 0 }; + }, + runPostCoreFinalizeAfterGatewayUpdate: async () => ({ status: "ok" }), + foldPostCoreFinalizeIntoResult: (result: unknown) => result, + buildUpdateRestartSentinelPayload: () => ({}), + writeRestartSentinel: async () => { + calls.push("sentinel-mutation"); + }, + recordLatestUpdateRestartSentinel: () => {}, + scheduleGatewaySigusr1Restart: () => { + calls.push("restart"); + return null; + }, + formatControlPlaneActor: () => "owned-control", + }; + const notifierImport = 'import("./update-run-notice.runtime.js")'; + const handlerSource = member.initializer.getText(tree); + assert.equal(handlerSource.split(notifierImport).length, 2); + // Replace only the notifier's external module boundary; execute the pinned + // handler through its ledger, update, sentinel and restart calls below. + const execute = new Function( + ...Object.keys(dependencies), + "return (" + + handlerSource + .replace(notifierImport, "loadUpdateRunNotifier()") + .replace("import.meta.url", JSON.stringify("file:///owned/update.js")) + + ");", + )(...Object.values(dependencies)) as (input: Input) => Promise; + const responses: unknown[][] = []; + return { + calls, + responses, + validations: () => validations, + run: () => + execute({ + params: {}, + client: { connect: { client: {} } }, + context, + respond: (...args) => responses.push(args), + }), + }; +} + +const before = handler(original, "win32", true); +await before.run(); +assert.ok( + before.calls.includes("install-surface-probe") && before.calls.includes("update-mutation"), +); +assert.ok( + before.calls.includes("ledger-create") && + before.calls.includes("sentinel-mutation") && + before.calls.includes("restart"), +); +assert.equal((before.responses[0][1] as { ok: boolean }).ok, true); +const blocked = handler(patched, "win32", true); +await blocked.run(); +assert.equal(blocked.validations(), 1); +assert.deepEqual( + blocked.calls, + [], + "Refusal must precede every package probe, mutation and restart.", +); +assert.equal(blocked.responses.length, 1); +assert.equal(blocked.responses[0][0], false); +assert.equal(blocked.responses[0][1], undefined); +assert.equal( + (blocked.responses[0][2] as Record).code, + protocol.ErrorCodes.UNAVAILABLE, +); +assert.match( + String((blocked.responses[0][2] as Record).message), + /NemoClaw installer.*update or repair/, +); +const invalid = handler(patched, "win32", false); +await invalid.run(); +assert.deepEqual(invalid.calls, []); +assert.equal( + (invalid.responses[0][2] as Record).code, + protocol.ErrorCodes.INVALID_REQUEST, +); +const other = handler(patched, "linux", true); +await other.run(); +assert.deepEqual( + other.calls, + before.calls, + "Other-platform handler behavior must remain unchanged.", +); +assert.equal(guardWindowsInstallerUpdate("unrelated.js", original), original); +assert.throws( + () => guardWindowsInstallerUpdate(relative, original + "\n"), + /reviewed gateway update handler changed/, +); +console.log( + JSON.stringify({ + passed: true, + controls: 6, + actualPinnedHandlerAndProtocol: true, + windowsBranchRefusedBeforeProbeOrMutation: true, + originalValidationPreserved: true, + otherPlatformUnchanged: true, + updaterExecuted: false, + }), +); diff --git a/packaging/windows/app/test_materialize_openclaw_build.py b/packaging/windows/app/test_materialize_openclaw_build.py new file mode 100644 index 00000000000..7dfaf5df3b0 --- /dev/null +++ b/packaging/windows/app/test_materialize_openclaw_build.py @@ -0,0 +1,247 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import base64 +import copy +import hashlib +import importlib.util +import io +import json +from pathlib import Path +import tarfile +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch + + +MODULE = Path(__file__).with_name("materialize-openclaw-build.py") +SPEC = importlib.util.spec_from_file_location("openclaw_materializer", MODULE) +materializer = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(materializer) + + +def package(version, name="dependency"): + return { + "version": version, + "resolved": f"https://registry.npmjs.org/{name}/-/{name}-{version}.tgz", + "integrity": "sha512-test-fixture", + } + + +class RuntimeDependencyTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory(prefix="openclaw-dependency-plan-") + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.lock_file = self.root / "build.lock.json" + self.dependency_file = self.root / "runtime.lock.json" + self.core = package("2026.9.2", "openclaw") + self.document = { + "name": "nemoclaw-openclaw-runtime", + "lockfileVersion": 3, + "packages": { + "": {"dependencies": {"openclaw": "2026.9.2"}}, + "node_modules/openclaw": self.core, + "node_modules/dependency": package("2.0.0"), + "node_modules/openclaw/node_modules/dependency": package("1.0.0"), + "node_modules/consumer": package("1.0.0", "consumer"), + "node_modules/consumer/node_modules/dependency": package("1.0.0"), + }, + } + self.lock = { + "schemaVersion": 1, + "openclaw": { + "version": self.core["version"], + "url": self.core["resolved"], + "integrity": self.core["integrity"], + }, + "dependencyLock": {"path": self.dependency_file.name}, + "compilerPackages": [], + } + self.save_lock() + + def save_lock(self): + raw = json.dumps(self.document).encode() + self.dependency_file.write_bytes(raw) + self.lock["dependencyLock"]["sha256"] = hashlib.sha256(raw).hexdigest() + self.lock_file.write_text(json.dumps(self.lock)) + + def test_keeps_nested_versions_and_deduplicates_only_archive_downloads(self): + raw, core, plan, requested = materializer.dependency_plan(self.lock, self.lock_file) + self.assertEqual(raw, self.dependency_file.read_bytes()) + self.assertEqual(core, "node_modules/openclaw") + self.assertEqual(len(plan), 5) + self.assertEqual(len(requested), 4) + locations = {name: (parts, item["version"]) for name, parts, item in plan} + self.assertEqual(locations["node_modules/dependency"][1], "2.0.0") + self.assertEqual(locations["node_modules/openclaw/node_modules/dependency"], + (("node_modules", "openclaw", "node_modules", "dependency"), "1.0.0")) + self.assertEqual(locations["node_modules/consumer/node_modules/dependency"][1], "1.0.0") + + def test_rejects_changed_lock_bytes(self): + self.dependency_file.write_bytes(self.dependency_file.read_bytes() + b" ") + with self.assertRaisesRegex(ValueError, "SHA256 mismatch"): + materializer.dependency_plan(self.lock, self.lock_file) + + def test_rejects_source_version_url_or_integrity_drift(self): + for field, value in [("version", "2026.7.1"), ("url", "https://example.org/core.tgz"), + ("integrity", "sha512-changed")]: + with self.subTest(field=field): + lock = copy.deepcopy(self.lock) + lock["openclaw"][field] = value + with self.assertRaisesRegex(ValueError, "differs"): + materializer.dependency_plan(lock, self.lock_file) + + def test_rejects_nonpackage_and_windows_aliased_locations(self): + for name in ["../escape", "node_modules/a/../../escape", "node_modules/CON", + "node_modules/a.", "node_modules/a/payload", "node_modules/@scope", + "node_modules/DEPENDENCY"]: + with self.subTest(name=name): + self.document["packages"][name] = package("3.0.0") + self.save_lock() + with self.assertRaises(ValueError): + materializer.dependency_plan(self.lock, self.lock_file) + del self.document["packages"][name] + + def test_rejects_links_and_inconsistent_integrity_for_one_archive(self): + item = self.document["packages"]["node_modules/consumer/node_modules/dependency"] + item["link"] = True + self.save_lock() + with self.assertRaisesRegex(ValueError, "linked"): + materializer.dependency_plan(self.lock, self.lock_file) + del item["link"] + item["integrity"] = "sha512-different" + self.save_lock() + with self.assertRaisesRegex(ValueError, "Conflicting"): + materializer.dependency_plan(self.lock, self.lock_file) + + def test_materializes_distinct_versions_and_records_the_original_lock(self): + policy_parser = package("2.8.3", "yaml") + self.lock["compilerPackages"] = [{ + "package": "yaml", "version": policy_parser["version"], + "url": policy_parser["resolved"], "integrity": policy_parser["integrity"], + }] + self.save_lock() + archives = {} + inputs = [*self.document["packages"].items(), ("node_modules/yaml", policy_parser)] + for name, item in inputs: + if not name or item["resolved"] in archives: + continue + filename = self.root / f"archive-{len(archives)}.tgz" + content = json.dumps({"name": name.split("/")[-1], "version": item["version"]}).encode() + with tarfile.open(filename, "w:gz") as archive: + member = tarfile.TarInfo("package/package.json") + member.size = len(content) + archive.addfile(member, io.BytesIO(content)) + archives[item["resolved"]] = {"url": item["resolved"], "archive": str(filename)} + output = self.root / "inputs" + with patch.object(materializer, "fetch", side_effect=lambda item, *_: archives[item["url"]]), \ + patch("sys.argv", [str(MODULE), "--lock", str(self.lock_file), "--output", str(output), + "--cache", str(self.root / "cache"), "--portable-proof"]): + materializer.main() + for name, item in self.document["packages"].items(): + if name: + metadata = json.loads((output / name / "package.json").read_text()) + self.assertEqual(metadata["version"], item["version"]) + self.assertEqual((output / "runtime-package-lock.json").read_bytes(), self.dependency_file.read_bytes()) + receipt = json.loads((output / "materialization-receipt.json").read_text()) + self.assertEqual(receipt["sourceRoot"], "node_modules/openclaw") + self.assertEqual(receipt["dependencyLock"]["sha256"], self.lock["dependencyLock"]["sha256"]) + self.assertEqual(len(receipt["dependencies"]), 4) + self.assertEqual(json.loads((output / "tools/node_modules/yaml/package.json").read_text()), + {"name": "yaml", "version": "2.8.3"}) + self.assertEqual([item["package"] for item in receipt["compiler"]], ["yaml"]) + self.assertFalse(receipt["lifecycleScriptsExecuted"]) + self.assertFalse(receipt["runtimeReady"]) + + def test_checked_in_lock_matches_canonical_runtime(self): + lock_file = MODULE.with_name("windows-app-build.lock.json") + lock = json.loads(lock_file.read_text()) + _, core, plan, _ = materializer.dependency_plan(lock, lock_file) + self.assertEqual(core, "node_modules/openclaw") + paths = {name for name, _, _ in plan} + self.assertIn("node_modules/openclaw/node_modules/typescript", paths) + self.assertIn("node_modules/undici", paths) + self.assertEqual(lock["openclaw"]["version"], "2026.9.2") + + def test_shared_tools_restore_policy_parser_without_agent_payloads(self): + source = MODULE.parent.parent / "distribution/prepare-native-build-tools.py" + spec = importlib.util.spec_from_file_location("shared_tools", source) + shared = importlib.util.module_from_spec(spec) + spec.loader.exec_module(shared) + lock = json.loads(source.with_name("native-build-tools.lock.json").read_text()) + cache = self.root / "shared-cache" + cache.mkdir() + for pin in lock["packages"]: + archive_path = cache / (hashlib.sha256(pin["url"].encode()).hexdigest() + ".tgz") + content = json.dumps({"name": pin["package"], "version": pin["version"]}).encode() + with tarfile.open(archive_path, "w:gz") as archive: + member = tarfile.TarInfo("package/package.json") + member.size = len(content) + archive.addfile(member, io.BytesIO(content)) + pin["integrity"] = "sha512-" + base64.b64encode(hashlib.sha512(archive_path.read_bytes()).digest()).decode() + lock_file = self.root / "shared.lock.json" + lock_file.write_text(json.dumps(lock)) + output = self.root / "shared-tools" + with patch.object(shared, "os", SimpleNamespace(name="nt", environ={"GITHUB_ACTIONS": "true"})), \ + patch("urllib.request.urlopen", side_effect=AssertionError("Unexpected network request")): + shared.prepare(output, cache, lock_file) + parser = json.loads((output / "tools/node_modules/yaml/package.json").read_text()) + self.assertEqual(parser["name"], "yaml") + receipt = json.loads((output / "materialization-receipt.json").read_text()) + self.assertIn("yaml", [pin["package"] for pin in receipt["packages"]]) + self.assertEqual(receipt["agentPayloads"], []) + self.assertFalse(receipt["lifecycleScriptsExecuted"]) + self.assertFalse(receipt["installedAcceptance"]) + + def test_choice_plan_retains_nested_voice_and_native_platform_packages(self): + lock_file = MODULE.with_name("windows-app-build.lock.json") + lock = json.loads(lock_file.read_text()) + _, _, core_plan, _ = materializer.dependency_plan(lock, lock_file) + raw, plan = materializer.choice_dependency_plan(lock, lock_file, core_plan) + self.assertEqual(hashlib.sha256(raw).hexdigest(), lock["choiceDependencyLock"]["sha256"]) + locations = {location: item for location, _, item in plan} + self.assertEqual(locations["plugins/discord/node_modules/@discordjs/voice/node_modules/@snazzah/davey"]["version"], "0.1.12") + self.assertEqual(locations["plugins/discord/node_modules/@snazzah/davey-win32-arm64-msvc"]["version"], "0.1.12") + self.assertIn("node_modules/@emnapi/core", locations) + self.assertFalse(any("googlechat" in location or "msteams" in location for location in locations)) + + def test_choice_plan_rejects_hash_and_shared_version_drift(self): + lock_file = MODULE.with_name("windows-app-build.lock.json") + lock = json.loads(lock_file.read_text()) + _, _, core_plan, _ = materializer.dependency_plan(lock, lock_file) + changed = copy.deepcopy(lock) + changed["choiceDependencyLock"]["sha256"] = "0" * 64 + with self.assertRaisesRegex(ValueError, "Choice dependency lock SHA256"): + materializer.choice_dependency_plan(changed, lock_file, core_plan) + changed_plan = copy.deepcopy(core_plan) + next(item for location, _, item in changed_plan if location == "node_modules/tslib")["version"] = "0.0.0" + with self.assertRaisesRegex(ValueError, "Conflicting shared"): + materializer.choice_dependency_plan(lock, lock_file, changed_plan) + + def test_restores_missing_choice_package_but_rejects_existing_identity_drift(self): + archive_file = self.root / "native.tgz" + content = json.dumps({"name": "native", "version": "1.0.0"}).encode() + with tarfile.open(archive_file, "w:gz") as archive: + member = tarfile.TarInfo("package/package.json") + member.size = len(content) + archive.addfile(member, io.BytesIO(content)) + dependency = package("1.0.0", "native") + plan = [("plugins/discord/node_modules/native", "native", dependency)] + output = self.root / "choice-inputs" + with patch.object(materializer, "fetch", return_value={"archive": str(archive_file)}) as fetch: + restored = materializer.restore_choice_dependencies(plan, output, self.root / "cache", 0) + self.assertEqual(len(restored), 1) + fetch.assert_called_once() + fetch.reset_mock() + materializer.restore_choice_dependencies(plan, output, self.root / "cache", 0) + fetch.assert_not_called() + dependency["version"] = "2.0.0" + with self.assertRaisesRegex(ValueError, "identity differs"): + materializer.restore_choice_dependencies(plan, output, self.root / "cache", 0) + fetch.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/windows/app/windows-app-build.lock.json b/packaging/windows/app/windows-app-build.lock.json new file mode 100644 index 00000000000..bc14374b7b1 --- /dev/null +++ b/packaging/windows/app/windows-app-build.lock.json @@ -0,0 +1,93 @@ +{ + "schemaVersion": 1, + "classification": "windows-application-build-inputs", + "openclaw": { + "version": "2026.9.2", + "url": "https://registry.npmjs.org/openclaw/-/openclaw-2026.9.2.tgz", + "integrity": "sha512-M6C7UsnX815nv26qBJFYGe6aGzv+ftZLRzV6S9oRXUtXg2Yn67eVntpssT94kgkquKVSeUxerUg0j1ONp4WYQg==", + "sha256": "3431f4cd2d8dbd6b936def2694ac27e19fa0256295cf4ada0f652ecf1c9ee520", + "bytes": 58392574 + }, + "dependencyLock": { + "path": "../../../agents/openclaw/openclaw-runtime/package-lock.json", + "sha256": "0b1253c6570f55881623961c856b430a17d4271f5efe8c5beffa7ac0fc8d0199" + }, + "choiceDependencyLock": { + "path": "../../../agents/openclaw/managed-image-messaging-runtime/package-lock.json", + "sha256": "72aecf8caf45e9773cda0e40c9a61adb6eea48c2122d0a5e469a8f6bdcf168f6", + "packages": ["@openclaw/discord", "@openclaw/slack"], + "sharedPackages": ["@emnapi/core", "@emnapi/runtime", "@emnapi/wasi-threads", "tslib"] + }, + "compilerPackages": [ + { + "package": "yaml", + "version": "2.8.3", + "url": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz", + "integrity": "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg==" + }, + { + "package": "esbuild", + "version": "0.27.4", + "url": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz", + "integrity": "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==" + }, + { + "package": "@esbuild/win32-arm64", + "version": "0.27.4", + "url": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.4.tgz", + "integrity": "sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==" + }, + { + "package": "@esbuild/darwin-arm64", + "version": "0.27.4", + "url": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.4.tgz", + "integrity": "sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==" + } + ], + "sharedNodeLock": "../hermes/official-runtime.lock.json", + "sharedNodeArtifactId": "node", + "sharedNodeVersion": "22.23.2", + "target": { + "platform": "win32", + "architecture": "arm64" + }, + "dependencyLifecycleScripts": "not executed by materializer; native build admission remains separate", + "additionalPackages": [ + { + "package": "@openclaw/brave-plugin", + "version": "2026.9.2", + "target": "plugins/brave", + "url": "https://registry.npmjs.org/@openclaw/brave-plugin/-/brave-plugin-2026.9.2.tgz", + "integrity": "sha512-6416aPlfnAKlu8IBrrjgfoiss/10xB32ywFwnIf/fkVMQE61qsmzA/qxUniQuDwOB6EBFNEkNs54DhIT7g3UVg==", + "sha256": "40c0cf23e8373f2285034b8f0a575cc51ec1ed53d081b0e1592d219dd411e54d", + "bytes": 7980 + }, + { + "package": "@openclaw/discord", + "version": "2026.9.2", + "url": "https://registry.npmjs.org/@openclaw/discord/-/discord-2026.9.2.tgz", + "integrity": "sha512-j+fSHxbXA+DSxwbL8SvtsDNL6tvBX4+RmH+EerVW6dCbeIwSconXj6J/+AaN/mhzZI4g0jPPj30TUhdCRRbc2w==", + "sha256": "358b88763e7697e29eb1807240ab5cdc04e38662462fb93c14e2b563ca7521d6", + "bytes": 6237335, + "target": "plugins/discord" + }, + { + "package": "@openclaw/slack", + "version": "2026.9.2", + "url": "https://registry.npmjs.org/@openclaw/slack/-/slack-2026.9.2.tgz", + "integrity": "sha512-6M1M6gL3iXahpalNsYAUuA+wvnV8lbMlNNH2ToegFvaSJcIll4S9kFa5mv3GFoquhMRHQjEjnkXPHP/pXwaWcA==", + "sha256": "79ad40233b041c2081408efe59c93c2d38ca508429e016dd9843cccffc8cf49a", + "bytes": 4238253, + "target": "plugins/slack" + }, + { + "package": "@openclaw/tavily-plugin", + "version": "2026.9.2", + "url": "https://registry.npmjs.org/@openclaw/tavily-plugin/-/tavily-plugin-2026.9.2.tgz", + "integrity": "sha512-FYK2e7aXagwcGiTRQfidS3PThIfJkAQoqYEtlkadiGxmgeChYY71YLeD6nQAHZKHmTAOw9U7njDxMBvYyXPf5w==", + "sha256": "c5d65ff201a8178ec914736887802c38d33628c667be5b2453b890fe44086984", + "bytes": 267514, + "target": "plugins/tavily" + } + ] +} diff --git a/packaging/windows/assets/NemoClaw.ico b/packaging/windows/assets/NemoClaw.ico new file mode 100644 index 00000000000..7d8eb86af53 Binary files /dev/null and b/packaging/windows/assets/NemoClaw.ico differ diff --git a/packaging/windows/assets/NemoClawLogo.png b/packaging/windows/assets/NemoClawLogo.png new file mode 100644 index 00000000000..744f58d19cf Binary files /dev/null and b/packaging/windows/assets/NemoClawLogo.png differ diff --git a/packaging/windows/assets/NemoClawSidebar.png b/packaging/windows/assets/NemoClawSidebar.png new file mode 100644 index 00000000000..b43f6cfafd2 Binary files /dev/null and b/packaging/windows/assets/NemoClawSidebar.png differ diff --git a/packaging/windows/assets/desktop-icons/NemoClaw.ico b/packaging/windows/assets/desktop-icons/NemoClaw.ico new file mode 100644 index 00000000000..7d8eb86af53 Binary files /dev/null and b/packaging/windows/assets/desktop-icons/NemoClaw.ico differ diff --git a/packaging/windows/assets/desktop-icons/README.md b/packaging/windows/assets/desktop-icons/README.md new file mode 100644 index 00000000000..71cb1bd0414 --- /dev/null +++ b/packaging/windows/assets/desktop-icons/README.md @@ -0,0 +1,12 @@ + + + +# Desktop agent icons + +These desktop icons retain the existing agent artwork: + +- `NemoClaw.ico` is the unchanged installer icon from `../NemoClaw.ico`. +- `openclaw.ico` wraps the existing onboarding PNG bytes in a Windows ICO container. +- `hermes.ico` is a separately retained UI asset: the unchanged `hermes_cli/web_dist/favicon.ico` from the official `hermes_agent-0.19.0-py3-none-any.whl` (MIT license). It is not evidence of, or installed from, the separately pinned Hermes 0.21.1 runtime. The source wheel SHA-256 is `bd0bac012aee38a60894781f4597dc29ee7bedb3448540249921f10d3bef327f`; the retained icon SHA-256 is `aefe65e6574e6f46d3382588f46c508e1b3f3b3c9ce3dec6d335403a5374add9`. + +The build packages the three ICO files for NemoClaw Setup, OpenClaw, and Hermes. Shortcut targets use the installed launcher with an explicit agent identity; they contain no provider keys. diff --git a/packaging/windows/assets/desktop-icons/hermes.ico b/packaging/windows/assets/desktop-icons/hermes.ico new file mode 100644 index 00000000000..7a949324da9 Binary files /dev/null and b/packaging/windows/assets/desktop-icons/hermes.ico differ diff --git a/packaging/windows/assets/desktop-icons/openclaw.ico b/packaging/windows/assets/desktop-icons/openclaw.ico new file mode 100644 index 00000000000..57f4032af68 Binary files /dev/null and b/packaging/windows/assets/desktop-icons/openclaw.ico differ diff --git a/packaging/windows/bootstrapper/DownstreamOptions.xaml b/packaging/windows/bootstrapper/DownstreamOptions.xaml new file mode 100644 index 00000000000..cf5dffddbf7 --- /dev/null +++ b/packaging/windows/bootstrapper/DownstreamOptions.xaml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/bootstrapper/DownstreamOptions.xaml.cs b/packaging/windows/bootstrapper/DownstreamOptions.xaml.cs new file mode 100644 index 00000000000..cd3a3d63b4a --- /dev/null +++ b/packaging/windows/bootstrapper/DownstreamOptions.xaml.cs @@ -0,0 +1,110 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; + +namespace Nvidia.NemoClaw.Bootstrapper; + +public partial class DownstreamOptions : UserControl +{ + private string agent = string.Empty; + public DownstreamOptions() => this.InitializeComponent(); + + internal void SetAgent(string value) + { + if (this.agent == value) return; + this.agent = value; + this.ClearSecrets(); + foreach (var checkbox in new[] { this.SearchEnabled, this.TelegramEnabled, this.DiscordEnabled, this.SlackEnabled }) checkbox.IsChecked = false; + this.DiscordEnabled.IsEnabled = value == "hermes"; + this.DiscordEnabled.Content = value == "openclaw" ? "Discord (unavailable in this preview)" : "Discord"; + this.SearchProvider.Items.Clear(); + if (value == "openclaw") this.SearchProvider.Items.Add(new ComboBoxItem { Content = "Brave Search", Tag = "brave" }); + if (value is "openclaw" or "hermes") this.SearchProvider.Items.Add(new ComboBoxItem { Content = "Tavily", Tag = "tavily" }); + this.SearchProvider.SelectedIndex = this.SearchProvider.Items.Count > 0 ? 0 : -1; + this.Visibility = value is "openclaw" or "hermes" ? Visibility.Visible : Visibility.Collapsed; + } + + internal NativeSetupOptions ReadOptions() + { + if (this.SearchEnabled.IsChecked == true && this.SearchProvider.SelectedItem is not ComboBoxItem) + throw new InvalidOperationException("Choose a supported search provider."); + var channels = new Dictionary(); + if (this.TelegramEnabled.IsChecked == true) channels["telegram"] = UserIds(this.TelegramUsers.Text); + if (this.DiscordEnabled.IsChecked == true) channels["discord"] = UserIds(this.DiscordUsers.Text); + if (this.SlackEnabled.IsChecked == true) channels["slack"] = UserIds(this.SlackUsers.Text); + var result = new NativeSetupOptions + { + SearchProvider = this.SearchEnabled.IsChecked == true ? (this.SearchProvider.SelectedItem as ComboBoxItem)?.Tag as string : null, + Messaging = channels, + }; + result.Validate(this.agent); + return result; + } + + internal void SetOptions(NativeSetupOptions options) + { + options.Validate(this.agent); + var search = this.SearchProvider.Items.OfType().FirstOrDefault(item => item.Tag as string == options.SearchProvider); + if (options.SearchProvider is not null && search is null) + throw new InvalidOperationException("The saved search provider is unavailable for this agent."); + this.ClearSecrets(); + if (search is not null) this.SearchProvider.SelectedItem = search; + this.SearchEnabled.IsChecked = options.SearchProvider is not null; + this.TelegramEnabled.IsChecked = options.Messaging.ContainsKey("telegram"); + this.DiscordEnabled.IsChecked = options.Messaging.ContainsKey("discord"); + this.SlackEnabled.IsChecked = options.Messaging.ContainsKey("slack"); + this.TelegramUsers.Text = string.Join(", ", options.Messaging.GetValueOrDefault("telegram") ?? Array.Empty()); + this.DiscordUsers.Text = string.Join(", ", options.Messaging.GetValueOrDefault("discord") ?? Array.Empty()); + this.SlackUsers.Text = string.Join(", ", options.Messaging.GetValueOrDefault("slack") ?? Array.Empty()); + } + + internal NativeServiceCredentials CopyCredentials() + { + this.ReadOptions(); + var result = new NativeServiceCredentials(); + try + { + if (this.SearchEnabled.IsChecked == true && this.SearchProvider.SelectedItem is ComboBoxItem { Tag: string service }) result[service] = this.SearchKey.SecurePassword; + if (this.TelegramEnabled.IsChecked == true) result["telegram"] = this.TelegramKey.SecurePassword; + if (this.DiscordEnabled.IsChecked == true) result["discord"] = this.DiscordKey.SecurePassword; + if (this.SlackEnabled.IsChecked == true) { result["slack-bot"] = this.SlackBotKey.SecurePassword; result["slack-app"] = this.SlackAppKey.SecurePassword; } + if (result.Values.Any(secret => secret.Length == 0)) throw new InvalidOperationException("Enter the required keys for each enabled integration."); + return result; + } + catch { result.Dispose(); throw; } + } + + internal void ClearSecrets() + { + foreach (var box in new[] { this.SearchKey, this.TelegramKey, this.DiscordKey, this.SlackBotKey, this.SlackAppKey }) box.Clear(); + } + + private static string[] UserIds(string text) => text.Split(new[] { ',', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Distinct(StringComparer.Ordinal).ToArray(); + + private void SelectionChanged(object sender, RoutedEventArgs args) + { + if (this.SearchFields is null) return; + this.SearchFields.Visibility = this.SearchEnabled.IsChecked == true ? Visibility.Visible : Visibility.Collapsed; + this.TelegramFields.Visibility = this.TelegramEnabled.IsChecked == true ? Visibility.Visible : Visibility.Collapsed; + this.DiscordFields.Visibility = this.DiscordEnabled.IsChecked == true ? Visibility.Visible : Visibility.Collapsed; + this.SlackFields.Visibility = this.SlackEnabled.IsChecked == true ? Visibility.Visible : Visibility.Collapsed; + } + + private void SearchProviderChanged(object sender, SelectionChangedEventArgs args) + { + if (this.SearchKey is null) return; + this.SearchKey.Clear(); + this.SearchHelp.NavigateUri = new Uri((this.SearchProvider.SelectedItem as ComboBoxItem)?.Tag as string == "brave" ? "https://api-dashboard.search.brave.com/" : "https://app.tavily.com/home"); + } + + private void OpenHelp(object sender, RoutedEventArgs args) + { + if (sender is not Hyperlink { NavigateUri: Uri uri } || uri.Scheme != "https") return; + try { Process.Start(new ProcessStartInfo { FileName = uri.AbsoluteUri, UseShellExecute = true })?.Dispose(); } + catch (Exception) { this.HelpError.Text = $"Open this official page in your browser: {uri.AbsoluteUri}"; this.HelpError.Visibility = Visibility.Visible; } + } +} diff --git a/packaging/windows/bootstrapper/MainWindow.xaml b/packaging/windows/bootstrapper/MainWindow.xaml new file mode 100644 index 00000000000..4bf84d2a0f1 --- /dev/null +++ b/packaging/windows/bootstrapper/MainWindow.xaml @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +