From 055f2bcfb3090582f4560538f0a7e7bf77ab80f6 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 18:11:25 +0700 Subject: [PATCH 01/40] fix(e2e): build changed sandbox images locally Signed-off-by: San Dang --- .github/workflows/e2e-standard-profile.yaml | 46 +--- .github/workflows/e2e.yaml | 155 +++++------- .github/workflows/managed-images.yaml | 4 +- test/e2e/RETRY_INVENTORY.md | 2 +- test/e2e/fixtures/workload-source-env.ts | 23 +- ...mage-publication-workflow-boundary.test.ts | 52 +++- ...time-compatible-anthropic-progress.test.ts | 2 +- .../pr-managed-image-publication.test.ts | 201 --------------- .../support/pr-managed-image-source.test.ts | 205 ++++++++++++++++ test/e2e/support/workload-source-env.test.ts | 43 ++-- ...managed-image-publication-workflow.test.ts | 8 +- tools/e2e/cli-artifact-workflow-boundary.mts | 25 +- tools/e2e/operations-workflow-boundary.mts | 137 ++++++----- ...cation.mts => pr-managed-image-source.mts} | 231 ++++-------------- .../standard-profile-workflow-boundary.mts | 60 +---- tools/e2e/workflow-boundary.mts | 54 +--- 16 files changed, 513 insertions(+), 735 deletions(-) delete mode 100644 test/e2e/support/pr-managed-image-publication.test.ts create mode 100644 test/e2e/support/pr-managed-image-source.test.ts rename tools/e2e/{pr-managed-image-publication.mts => pr-managed-image-source.mts} (50%) diff --git a/.github/workflows/e2e-standard-profile.yaml b/.github/workflows/e2e-standard-profile.yaml index 64eb1918244..9f8c665aeae 100644 --- a/.github/workflows/e2e-standard-profile.yaml +++ b/.github/workflows/e2e-standard-profile.yaml @@ -21,7 +21,10 @@ on: cli_artifact_provenance: required: true type: string - managed_image_catalog: + managed_image_revision: + required: true + type: string + workload_source: required: true type: string credential_boundary: @@ -106,7 +109,9 @@ jobs: timeout-minutes: ${{ inputs.timeout_minutes }} env: E2E_JOB: "1" + E2E_MANAGED_IMAGE_REVISION: ${{ inputs.managed_image_revision }} E2E_TARGET_ID: ${{ inputs.target_id }} + E2E_WORKLOAD_SOURCE: ${{ inputs.workload_source }} NEMOCLAW_RUN_LIVE_E2E: "1" NEMOCLAW_E2E_EXPECTED_SHA: ${{ inputs.candidate_sha }} NEMOCLAW_E2E_CORRELATION_ID: ${{ inputs.risk_signal_correlation_id }} @@ -392,45 +397,6 @@ jobs: with: provenance-json: ${{ inputs.cli_artifact_provenance }} - - name: Materialize temporary managed-image catalog - if: ${{ inputs.managed_image_catalog != '' }} - shell: /bin/bash --noprofile --norc -e -o pipefail {0} - env: - CANDIDATE_SHA: ${{ inputs.candidate_sha }} - MANAGED_IMAGE_CATALOG: ${{ inputs.managed_image_catalog }} - RESTORE_CLI: ${{ inputs.restore_cli && 'true' || 'false' }} - run: | - set -euo pipefail - catalog_path="${RUNNER_TEMP}/e2e-managed-image-catalog.json" - jq -e --arg revision "$CANDIDATE_SHA" ' - type == "object" and length > 0 and - all(.[]; - .source.revision == $revision and - (.source.release | type == "string" and length > 0) and - (.source.cohort | type == "string" and length > 0) - ) and - ([.[].source.release] | unique | length) == 1 and - ([.[].source.cohort] | unique | length) == 1 - ' <<<"$MANAGED_IMAGE_CATALOG" >/dev/null || { - echo "::error::managed-image catalog source identity does not match the candidate" >&2 - exit 1 - } - if [[ "$RESTORE_CLI" == "true" ]]; then - candidate_release="v$(jq -r '.nemoclawVersion' dist/build-identity.json)" - jq -e --arg release "$candidate_release" ' - all(.[]; .source.release == $release) - ' <<<"$MANAGED_IMAGE_CATALOG" >/dev/null || { - echo "::error::managed-image catalog release does not match the restored CLI" >&2 - exit 1 - } - fi - jq -c . <<<"$MANAGED_IMAGE_CATALOG" >"$catalog_path" - [[ -s "$catalog_path" && ! -L "$catalog_path" ]] || { - echo "::error::temporary managed-image catalog is invalid" >&2 - exit 1 - } - printf 'NEMOCLAW_E2E_MANAGED_IMAGE_CATALOG=%s\n' "$catalog_path" >>"$GITHUB_ENV" - - name: Install reviewed cloudflared if: ${{ inputs.cloudflared }} shell: /bin/bash --noprofile --norc -e -o pipefail {0} diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 4c73ff0c64f..c9a70359f2d 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -99,12 +99,14 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 55 outputs: - dcode_base_contract: ${{ steps.validate_dcode_base.outputs.contract || steps.validate_reused_dcode_base.outputs.contract }} - dcode_base_ref: ${{ steps.validate_dcode_base.outputs.base_ref || steps.validate_reused_dcode_base.outputs.base_ref }} - managed_image_revision: ${{ steps.publication.outputs.head_sha || (steps.publication_mode.outputs.reuse == '1' && 'e38db201413b457614904187377ed9fd002d281d') || inputs.checkout_sha || github.sha }} + dcode_base_contract: ${{ steps.validate_dcode_base.outputs.contract }} + dcode_base_ref: ${{ steps.validate_dcode_base.outputs.base_ref }} + managed_image_revision: ${{ steps.publication.outputs.head_sha }} + workload_source: ${{ steps.select_pr_source.outputs.workload_source || 'managed-image' }} permissions: actions: read contents: read + pull-requests: read steps: - id: publication_mode name: Classify base-image publication requirement @@ -116,14 +118,14 @@ jobs: shell: bash run: | set -euo pipefail - reuse=0 + pr=0 case "${REPOSITORY}:${REF}:${EVENT_NAME}:${CHECKOUT_SHA:+controller}" in NVIDIA/NemoClaw:refs/heads/main:push:|NVIDIA/NemoClaw:refs/heads/main:workflow_dispatch:) required=1 ;; NVIDIA/NemoClaw:refs/heads/*:workflow_dispatch:controller) required=0 - reuse=1 + pr=1 ;; *) echo "::error::base-image publication mode is not trusted" >&2 @@ -131,10 +133,10 @@ jobs: ;; esac printf 'required=%s\n' "${required}" >> "${GITHUB_OUTPUT}" - printf 'reuse=%s\n' "${reuse}" >> "${GITHUB_OUTPUT}" + printf 'pr=%s\n' "${pr}" >> "${GITHUB_OUTPUT}" - name: Check out trusted E2E workflow - if: ${{ steps.publication_mode.outputs.required == '1' || steps.publication_mode.outputs.reuse == '1' }} + if: ${{ steps.publication_mode.outputs.required == '1' || steps.publication_mode.outputs.pr == '1' }} uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.workflow_sha || github.workflow_sha }} @@ -142,16 +144,45 @@ jobs: persist-credentials: false - name: Set up Node for publication verification - if: ${{ steps.publication_mode.outputs.required == '1' || steps.publication_mode.outputs.reuse == '1' }} + if: ${{ steps.publication_mode.outputs.required == '1' || steps.publication_mode.outputs.pr == '1' }} uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: node-version: 22 + - id: select_pr_source + name: Select PR workload source + if: ${{ steps.publication_mode.outputs.pr == '1' }} + env: + BASE_SHA: ${{ inputs.base_sha }} + CANDIDATE_REPOSITORY: ${{ inputs.checkout_repository }} + CANDIDATE_SHA: ${{ inputs.checkout_sha }} + GITHUB_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.pr_number }} + shell: bash + run: | + set -euo pipefail + source_path="${RUNNER_TEMP}/pr-managed-image-source" + node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-source.mts select "$source_path" + workload_source="$(cat "$source_path")" + case "$workload_source" in + managed-image|local-dockerfile) ;; + *) echo "::error::PR workload source is invalid" >&2; exit 1 ;; + esac + printf 'workload_source=%s\n' "$workload_source" >>"$GITHUB_OUTPUT" + + - name: Check out trusted PR base + if: ${{ steps.select_pr_source.outputs.workload_source == 'managed-image' }} + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.base_sha }} + fetch-depth: 0 + persist-credentials: false + - id: publication name: Verify applicable base-image publication - if: ${{ steps.publication_mode.outputs.required == '1' }} + if: ${{ steps.publication_mode.outputs.required == '1' || steps.select_pr_source.outputs.workload_source == 'managed-image' }} env: - EXPECTED_SHA: ${{ inputs.checkout_sha || github.sha }} + EXPECTED_SHA: ${{ steps.publication_mode.outputs.required == '1' && (inputs.checkout_sha || github.sha) || inputs.base_sha }} GITHUB_TOKEN: ${{ github.token }} REQUIRE_MANAGED_IMAGE_PUBLICATION: "1" shell: bash @@ -162,7 +193,7 @@ jobs: node --experimental-strip-types --no-warnings tools/e2e/base-image-publication.mts --wait-seconds 3000 --poll-seconds 30 - name: Download immutable Deep Agents Code base contract - if: ${{ steps.publication_mode.outputs.required == '1' }} + if: ${{ steps.publication_mode.outputs.required == '1' || steps.select_pr_source.outputs.workload_source == 'managed-image' }} env: GITHUB_TOKEN: ${{ github.token }} PUBLICATION_HEAD_SHA: ${{ steps.publication.outputs.head_sha }} @@ -170,34 +201,17 @@ jobs: PUBLICATION_RUN_ID: ${{ steps.publication.outputs.run_id }} run: node --experimental-strip-types --no-warnings tools/e2e/exact-artifact-download.mts "${RUNNER_TEMP}/dcode-base-contract" - - name: Download reused Deep Agents Code base contract - if: ${{ steps.publication_mode.outputs.reuse == '1' }} - env: - GITHUB_TOKEN: ${{ github.token }} - PUBLICATION_HEAD_SHA: e38db201413b457614904187377ed9fd002d281d - PUBLICATION_RUN_ATTEMPT: "1" - PUBLICATION_RUN_ID: "32544159037" - run: node --experimental-strip-types --no-warnings tools/e2e/exact-artifact-download.mts "${RUNNER_TEMP}/dcode-base-contract-reused" - - id: validate_dcode_base name: Validate immutable Deep Agents Code base - if: ${{ steps.publication_mode.outputs.required == '1' }} + if: ${{ steps.publication_mode.outputs.required == '1' || steps.select_pr_source.outputs.workload_source == 'managed-image' }} env: PUBLICATION_HEAD_SHA: ${{ steps.publication.outputs.head_sha }} PUBLICATION_RUN_ATTEMPT: ${{ steps.publication.outputs.run_attempt }} PUBLICATION_RUN_ID: ${{ steps.publication.outputs.run_id }} run: node --experimental-strip-types --no-warnings tools/e2e/dcode-base-image-contract.mts "${RUNNER_TEMP}/dcode-base-contract/contract.json" - - id: validate_reused_dcode_base - name: Validate reused Deep Agents Code base - if: ${{ steps.publication_mode.outputs.reuse == '1' }} - env: - PUBLICATION_HEAD_SHA: e38db201413b457614904187377ed9fd002d281d - PUBLICATION_RUN_ATTEMPT: "1" - PUBLICATION_RUN_ID: "32544159037" - run: node --experimental-strip-types --no-warnings tools/e2e/dcode-base-image-contract.mts "${RUNNER_TEMP}/dcode-base-contract-reused/contract.json" - generate-matrix: + needs: base-image-publication runs-on: ubuntu-latest timeout-minutes: 10 permissions: @@ -206,7 +220,8 @@ jobs: pull-requests: read outputs: cli_artifact_provenance: ${{ steps.record_cli_artifact.outputs.provenance }} - managed_image_catalog: ${{ steps.package_cli_artifact.outputs.managed_image_catalog }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + workload_source: ${{ needs.base-image-publication.outputs.workload_source }} e2e_credentials_allowed: ${{ steps.e2e_credentials.outputs.allowed }} matrix: ${{ steps.matrix.outputs.matrix }} test_matrix: ${{ steps.matrix.outputs.test_matrix }} @@ -574,16 +589,6 @@ jobs: fi fi - - name: Resolve exact PR managed-image catalog - if: ${{ inputs.checkout_sha != '' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} - env: - BASE_SHA: ${{ inputs.base_sha }} - CANDIDATE_REPOSITORY: ${{ inputs.checkout_repository }} - CANDIDATE_SHA: ${{ inputs.checkout_sha }} - GITHUB_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ inputs.pr_number }} - run: node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-publication.mts "${RUNNER_TEMP}/pr-managed-image-catalog.json" - - name: Check out E2E candidate uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 if: ${{ inputs.checkout_sha == '' || inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '' }} @@ -700,21 +705,6 @@ jobs: ' dist/build-identity.json >/dev/null || { echo "::error::candidate CLI build identity does not match the candidate commit SHA"; exit 1; } - managed_catalog="${RUNNER_TEMP}/pr-managed-image-catalog.json" - rm -f -- dist/e2e-managed-image-catalog.json - if [[ -e "$managed_catalog" ]]; then - [[ -f "$managed_catalog" && ! -L "$managed_catalog" && -s "$managed_catalog" ]] || - { echo "::error::trusted PR managed-image catalog is not a nonempty regular file"; exit 1; } - candidate_release="v$(jq -r '.nemoclawVersion' dist/build-identity.json)" - jq -e --arg release "$candidate_release" --arg revision "$CANDIDATE_SHA" ' - type == "object" and length > 0 and - all(.[]; .source.revision == $revision and .source.release == $release) - ' "$managed_catalog" >/dev/null || - { echo "::error::managed-image catalog source identity does not match the candidate"; exit 1; } - install -m 0600 "$managed_catalog" dist/e2e-managed-image-catalog.json - printf 'managed_image_catalog=%s\n' "$(jq -c . "$managed_catalog")" >>"$GITHUB_OUTPUT" - fi - artifact_dir="${RUNNER_TEMP}/nemoclaw-cli-artifact" install -d -m 0700 "$artifact_dir" payload="$artifact_dir/nemoclaw-cli.tar" @@ -2708,8 +2698,9 @@ jobs: include: ${{ fromJSON(needs.generate-matrix.outputs.matrix) }} env: E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - NEMOCLAW_LANGCHAIN_DEEPAGENTS_CODE_SANDBOX_BASE_IMAGE_REF: ${{ needs.base-image-publication.outputs.dcode_base_ref }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_revision }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} + NEMOCLAW_LANGCHAIN_DEEPAGENTS_CODE_SANDBOX_BASE_IMAGE_REF: ${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && needs.base-image-publication.outputs.dcode_base_ref || '' }} NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js NEMOCLAW_RUN_LIVE_E2E: "1" NEMOCLAW_E2E_USE_HOSTED_INFERENCE: "1" @@ -2765,7 +2756,7 @@ jobs: build-cli: "false" - name: Record immutable Deep Agents Code base evidence - if: ${{ matrix.id == 'ubuntu-repo-cloud-langchain-deepagents-code' }} + if: ${{ matrix.id == 'ubuntu-repo-cloud-langchain-deepagents-code' && needs.generate-matrix.outputs.workload_source == 'managed-image' }} env: BASE_CONTRACT: ${{ needs.base-image-publication.outputs.dcode_base_contract }} CANDIDATE_SHA: ${{ inputs.checkout_sha || github.sha }} @@ -2998,7 +2989,8 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} + managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_revision }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: no provider credential target_id: ${{ matrix.target_id }} catalogue_id: ${{ matrix.id }} @@ -3038,7 +3030,8 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} + managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_revision }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: NVIDIA API key target_id: ${{ matrix.target_id }} catalogue_id: ${{ matrix.id }} @@ -3079,7 +3072,8 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} + managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_revision }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: NVIDIA inference API key target_id: ${{ matrix.target_id }} catalogue_id: ${{ matrix.id }} @@ -3120,7 +3114,8 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} + managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_revision }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: GitHub read token target_id: ${{ matrix.target_id }} catalogue_id: ${{ matrix.id }} @@ -3161,7 +3156,8 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} + managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_revision }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: Brave and NVIDIA inference API keys target_id: ${{ matrix.target_id }} catalogue_id: ${{ matrix.id }} @@ -4969,6 +4965,8 @@ jobs: E2E_OBSERVABLE_OUTCOME: "Install onboarding health inference lifecycle dashboard and security succeed" E2E_ENVIRONMENT_OR_INFERENCE_ENDPOINT: "Ubuntu; mock or NVIDIA hosted inference" E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live/hermes-e2e + E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_revision }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js NEMOCLAW_RUN_LIVE_E2E: "1" NEMOCLAW_E2E_INFERENCE_MODE: ${{ inputs.inference_mode || 'mock' }} @@ -5380,7 +5378,8 @@ jobs: E2E_OBSERVABLE_OUTCOME: "Public install onboarding hosted inference and security checks succeed" E2E_ENVIRONMENT_OR_INFERENCE_ENDPOINT: "Ubuntu; NVIDIA hosted inference" E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live/cloud-onboard - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_revision }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js NEMOCLAW_RUN_LIVE_E2E: "1" NEMOCLAW_E2E_USE_HOSTED_INFERENCE: "1" @@ -5431,30 +5430,6 @@ jobs: with: provenance-json: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - - name: Materialize cloud-onboard managed-image catalog - if: ${{ needs.generate-matrix.outputs.managed_image_catalog != '' }} - env: - CANDIDATE_SHA: ${{ inputs.checkout_sha || github.sha }} - MANAGED_IMAGE_CATALOG: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - shell: bash - run: | - set -euo pipefail - candidate_release="v$(jq -r '.nemoclawVersion' dist/build-identity.json)" - catalog_path="${RUNNER_TEMP}/e2e-managed-image-catalog.json" - jq -e --arg release "$candidate_release" --arg revision "$CANDIDATE_SHA" ' - type == "object" and length > 0 and - all(.[]; .source.revision == $revision and .source.release == $release) - ' <<<"$MANAGED_IMAGE_CATALOG" >/dev/null || { - echo "::error::managed-image catalog source identity does not match the candidate" >&2 - exit 1 - } - jq -c . <<<"$MANAGED_IMAGE_CATALOG" >"$catalog_path" - [[ -s "$catalog_path" && ! -L "$catalog_path" ]] || { - echo "::error::temporary managed-image catalog is invalid" >&2 - exit 1 - } - printf 'NEMOCLAW_E2E_MANAGED_IMAGE_CATALOG=%s\n' "$catalog_path" >>"$GITHUB_ENV" - - name: Install OpenShell CLI run: bash scripts/install-openshell.sh @@ -5529,6 +5504,8 @@ jobs: E2E_OBSERVABLE_OUTCOME: "Provider configuration redaction and optional real sends succeed" E2E_ENVIRONMENT_OR_INFERENCE_ENDPOINT: "Ubuntu; NVIDIA hosted inference and messaging providers" E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live/messaging-providers + E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_revision }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js NEMOCLAW_RUN_LIVE_E2E: "1" NEMOCLAW_E2E_USE_HOSTED_INFERENCE: "1" diff --git a/.github/workflows/managed-images.yaml b/.github/workflows/managed-images.yaml index 8caf027abc1..07074cdb779 100644 --- a/.github/workflows/managed-images.yaml +++ b/.github/workflows/managed-images.yaml @@ -1044,7 +1044,7 @@ jobs: find "$RUNNER_TEMP/managed-pr-contracts" -type f -name contract.json -print0 ) node --experimental-strip-types --no-warnings \ - tools/e2e/pr-managed-image-publication.mts assemble \ + tools/e2e/pr-managed-image-source.mts assemble \ "$CANDIDATE_SHA" \ "$NEMOCLAW_MANAGED_ACTIVATION_CATALOG" \ "${contracts[@]}" @@ -1146,7 +1146,7 @@ jobs: find "$RUNNER_TEMP/managed-pr-contracts" -type f -name contract.json -print0 ) node --experimental-strip-types --no-warnings \ - tools/e2e/pr-managed-image-publication.mts assemble \ + tools/e2e/pr-managed-image-source.mts assemble \ "$CANDIDATE_SHA" \ "$NEMOCLAW_E2E_MANAGED_IMAGE_CATALOG" \ "${contracts[@]}" diff --git a/test/e2e/RETRY_INVENTORY.md b/test/e2e/RETRY_INVENTORY.md index 46ac38bd787..6214d2e0613 100644 --- a/test/e2e/RETRY_INVENTORY.md +++ b/test/e2e/RETRY_INVENTORY.md @@ -23,7 +23,7 @@ Exhaustion remains failed. | `hermes-pinned-source-archive` | Hermes base-image source archive; `scripts/checks/download-hermes-source-archive.sh`, `agents/hermes/Dockerfile.base` | Final HTTP 429 only; curl transport failures and every other HTTP status are terminal | 3 total attempts; fixed 1s then 2s | Each attempt repeats the same read-only GET for one version-pinned archive. A failed or partial file is removed before another attempt, and the existing SHA-256 check remains before extraction. | GitHub source archive | `passed-first-attempt`, `passed-after-retry`, `failed-no-retry`, or `exhausted` | The build log records only the attempt number, total attempts, outcome, retry delay, and bounded failure class. Curl output, response content, URLs, paths, headers, and environment values are excluded. | Eligible bounded external read after HTTP 429 in both native Hermes base-image builds in #9815; checksum, archive, extraction, and patch failures remain terminal, and no workflow or platform-build retry occurs | | `trusted-controller-collaborator-permission-read` | Collaborator-permission reads for manual PR dispatch and Launchable E2E dispatch; `.github/workflows/e2e.yaml` | Curl exit 5, 6, 7, 16, 18, 28, 35, 52, 55, 56, 92, 95, or 96; HTTP 408, 429, or 5xx | 3 attempts; linear 1s then 2s | Read-only GitHub API request | GitHub API | Transient API read versus terminal authentication, authorization, actor, or response failure | Operation name, attempt number, and sanitized failure class or HTTP status; no response body, header, or token | Eligible bounded read; HTTP 401, 403, 404, and 422, malformed responses, actor failures, and insufficient roles remain terminal; no cached permission or workflow rerun | | `pr-exact-openclaw-mcp-repetition` | Exact managed-image OpenClaw MCP discovery and lifecycle acceptance; `.github/workflows/managed-images.yaml`, `test/e2e/live/mcp-bridge.test.ts` | Either independent matrix execution fails | 2 required executions on fresh runners; 0 workflow or test retries | Each execution creates and cleans up its own sandbox against the same exact candidate publication cohort | NemoClaw | Each execution passes or fails independently; both must pass | Existing redacted MCP diagnostics, request ledger, cleanup evidence, and fixture-credential scan for each matrix pass | Fixed acceptance repetition required by #8746; not a retry, and one pass never masks the other; trusted-private DNS-rebinding remains in full E2E where the supervisor resolver is authoritative | -| `github-exact-artifact-content-read` | Bound base-image or PR managed-image contract artifact; `tools/e2e/exact-artifact-download.mts`, `tools/e2e/pr-managed-image-publication.mts` | Transport failure, HTTP 408, HTTP 429, or HTTP 5xx while reading one pre-bound artifact ID | 3 attempts; Retry-After or linear delay capped at 10s | Read-only request against one immutable artifact ID, name, size, digest, producer run, attempt, and producer commit | GitHub artifact service | `passed-first-attempt`, `passed-after-retry`, `exhausted` for transient exhaustion, or `failed-no-retry` for terminal HTTP; identity, size, digest, archive, and contract failures throw without an aggregate outcome or `failureClass` | Content-read attempts log only the sanitized operation, attempt, HTTP status or transport class, and outcome; thrown validation failures expose only their bounded error message, never headers, body, token, signed URL, or artifact content | Standalone bounded content read; it does not use `retry-policy.ts` or `RetryEvidence`, and all identity, integrity, archive, and contract failures remain terminal | +| `github-exact-artifact-content-read` | Bound base-image or managed-image contract artifact; `tools/e2e/exact-artifact-download.mts` | Transport failure, HTTP 408, HTTP 429, or HTTP 5xx while reading one pre-bound artifact ID | 3 attempts; Retry-After or linear delay capped at 10s | Read-only request against one immutable artifact ID, name, size, digest, producer run, attempt, and producer commit | GitHub artifact service | `passed-first-attempt`, `passed-after-retry`, `exhausted` for transient exhaustion, or `failed-no-retry` for terminal HTTP; identity, size, digest, archive, and contract failures throw without an aggregate outcome or `failureClass` | Content-read attempts log only the sanitized operation, attempt, HTTP status or transport class, and outcome; thrown validation failures expose only their bounded error message, never headers, body, token, signed URL, or artifact content | Standalone bounded content read; it does not use `retry-policy.ts` or `RetryEvidence`, and all identity, integrity, archive, and contract failures remain terminal | | `inference-set-route-convergence` | Sandbox inference probe after one OpenShell route selection; `src/lib/actions/inference-set-provider.ts`, `src/lib/actions/inference-set.ts` | HTTP 400 or 404 only when the selected API family changes; authentication, authorization, unsafe or malformed input, every other HTTP status, transport failure, and probe failure are terminal | Initial 6s route-cache wait after a provider/model change; then up to 3 probes with 2s and 4s retry delays | Each retry repeats only the read-only sandbox inference probe after one route mutation | OpenShell route cache | Converged, terminal failure, or exhausted rollback | Retry progress records only HTTP status, attempt number, and delay; the final command error stays redacted, and focused tests assert the exact attempt count and rollback | The initial wait covers one full 5s OpenShell 0.0.106 cache-refresh interval even when the stale route returns a valid 2xx; exhaustion restores the prior route, removes the uncommitted provider, and remains failed | | `inference-switch-ts` | Verified inference route update; `test/e2e/fixtures/inference-switch-retry.ts` | Timeout, reset, DNS/connectivity/connect error, request transport error, or exact 502/503/504 status; authentication, authorization, policy, malformed-input, and invalid-request signals take precedence | 1-10 attempts; linear 5s | Setting the same desired provider/model is idempotent | Inference provider | Shared `RetryEvidence` classifications | Every attempt classification and aggregate outcome; command artifacts remain separate and redacted | Uses `runBoundedRetry`; deterministic verification mismatches stop; no `--no-verify` exhaustion bypass | | `inference-switch-shell` | Verified shell inference route update; `test/e2e/lib/inference-switch-retry.sh` | Same bounded transient and terminal-precedence signatures as the TypeScript helper | 1-10 attempts; linear 5s | Setting the same desired provider/model is idempotent | Inference provider | Exit status remains failed on exhaustion | Existing command output and retry progress | Bounded compatibility helper; no `--no-verify` exhaustion bypass | diff --git a/test/e2e/fixtures/workload-source-env.ts b/test/e2e/fixtures/workload-source-env.ts index 23f363adc93..3d801953af2 100644 --- a/test/e2e/fixtures/workload-source-env.ts +++ b/test/e2e/fixtures/workload-source-env.ts @@ -5,36 +5,35 @@ import path from "node:path"; import { REPO_ROOT } from "./paths.ts"; -const LEGACY_DOCKERFILE_BY_AGENT = { +const LOCAL_DOCKERFILE_BY_AGENT = { openclaw: "Dockerfile", hermes: "agents/hermes/Dockerfile", "langchain-deepagents-code": "agents/langchain-deepagents-code/Dockerfile", } as const; -type LegacyDockerfileAgent = keyof typeof LEGACY_DOCKERFILE_BY_AGENT; +type LocalDockerfileAgent = keyof typeof LOCAL_DOCKERFILE_BY_AGENT; -function legacyDockerfileAgent(env: NodeJS.ProcessEnv): LegacyDockerfileAgent { +function localDockerfileAgent(env: NodeJS.ProcessEnv): LocalDockerfileAgent { const agent = env.NEMOCLAW_AGENT ?? "openclaw"; - if (agent in LEGACY_DOCKERFILE_BY_AGENT) return agent as LegacyDockerfileAgent; + if (agent in LOCAL_DOCKERFILE_BY_AGENT) return agent as LocalDockerfileAgent; return "openclaw"; } /** - * Existing live E2E targets retain the product's default legacy-Dockerfile - * path. Targets that must select a source explicitly do so through the - * provider-neutral E2E_WORKLOAD_SOURCE contract. + * Live E2E targets select the trusted managed image or a Dockerfile from the + * candidate checkout through the E2E_WORKLOAD_SOURCE contract. * * This is applied at the final fixture spawn boundary so an agent selected by * a test command receives its own Dockerfile rather than an OpenClaw default. */ export function resolveLiveE2eWorkloadSourceEnv(input: NodeJS.ProcessEnv): NodeJS.ProcessEnv { - const targetId = input.E2E_TARGET_ID; - const source = input.E2E_WORKLOAD_SOURCE; - if (!targetId || source !== "legacy-dockerfile") return input; + const targetId = input.E2E_TARGET_ID ?? process.env.E2E_TARGET_ID; + const source = input.E2E_WORKLOAD_SOURCE ?? process.env.E2E_WORKLOAD_SOURCE; + if (!targetId || source !== "local-dockerfile") return input; if (input.NEMOCLAW_FROM_DOCKERFILE) return input; - const agent = legacyDockerfileAgent(input); + const agent = localDockerfileAgent({ ...process.env, ...input }); return { ...input, - NEMOCLAW_FROM_DOCKERFILE: path.join(REPO_ROOT, LEGACY_DOCKERFILE_BY_AGENT[agent]), + NEMOCLAW_FROM_DOCKERFILE: path.join(REPO_ROOT, LOCAL_DOCKERFILE_BY_AGENT[agent]), }; } diff --git a/test/e2e/support/base-image-publication-workflow-boundary.test.ts b/test/e2e/support/base-image-publication-workflow-boundary.test.ts index 3e4be2fd102..7c4fa7cef92 100644 --- a/test/e2e/support/base-image-publication-workflow-boundary.test.ts +++ b/test/e2e/support/base-image-publication-workflow-boundary.test.ts @@ -127,7 +127,7 @@ describe("base-image publication workflow boundary (#7372)", () => { ], ])( "classifies %s without executing untrusted code (#7372)", - (_case, eventName, checkoutSha, ref, required, reuse) => { + (_case, eventName, checkoutSha, ref, required, pr) => { expect( runClassifier({ checkoutSha, @@ -135,7 +135,7 @@ describe("base-image publication workflow boundary (#7372)", () => { ref, repository: "NVIDIA/NemoClaw", }), - ).toEqual({ output: `required=${required}\nreuse=${reuse}\n`, status: 0 }); + ).toEqual({ output: `required=${required}\npr=${pr}\n`, status: 0 }); }, ); @@ -193,20 +193,49 @@ describe("base-image publication workflow boundary (#7372)", () => { ["Node condition", (value) => (gateSteps(value)[2].if = "${{ always() }}")], ["Node pin", (value) => (gateSteps(value)[2].uses = "actions/setup-node@v6")], ["Node version", (value) => (gateSteps(value)[2].with!["node-version"] = 20)], - ["verifier condition", (value) => (gateSteps(value)[3].if = "${{ always() }}")], - ["verifier token", (value) => (gateSteps(value)[3].env!.GITHUB_TOKEN = "${{ secrets.TOKEN }}")], + [ + "selector condition", + (value) => (gateStep(value, "Select PR workload source").if = "${{ always() }}"), + ], + [ + "selector token", + (value) => + (gateStep(value, "Select PR workload source").env!.GITHUB_TOKEN = "${{ secrets.TOKEN }}"), + ], + [ + "PR base checkout ref", + (value) => + (gateStep(value, "Check out trusted PR base").with!.ref = "${{ inputs.checkout_sha }}"), + ], + [ + "verifier condition", + (value) => + (gateStep(value, "Verify applicable base-image publication").if = "${{ always() }}"), + ], + [ + "verifier token", + (value) => + (gateStep(value, "Verify applicable base-image publication").env!.GITHUB_TOKEN = + "${{ secrets.TOKEN }}"), + ], [ "verifier SHA", - (value) => (gateSteps(value)[3].env!.EXPECTED_SHA = "${{ inputs.checkout_sha }}"), + (value) => + (gateStep(value, "Verify applicable base-image publication").env!.EXPECTED_SHA = + "${{ inputs.checkout_sha }}"), ], [ "managed-image publication requirement", - (value) => (gateSteps(value)[3].env!.REQUIRE_MANAGED_IMAGE_PUBLICATION = "0"), + (value) => + (gateStep(value, "Verify applicable base-image publication").env![ + "REQUIRE_MANAGED_IMAGE_PUBLICATION" + ] = "0"), ], [ "verifier command", (value) => { - gateSteps(value)[3].run = "node tools/e2e/base-image-publication.mts"; + gateStep(value, "Verify applicable base-image publication").run = + "node tools/e2e/base-image-publication.mts"; }, ], [ @@ -229,15 +258,20 @@ describe("base-image publication workflow boundary (#7372)", () => { "node tools/e2e/dcode-base-image-contract.mts contract.json"), ], ["step count", (value) => gateSteps(value).push({ name: "Unreviewed step", run: "true" })], + ["matrix publication dependency", (value) => (value.jobs["generate-matrix"].needs = [])], [ - "matrix publication dependency", - (value) => (value.jobs["generate-matrix"].needs = "base-image-publication"), + "matrix workload source", + (value) => (value.jobs["generate-matrix"].outputs!.workload_source = "${{ github.sha }}"), ], ["live publication dependency", (value) => (value.jobs.live.needs = ["generate-matrix"])], [ "live managed-image revision", (value) => (value.jobs.live.env!.E2E_MANAGED_IMAGE_REVISION = "${{ github.sha }}"), ], + [ + "live workload source", + (value) => (value.jobs.live.env!.E2E_WORKLOAD_SOURCE = "managed-image"), + ], [ "cloud-onboard publication dependency", (value) => (value.jobs["cloud-onboard"].needs = ["generate-matrix"]), diff --git a/test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts b/test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts index a70a95dee41..f8f95563531 100644 --- a/test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts +++ b/test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts @@ -66,7 +66,7 @@ describe("Bedrock raw-command progress", () => { artifacts, env: { E2E_TARGET_ID: "inference-routing", - E2E_WORKLOAD_SOURCE: "legacy-dockerfile", + E2E_WORKLOAD_SOURCE: "local-dockerfile", NEMOCLAW_AGENT: "langchain-deepagents-code", }, progress: observation.progress, diff --git a/test/e2e/support/pr-managed-image-publication.test.ts b/test/e2e/support/pr-managed-image-publication.test.ts deleted file mode 100644 index 18eb4bc35d9..00000000000 --- a/test/e2e/support/pr-managed-image-publication.test.ts +++ /dev/null @@ -1,201 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { describe, expect, it } from "vitest"; - -import { - MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, - MANAGED_IMAGE_CONTRACT_VERSION, - MANAGED_IMAGE_REPOSITORIES, - MANAGED_IMAGE_SOURCE_REPOSITORY, - MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, - type ManagedImageAgent, - type ManagedImageContractV1, - SHIPPED_MANAGED_IMAGE_AGENTS, -} from "../../../src/lib/onboard/managed-image/contract"; -import { - assembleManagedImageCatalog, - main, - managedImagePublicationRequired, - parseManagedImagePullRequestPaths, - selectManagedImagePublicationRun, -} from "../../../tools/e2e/pr-managed-image-publication.mts"; - -const CANDIDATE_SHA = "a".repeat(40); -const PR_NUMBER = 8746; -const WORKFLOW_ID = 12345; - -function contract(agent: ManagedImageAgent, index: number): ManagedImageContractV1 { - const image = MANAGED_IMAGE_REPOSITORIES[agent]; - const digest = `sha256:${String(index + 1).repeat(64)}` as const; - return { - contractVersion: MANAGED_IMAGE_CONTRACT_VERSION, - agent, - platform: "linux/amd64", - image, - digest, - reference: `${image}@${digest}`, - source: { - repository: MANAGED_IMAGE_SOURCE_REPOSITORY, - revision: CANDIDATE_SHA, - release: "v0.0.110", - cohort: "ghrun-32144654845-1", - }, - startupProfileContractVersion: MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, - capabilityContractVersion: MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, - }; -} - -function run(overrides: Record = {}): unknown { - return { - total_count: 1, - workflow_runs: [ - { - id: 32144654845, - run_attempt: 1, - workflow_id: WORKFLOW_ID, - name: "Images / Build, Test, and Publish Managed Images", - path: ".github/workflows/managed-images.yaml", - event: "pull_request", - head_sha: CANDIDATE_SHA, - status: "completed", - conclusion: "success", - repository: { full_name: "NVIDIA/NemoClaw" }, - head_repository: { full_name: "NVIDIA/NemoClaw" }, - pull_requests: [{ number: PR_NUMBER }], - ...overrides, - }, - ], - }; -} - -describe("exact PR managed-image publication (#8746, #9464)", () => { - it("derives applicability from the trusted managed-image workflow", () => { - const patterns = parseManagedImagePullRequestPaths( - fs.readFileSync(".github/workflows/managed-images.yaml", "utf8"), - ); - - expect( - managedImagePublicationRequired(["src/lib/onboard/workload/preparation.ts"], patterns), - ).toBe(true); - expect( - managedImagePublicationRequired(["tools/mcp-tool-discovery-runtime/server.mts"], patterns), - ).toBe(true); - expect( - managedImagePublicationRequired( - ["src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.ts"], - patterns, - ), - ).toBe(true); - expect(managedImagePublicationRequired(["docs/My Guide.md"], patterns)).toBe(false); - expect(() => - managedImagePublicationRequired(["src/lib/onboard/file.ts\nother"], patterns), - ).toThrow("changed-file path is invalid"); - }); - - it("rejects an unreviewed path-filter glob", () => { - expect(() => - parseManagedImagePullRequestPaths(` -on: - pull_request: - paths: - - ".github/workflows/managed-images.yaml" - - "src/**/nested/**" -`), - ).toThrow("unsupported glob"); - }); - - it("selects one successful workflow run for the candidate commit", () => { - expect( - selectManagedImagePublicationRun(run(), { - headSha: CANDIDATE_SHA, - prNumber: PR_NUMBER, - workflowId: WORKFLOW_ID, - }), - ).toEqual({ id: 32144654845, attempt: 1, headSha: CANDIDATE_SHA }); - }); - - it.each([ - ["pending", { status: "in_progress", conclusion: null }, "must complete successfully"], - ["failed", { conclusion: "failure" }, "must complete successfully"], - ["different commit", { head_sha: "b".repeat(40) }, "commit must be"], - ["different PR", { pull_requests: [{ number: 9464 }] }, "PR number"], - ])("rejects a %s publication run", (_label, overrides, message) => { - expect(() => - selectManagedImagePublicationRun(run(overrides), { - headSha: CANDIDATE_SHA, - prNumber: PR_NUMBER, - workflowId: WORKFLOW_ID, - }), - ).toThrow(message); - }); - - it("assembles one exact all-agent catalog", () => { - const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map(contract); - - expect(assembleManagedImageCatalog(contracts, CANDIDATE_SHA)).toEqual( - Object.fromEntries(contracts.map((value) => [value.agent, value])), - ); - }); - - it("writes a validated catalog through the shared assembly command", async () => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-catalog-test-")); - try { - const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => { - const contractPath = path.join(directory, `${agent}.json`); - fs.writeFileSync(contractPath, JSON.stringify(contract(agent, index))); - return contractPath; - }); - const outputPath = path.join(directory, "catalog.json"); - - await main(["assemble", CANDIDATE_SHA, outputPath, ...contracts], {}); - - expect(JSON.parse(fs.readFileSync(outputPath, "utf8"))).toEqual( - Object.fromEntries( - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => [agent, contract(agent, index)]), - ), - ); - expect(fs.statSync(outputPath).mode & 0o777).toBe(0o600); - } finally { - fs.rmSync(directory, { force: true, recursive: true }); - } - }); - - it.each([ - [ - "candidate revision", - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => - index === 0 - ? { - ...contract(agent, index), - source: { ...contract(agent, index).source, revision: "b".repeat(40) }, - } - : contract(agent, index), - ), - "candidate commit", - ], - [ - "publication cohort", - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => - index === 0 - ? { - ...contract(agent, index), - source: { ...contract(agent, index).source, cohort: "ghrun-32144654845-2" }, - } - : contract(agent, index), - ), - "publication cohort", - ], - [ - "agent set", - [contract("openclaw", 0), contract("openclaw", 0), contract("hermes", 1)], - "every shipped agent", - ], - ])("rejects mixed %s authority", (_label, contracts, message) => { - expect(() => assembleManagedImageCatalog(contracts, CANDIDATE_SHA)).toThrow(message); - }); -}); diff --git a/test/e2e/support/pr-managed-image-source.test.ts b/test/e2e/support/pr-managed-image-source.test.ts new file mode 100644 index 00000000000..b6385909388 --- /dev/null +++ b/test/e2e/support/pr-managed-image-source.test.ts @@ -0,0 +1,205 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { + MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, + MANAGED_IMAGE_CONTRACT_VERSION, + MANAGED_IMAGE_REPOSITORIES, + MANAGED_IMAGE_SOURCE_REPOSITORY, + MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, + type ManagedImageAgent, + type ManagedImageContractV1, + SHIPPED_MANAGED_IMAGE_AGENTS, +} from "../../../src/lib/onboard/managed-image/contract"; +import { parseBaseImagePushPaths } from "../../../tools/e2e/base-image-publication.mts"; +import { + assembleManagedImageCatalog, + managedImageInputsChanged, + resolvePrManagedImageSource, + writeManagedImageCatalog, + writePrManagedImageSource, +} from "../../../tools/e2e/pr-managed-image-source.mts"; + +const BASE_SHA = "b".repeat(40); +const CANDIDATE_SHA = "a".repeat(40); +const PR_NUMBER = 10_113; +const CANDIDATE_REPOSITORY = "NVIDIA/NemoClaw"; + +function contract(agent: ManagedImageAgent, index: number): ManagedImageContractV1 { + const image = MANAGED_IMAGE_REPOSITORIES[agent]; + const digest = `sha256:${String(index + 1).repeat(64)}` as const; + return { + contractVersion: MANAGED_IMAGE_CONTRACT_VERSION, + agent, + platform: "linux/amd64", + image, + digest, + reference: `${image}@${digest}`, + source: { + repository: MANAGED_IMAGE_SOURCE_REPOSITORY, + revision: CANDIDATE_SHA, + release: "v0.0.110", + cohort: "ghrun-32144654845-1", + }, + startupProfileContractVersion: MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, + capabilityContractVersion: MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, + }; +} + +function pull(changedFiles: number, overrides: Record = {}): unknown { + return { + state: "open", + changed_files: changedFiles, + base: { sha: BASE_SHA, repo: { full_name: "NVIDIA/NemoClaw" } }, + head: { sha: CANDIDATE_SHA, repo: { full_name: CANDIDATE_REPOSITORY } }, + ...overrides, + }; +} + +function unexpectedRequest(requestPath: string): never { + throw new Error(`unexpected request ${requestPath}`); +} + +function requestFor( + files: Array<{ filename: string; previous_filename?: string }>, + pullOverrides: Record = {}, +) { + const responses = new Map([ + [`/repos/NVIDIA/NemoClaw/pulls/${PR_NUMBER}`, pull(files.length, pullOverrides)], + [`/repos/NVIDIA/NemoClaw/pulls/${PR_NUMBER}/files?per_page=100&page=1`, files], + ]); + return async (requestPath: string): Promise => + responses.get(requestPath) ?? unexpectedRequest(requestPath); +} + +function selectorInput() { + return { + baseSha: BASE_SHA, + candidateRepository: CANDIDATE_REPOSITORY, + candidateSha: CANDIDATE_SHA, + prNumber: PR_NUMBER, + token: "test-token", + workflowSource: fs.readFileSync(".github/workflows/base-image.yaml", "utf8"), + }; +} + +describe("PR managed-image source selection", () => { + it("selects a local Dockerfile when a reviewed image input changes", async () => { + await expect( + resolvePrManagedImageSource(selectorInput(), requestFor([{ filename: "Dockerfile.base" }])), + ).resolves.toBe("local-dockerfile"); + }); + + it("selects a trusted managed image when reviewed image inputs are unchanged", async () => { + await expect( + resolvePrManagedImageSource(selectorInput(), requestFor([{ filename: "docs/guide.mdx" }])), + ).resolves.toBe("managed-image"); + }); + + it("uses the trusted base-image workflow path families", () => { + const patterns = parseBaseImagePushPaths( + fs.readFileSync(".github/workflows/base-image.yaml", "utf8"), + ); + + expect(managedImageInputsChanged(["agents/hermes/Dockerfile.base"], patterns)).toBe(true); + expect( + managedImageInputsChanged(["src/lib/onboard/managed-startup/profile.ts"], patterns), + ).toBe(true); + expect(managedImageInputsChanged(["docs/guide.mdx"], patterns)).toBe(false); + expect(() => managedImageInputsChanged(["Dockerfile.base\nother"], patterns)).toThrow( + "changed-file path is invalid", + ); + }); + + it("rejects PR identity drift before selecting a source", async () => { + const request = requestFor([{ filename: "Dockerfile" }], { + head: { sha: CANDIDATE_SHA, repo: { full_name: "attacker/fork" } }, + }); + + await expect(resolvePrManagedImageSource(selectorInput(), request)).rejects.toThrow( + "pull request source repository must be NVIDIA/NemoClaw", + ); + }); + + it("writes a private source decision file", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-source-test-")); + try { + const outputPath = path.join(directory, "source"); + writePrManagedImageSource(outputPath, "local-dockerfile"); + expect(fs.readFileSync(outputPath, "utf8")).toBe("local-dockerfile\n"); + expect(fs.statSync(outputPath).mode & 0o777).toBe(0o600); + } finally { + fs.rmSync(directory, { force: true, recursive: true }); + } + }); +}); + +describe("managed-image activation catalog assembly", () => { + it("assembles one exact all-agent catalog", () => { + const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map(contract); + expect(assembleManagedImageCatalog(contracts, CANDIDATE_SHA)).toEqual( + Object.fromEntries(contracts.map((value) => [value.agent, value])), + ); + }); + + it("writes a validated private catalog", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-catalog-test-")); + try { + const contractPaths = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => { + const contractPath = path.join(directory, `${agent}.json`); + fs.writeFileSync(contractPath, JSON.stringify(contract(agent, index))); + return contractPath; + }); + const outputPath = path.join(directory, "catalog.json"); + writeManagedImageCatalog(contractPaths, CANDIDATE_SHA, outputPath); + expect(JSON.parse(fs.readFileSync(outputPath, "utf8"))).toEqual( + Object.fromEntries( + SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => [agent, contract(agent, index)]), + ), + ); + expect(fs.statSync(outputPath).mode & 0o777).toBe(0o600); + } finally { + fs.rmSync(directory, { force: true, recursive: true }); + } + }); + + it.each([ + [ + "candidate revision", + SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => + index === 0 + ? { + ...contract(agent, index), + source: { ...contract(agent, index).source, revision: "c".repeat(40) }, + } + : contract(agent, index), + ), + "candidate commit", + ], + [ + "publication cohort", + SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => + index === 0 + ? { + ...contract(agent, index), + source: { ...contract(agent, index).source, cohort: "ghrun-32144654845-2" }, + } + : contract(agent, index), + ), + "publication cohort", + ], + [ + "agent set", + [contract("openclaw", 0), contract("openclaw", 0), contract("hermes", 1)], + "every shipped agent", + ], + ])("rejects mixed %s authority", (_label, contracts, message) => { + expect(() => assembleManagedImageCatalog(contracts, CANDIDATE_SHA)).toThrow(message); + }); +}); diff --git a/test/e2e/support/workload-source-env.test.ts b/test/e2e/support/workload-source-env.test.ts index f148454fa6f..4abbc3320f4 100644 --- a/test/e2e/support/workload-source-env.test.ts +++ b/test/e2e/support/workload-source-env.test.ts @@ -3,21 +3,23 @@ import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { REPO_ROOT } from "../fixtures/paths.ts"; import { resolveLiveE2eWorkloadSourceEnv } from "../fixtures/workload-source-env.ts"; describe("live E2E workload source environment", () => { + afterEach(() => vi.unstubAllEnvs()); + it.each([ ["openclaw", "Dockerfile"], ["hermes", "agents/hermes/Dockerfile"], ["langchain-deepagents-code", "agents/langchain-deepagents-code/Dockerfile"], - ])("honors the explicit legacy-Dockerfile source for %s", (agent, dockerfile) => { + ])("uses the candidate Dockerfile for %s", (agent, dockerfile) => { expect( resolveLiveE2eWorkloadSourceEnv({ E2E_TARGET_ID: "full-e2e", - E2E_WORKLOAD_SOURCE: "legacy-dockerfile", + E2E_WORKLOAD_SOURCE: "local-dockerfile", NEMOCLAW_AGENT: agent, }), ).toMatchObject({ @@ -30,19 +32,28 @@ describe("live E2E workload source environment", () => { expect(resolveLiveE2eWorkloadSourceEnv(input)).toEqual(input); }); - it.each([ - "managed-image-protected-runtime", - "podman-native-cpu", - "mxc-runtime-proof", - ])("honors the provider-neutral managed-image source for %s", (targetId) => { - expect( - resolveLiveE2eWorkloadSourceEnv({ - E2E_TARGET_ID: targetId, - E2E_WORKLOAD_SOURCE: "managed-image", - }), - ).toEqual({ - E2E_TARGET_ID: targetId, - E2E_WORKLOAD_SOURCE: "managed-image", + it("inherits the workflow source decision at the child command boundary", () => { + vi.stubEnv("E2E_TARGET_ID", "hermes-e2e"); + vi.stubEnv("E2E_WORKLOAD_SOURCE", "local-dockerfile"); + vi.stubEnv("NEMOCLAW_AGENT", "hermes"); + + expect(resolveLiveE2eWorkloadSourceEnv({})).toEqual({ + NEMOCLAW_FROM_DOCKERFILE: path.join(REPO_ROOT, "agents/hermes/Dockerfile"), }); }); + + it.each(["managed-image-protected-runtime", "podman-native-cpu", "mxc-runtime-proof"])( + "honors the provider-neutral managed-image source for %s", + (targetId) => { + expect( + resolveLiveE2eWorkloadSourceEnv({ + E2E_TARGET_ID: targetId, + E2E_WORKLOAD_SOURCE: "managed-image", + }), + ).toEqual({ + E2E_TARGET_ID: targetId, + E2E_WORKLOAD_SOURCE: "managed-image", + }); + }, + ); }); diff --git a/test/inference/managed/managed-image-publication-workflow.test.ts b/test/inference/managed/managed-image-publication-workflow.test.ts index 62a1e59b720..30076c6a60d 100644 --- a/test/inference/managed/managed-image-publication-workflow.test.ts +++ b/test/inference/managed/managed-image-publication-workflow.test.ts @@ -379,9 +379,7 @@ describe("complete managed-image publication workflow", () => { expect(step(prBuilder, "Checkout").with?.["persist-credentials"]).toBe(false); expect(step(prBuilder, "Checkout").with?.ref).toBe("${{ github.event.pull_request.head.sha }}"); expect(releaseIdentity.id).toBe("release"); - expect(releaseIdentity.run).toContain( - "git describe --tags --match 'v*' \"$CANDIDATE_SHA\"", - ); + expect(releaseIdentity.run).toContain("git describe --tags --match 'v*' \"$CANDIDATE_SHA\""); expect(releaseIdentity.run).toContain("value=%s"); expect(step(prBuilder, "Set up Docker Buildx").id).toBe("buildx"); const matrixByAgent = new Map(matrix.map((entry) => [entry.agent, entry])); @@ -637,7 +635,7 @@ describe("complete managed-image publication workflow", () => { "${{ github.event.pull_request.head.sha }}", ); expect(step(activation, "Assemble exact all-agent activation catalog").run).toMatch( - /npm ci --ignore-scripts[\s\S]*pr-managed-image-publication\.mts assemble[\s\S]*"\$CANDIDATE_SHA"[\s\S]*"\$\{contracts\[@\]\}"/u, + /npm ci --ignore-scripts[\s\S]*pr-managed-image-source\.mts assemble[\s\S]*"\$CANDIDATE_SHA"[\s\S]*"\$\{contracts\[@\]\}"/u, ); expect(step(activation, "Build exact candidate CLI").run).toContain("npm run build:cli"); expect(step(activation, "Install OpenShell CLI").run).toContain("scripts/install-openshell.sh"); @@ -689,7 +687,7 @@ describe("complete managed-image publication workflow", () => { expect(step(discovery, "Bind E2E correlation identity").run).toContain("randomUUID()"); const assemble = step(discovery, "Assemble exact all-agent MCP catalog").run ?? ""; expect(assemble).toMatch( - /npm ci --ignore-scripts[\s\S]*pr-managed-image-publication\.mts assemble[\s\S]*"\$CANDIDATE_SHA"[\s\S]*"\$\{contracts\[@\]\}"/u, + /npm ci --ignore-scripts[\s\S]*pr-managed-image-source\.mts assemble[\s\S]*"\$CANDIDATE_SHA"[\s\S]*"\$\{contracts\[@\]\}"/u, ); const run = step(discovery, "Run exact OpenClaw managed-image MCP discovery").run ?? ""; expect(run).toContain('[[ "$(git rev-parse --verify HEAD)" == "$CANDIDATE_SHA" ]]'); diff --git a/tools/e2e/cli-artifact-workflow-boundary.mts b/tools/e2e/cli-artifact-workflow-boundary.mts index a14b94b91d8..2d2bb8c00f0 100644 --- a/tools/e2e/cli-artifact-workflow-boundary.mts +++ b/tools/e2e/cli-artifact-workflow-boundary.mts @@ -267,9 +267,6 @@ function validateProducer(errors: string[], producer: WorkflowRecord): void { ".sourceRevision == $candidateSha", "candidate CLI build identity does not match the candidate commit SHA", - ".source.revision == $revision", - ".source.release == $release", - "managed-image catalog source identity does not match the candidate", "--sort=name", "--mtime=@0", "nemoclaw/dist/shared", @@ -349,9 +346,7 @@ function validateConsumer( ): void { if (jobName === "mcp-bridge-dev") { const { steps: _jobSteps, ...jobExecutionContext } = job; - if ( - contentSha256(jobExecutionContext) !== MCP_DEV_JOB_EXECUTION_CONTEXT_SHA256 - ) { + if (contentSha256(jobExecutionContext) !== MCP_DEV_JOB_EXECUTION_CONTEXT_SHA256) { errors.push( "mcp-bridge-dev must preserve its reviewed job execution context before candidate activation", ); @@ -402,10 +397,7 @@ function validateConsumer( ? trustedInstallIndex : jobSteps.length - 1 : restoreIndex; - const stepsThroughSecurityBoundary = jobSteps.slice( - 0, - securityBoundaryIndex + 1, - ); + const stepsThroughSecurityBoundary = jobSteps.slice(0, securityBoundaryIndex + 1); const jobEnv = record(job.env); const defaultShell = record(record(job.defaults).run).shell; const unsafePreRestoreStep = stepsThroughSecurityBoundary.some( @@ -451,9 +443,7 @@ function validateConsumer( contentSha256(jobSteps.slice(0, trustedInstallIndex + 1)) !== MCP_DEV_TRUSTED_PREFIX_CONTENT_SHA256) ) { - errors.push( - "mcp-bridge-dev must preserve every reviewed step through trusted installation", - ); + errors.push("mcp-bridge-dev must preserve every reviewed step through trusted installation"); } if ( jobName === "mcp-bridge-dev" && @@ -485,13 +475,8 @@ function validateConsumer( const stepsBeforeRestore = jobSteps .slice(reviewedStepsStart, restoreIndex) .map((step) => step.name); - if ( - prepareIndex >= 0 && - !isDeepStrictEqual(stepsBeforeRestore, reviewedStepsBeforeRestore) - ) { - errors.push( - `${jobName} must preserve its reviewed steps through CLI artifact restore`, - ); + if (prepareIndex >= 0 && !isDeepStrictEqual(stepsBeforeRestore, reviewedStepsBeforeRestore)) { + errors.push(`${jobName} must preserve its reviewed steps through CLI artifact restore`); } } diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index 50b2bcb9bf2..fb8b1011f21 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -34,20 +34,22 @@ const E2E_ARTIFACT_ACTION = "NVIDIA/NemoClaw/.github/actions/upload-e2e-artifact const COLD_ONBOARD_PERFORMANCE_EVIDENCE_PATH = "e2e-artifacts/live/${{ matrix.id }}/onboard-progress-budget.json"; const PUBLICATION_REQUIRED_CONDITION = "${{ steps.publication_mode.outputs.required == '1' }}"; -const PUBLICATION_REUSE_CONDITION = "${{ steps.publication_mode.outputs.reuse == '1' }}"; -const PUBLICATION_REQUIRED_OR_REUSE_CONDITION = - "${{ steps.publication_mode.outputs.required == '1' || steps.publication_mode.outputs.reuse == '1' }}"; +const PUBLICATION_PR_CONDITION = "${{ steps.publication_mode.outputs.pr == '1' }}"; +const PUBLICATION_REQUIRED_OR_PR_CONDITION = + "${{ steps.publication_mode.outputs.required == '1' || steps.publication_mode.outputs.pr == '1' }}"; +const PUBLICATION_OR_MANAGED_SOURCE_CONDITION = + "${{ steps.publication_mode.outputs.required == '1' || steps.select_pr_source.outputs.workload_source == 'managed-image' }}"; const PUBLICATION_CLASSIFIER_SCRIPT = [ "set -euo pipefail", - "reuse=0", + "pr=0", 'case "${REPOSITORY}:${REF}:${EVENT_NAME}:${CHECKOUT_SHA:+controller}" in', " NVIDIA/NemoClaw:refs/heads/main:push:|NVIDIA/NemoClaw:refs/heads/main:workflow_dispatch:)", " required=1", " ;;", " NVIDIA/NemoClaw:refs/heads/*:workflow_dispatch:controller)", " required=0", - " reuse=1", + " pr=1", " ;;", " *)", ' echo "::error::base-image publication mode is not trusted" >&2', @@ -55,7 +57,7 @@ const PUBLICATION_CLASSIFIER_SCRIPT = " ;;", "esac", 'printf \'required=%s\\n\' "${required}" >> "${GITHUB_OUTPUT}"', - 'printf \'reuse=%s\\n\' "${reuse}" >> "${GITHUB_OUTPUT}"', + 'printf \'pr=%s\\n\' "${pr}" >> "${GITHUB_OUTPUT}"', ].join("\n") + "\n"; const ISSUE_API_REFERENCE = /\bgithub\.rest\.issues\b/u; const ISSUE_MUTATION_BEYOND_COMMENT = @@ -483,9 +485,13 @@ function validateManualPrDispatch(errors: string[], workflow: OperationsWorkflow step.with?.ref === "${{ github.workflow_sha }}"; const trustedPublicationCheckout = jobName === "base-image-publication" && - step.name === "Check out trusted E2E workflow" && - step.if === PUBLICATION_REQUIRED_OR_REUSE_CONDITION && - step.with?.ref === "${{ inputs.workflow_sha || github.workflow_sha }}"; + ((step.name === "Check out trusted E2E workflow" && + step.if === PUBLICATION_REQUIRED_OR_PR_CONDITION && + step.with?.ref === "${{ inputs.workflow_sha || github.workflow_sha }}") || + (step.name === "Check out trusted PR base" && + step.if === + "${{ steps.select_pr_source.outputs.workload_source == 'managed-image' }}" && + step.with?.ref === "${{ inputs.base_sha }}")); const trustedManagedImageRuntimeCheckout = jobName === "managed-image-protected-runtime" && step.name === "Checkout trusted protected runtime qualification" && @@ -593,16 +599,15 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): "runs-on": "ubuntu-latest", "timeout-minutes": 55, outputs: { - dcode_base_contract: - "${{ steps.validate_dcode_base.outputs.contract || steps.validate_reused_dcode_base.outputs.contract }}", - dcode_base_ref: - "${{ steps.validate_dcode_base.outputs.base_ref || steps.validate_reused_dcode_base.outputs.base_ref }}", - managed_image_revision: - "${{ steps.publication.outputs.head_sha || (steps.publication_mode.outputs.reuse == '1' && 'e38db201413b457614904187377ed9fd002d281d') || inputs.checkout_sha || github.sha }}", + dcode_base_contract: "${{ steps.validate_dcode_base.outputs.contract }}", + dcode_base_ref: "${{ steps.validate_dcode_base.outputs.base_ref }}", + managed_image_revision: "${{ steps.publication.outputs.head_sha }}", + workload_source: "${{ steps.select_pr_source.outputs.workload_source || 'managed-image' }}", }, permissions: { actions: "read", contents: "read", + "pull-requests": "read", }, steps: [ { @@ -619,7 +624,7 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): }, { name: "Check out trusted E2E workflow", - if: PUBLICATION_REQUIRED_OR_REUSE_CONDITION, + if: PUBLICATION_REQUIRED_OR_PR_CONDITION, uses: "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1", with: { ref: "${{ inputs.workflow_sha || github.workflow_sha }}", @@ -629,18 +634,54 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): }, { name: "Set up Node for publication verification", - if: PUBLICATION_REQUIRED_OR_REUSE_CONDITION, + if: PUBLICATION_REQUIRED_OR_PR_CONDITION, uses: "actions/setup-node@820762786026740c76f36085b0efc47a31fe5020", with: { "node-version": 22, }, }, + { + id: "select_pr_source", + name: "Select PR workload source", + if: PUBLICATION_PR_CONDITION, + env: { + BASE_SHA: "${{ inputs.base_sha }}", + CANDIDATE_REPOSITORY: "${{ inputs.checkout_repository }}", + CANDIDATE_SHA: "${{ inputs.checkout_sha }}", + GITHUB_TOKEN: "${{ github.token }}", + PR_NUMBER: "${{ inputs.pr_number }}", + }, + shell: "bash", + run: [ + "set -euo pipefail", + 'source_path="${RUNNER_TEMP}/pr-managed-image-source"', + 'node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-source.mts select "$source_path"', + 'workload_source="$(cat "$source_path")"', + 'case "$workload_source" in', + " managed-image|local-dockerfile) ;;", + ' *) echo "::error::PR workload source is invalid" >&2; exit 1 ;;', + "esac", + 'printf \'workload_source=%s\\n\' "$workload_source" >>"$GITHUB_OUTPUT"', + "", + ].join("\n"), + }, + { + name: "Check out trusted PR base", + if: "${{ steps.select_pr_source.outputs.workload_source == 'managed-image' }}", + uses: "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1", + with: { + ref: "${{ inputs.base_sha }}", + "fetch-depth": 0, + "persist-credentials": false, + }, + }, { id: "publication", name: "Verify applicable base-image publication", - if: PUBLICATION_REQUIRED_CONDITION, + if: PUBLICATION_OR_MANAGED_SOURCE_CONDITION, env: { - EXPECTED_SHA: "${{ inputs.checkout_sha || github.sha }}", + EXPECTED_SHA: + "${{ steps.publication_mode.outputs.required == '1' && (inputs.checkout_sha || github.sha) || inputs.base_sha }}", GITHUB_TOKEN: "${{ github.token }}", REQUIRE_MANAGED_IMAGE_PUBLICATION: "1", }, @@ -655,7 +696,7 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): }, { name: "Download immutable Deep Agents Code base contract", - if: PUBLICATION_REQUIRED_CONDITION, + if: PUBLICATION_OR_MANAGED_SOURCE_CONDITION, env: { GITHUB_TOKEN: "${{ github.token }}", PUBLICATION_HEAD_SHA: "${{ steps.publication.outputs.head_sha }}", @@ -664,21 +705,10 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): }, run: 'node --experimental-strip-types --no-warnings tools/e2e/exact-artifact-download.mts "${RUNNER_TEMP}/dcode-base-contract"', }, - { - name: "Download reused Deep Agents Code base contract", - if: PUBLICATION_REUSE_CONDITION, - env: { - GITHUB_TOKEN: "${{ github.token }}", - PUBLICATION_HEAD_SHA: "e38db201413b457614904187377ed9fd002d281d", - PUBLICATION_RUN_ATTEMPT: "1", - PUBLICATION_RUN_ID: "32544159037", - }, - run: 'node --experimental-strip-types --no-warnings tools/e2e/exact-artifact-download.mts "${RUNNER_TEMP}/dcode-base-contract-reused"', - }, { id: "validate_dcode_base", name: "Validate immutable Deep Agents Code base", - if: PUBLICATION_REQUIRED_CONDITION, + if: PUBLICATION_OR_MANAGED_SOURCE_CONDITION, env: { PUBLICATION_HEAD_SHA: "${{ steps.publication.outputs.head_sha }}", PUBLICATION_RUN_ATTEMPT: "${{ steps.publication.outputs.run_attempt }}", @@ -686,17 +716,6 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): }, run: 'node --experimental-strip-types --no-warnings tools/e2e/dcode-base-image-contract.mts "${RUNNER_TEMP}/dcode-base-contract/contract.json"', }, - { - id: "validate_reused_dcode_base", - name: "Validate reused Deep Agents Code base", - if: PUBLICATION_REUSE_CONDITION, - env: { - PUBLICATION_HEAD_SHA: "e38db201413b457614904187377ed9fd002d281d", - PUBLICATION_RUN_ATTEMPT: "1", - PUBLICATION_RUN_ID: "32544159037", - }, - run: 'node --experimental-strip-types --no-warnings tools/e2e/dcode-base-image-contract.mts "${RUNNER_TEMP}/dcode-base-contract-reused/contract.json"', - }, ], }; @@ -706,13 +725,20 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): ); } const matrix = workflow.jobs["generate-matrix"] ?? {}; - if (needs(matrix).includes("base-image-publication")) { - errors.push("generate-matrix must not wait for base-image-publication"); + if (!sameMembers(needs(matrix), ["base-image-publication"])) { + errors.push("generate-matrix must wait for workload-source selection"); } const matrixOutputs = matrix.outputs ?? {}; if ("dcode_base_contract" in matrixOutputs || "dcode_base_ref" in matrixOutputs) { errors.push("generate-matrix must not relay Deep Agents Code base outputs"); } + if ( + matrixOutputs.managed_image_revision !== + "${{ needs.base-image-publication.outputs.managed_image_revision }}" || + matrixOutputs.workload_source !== "${{ needs.base-image-publication.outputs.workload_source }}" + ) { + errors.push("generate-matrix must relay the selected workload source and image revision"); + } const live = workflow.jobs.live ?? {}; if (!sameMembers(needs(live), ["base-image-publication", "generate-matrix"])) { errors.push("live E2E must wait for matrix generation and base-image publication"); @@ -723,25 +749,23 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): } if ( cloudOnboard.env?.E2E_MANAGED_IMAGE_REVISION !== - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}" + "${{ needs.generate-matrix.outputs.managed_image_revision }}" || + cloudOnboard.env?.E2E_WORKLOAD_SOURCE !== "${{ needs.generate-matrix.outputs.workload_source }}" ) { - errors.push( - "cloud-onboard must use the selected managed-image revision when no exact PR catalog is present", - ); + errors.push("cloud-onboard must use the selected workload source and image revision"); } if ( live.env?.E2E_MANAGED_IMAGE_REVISION !== - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}" + "${{ needs.generate-matrix.outputs.managed_image_revision }}" || + live.env?.E2E_WORKLOAD_SOURCE !== "${{ needs.generate-matrix.outputs.workload_source }}" ) { - errors.push( - "live stock onboarding must use the selected managed-image revision when no exact PR catalog is present", - ); + errors.push("live stock onboarding must use the selected workload source and image revision"); } if ( live.env?.NEMOCLAW_LANGCHAIN_DEEPAGENTS_CODE_SANDBOX_BASE_IMAGE_REF !== - "${{ needs.base-image-publication.outputs.dcode_base_ref }}" + "${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && needs.base-image-publication.outputs.dcode_base_ref || '' }}" ) { - errors.push("live DCode must use the selected immutable base reference"); + errors.push("live DCode must use an immutable base reference only with managed images"); } const evidence = findStep(live, "Record immutable Deep Agents Code base evidence"); const upload = findStep(live, "Upload E2E artifacts"); @@ -751,7 +775,8 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): .filter(Boolean); const liveSteps = live.steps ?? []; if ( - evidence.if !== "${{ matrix.id == 'ubuntu-repo-cloud-langchain-deepagents-code' }}" || + evidence.if !== + "${{ matrix.id == 'ubuntu-repo-cloud-langchain-deepagents-code' && needs.generate-matrix.outputs.workload_source == 'managed-image' }}" || evidence.env?.BASE_CONTRACT !== "${{ needs.base-image-publication.outputs.dcode_base_contract }}" || !String(evidence.run ?? "").includes("dcode-base-image.json") || diff --git a/tools/e2e/pr-managed-image-publication.mts b/tools/e2e/pr-managed-image-source.mts similarity index 50% rename from tools/e2e/pr-managed-image-publication.mts rename to tools/e2e/pr-managed-image-source.mts index 0c7e0b4e09f..cf7f1d411d3 100644 --- a/tools/e2e/pr-managed-image-publication.mts +++ b/tools/e2e/pr-managed-image-source.mts @@ -2,41 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; -import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import YAML from "yaml"; - import { parseManagedImageContractV1, SHIPPED_MANAGED_IMAGE_AGENTS, type ManagedImageContractCatalog, - type ManagedImageContractV1, } from "../../src/lib/onboard/managed-image/contract.ts"; -import { githubRequest } from "./base-image-publication.mts"; -import { - bindNamedExactArtifact, - downloadBoundArtifact, - materializeContractArchive, -} from "./exact-artifact-download.mts"; +import { githubRequest, parseBaseImagePushPaths } from "./base-image-publication.mts"; const REPOSITORY = "NVIDIA/NemoClaw"; -const WORKFLOW_PATH = ".github/workflows/managed-images.yaml"; -const WORKFLOW_FILE = "managed-images.yaml"; -const WORKFLOW_NAME = "Images / Build, Test, and Publish Managed Images"; +const BASE_IMAGE_WORKFLOW_PATH = ".github/workflows/base-image.yaml"; const MAX_CHANGED_FILES = 3_000; const PAGE_SIZE = 100; const SHA_PATTERN = /^[0-9a-f]{40}$/u; +const REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u; const SAFE_PATH_PATTERN = /^[A-Za-z0-9._/*-]+$/u; type JsonRecord = Record; -export interface ManagedImagePublicationRun { - readonly id: number; - readonly attempt: number; - readonly headSha: string; -} +export type PrManagedImageSource = "local-dockerfile" | "managed-image"; function record(value: unknown, label: string): JsonRecord { if (!value || typeof value !== "object" || Array.isArray(value)) { @@ -63,7 +49,7 @@ function compileManagedImagePath(pattern: string): RegExp { pattern.includes("//") || pattern.split("/").some((segment) => segment === "" || segment === "." || segment === "..") ) { - throw new Error(`managed-image PR path '${pattern}' is invalid`); + throw new Error(`managed-image input path '${pattern}' is invalid`); } const stars = [...pattern.matchAll(/\*/gu)].map((match) => match.index); if (stars.length === 0) { @@ -77,35 +63,11 @@ function compileManagedImagePath(pattern: string): RegExp { const escaped = pattern.replace(/[.+?^${}()|[\]\\]/gu, "\\$&").replaceAll("*", "[^/]*"); return new RegExp(`^${escaped}$`, "u"); } - throw new Error(`managed-image PR path '${pattern}' uses an unsupported glob`); -} - -/** Read the managed-image workflow path filter from the trusted workflow source. */ -export function parseManagedImagePullRequestPaths(source: string): string[] { - const workflow = record(YAML.parse(source), "managed-image workflow"); - const triggers = record(workflow.on, "managed-image workflow on block"); - const pullRequest = record(triggers.pull_request, "managed-image pull_request trigger"); - if (!Array.isArray(pullRequest.paths) || pullRequest.paths.length === 0) { - throw new Error("managed-image pull_request trigger must declare paths"); - } - const paths = pullRequest.paths.map((value) => { - if (typeof value !== "string" || value.length === 0 || value.trim() !== value) { - throw new Error("managed-image PR paths must be non-empty strings"); - } - compileManagedImagePath(value); - return value; - }); - if (new Set(paths).size !== paths.length) { - throw new Error("managed-image PR paths must be unique"); - } - if (!paths.includes(WORKFLOW_PATH)) { - throw new Error(`managed-image PR paths must include ${WORKFLOW_PATH}`); - } - return paths; + throw new Error(`managed-image input path '${pattern}' uses an unsupported glob`); } -/** Determine whether changed PR files require exact managed-image publication. */ -export function managedImagePublicationRequired( +/** Determine whether the PR changes a reviewed base- or managed-image input. */ +export function managedImageInputsChanged( changedFiles: readonly string[], patterns: readonly string[], ): boolean { @@ -129,57 +91,7 @@ export function managedImagePublicationRequired( return false; } -/** Select the unique successful managed-image workflow run for one PR commit. */ -export function selectManagedImagePublicationRun( - payload: unknown, - expected: { readonly headSha: string; readonly prNumber: number; readonly workflowId: number }, -): ManagedImagePublicationRun { - if (!SHA_PATTERN.test(expected.headSha)) throw new Error("candidate SHA is invalid"); - positiveInteger(expected.prNumber, "PR number"); - positiveInteger(expected.workflowId, "managed-image workflow id"); - const response = record(payload, "managed-image workflow runs"); - if (response.total_count !== 1 || !Array.isArray(response.workflow_runs)) { - throw new Error("exact managed-image workflow run is missing or ambiguous"); - } - if (response.workflow_runs.length !== 1) { - throw new Error("exact managed-image workflow run listing is incomplete"); - } - const run = record(response.workflow_runs[0], "managed-image workflow run"); - const id = positiveInteger(run.id, "managed-image workflow run id"); - const attempt = positiveInteger(run.run_attempt, "managed-image workflow run attempt"); - if (run.workflow_id !== expected.workflowId) { - throw new Error("managed-image workflow run does not match the trusted workflow"); - } - exactString(run.name, WORKFLOW_NAME, "managed-image workflow run name"); - exactString(run.path, WORKFLOW_PATH, "managed-image workflow run path"); - exactString(run.event, "pull_request", "managed-image workflow run event"); - exactString(run.head_sha, expected.headSha, "managed-image workflow run commit"); - exactString( - record(run.repository, "managed-image workflow repository").full_name, - REPOSITORY, - "managed-image workflow repository", - ); - exactString( - record(run.head_repository, "managed-image workflow source repository").full_name, - REPOSITORY, - "managed-image workflow source repository", - ); - if ( - !Array.isArray(run.pull_requests) || - run.pull_requests.length !== 1 || - record(run.pull_requests[0], "managed-image workflow pull request").number !== expected.prNumber - ) { - throw new Error("managed-image workflow run does not match the PR number"); - } - if (run.status !== "completed" || run.conclusion !== "success") { - throw new Error( - `managed-image workflow for candidate ${expected.headSha} must complete successfully before live E2E`, - ); - } - return { id, attempt, headSha: expected.headSha }; -} - -/** Assemble one all-agent catalog and reject mixed publication authority. */ +/** Assemble one all-agent catalog for the managed-image workflow's activation check. */ export function assembleManagedImageCatalog( values: readonly unknown[], candidateSha: string, @@ -232,15 +144,6 @@ export function writeManagedImageCatalog( }); } -function validateWorkflow(payload: unknown): number { - const workflow = record(payload, "managed-image workflow"); - const id = positiveInteger(workflow.id, "managed-image workflow id"); - exactString(workflow.name, WORKFLOW_NAME, "managed-image workflow name"); - exactString(workflow.path, WORKFLOW_PATH, "managed-image workflow path"); - exactString(workflow.state, "active", "managed-image workflow state"); - return id; -} - async function readChangedFiles( prNumber: number, count: number, @@ -274,59 +177,55 @@ async function readChangedFiles( listedFiles += 1; } } - if (listedFiles !== count) { - throw new Error("PR changed-file listing is incomplete"); - } + if (listedFiles !== count) throw new Error("PR changed-file listing is incomplete"); return [...new Set(files)]; } function validatePr( payload: unknown, - expected: { readonly baseSha: string; readonly candidateSha: string; readonly prNumber: number }, + expected: { + readonly baseSha: string; + readonly candidateRepository: string; + readonly candidateSha: string; + }, ): number { const pull = record(payload, "pull request"); exactString(pull.state, "open", "pull request state"); + const base = record(pull.base, "pull request base"); + const candidate = record(pull.head, "pull request source"); + exactString(base.sha, expected.baseSha, "pull request base commit"); + exactString(candidate.sha, expected.candidateSha, "pull request source commit"); exactString( - record(pull.base, "pull request base").sha, - expected.baseSha, - "pull request base commit", - ); - exactString( - record(pull.head, "pull request source").sha, - expected.candidateSha, - "pull request source commit", - ); - exactString( - record(record(pull.base, "pull request base").repo, "pull request base repository").full_name, + record(base.repo, "pull request base repository").full_name, REPOSITORY, "pull request base repository", ); exactString( - record(record(pull.head, "pull request source").repo, "pull request source repository") - .full_name, - REPOSITORY, + record(candidate.repo, "pull request source repository").full_name, + expected.candidateRepository, "pull request source repository", ); return positiveInteger(pull.changed_files, "PR changed-file count"); } -/** Resolve and download the exact all-agent catalog before candidate code executes. */ -export async function resolvePrManagedImageCatalog( +/** Select a trusted managed image or the candidate's local Dockerfile path. */ +export async function resolvePrManagedImageSource( input: { readonly baseSha: string; readonly candidateRepository: string; readonly candidateSha: string; - readonly outputPath: string; readonly prNumber: number; readonly token: string; readonly workflowSource: string; }, request: (path: string) => Promise = (apiPath) => githubRequest(apiPath, input.token), -): Promise<"not-required" | "written"> { - if (input.candidateRepository !== REPOSITORY) return "not-required"; +): Promise { if (!SHA_PATTERN.test(input.baseSha) || !SHA_PATTERN.test(input.candidateSha)) { throw new Error("PR base and candidate SHAs are required"); } + if (!REPOSITORY_PATTERN.test(input.candidateRepository)) { + throw new Error("candidate repository is invalid"); + } positiveInteger(input.prNumber, "PR number"); if (!input.token) throw new Error("GITHUB_TOKEN is required"); const changedCount = validatePr( @@ -334,55 +233,17 @@ export async function resolvePrManagedImageCatalog( input, ); const changedFiles = await readChangedFiles(input.prNumber, changedCount, request); - const patterns = parseManagedImagePullRequestPaths(input.workflowSource); - if (!managedImagePublicationRequired(changedFiles, patterns)) return "not-required"; + const patterns = parseBaseImagePushPaths(input.workflowSource); + return managedImageInputsChanged(changedFiles, patterns) ? "local-dockerfile" : "managed-image"; +} - const workflowId = validateWorkflow( - await request(`/repos/${REPOSITORY}/actions/workflows/${WORKFLOW_FILE}`), - ); - const runs = await request( - `/repos/${REPOSITORY}/actions/workflows/${WORKFLOW_FILE}/runs?event=pull_request&head_sha=${input.candidateSha}&per_page=100`, - ); - const run = selectManagedImagePublicationRun(runs, { - headSha: input.candidateSha, - prNumber: input.prNumber, - workflowId, +export function writePrManagedImageSource(outputPath: string, source: PrManagedImageSource): void { + fs.mkdirSync(path.dirname(path.resolve(outputPath)), { mode: 0o700, recursive: true }); + fs.writeFileSync(outputPath, `${source}\n`, { + encoding: "utf8", + flag: "wx", + mode: 0o600, }); - - const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-managed-catalog-")); - try { - const contracts: ManagedImageContractV1[] = []; - for (const agent of SHIPPED_MANAGED_IMAGE_AGENTS) { - const name = `managed-pr-contract-${run.id}-${run.attempt}-${agent}`; - const metadata = await request( - `/repos/${REPOSITORY}/actions/runs/${run.id}/artifacts?name=${encodeURIComponent(name)}&per_page=100`, - ); - const identity = bindNamedExactArtifact( - metadata, - { - headSha: run.headSha, - runAttempt: run.attempt, - runId: run.id, - }, - name, - ); - const archive = await downloadBoundArtifact(identity, input.token); - const contractPath = materializeContractArchive(archive, path.join(tempDirectory, agent)); - contracts.push( - JSON.parse(fs.readFileSync(contractPath, "utf8")) as unknown as ManagedImageContractV1, - ); - } - const catalog = assembleManagedImageCatalog(contracts, input.candidateSha); - fs.mkdirSync(path.dirname(path.resolve(input.outputPath)), { mode: 0o700, recursive: true }); - fs.writeFileSync(input.outputPath, `${JSON.stringify(catalog)}\n`, { - encoding: "utf8", - flag: "wx", - mode: 0o600, - }); - return "written"; - } finally { - fs.rmSync(tempDirectory, { force: true, recursive: true }); - } } function requiredInteger(value: string | undefined, label: string): number { @@ -399,26 +260,26 @@ export async function main(argv = process.argv.slice(2), env = process.env): Pro console.log("pr-managed-image-catalog outcome=assembled"); return; } - if (argv.length !== 1) throw new Error("expected one managed-image catalog output path"); - const candidateSha = env.CANDIDATE_SHA ?? ""; - if (!candidateSha) return; - const result = await resolvePrManagedImageCatalog({ + if (argv[0] !== "select" || argv.length !== 2) { + throw new Error("expected select and one managed-image source output path"); + } + const source = await resolvePrManagedImageSource({ baseSha: env.BASE_SHA ?? "", candidateRepository: env.CANDIDATE_REPOSITORY ?? "", - candidateSha, - outputPath: argv[0], + candidateSha: env.CANDIDATE_SHA ?? "", prNumber: requiredInteger(env.PR_NUMBER, "PR_NUMBER"), token: env.GITHUB_TOKEN ?? "", - workflowSource: fs.readFileSync(WORKFLOW_PATH, "utf8"), + workflowSource: fs.readFileSync(BASE_IMAGE_WORKFLOW_PATH, "utf8"), }); - console.log(`pr-managed-image-catalog outcome=${result}`); + writePrManagedImageSource(argv[1], source); + console.log(`pr-managed-image-source outcome=${source}`); } if (path.resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) { try { await main(); } catch (error) { - console.error(error instanceof Error ? error.message : "unknown PR managed-image error"); + console.error(error instanceof Error ? error.message : "unknown PR managed-image source error"); process.exitCode = 1; } } diff --git a/tools/e2e/standard-profile-workflow-boundary.mts b/tools/e2e/standard-profile-workflow-boundary.mts index 55da34c0179..5f67b94d68c 100644 --- a/tools/e2e/standard-profile-workflow-boundary.mts +++ b/tools/e2e/standard-profile-workflow-boundary.mts @@ -79,12 +79,7 @@ const PROFILE_JOBS = { job: "catalogue-brave-nvidia-inference", matrix: "catalogue_brave_nvidia_inference_matrix", credentialBoundary: "Brave and NVIDIA inference API keys", - secrets: [ - "BRAVE_API_KEY", - "DOCKERHUB_TOKEN", - "DOCKERHUB_USERNAME", - "NVIDIA_INFERENCE_API_KEY", - ], + secrets: ["BRAVE_API_KEY", "DOCKERHUB_TOKEN", "DOCKERHUB_USERNAME", "NVIDIA_INFERENCE_API_KEY"], githubToken: false, maxParallel: 2, }, @@ -158,7 +153,8 @@ function validateProfileCallers(errors: string[], workflow: WorkflowRecord): voi risk_signal_correlation_id: "${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }}", cli_artifact_provenance: "${{ needs.generate-matrix.outputs.cli_artifact_provenance }}", - managed_image_catalog: "${{ needs.generate-matrix.outputs.managed_image_catalog }}", + managed_image_revision: "${{ needs.generate-matrix.outputs.managed_image_revision }}", + workload_source: "${{ needs.generate-matrix.outputs.workload_source }}", credential_boundary: contract.credentialBoundary, catalogue_id: "${{ matrix.id }}", target_id: "${{ matrix.target_id }}", @@ -206,7 +202,8 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi risk_signal_expected_sha: "string", risk_signal_correlation_id: "string", cli_artifact_provenance: "string", - managed_image_catalog: "string", + managed_image_revision: "string", + workload_source: "string", credential_boundary: "string", catalogue_id: "string", target_id: "string", @@ -274,7 +271,9 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi const jobEnv = record(runJob.env); const expectedJobEnv = { E2E_JOB: "1", + E2E_MANAGED_IMAGE_REVISION: "${{ inputs.managed_image_revision }}", E2E_TARGET_ID: "${{ inputs.target_id }}", + E2E_WORKLOAD_SOURCE: "${{ inputs.workload_source }}", NEMOCLAW_RUN_LIVE_E2E: "1", NEMOCLAW_E2E_EXPECTED_SHA: "${{ inputs.candidate_sha }}", NEMOCLAW_E2E_CORRELATION_ID: "${{ inputs.risk_signal_correlation_id }}", @@ -297,7 +296,6 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi "Install target host dependencies", "Prepare E2E workspace", "Restore exact-commit CLI artifact", - "Materialize temporary managed-image catalog", "Install reviewed cloudflared", "Add swap for Hermes image rebuild", "Initialize runner comparison telemetry", @@ -448,40 +446,6 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi ) { errors.push("standard E2E profile must restore the planned exact-commit CLI artifact"); } - const managedCatalog = requireStep( - errors, - workflowSteps, - "Materialize temporary managed-image catalog", - ); - const managedCatalogRun = String(managedCatalog?.run ?? ""); - if ( - managedCatalog?.if !== "${{ inputs.managed_image_catalog != '' }}" || - managedCatalog.shell !== EXECUTION_PLAN_SHELL || - !isDeepStrictEqual(record(managedCatalog.env), { - CANDIDATE_SHA: "${{ inputs.candidate_sha }}", - MANAGED_IMAGE_CATALOG: "${{ inputs.managed_image_catalog }}", - RESTORE_CLI: "${{ inputs.restore_cli && 'true' || 'false' }}", - }) || - !managedCatalogRun.includes(".source.revision == $revision") || - !managedCatalogRun.includes("[.[].source.release] | unique | length") || - !managedCatalogRun.includes("[.[].source.cohort] | unique | length") || - !managedCatalogRun.includes('[[ "$RESTORE_CLI" == "true" ]]') || - !managedCatalogRun.includes(".source.release == $release") || - !managedCatalogRun.includes( - "managed-image catalog source identity does not match the candidate", - ) || - !managedCatalogRun.includes( - "managed-image catalog release does not match the restored CLI", - ) || - !managedCatalogRun.includes("NEMOCLAW_E2E_MANAGED_IMAGE_CATALOG") || - managedCatalogRun.includes("NEMOCLAW_E2E_EXACT_RELEASE") || - managedCatalogRun.includes(".source.release = $release") || - workflowSteps.indexOf(managedCatalog ?? {}) !== workflowSteps.indexOf(restore ?? {}) + 1 - ) { - errors.push( - "standard E2E profile must materialize only the exact-candidate managed-image catalog", - ); - } const cloudflared = requireStep(errors, workflowSteps, "Install reviewed cloudflared"); const cloudflaredRun = String(cloudflared?.run ?? ""); if ( @@ -489,17 +453,16 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi cloudflared.shell !== EXECUTION_PLAN_SHELL || !isDeepStrictEqual(record(cloudflared.env), { CLOUDFLARED_VERSION: "2026.6.1", - CLOUDFLARED_DEB_SHA256: - "ccd02ec216c62bfa573395d8f72cb2e91e95cbdf8726a8acc06b3e2d9aa31526", + CLOUDFLARED_DEB_SHA256: "ccd02ec216c62bfa573395d8f72cb2e91e95cbdf8726a8acc06b3e2d9aa31526", }) || !cloudflaredRun.includes( - 'https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}/cloudflared-linux-amd64.deb', + "https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}/cloudflared-linux-amd64.deb", ) || !cloudflaredRun.includes("sha256sum -c -") || !cloudflaredRun.includes('dpkg-deb -f "${cloudflared_deb}" Package') || !cloudflaredRun.includes('"${architecture}" != "amd64"') || cloudflaredRun.includes("command -v cloudflared") || - workflowSteps.indexOf(cloudflared ?? {}) !== workflowSteps.indexOf(managedCatalog ?? {}) + 1 + workflowSteps.indexOf(cloudflared ?? {}) !== workflowSteps.indexOf(restore ?? {}) + 1 ) { errors.push("standard E2E profile must install only the reviewed cloudflared package"); } @@ -596,8 +559,7 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi "${{ inputs.trusted_main && secrets.NVIDIA_INFERENCE_API_KEY || '' }}" || executeEnv.COMPATIBLE_API_KEY !== "${{ inputs.compatible_api_key && inputs.trusted_main && secrets.NVIDIA_INFERENCE_API_KEY || '' }}" || - executeEnv.BRAVE_API_KEY !== - "${{ inputs.trusted_main && secrets.BRAVE_API_KEY || '' }}" || + executeEnv.BRAVE_API_KEY !== "${{ inputs.trusted_main && secrets.BRAVE_API_KEY || '' }}" || executeEnv.GITHUB_TOKEN !== "${{ inputs.github_token && inputs.trusted_main && github.token || '' }}" ) { diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 6ab0b7f5b13..6fb66b33503 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -1179,7 +1179,7 @@ function validateFreeStandingJobSelector( ? ["generate-matrix", "openshell-dev-artifact"] : jobName === "cloud-onboard" ? ["base-image-publication", "generate-matrix"] - : "generate-matrix"; + : "generate-matrix"; if (!isDeepStrictEqual(job.needs, expectedNeeds)) { errors.push(`${jobName} job must depend on generate-matrix`); } @@ -1745,7 +1745,7 @@ function validateJetsonControllerBoundary(errors: string[], jobs: WorkflowRecord const publication = asRecord(jobs["base-image-publication"]); if ( asRecord(publication.outputs).managed_image_revision !== - "${{ steps.publication.outputs.head_sha || (steps.publication_mode.outputs.reuse == '1' && 'e38db201413b457614904187377ed9fd002d281d') || inputs.checkout_sha || github.sha }}" + "${{ steps.publication.outputs.head_sha }}" ) { errors.push("base-image-publication must expose the managed-image revision to Jetson dispatch"); } @@ -2577,43 +2577,6 @@ function validateTrustedE2ePlannerBoundary( } } -function validateExactPrManagedImageCatalogBoundary( - errors: string[], - generateSteps: WorkflowRecord[], - generate: WorkflowRecord | undefined, - generateCheckout: WorkflowRecord | undefined, -): void { - const managedCatalog = requireStep( - errors, - generateSteps, - "Resolve exact PR managed-image catalog", - ); - if ( - managedCatalog?.if !== - "${{ inputs.checkout_sha != '' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || - !isDeepStrictEqual(asRecord(managedCatalog?.env), { - BASE_SHA: "${{ inputs.base_sha }}", - CANDIDATE_REPOSITORY: "${{ inputs.checkout_repository }}", - CANDIDATE_SHA: "${{ inputs.checkout_sha }}", - GITHUB_TOKEN: "${{ github.token }}", - PR_NUMBER: "${{ inputs.pr_number }}", - }) || - managedCatalog?.run !== - 'node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-publication.mts "${RUNNER_TEMP}/pr-managed-image-catalog.json"' - ) { - errors.push("manual PR E2E must resolve the exact candidate managed-image publication"); - } - if ( - generate && - managedCatalog && - generateCheckout && - (generateSteps.indexOf(managedCatalog) <= generateSteps.indexOf(generate) || - generateSteps.indexOf(managedCatalog) >= generateSteps.indexOf(generateCheckout)) - ) { - errors.push("exact managed-image publication must resolve before candidate checkout"); - } -} - export function validateE2eWorkflow(workflowValue: unknown): string[] { const workflow = asRecord(workflowValue); const errors: string[] = []; @@ -2838,12 +2801,6 @@ export function validateE2eWorkflow(workflowValue: unknown): string[] { validateLargerRunnerRouting(errors, jobs, generateMatrix, generateSteps, generateCheckout); const generate = requireStep(errors, generateSteps, "Generate E2E target matrix"); validateTrustedE2ePlannerBoundary(errors, generateSteps, generate, generateCheckout); - validateExactPrManagedImageCatalogBoundary( - errors, - generateSteps, - generate, - generateCheckout, - ); const generateEnv = asRecord(generate?.env); if (generateEnv.CHECKOUT_SHA !== "${{ inputs.checkout_sha }}") { errors.push("matrix generation step must bind controller checkout through CHECKOUT_SHA env"); @@ -2911,11 +2868,10 @@ export function validateE2eWorkflow(workflowValue: unknown): string[] { const jobEnv = asRecord(liveTargets.env); if ( jobEnv.E2E_MANAGED_IMAGE_REVISION !== - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}" + "${{ needs.generate-matrix.outputs.managed_image_revision }}" || + jobEnv.E2E_WORKLOAD_SOURCE !== "${{ needs.generate-matrix.outputs.workload_source }}" ) { - errors.push( - "live stock onboarding must use the selected managed-image revision when no exact PR catalog is present", - ); + errors.push("live stock onboarding must use the selected workload source and image revision"); } if (jobEnv.NEMOCLAW_RUN_LIVE_E2E !== "1") { errors.push("live job must set NEMOCLAW_RUN_LIVE_E2E=1"); From 723a32bc4c3da12dbfd218ca380fb03747b0f228 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 19:17:53 +0700 Subject: [PATCH 02/40] fix(e2e): complete local image qualification Signed-off-by: San Dang --- .github/workflows/base-image.yaml | 1 + .github/workflows/e2e.yaml | 20 ++++--- .../onboard/machine/finalization-deps.test.ts | 19 ++++--- src/lib/onboard/machine/finalization-deps.ts | 53 ++++++++++++------- test/e2e/RETRY_INVENTORY.md | 2 +- ...mage-publication-workflow-boundary.test.ts | 28 ++++++++++ .../support/pr-managed-image-source.test.ts | 25 +++++---- tools/e2e/cli-artifact-workflow-boundary.mts | 4 +- .../hermes-gpu-startup-workflow-boundary.mts | 2 + ...aged-image-multiarch-workflow-boundary.mts | 7 ++- ...ge-protected-runtime-workflow-boundary.mts | 2 +- .../e2e/mcp-dev-workflow-boundary-digests.mts | 2 +- tools/e2e/mcp-workflow-boundary.mts | 18 ++++++- tools/e2e/operations-workflow-boundary.mts | 35 ++++++------ tools/e2e/pr-managed-image-source.mts | 16 ++---- .../trusted-hermes-swap-workflow-boundary.mts | 4 +- tools/e2e/workflow-boundary.mts | 4 +- 17 files changed, 154 insertions(+), 88 deletions(-) diff --git a/.github/workflows/base-image.yaml b/.github/workflows/base-image.yaml index 8ffa53a5b6a..c06f4ce4d88 100644 --- a/.github/workflows/base-image.yaml +++ b/.github/workflows/base-image.yaml @@ -25,6 +25,7 @@ on: - ".github/workflows/managed-images.yaml" - "test/e2e/live/managed-image-activation-e2e.test.ts" - "test/e2e/live/managed-image-activation-e2e-helpers.ts" + - "test/e2e/fixtures/workload-source-env.ts" - ".github/actions/ci-reviewed-npm-audit/**" - ".github/actions/build-base-image-platform/**" - ".github/actions/publish-base-image-manifest/**" diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index c9a70359f2d..23af2126a8c 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -161,9 +161,7 @@ jobs: shell: bash run: | set -euo pipefail - source_path="${RUNNER_TEMP}/pr-managed-image-source" - node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-source.mts select "$source_path" - workload_source="$(cat "$source_path")" + workload_source="$(node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-source.mts select)" case "$workload_source" in managed-image|local-dockerfile) ;; *) echo "::error::PR workload source is invalid" >&2; exit 1 ;; @@ -3263,7 +3261,7 @@ jobs: run: bash .github/scripts/docker-auth-cleanup.sh mcp-bridge: - needs: generate-matrix + needs: [base-image-publication, generate-matrix] if: ${{ contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'mcp-bridge') }} runs-on: ${{ fromJSON(needs.generate-matrix.outputs.runner_routing)[format('mcp-bridge-{0}', matrix.agent)] }} permissions: @@ -3286,6 +3284,8 @@ jobs: agent_runtime: langchain-deepagents-code coverage_variant: deepagents env: + E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_revision }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "mcp-bridge" E2E_OBSERVABLE_OUTCOME: "Stable OpenShell MCP bridge reaches tools and inference" @@ -3618,6 +3618,8 @@ jobs: # MCP lifecycle without sharing destructive sandbox state. timeout-minutes: 90 env: + E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_revision }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "openshell-credential-generation-window" E2E_AGENT_RUNTIME: "openclaw" @@ -3790,6 +3792,8 @@ jobs: agent_runtime: langchain-deepagents-code coverage_variant: deepagents env: + E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_revision }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "mcp-bridge-dev" E2E_OBSERVABLE_OUTCOME: "Development OpenShell MCP bridge reaches tools and inference" @@ -3974,7 +3978,7 @@ jobs: managed-image-multiarch-startup: name: Protected managed-image startup (${{ matrix.platform }}) needs: [base-image-publication, generate-matrix] - if: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-multiarch-startup') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime')) }} + if: ${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-multiarch-startup') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime')) }} runs-on: ${{ matrix.runner }} timeout-minutes: 210 permissions: @@ -4658,7 +4662,7 @@ jobs: managed-image-protected-runtime: name: Protected managed-image GPU and local inference needs: [base-image-publication, generate-matrix, managed-image-multiarch-startup] - if: ${{ always() && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }} + if: ${{ always() && needs.generate-matrix.outputs.workload_source == 'managed-image' && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }} runs-on: linux-amd64-gpu-rtxpro6000-latest-1 timeout-minutes: 300 permissions: @@ -5068,6 +5072,8 @@ jobs: observable_outcome: "Compatibility-only GPU startup reaches the stable Ready route" coverage_variant: compatibility-only env: + E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_revision }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "hermes-gpu-startup" E2E_AGENT_RUNTIME: "hermes" @@ -5329,7 +5335,7 @@ jobs: jetson-nvmap-gpu: needs: [base-image-publication, generate-matrix] - if: ${{ always() && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && github.repository == 'NVIDIA/NemoClaw' && github.ref == 'refs/heads/main' && (github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.allow_jetson_dispatch && (inputs.checkout_repository == '' || inputs.checkout_repository == github.repository) && ((inputs.jobs == '' && inputs.targets == '') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'jetson-nvmap-gpu')))) }} + if: ${{ always() && needs.generate-matrix.outputs.workload_source == 'managed-image' && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && github.repository == 'NVIDIA/NemoClaw' && github.ref == 'refs/heads/main' && (github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.allow_jetson_dispatch && (inputs.checkout_repository == '' || inputs.checkout_repository == github.repository) && ((inputs.jobs == '' && inputs.targets == '') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'jetson-nvmap-gpu')))) }} concurrency: group: jetson-nvmap-gpu-dispatch cancel-in-progress: false diff --git a/src/lib/onboard/machine/finalization-deps.test.ts b/src/lib/onboard/machine/finalization-deps.test.ts index 9cadcb507ea..21aff1c9e09 100644 --- a/src/lib/onboard/machine/finalization-deps.test.ts +++ b/src/lib/onboard/machine/finalization-deps.test.ts @@ -113,7 +113,7 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); - it("runs the canonical request probe before waiting for fresh pairing (#10014)", async () => { + it("waits for canonical pairing before running the one request producer (#10014)", async () => { const observePairing = vi .fn(() => SCOPE_UPGRADE_PENDING) .mockImplementationOnce(() => { @@ -135,7 +135,7 @@ describe("ordinary OpenClaw pairing settlement", () => { kind: "settled", }); - expect(scope.calls).toEqual(["warmup", "sleep", "approval"]); + expect(scope.calls).toEqual(["warmup", "approval"]); expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); @@ -406,9 +406,7 @@ describe("ordinary OpenClaw pairing settlement", () => { throw new Error("not published"); }; const scope = ordinaryPairingDeps({ - observePairing: vi.fn(() => - attempts++ < 10 ? unavailable() : SCOPE_UPGRADE_PENDING, - ), + observePairing: vi.fn(() => (attempts++ < 10 ? unavailable() : SCOPE_UPGRADE_PENDING)), }); await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).resolves.toEqual({ @@ -416,7 +414,7 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "scope-upgrade-incomplete", }); expect(scope.deps.sleep).toHaveBeenCalledTimes(39); - expect(scope.deps.runWarmup).toHaveBeenCalledOnce(); + expect(scope.deps.runWarmup).not.toHaveBeenCalled(); expect(scope.deps.runApproval).toHaveBeenCalledOnce(); }); @@ -436,6 +434,7 @@ describe("ordinary OpenClaw pairing settlement", () => { .mockImplementationOnce(() => { throw new Error("not pending"); }) + .mockReturnValueOnce(PAIRING_ONLY) .mockReturnValueOnce(SCOPE_UPGRADE_PENDING) .mockReturnValue(SETTLED), runWarmup: vi.fn(() => { @@ -452,7 +451,7 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); - expect(scope.deps.observePairing).toHaveBeenCalledTimes(4); + expect(scope.deps.observePairing).toHaveBeenCalledTimes(5); expect(now).toBe( OPENCLAW_PAIRING_OBSERVATION_TIMEOUT_MS + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS - @@ -489,11 +488,11 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "pairing-unavailable", }); expect(scope.deps.sleep).not.toHaveBeenCalled(); - expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); + expect(scope.deps.runWarmup).not.toHaveBeenCalled(); expect(scope.deps.runApproval).not.toHaveBeenCalled(); }); - it("performs one request-producer write when a canonical CLI pairing never appears (#9844)", async () => { + it("does not run a request producer without a canonical CLI pairing (#9844)", async () => { const scope = ordinaryPairingDeps({ observePairing: vi.fn(() => { throw new Error("not published"); @@ -505,7 +504,7 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "pairing-unavailable", }); - expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); + expect(scope.deps.runWarmup).not.toHaveBeenCalled(); expect(scope.deps.runApproval).not.toHaveBeenCalled(); }); diff --git a/src/lib/onboard/machine/finalization-deps.ts b/src/lib/onboard/machine/finalization-deps.ts index 55d323f53ea..c4f51c32bf5 100644 --- a/src/lib/onboard/machine/finalization-deps.ts +++ b/src/lib/onboard/machine/finalization-deps.ts @@ -155,9 +155,7 @@ function defaultPairingSettlementDeps(): OrdinaryOpenClawPairingSettlementDeps { .loadPairingQualification() .observeOrdinaryOpenClawPairingSettlement(...args), runWarmup: (name, gatewayName) => - finalizationHandlerRuntime - .loadAutoPairWarmup() - .runSandboxScopeWarmupRun(name, gatewayName), + finalizationHandlerRuntime.loadAutoPairWarmup().runSandboxScopeWarmupRun(name, gatewayName), runApproval: (name, gatewayName) => { finalizationHandlerRuntime.loadAutoPairApproval().runSandboxAutoPairApprovalPass(name, { budget: { @@ -222,7 +220,7 @@ export async function settleOrdinaryOpenClawPairing( ); sawCanonicalPairing = true; } catch { - // Pairing may not have appeared yet; the producer handles that path. + // Pairing may not have appeared yet; the bounded observer handles that path. } if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; @@ -232,14 +230,36 @@ export async function settleOrdinaryOpenClawPairing( } if (initial?.state === "settled") return { kind: "settled" }; - let baseline: PairingWaitResult; - if (initial?.state === "scope-upgrade-pending") { - baseline = { kind: "observed", value: initial }; - } else { - // A valid non-interactive path can reach finalization before the - // startup watcher publishes its first CLI request. Run the bounded - // direct producer once, then require canonical evidence that its - // exact write upgrade is pending before the approval pass (#10014). + const pairingAppearanceDeadline = Math.min( + settlementDeadline, + deps.now() + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS, + ); + let baseline: PairingWaitResult = initial + ? { kind: "observed", value: initial } + : await waitForPairingObservation( + name, + target, + pairingAppearanceDeadline, + (value) => { + sawCanonicalPairing = true; + return true; + }, + deps, + ); + if (baseline.kind === "target-changed") { + return { kind: "incomplete", reason: "runtime-identity-invalid" }; + } + if (baseline.kind === "timeout") { + return { kind: "incomplete", reason: "pairing-unavailable" }; + } + if (baseline.value.state === "settled") return { kind: "settled" }; + + if (baseline.value.state === "pairing-only") { + // Wait for the startup watcher to publish the canonical CLI + // pairing before issuing the one bounded write-scope producer. + // Running the producer before that identity exists can create no + // upgrade and leaves an otherwise healthy fresh onboard stuck at + // pairing-only (#10014). try { await deps.runWarmup(name, target.gatewayName); } catch { @@ -248,14 +268,14 @@ export async function settleOrdinaryOpenClawPairing( if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } - const pairingAppearanceDeadline = Math.min( + const scopeUpgradeDeadline = Math.min( settlementDeadline, deps.now() + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS, ); baseline = await waitForPairingObservation( name, target, - pairingAppearanceDeadline, + scopeUpgradeDeadline, (value) => { sawCanonicalPairing = true; return value.state !== "pairing-only"; @@ -272,10 +292,7 @@ export async function settleOrdinaryOpenClawPairing( reason: sawCanonicalPairing ? "scope-upgrade-incomplete" : "pairing-unavailable", }; } - if ( - initial && - baseline.value.deviceIdentitySha256 !== initial.deviceIdentitySha256 - ) { + if (initial && baseline.value.deviceIdentitySha256 !== initial.deviceIdentitySha256) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } if (baseline.value.state === "settled") return { kind: "settled" }; diff --git a/test/e2e/RETRY_INVENTORY.md b/test/e2e/RETRY_INVENTORY.md index 6214d2e0613..1be96059bc2 100644 --- a/test/e2e/RETRY_INVENTORY.md +++ b/test/e2e/RETRY_INVENTORY.md @@ -16,7 +16,7 @@ Exhaustion remains failed. | `workflow-main-observer` | Completed `E2E main` run; `tools/e2e/main-run-retry.mts`, `.github/workflows/e2e-main-retry.yaml` | Any failed job | 0 automatic reruns | Not established at workflow scope | Test owner | `failed-no-retry`, `ignored`, `passed-first-attempt`, or `passed-after-retry` for a later manually requested rerun | Failed job names, non-skipped job count, runner minutes, and source SHA for each attempt | Broad rerun removed; operation-level evidence is required | | `hosted-runner-recovery` | Confirmed GitHub-hosted runner loss; `tools/e2e/hosted-runner-recovery.mts`, `tools/e2e/hosted-runner-loss*.mts` | Authenticated runner-allocation or internal-runner evidence that remains identical across 2 consecutive reads | 2 immediate evidence reads and at most 1 recovery request; no delay | GitHub reruns a workflow attempt | GitHub Actions | Dedicated runner-loss classifications | Source and recovery run links plus authenticated job evidence | External owner; governed by #7146, not this policy | | `pr-rerun-reconciliation` | PR E2E dispatch reconciliation; `tools/e2e/pr-e2e-dispatch-reconciliation.mts`, `tools/e2e/pr-e2e-retry-receipt.mts` | Trusted dispatch receipt state | Contract-defined single reconciliation | Reconciles workflow and commit identity before action | GitHub Actions | Receipt-specific terminal states | Signed workflow identity and receipt | External scope; governed by #7206 | -| `github-publication-read` | GitHub API reads; `tools/e2e/base-image-publication.mts` | Fetch error, 408, rate limit, or 5xx | 3 attempts; Retry-After/rate-limit reset or linear delay capped at 10s | Read-only | GitHub API | Returned parsed selection on success; thrown terminal HTTP/fetch error on failure or exhaustion | Caller artifact records the returned publication selection; terminal errors identify exhausted fetch or HTTP status without response content | Eligible bounded read; existing implementation retained | +| `github-publication-read` | Publication and PR metadata reads; `tools/e2e/base-image-publication.mts`, `tools/e2e/pr-managed-image-source.mts` | Fetch error, 408, rate limit, or 5xx | 3 attempts; Retry-After/rate-limit reset or linear delay capped at 10s | Read-only | GitHub API | Returned publication or workload-source selection on success; thrown terminal HTTP/fetch error on failure or exhaustion | Caller records the publication selection or PR workload source; terminal errors identify exhausted fetch or HTTP status without response content | Eligible bounded read; existing implementation retained | | `ghcr-pr-exact-digest-visibility` | Anonymous pull after same-repository PR publication; `scripts/checks/pull-public-exact-digest.sh`, `.github/workflows/managed-images.yaml` | Final nonempty Docker output line is exactly `ERROR: : not found`; every other Docker failure is terminal | 5 attempts; exponential 2s, 4s, 8s, then 16s | Read-only registry request for one immutable digest; any local image-cache write repeats the same content-addressed result | GHCR | `passed-first-attempt`, `passed-after-retry`, `failed-no-retry`, or `exhausted` | Sanitized outcome, attempt number, total attempts, retry delay or Docker exit status; raw Docker output, credentials, and environment values are excluded | Eligible bounded external read after the independently fetched manifest bytes match the publication digest; every non-exact failure remains terminal and no workflow rerun occurs | | `protected-managed-image-buildkit-transport` | One agent's exact protected managed-image `docker buildx build`; `scripts/checks/build-protected-managed-images.sh` | Final nonempty line exactly matches BuildKit's `ERROR: failed to build: failed to solve: stream error: stream ID ; INTERNAL_ERROR; received from peer`; every near-match and other Docker failure is terminal | 2 attempts; fixed 2s delay | Before retry, a read-only local registry `HEAD` request confirms that the isolated revision tag is absent. The script then repeats the same agent, inputs, revision tag, and content-addressed push. A present tag or any inconclusive registry result is terminal. Existing digest, registry-byte, and image-contract checks still gate success. | BuildKit transport | `passed-first-attempt`, `passed-after-retry`, `failed-no-retry`, or `exhausted` | Existing Docker attempt output remains in the job log. Sanitized job-log annotations retain the agent, attempt, outcome, retry delay or Docker exit status, failure class, and revision-tag state without image content. | Eligible bounded operation retry for the exact pre-export transport failure observed in #9763; repeated exact failure remains failed and no workflow rerun occurs | | `protected-managed-image-npm-registry-dns` | One agent's exact protected managed-image `docker buildx build`; `scripts/checks/build-protected-managed-images.sh` | One attempt line has an optional BuildKit step prefix, an elapsed-time field, and exact text `ERROR: curl failed: curl: (6) Could not resolve host: registry.npmjs.org`; every other curl exit, host, and near-match is terminal | 2 attempts; fixed 2s delay | Before retry, a read-only local registry `HEAD` request confirms that the isolated revision tag is absent. The script then repeats the same agent, inputs, revision tag, and content-addressed push. A present tag or any inconclusive registry result is terminal. Existing digest, registry-byte, and image-contract checks still gate success. | npm registry DNS | `passed-first-attempt`, `passed-after-retry`, `failed-no-retry`, or `exhausted` | Existing Docker attempt output remains in the job log. Sanitized job-log annotations retain the agent, attempt, outcome, retry delay or Docker exit status, failure class, and revision-tag state without image content. | Eligible bounded operation retry for the exact pre-export DNS failure observed in run 32621454757, job 97154036894; repeated exact failure remains failed and no workflow rerun occurs | diff --git a/test/e2e/support/base-image-publication-workflow-boundary.test.ts b/test/e2e/support/base-image-publication-workflow-boundary.test.ts index 7c4fa7cef92..0d298d8176f 100644 --- a/test/e2e/support/base-image-publication-workflow-boundary.test.ts +++ b/test/e2e/support/base-image-publication-workflow-boundary.test.ts @@ -281,6 +281,34 @@ describe("base-image publication workflow boundary (#7372)", () => { (value) => (value.jobs["cloud-onboard"].env!.E2E_MANAGED_IMAGE_REVISION = "${{ github.sha }}"), ], + [ + "cloud-onboard workload source", + (value) => (value.jobs["cloud-onboard"].env!.E2E_WORKLOAD_SOURCE = "managed-image"), + ], + [ + "MCP bridge workload source", + (value) => (value.jobs["mcp-bridge"].env!.E2E_WORKLOAD_SOURCE = "managed-image"), + ], + [ + "MCP bridge publication dependency", + (value) => (value.jobs["mcp-bridge"].needs = ["generate-matrix"]), + ], + [ + "MCP bridge dev managed-image revision", + (value) => + (value.jobs["mcp-bridge-dev"].env!.E2E_MANAGED_IMAGE_REVISION = "${{ github.sha }}"), + ], + [ + "credential-window workload source", + (value) => + (value.jobs["openshell-credential-generation-window"].env!.E2E_WORKLOAD_SOURCE = + "managed-image"), + ], + [ + "Hermes GPU managed-image revision", + (value) => + (value.jobs["hermes-gpu-startup"].env!.E2E_MANAGED_IMAGE_REVISION = "${{ github.sha }}"), + ], [ "Launchable publication dependency", (value) => diff --git a/test/e2e/support/pr-managed-image-source.test.ts b/test/e2e/support/pr-managed-image-source.test.ts index b6385909388..83e59781d4c 100644 --- a/test/e2e/support/pr-managed-image-source.test.ts +++ b/test/e2e/support/pr-managed-image-source.test.ts @@ -23,7 +23,6 @@ import { managedImageInputsChanged, resolvePrManagedImageSource, writeManagedImageCatalog, - writePrManagedImageSource, } from "../../../tools/e2e/pr-managed-image-source.mts"; const BASE_SHA = "b".repeat(40); @@ -111,6 +110,10 @@ describe("PR managed-image source selection", () => { expect( managedImageInputsChanged(["src/lib/onboard/managed-startup/profile.ts"], patterns), ).toBe(true); + expect(managedImageInputsChanged(["test/e2e/fixtures/workload-source-env.ts"], patterns)).toBe( + true, + ); + expect(managedImageInputsChanged(["test/e2e/fixtures/progress.ts"], patterns)).toBe(false); expect(managedImageInputsChanged(["docs/guide.mdx"], patterns)).toBe(false); expect(() => managedImageInputsChanged(["Dockerfile.base\nother"], patterns)).toThrow( "changed-file path is invalid", @@ -127,16 +130,16 @@ describe("PR managed-image source selection", () => { ); }); - it("writes a private source decision file", () => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-source-test-")); - try { - const outputPath = path.join(directory, "source"); - writePrManagedImageSource(outputPath, "local-dockerfile"); - expect(fs.readFileSync(outputPath, "utf8")).toBe("local-dockerfile\n"); - expect(fs.statSync(outputPath).mode & 0o777).toBe(0o600); - } finally { - fs.rmSync(directory, { force: true, recursive: true }); - } + it("records PR source reads in the retry inventory", () => { + const row = fs + .readFileSync("test/e2e/RETRY_INVENTORY.md", "utf8") + .split("\n") + .find((line) => line.startsWith("| `github-publication-read` |")); + + expect(row).toContain("tools/e2e/base-image-publication.mts"); + expect(row).toContain("tools/e2e/pr-managed-image-source.mts"); + expect(row).toContain("PR metadata reads"); + expect(row).toContain("workload-source selection"); }); }); diff --git a/tools/e2e/cli-artifact-workflow-boundary.mts b/tools/e2e/cli-artifact-workflow-boundary.mts index 2d2bb8c00f0..1fccab52dc2 100644 --- a/tools/e2e/cli-artifact-workflow-boundary.mts +++ b/tools/e2e/cli-artifact-workflow-boundary.mts @@ -355,9 +355,7 @@ function validateConsumer( let expectedNeeds: string | string[] = CLI_ARTIFACT_PRODUCER_JOB; if (jobName === "mcp-bridge-dev") { expectedNeeds = [CLI_ARTIFACT_PRODUCER_JOB, "openshell-dev-artifact"]; - } else if (jobName === "live") { - expectedNeeds = ["base-image-publication", CLI_ARTIFACT_PRODUCER_JOB]; - } else if (jobName === "cloud-onboard") { + } else if (["cloud-onboard", "live", "mcp-bridge"].includes(jobName)) { expectedNeeds = ["base-image-publication", CLI_ARTIFACT_PRODUCER_JOB]; } if (!isDeepStrictEqual(job.needs, expectedNeeds)) { diff --git a/tools/e2e/hermes-gpu-startup-workflow-boundary.mts b/tools/e2e/hermes-gpu-startup-workflow-boundary.mts index cbd2e8d54de..f732b72c90e 100644 --- a/tools/e2e/hermes-gpu-startup-workflow-boundary.mts +++ b/tools/e2e/hermes-gpu-startup-workflow-boundary.mts @@ -162,6 +162,8 @@ export function validateHermesGpuStartupWorkflow( const requiredEnv = { E2E_ARTIFACT_DIR: "${{ github.workspace }}/e2e-artifacts/live/hermes-gpu-startup/${{ matrix.scenario }}", + E2E_MANAGED_IMAGE_REVISION: "${{ needs.generate-matrix.outputs.managed_image_revision }}", + E2E_WORKLOAD_SOURCE: "${{ needs.generate-matrix.outputs.workload_source }}", E2E_HERMES_GPU_STARTUP_SCENARIO: "${{ matrix.scenario }}", E2E_JOB: "1", E2E_TARGET_ID: JOB_NAME, diff --git a/tools/e2e/managed-image-multiarch-workflow-boundary.mts b/tools/e2e/managed-image-multiarch-workflow-boundary.mts index 92de6129e55..798529adc11 100644 --- a/tools/e2e/managed-image-multiarch-workflow-boundary.mts +++ b/tools/e2e/managed-image-multiarch-workflow-boundary.mts @@ -29,7 +29,7 @@ type WorkflowStep = WorkflowRecord & { const JOB_ID = PROTECTED_MANAGED_IMAGE_MULTIARCH_JOB_ID; const PROTECTED_RUNTIME_JOB_ID = "managed-image-protected-runtime"; -const SELECTOR = `\${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), '${JOB_ID}') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), '${PROTECTED_RUNTIME_JOB_ID}')) }}`; +const SELECTOR = `\${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), '${JOB_ID}') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), '${PROTECTED_RUNTIME_JOB_ID}')) }}`; const ACTIVATION_PATH = PROTECTED_MANAGED_IMAGE_ACTIVATION_PATH; const DIRECT_TEST_PATH = "test/e2e/live/managed-image-multiarch-startup.test.ts"; const REGISTRY_IMAGE = @@ -292,8 +292,7 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): const bases = requireStep(errors, steps, "Resolve exact platform base images"); requireValues(errors, `${JOB_ID} exact base resolution`, record(bases?.env), { - DCODE_BASE_CONTRACT: - "${{ needs.base-image-publication.outputs.dcode_base_contract }}", + DCODE_BASE_CONTRACT: "${{ needs.base-image-publication.outputs.dcode_base_contract }}", PLATFORM: "${{ matrix.platform }}", }); requireFragments(errors, bases, [ @@ -306,7 +305,7 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): "'.platformReferences[$platform]' <<< \"$DCODE_BASE_CONTRACT\"", 'docker buildx imagetools inspect "$dcode_reference" --raw', '"sha256:$(sha256sum "$work_dir/dcode-exact.raw" | awk \'{print $1}\')" == "$dcode_digest"', - "printf 'dcode=%s\\n' \"$dcode_reference\" >> \"$GITHUB_OUTPUT\"", + 'printf \'dcode=%s\\n\' "$dcode_reference" >> "$GITHUB_OUTPUT"', ]); if ( text(bases?.run).includes( diff --git a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts index e7031afd020..0e8d6de8c75 100644 --- a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts +++ b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts @@ -14,7 +14,7 @@ type WorkflowStep = WorkflowRecord & { const JOB_ID = "managed-image-protected-runtime"; const SELECTOR = - "${{ always() && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }}"; + "${{ always() && needs.generate-matrix.outputs.workload_source == 'managed-image' && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }}"; const ACTIVATION_PATH = "ci/protected-managed-image-runtime-activation-v1.json"; const LIVE_TEST_PATH = "test/e2e/live/managed-image-protected-runtime.test.ts"; const REGISTRY_IMAGE = diff --git a/tools/e2e/mcp-dev-workflow-boundary-digests.mts b/tools/e2e/mcp-dev-workflow-boundary-digests.mts index bdaa805a6ee..ab01afea82e 100644 --- a/tools/e2e/mcp-dev-workflow-boundary-digests.mts +++ b/tools/e2e/mcp-dev-workflow-boundary-digests.mts @@ -6,7 +6,7 @@ import { createHash } from "node:crypto"; export const MCP_DEV_WORKFLOW_EXECUTION_CONTEXT_SHA256 = "052c49d5e8688266dbf38fa911733132d33e4470a29a61deb6e7a11067737559"; export const MCP_DEV_JOB_EXECUTION_CONTEXT_SHA256 = - "b9219b0f29da3834499a7c9dcb0acc8287cb3441d01a51bed615d7b2ea4383f9"; + "09a04d1ba5a8a79ec9796dc1ca6f6d28f65911bd614ba2310772e3bfd698f5c0"; export const MCP_DEV_TRUSTED_NODE_SETUP_CONTENT_SHA256 = "504821ad93c57971d0281ef1130ed6008fadd331bd56acb1a6b5e6a3358f3e49"; export const MCP_DEV_TRUSTED_PREFIX_CONTENT_SHA256 = diff --git a/tools/e2e/mcp-workflow-boundary.mts b/tools/e2e/mcp-workflow-boundary.mts index a51f6eeca15..3460910f9eb 100644 --- a/tools/e2e/mcp-workflow-boundary.mts +++ b/tools/e2e/mcp-workflow-boundary.mts @@ -167,6 +167,18 @@ function validateJobIdentity( jobName, `${jobName} must use its job id as E2E_TARGET_ID`, ); + requireEqual( + errors, + env.E2E_MANAGED_IMAGE_REVISION, + "${{ needs.generate-matrix.outputs.managed_image_revision }}", + `${jobName} must receive the selected managed-image revision`, + ); + requireEqual( + errors, + env.E2E_WORKLOAD_SOURCE, + "${{ needs.generate-matrix.outputs.workload_source }}", + `${jobName} must receive the selected workload source`, + ); requireEqual( errors, job["timeout-minutes"], @@ -178,7 +190,9 @@ function validateJobIdentity( errors, JSON.stringify(jobNeeds(job)), JSON.stringify( - jobName === "mcp-bridge-dev" ? ["generate-matrix", DEV_ARTIFACT_JOB] : ["generate-matrix"], + jobName === "mcp-bridge-dev" + ? ["generate-matrix", DEV_ARTIFACT_JOB] + : ["base-image-publication", "generate-matrix"], ), `${jobName} must depend on its reviewed artifact producers`, ); @@ -865,6 +879,8 @@ function validateCredentialWindowJob( const env = asRecord(job.env); const expectedEnv = { + E2E_MANAGED_IMAGE_REVISION: "${{ needs.generate-matrix.outputs.managed_image_revision }}", + E2E_WORKLOAD_SOURCE: "${{ needs.generate-matrix.outputs.workload_source }}", E2E_JOB: "1", E2E_TARGET_ID: CREDENTIAL_WINDOW_JOB, E2E_AGENT_RUNTIME: "openclaw", diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index fb8b1011f21..4e2fd2f4027 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -654,9 +654,7 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): shell: "bash", run: [ "set -euo pipefail", - 'source_path="${RUNNER_TEMP}/pr-managed-image-source"', - 'node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-source.mts select "$source_path"', - 'workload_source="$(cat "$source_path")"', + 'workload_source="$(node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-source.mts select)"', 'case "$workload_source" in', " managed-image|local-dockerfile) ;;", ' *) echo "::error::PR workload source is invalid" >&2; exit 1 ;;', @@ -747,19 +745,26 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): if (!sameMembers(needs(cloudOnboard), ["base-image-publication", "generate-matrix"])) { errors.push("cloud-onboard must wait for matrix generation and base-image publication"); } - if ( - cloudOnboard.env?.E2E_MANAGED_IMAGE_REVISION !== - "${{ needs.generate-matrix.outputs.managed_image_revision }}" || - cloudOnboard.env?.E2E_WORKLOAD_SOURCE !== "${{ needs.generate-matrix.outputs.workload_source }}" - ) { - errors.push("cloud-onboard must use the selected workload source and image revision"); + const mcpBridge = workflow.jobs["mcp-bridge"] ?? {}; + if (!sameMembers(needs(mcpBridge), ["base-image-publication", "generate-matrix"])) { + errors.push("mcp-bridge must wait for matrix generation and base-image publication"); } - if ( - live.env?.E2E_MANAGED_IMAGE_REVISION !== - "${{ needs.generate-matrix.outputs.managed_image_revision }}" || - live.env?.E2E_WORKLOAD_SOURCE !== "${{ needs.generate-matrix.outputs.workload_source }}" - ) { - errors.push("live stock onboarding must use the selected workload source and image revision"); + for (const jobName of [ + "cloud-onboard", + "hermes-gpu-startup", + "live", + "mcp-bridge", + "mcp-bridge-dev", + "openshell-credential-generation-window", + ]) { + const job = workflow.jobs[jobName] ?? {}; + if ( + job.env?.E2E_MANAGED_IMAGE_REVISION !== + "${{ needs.generate-matrix.outputs.managed_image_revision }}" || + job.env?.E2E_WORKLOAD_SOURCE !== "${{ needs.generate-matrix.outputs.workload_source }}" + ) { + errors.push(`${jobName} must use the selected workload source and image revision`); + } } if ( live.env?.NEMOCLAW_LANGCHAIN_DEEPAGENTS_CODE_SANDBOX_BASE_IMAGE_REF !== diff --git a/tools/e2e/pr-managed-image-source.mts b/tools/e2e/pr-managed-image-source.mts index cf7f1d411d3..e54a9dcab0c 100644 --- a/tools/e2e/pr-managed-image-source.mts +++ b/tools/e2e/pr-managed-image-source.mts @@ -237,15 +237,6 @@ export async function resolvePrManagedImageSource( return managedImageInputsChanged(changedFiles, patterns) ? "local-dockerfile" : "managed-image"; } -export function writePrManagedImageSource(outputPath: string, source: PrManagedImageSource): void { - fs.mkdirSync(path.dirname(path.resolve(outputPath)), { mode: 0o700, recursive: true }); - fs.writeFileSync(outputPath, `${source}\n`, { - encoding: "utf8", - flag: "wx", - mode: 0o600, - }); -} - function requiredInteger(value: string | undefined, label: string): number { if (!value || !/^[1-9][0-9]*$/u.test(value)) throw new Error(`${label} is required`); return positiveInteger(Number(value), label); @@ -260,8 +251,8 @@ export async function main(argv = process.argv.slice(2), env = process.env): Pro console.log("pr-managed-image-catalog outcome=assembled"); return; } - if (argv[0] !== "select" || argv.length !== 2) { - throw new Error("expected select and one managed-image source output path"); + if (argv[0] !== "select" || argv.length !== 1) { + throw new Error("expected select"); } const source = await resolvePrManagedImageSource({ baseSha: env.BASE_SHA ?? "", @@ -271,8 +262,7 @@ export async function main(argv = process.argv.slice(2), env = process.env): Pro token: env.GITHUB_TOKEN ?? "", workflowSource: fs.readFileSync(BASE_IMAGE_WORKFLOW_PATH, "utf8"), }); - writePrManagedImageSource(argv[1], source); - console.log(`pr-managed-image-source outcome=${source}`); + process.stdout.write(`${source}\n`); } if (path.resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) { diff --git a/tools/e2e/trusted-hermes-swap-workflow-boundary.mts b/tools/e2e/trusted-hermes-swap-workflow-boundary.mts index ca841803cc5..6f3dba090bf 100644 --- a/tools/e2e/trusted-hermes-swap-workflow-boundary.mts +++ b/tools/e2e/trusted-hermes-swap-workflow-boundary.mts @@ -258,7 +258,9 @@ export function validateTrustedHermesSwapWorkflow(workflowValue: unknown): strin continue; } - if (job.needs !== "generate-matrix") { + const expectedNeeds = + jobName === "mcp-bridge" ? ["base-image-publication", "generate-matrix"] : "generate-matrix"; + if (!isDeepStrictEqual(job.needs, expectedNeeds)) { errors.push(`${jobName} trusted Hermes swap job must depend on controller validation`); } if (provisionSteps.length !== 1) { diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 6fb66b33503..5135fb845f3 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -1177,7 +1177,7 @@ function validateFreeStandingJobSelector( const expectedNeeds = jobName === "mcp-bridge-dev" ? ["generate-matrix", "openshell-dev-artifact"] - : jobName === "cloud-onboard" + : jobName === "cloud-onboard" || jobName === "mcp-bridge" ? ["base-image-publication", "generate-matrix"] : "generate-matrix"; if (!isDeepStrictEqual(job.needs, expectedNeeds)) { @@ -1754,7 +1754,7 @@ function validateJetsonControllerBoundary(errors: string[], jobs: WorkflowRecord errors.push("jetson-nvmap-gpu job must depend on managed publication and generate-matrix"); } const trustedPushOrManualSelector = - "${{ always() && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && github.repository == 'NVIDIA/NemoClaw' && github.ref == 'refs/heads/main' && (github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.allow_jetson_dispatch && (inputs.checkout_repository == '' || inputs.checkout_repository == github.repository) && ((inputs.jobs == '' && inputs.targets == '') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'jetson-nvmap-gpu')))) }}"; + "${{ always() && needs.generate-matrix.outputs.workload_source == 'managed-image' && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && github.repository == 'NVIDIA/NemoClaw' && github.ref == 'refs/heads/main' && (github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.allow_jetson_dispatch && (inputs.checkout_repository == '' || inputs.checkout_repository == github.repository) && ((inputs.jobs == '' && inputs.targets == '') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'jetson-nvmap-gpu')))) }}"; if (job.if !== trustedPushOrManualSelector) { errors.push( "jetson-nvmap-gpu job must run on trusted main pushes and require opt-in for same-repository manual selections", From 6a55a5f255ce8dfa4195fefd265991acce92a620 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 19:41:36 +0700 Subject: [PATCH 03/40] refactor(e2e): share image input matching Signed-off-by: San Dang --- .../support/base-image-publication.test.ts | 36 ++++++++++-- .../support/pr-managed-image-source.test.ts | 22 +++---- tools/e2e/base-image-publication.mts | 44 +++++++++++--- tools/e2e/pr-managed-image-source.mts | 58 ++----------------- 4 files changed, 84 insertions(+), 76 deletions(-) diff --git a/test/e2e/support/base-image-publication.test.ts b/test/e2e/support/base-image-publication.test.ts index a1ed7f41ef4..5171e0fa68d 100644 --- a/test/e2e/support/base-image-publication.test.ts +++ b/test/e2e/support/base-image-publication.test.ts @@ -9,6 +9,7 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; import { + baseImageInputsChanged, collectPaginated, expandBaseImagePushPaths, type FirstParentHistory, @@ -33,6 +34,11 @@ const RUN_ID = 29891942278; const WORKFLOW_ID = 251475843; const RUN_URL_ROOT = "https://github.com/NVIDIA/NemoClaw/actions/runs"; const RUN_URL = `https://github.com/NVIDIA/NemoClaw/actions/runs/${RUN_ID}`; +const BASE_IMAGE_WORKFLOW_SOURCE = fs.readFileSync( + path.resolve(import.meta.dirname, "../../../.github/workflows/base-image.yaml"), + "utf8", +); +const BASE_IMAGE_PUSH_PATHS = parseBaseImagePushPaths(BASE_IMAGE_WORKFLOW_SOURCE); const WORKFLOW_SOURCE = `on: push: branches: [main] @@ -175,12 +181,7 @@ describe("base-image publication evidence", () => { ); it("extracts literal paths and the reviewed managed-image input families (#7372)", () => { - const source = fs.readFileSync( - path.resolve(import.meta.dirname, "../../../.github/workflows/base-image.yaml"), - "utf8", - ); - - expect(parseBaseImagePushPaths(source)).toEqual( + expect(BASE_IMAGE_PUSH_PATHS).toEqual( expect.arrayContaining([ ".github/actions/ci-reviewed-npm-audit/**", ".github/workflows/base-image.yaml", @@ -201,6 +202,29 @@ describe("base-image publication evidence", () => { ); }); + it.each(BASE_IMAGE_PUSH_PATHS)( + "matches reviewed literal or wildcard path %s with one predicate (#7372)", + (reviewedPath) => { + const changedPath = reviewedPath.endsWith("/**") + ? `${reviewedPath.slice(0, -3)}/fixture.ts` + : reviewedPath.replace("*", "fixture"); + expect(baseImageInputsChanged([changedPath], BASE_IMAGE_PUSH_PATHS)).toBe(true); + }, + ); + + it("does not match a path outside the reviewed image inputs (#7372)", () => { + expect(baseImageInputsChanged(["docs/guide.mdx"], BASE_IMAGE_PUSH_PATHS)).toBe(false); + }); + + it.each(["../Dockerfile", "/Dockerfile", "Dockerfile\nother", "agents//Dockerfile"])( + "rejects invalid changed-file path %j before matching (#7372)", + (changedPath) => { + expect(() => baseImageInputsChanged([changedPath], ["Dockerfile"])).toThrow( + "PR changed-file path is invalid", + ); + }, + ); + it.each([ [ "a duplicate", diff --git a/test/e2e/support/pr-managed-image-source.test.ts b/test/e2e/support/pr-managed-image-source.test.ts index 83e59781d4c..1df32b64c50 100644 --- a/test/e2e/support/pr-managed-image-source.test.ts +++ b/test/e2e/support/pr-managed-image-source.test.ts @@ -17,10 +17,12 @@ import { type ManagedImageContractV1, SHIPPED_MANAGED_IMAGE_AGENTS, } from "../../../src/lib/onboard/managed-image/contract"; -import { parseBaseImagePushPaths } from "../../../tools/e2e/base-image-publication.mts"; +import { + baseImageInputsChanged, + parseBaseImagePushPaths, +} from "../../../tools/e2e/base-image-publication.mts"; import { assembleManagedImageCatalog, - managedImageInputsChanged, resolvePrManagedImageSource, writeManagedImageCatalog, } from "../../../tools/e2e/pr-managed-image-source.mts"; @@ -106,16 +108,16 @@ describe("PR managed-image source selection", () => { fs.readFileSync(".github/workflows/base-image.yaml", "utf8"), ); - expect(managedImageInputsChanged(["agents/hermes/Dockerfile.base"], patterns)).toBe(true); - expect( - managedImageInputsChanged(["src/lib/onboard/managed-startup/profile.ts"], patterns), - ).toBe(true); - expect(managedImageInputsChanged(["test/e2e/fixtures/workload-source-env.ts"], patterns)).toBe( + expect(baseImageInputsChanged(["agents/hermes/Dockerfile.base"], patterns)).toBe(true); + expect(baseImageInputsChanged(["src/lib/onboard/managed-startup/profile.ts"], patterns)).toBe( + true, + ); + expect(baseImageInputsChanged(["test/e2e/fixtures/workload-source-env.ts"], patterns)).toBe( true, ); - expect(managedImageInputsChanged(["test/e2e/fixtures/progress.ts"], patterns)).toBe(false); - expect(managedImageInputsChanged(["docs/guide.mdx"], patterns)).toBe(false); - expect(() => managedImageInputsChanged(["Dockerfile.base\nother"], patterns)).toThrow( + expect(baseImageInputsChanged(["test/e2e/fixtures/progress.ts"], patterns)).toBe(false); + expect(baseImageInputsChanged(["docs/guide.mdx"], patterns)).toBe(false); + expect(() => baseImageInputsChanged(["Dockerfile.base\nother"], patterns)).toThrow( "changed-file path is invalid", ); }); diff --git a/tools/e2e/base-image-publication.mts b/tools/e2e/base-image-publication.mts index 2c5bff93fda..2bfa548c532 100644 --- a/tools/e2e/base-image-publication.mts +++ b/tools/e2e/base-image-publication.mts @@ -21,6 +21,7 @@ const PAGINATION_ATTEMPTS = 3; const REQUEST_ATTEMPTS = 3; const REQUEST_TIMEOUT_MS = 20_000; const MAX_RETRY_DELAY_MS = 10_000; +const MAX_CHANGED_PATHS = 6_000; const SHA_PATTERN = /^[0-9a-f]{40}$/u; const SAFE_PATH_PATTERN = /^[A-Za-z0-9._/-]+$/u; const REVIEWED_PATH_GLOBS = new Map([ @@ -157,6 +158,19 @@ function sha(value: unknown, label: string): string { return value; } +function isSafeLiteralPath(value: string): boolean { + return ( + value.length > 0 && + value.length <= 4_096 && + SAFE_PATH_PATTERN.test(value) && + !value.startsWith("/") && + !value.startsWith("-") && + !value.startsWith(":") && + !value.includes("//") && + !value.split("/").some((segment) => segment === "" || segment === "." || segment === "..") + ); +} + function parseQuotedPath(raw: string, lineNumber: number): string { let value: unknown; try { @@ -174,14 +188,7 @@ function parseQuotedPath(raw: string, lineNumber: number): string { throw new Error(`base-image push path on line ${lineNumber} must be a non-empty exact path`); } if (REVIEWED_PATH_GLOBS.has(value)) return value; - if ( - !SAFE_PATH_PATTERN.test(value) || - value.startsWith("/") || - value.startsWith("-") || - value.startsWith(":") || - value.includes("//") || - value.split("/").some((segment) => segment === "" || segment === "." || segment === "..") - ) { + if (!isSafeLiteralPath(value)) { throw new Error(`base-image push path on line ${lineNumber} is not a safe literal path`); } return value; @@ -280,6 +287,27 @@ export function expandBaseImagePushPaths(expectedSha: string, paths: readonly st ].sort(); } +/** Determine whether reviewed base-image inputs contain a changed repository path. */ +export function baseImageInputsChanged( + changedFiles: readonly string[], + reviewedPaths: readonly string[], +): boolean { + if (changedFiles.length > MAX_CHANGED_PATHS) { + throw new Error(`PR changed-path count exceeds ${MAX_CHANGED_PATHS}`); + } + const matchers = reviewedPaths.map((reviewedPath) => { + const reviewedGlob = REVIEWED_PATH_GLOBS.get(reviewedPath); + if (reviewedGlob) return (changedPath: string) => reviewedGlob.test(changedPath); + if (!isSafeLiteralPath(reviewedPath)) throw new Error("base-image input path is invalid"); + return (changedPath: string) => changedPath === reviewedPath; + }); + for (const changedPath of changedFiles) { + if (!isSafeLiteralPath(changedPath)) throw new Error("PR changed-file path is invalid"); + if (matchers.some((matches) => matches(changedPath))) return true; + } + return false; +} + export function resolveFirstParentHistory( expectedSha: string, paths: readonly string[], diff --git a/tools/e2e/pr-managed-image-source.mts b/tools/e2e/pr-managed-image-source.mts index e54a9dcab0c..5bc83c9c962 100644 --- a/tools/e2e/pr-managed-image-source.mts +++ b/tools/e2e/pr-managed-image-source.mts @@ -10,7 +10,11 @@ import { SHIPPED_MANAGED_IMAGE_AGENTS, type ManagedImageContractCatalog, } from "../../src/lib/onboard/managed-image/contract.ts"; -import { githubRequest, parseBaseImagePushPaths } from "./base-image-publication.mts"; +import { + baseImageInputsChanged, + githubRequest, + parseBaseImagePushPaths, +} from "./base-image-publication.mts"; const REPOSITORY = "NVIDIA/NemoClaw"; const BASE_IMAGE_WORKFLOW_PATH = ".github/workflows/base-image.yaml"; @@ -18,7 +22,6 @@ const MAX_CHANGED_FILES = 3_000; const PAGE_SIZE = 100; const SHA_PATTERN = /^[0-9a-f]{40}$/u; const REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u; -const SAFE_PATH_PATTERN = /^[A-Za-z0-9._/*-]+$/u; type JsonRecord = Record; @@ -42,55 +45,6 @@ function exactString(value: unknown, expected: string, label: string): void { if (value !== expected) throw new Error(`${label} must be ${expected}`); } -function compileManagedImagePath(pattern: string): RegExp { - if ( - !SAFE_PATH_PATTERN.test(pattern) || - pattern.startsWith("/") || - pattern.includes("//") || - pattern.split("/").some((segment) => segment === "" || segment === "." || segment === "..") - ) { - throw new Error(`managed-image input path '${pattern}' is invalid`); - } - const stars = [...pattern.matchAll(/\*/gu)].map((match) => match.index); - if (stars.length === 0) { - return new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}$`, "u"); - } - if (pattern.endsWith("/**") && stars.length === 2) { - const prefix = pattern.slice(0, -3).replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); - return new RegExp(`^${prefix}/.+$`, "u"); - } - if (stars.length === 1) { - const escaped = pattern.replace(/[.+?^${}()|[\]\\]/gu, "\\$&").replaceAll("*", "[^/]*"); - return new RegExp(`^${escaped}$`, "u"); - } - throw new Error(`managed-image input path '${pattern}' uses an unsupported glob`); -} - -/** Determine whether the PR changes a reviewed base- or managed-image input. */ -export function managedImageInputsChanged( - changedFiles: readonly string[], - patterns: readonly string[], -): boolean { - if (changedFiles.length > MAX_CHANGED_FILES * 2) { - throw new Error(`PR changed-path count exceeds ${MAX_CHANGED_FILES * 2}`); - } - const matchers = patterns.map(compileManagedImagePath); - for (const file of changedFiles) { - if ( - file.length === 0 || - file.length > 4_096 || - /[\0\r\n]/u.test(file) || - file.startsWith("/") || - file.includes("//") || - file.split("/").some((segment) => segment === "" || segment === "." || segment === "..") - ) { - throw new Error("PR changed-file path is invalid"); - } - if (matchers.some((matcher) => matcher.test(file))) return true; - } - return false; -} - /** Assemble one all-agent catalog for the managed-image workflow's activation check. */ export function assembleManagedImageCatalog( values: readonly unknown[], @@ -234,7 +188,7 @@ export async function resolvePrManagedImageSource( ); const changedFiles = await readChangedFiles(input.prNumber, changedCount, request); const patterns = parseBaseImagePushPaths(input.workflowSource); - return managedImageInputsChanged(changedFiles, patterns) ? "local-dockerfile" : "managed-image"; + return baseImageInputsChanged(changedFiles, patterns) ? "local-dockerfile" : "managed-image"; } function requiredInteger(value: string | undefined, label: string): number { From 72e7af88ea3bebc2266b7905a13e7ead34e87878 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 20:30:01 +0700 Subject: [PATCH 04/40] fix(e2e): route Pi to its candidate image Signed-off-by: San Dang --- test/e2e/fixtures/workload-source-env.ts | 1 + .../support/base-image-publication.test.ts | 2 +- .../support/pr-managed-image-source.test.ts | 23 ------------------- test/e2e/support/workload-source-env.test.ts | 1 + 4 files changed, 3 insertions(+), 24 deletions(-) diff --git a/test/e2e/fixtures/workload-source-env.ts b/test/e2e/fixtures/workload-source-env.ts index 3d801953af2..b745516a4e3 100644 --- a/test/e2e/fixtures/workload-source-env.ts +++ b/test/e2e/fixtures/workload-source-env.ts @@ -9,6 +9,7 @@ const LOCAL_DOCKERFILE_BY_AGENT = { openclaw: "Dockerfile", hermes: "agents/hermes/Dockerfile", "langchain-deepagents-code": "agents/langchain-deepagents-code/Dockerfile", + pi: "agents/pi/Dockerfile", } as const; type LocalDockerfileAgent = keyof typeof LOCAL_DOCKERFILE_BY_AGENT; diff --git a/test/e2e/support/base-image-publication.test.ts b/test/e2e/support/base-image-publication.test.ts index 5171e0fa68d..85c109f4439 100644 --- a/test/e2e/support/base-image-publication.test.ts +++ b/test/e2e/support/base-image-publication.test.ts @@ -207,7 +207,7 @@ describe("base-image publication evidence", () => { (reviewedPath) => { const changedPath = reviewedPath.endsWith("/**") ? `${reviewedPath.slice(0, -3)}/fixture.ts` - : reviewedPath.replace("*", "fixture"); + : reviewedPath.replaceAll("*", "fixture"); expect(baseImageInputsChanged([changedPath], BASE_IMAGE_PUSH_PATHS)).toBe(true); }, ); diff --git a/test/e2e/support/pr-managed-image-source.test.ts b/test/e2e/support/pr-managed-image-source.test.ts index 1df32b64c50..543d1698168 100644 --- a/test/e2e/support/pr-managed-image-source.test.ts +++ b/test/e2e/support/pr-managed-image-source.test.ts @@ -17,10 +17,6 @@ import { type ManagedImageContractV1, SHIPPED_MANAGED_IMAGE_AGENTS, } from "../../../src/lib/onboard/managed-image/contract"; -import { - baseImageInputsChanged, - parseBaseImagePushPaths, -} from "../../../tools/e2e/base-image-publication.mts"; import { assembleManagedImageCatalog, resolvePrManagedImageSource, @@ -103,25 +99,6 @@ describe("PR managed-image source selection", () => { ).resolves.toBe("managed-image"); }); - it("uses the trusted base-image workflow path families", () => { - const patterns = parseBaseImagePushPaths( - fs.readFileSync(".github/workflows/base-image.yaml", "utf8"), - ); - - expect(baseImageInputsChanged(["agents/hermes/Dockerfile.base"], patterns)).toBe(true); - expect(baseImageInputsChanged(["src/lib/onboard/managed-startup/profile.ts"], patterns)).toBe( - true, - ); - expect(baseImageInputsChanged(["test/e2e/fixtures/workload-source-env.ts"], patterns)).toBe( - true, - ); - expect(baseImageInputsChanged(["test/e2e/fixtures/progress.ts"], patterns)).toBe(false); - expect(baseImageInputsChanged(["docs/guide.mdx"], patterns)).toBe(false); - expect(() => baseImageInputsChanged(["Dockerfile.base\nother"], patterns)).toThrow( - "changed-file path is invalid", - ); - }); - it("rejects PR identity drift before selecting a source", async () => { const request = requestFor([{ filename: "Dockerfile" }], { head: { sha: CANDIDATE_SHA, repo: { full_name: "attacker/fork" } }, diff --git a/test/e2e/support/workload-source-env.test.ts b/test/e2e/support/workload-source-env.test.ts index 4abbc3320f4..0c39a67d9e2 100644 --- a/test/e2e/support/workload-source-env.test.ts +++ b/test/e2e/support/workload-source-env.test.ts @@ -15,6 +15,7 @@ describe("live E2E workload source environment", () => { ["openclaw", "Dockerfile"], ["hermes", "agents/hermes/Dockerfile"], ["langchain-deepagents-code", "agents/langchain-deepagents-code/Dockerfile"], + ["pi", "agents/pi/Dockerfile"], ])("uses the candidate Dockerfile for %s", (agent, dockerfile) => { expect( resolveLiveE2eWorkloadSourceEnv({ From f151510dff1e4ecd11cddeb94b3db3ee8d44b415 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 20:50:32 +0700 Subject: [PATCH 05/40] fix(onboard): report pairing settlement failures Signed-off-by: San Dang --- .../onboard/machine/finalization-deps.test.ts | 35 +++++++++++++++++++ src/lib/onboard/machine/finalization-deps.ts | 24 +++++++++++-- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/src/lib/onboard/machine/finalization-deps.test.ts b/src/lib/onboard/machine/finalization-deps.test.ts index 21aff1c9e09..e216b72d9d7 100644 --- a/src/lib/onboard/machine/finalization-deps.test.ts +++ b/src/lib/onboard/machine/finalization-deps.test.ts @@ -140,6 +140,41 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); + it("reports a failed warm-up without attempting pairing approval", async () => { + const scope = ordinaryPairingDeps({ + observePairing: vi.fn(() => PAIRING_ONLY), + runWarmup: vi.fn(() => { + throw new Error("secret runtime detail"); + }), + }); + + await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).resolves.toEqual({ + kind: "incomplete", + reason: "warmup-failed", + }); + expect(scope.deps.runApproval).not.toHaveBeenCalled(); + expect(ordinaryOpenClawPairingIncompleteMessage("alpha", "warmup-failed")).toBe( + "OpenClaw onboarding for 'alpha' is incomplete because its scope-upgrade warm-up request failed. Verify the OpenClaw gateway is reachable, then resume or rerun onboarding.", + ); + }); + + it("reports a failed local pairing approval", async () => { + const scope = ordinaryPairingDeps({ + observePairing: vi.fn(() => SCOPE_UPGRADE_PENDING), + runApproval: vi.fn(() => { + throw new Error("secret runtime detail"); + }), + }); + + await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).resolves.toEqual({ + kind: "incomplete", + reason: "approval-failed", + }); + expect(ordinaryOpenClawPairingIncompleteMessage("alpha", "approval-failed")).toBe( + "OpenClaw onboarding for 'alpha' is incomplete because its local pairing approval failed. Verify the pending local pairing request can be approved, then resume or rerun onboarding.", + ); + }); + it("holds lifecycle then gateway-route ownership across the full settlement (#9844)", async () => { const events: string[] = []; const scope = ordinaryPairingDeps({ diff --git a/src/lib/onboard/machine/finalization-deps.ts b/src/lib/onboard/machine/finalization-deps.ts index c4f51c32bf5..862d84fd783 100644 --- a/src/lib/onboard/machine/finalization-deps.ts +++ b/src/lib/onboard/machine/finalization-deps.ts @@ -36,6 +36,8 @@ export type OrdinaryOpenClawPairingSettlementResult = | "runtime-identity-invalid" | "pairing-lock-unavailable" | "pairing-unavailable" + | "warmup-failed" + | "approval-failed" | "scope-upgrade-incomplete"; }; @@ -51,10 +53,20 @@ const ORDINARY_OPENCLAW_PAIRING_INCOMPLETE_CAUSES: Record< "runtime-identity-invalid": "its recorded OpenClaw runtime identity changed or is invalid", "pairing-lock-unavailable": "NemoClaw could not acquire the pairing settlement locks", "pairing-unavailable": "its canonical CLI device pairing did not appear", + "warmup-failed": "its scope-upgrade warm-up request failed", + "approval-failed": "its local pairing approval failed", "scope-upgrade-incomplete": "its canonical CLI device did not receive the required baseline scopes", }; +const ORDINARY_OPENCLAW_PAIRING_RECOVERY: Partial< + Record +> = { + "warmup-failed": "Verify the OpenClaw gateway is reachable, then resume or rerun onboarding.", + "approval-failed": + "Verify the pending local pairing request can be approved, then resume or rerun onboarding.", +}; + interface OrdinaryOpenClawPairingSettlementDeps { getTarget(name: string): OpenClawPairingSettlementTarget | null; observePairing( @@ -260,14 +272,18 @@ export async function settleOrdinaryOpenClawPairing( // Running the producer before that identity exists can create no // upgrade and leaves an otherwise healthy fresh onboard stuck at // pairing-only (#10014). + let warmupFailed = false; try { await deps.runWarmup(name, target.gatewayName); } catch { - // The bounded observation below remains fail closed. + warmupFailed = true; } if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } + if (warmupFailed) { + return { kind: "incomplete", reason: "warmup-failed" }; + } const scopeUpgradeDeadline = Math.min( settlementDeadline, deps.now() + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS, @@ -313,7 +329,7 @@ export async function settleOrdinaryOpenClawPairing( return { kind: "incomplete", reason: "runtime-identity-invalid" }; } if (approvalFailed) { - return { kind: "incomplete", reason: "scope-upgrade-incomplete" }; + return { kind: "incomplete", reason: "approval-failed" }; } const finalObservationDeadline = Math.min( @@ -352,7 +368,9 @@ export function ordinaryOpenClawPairingIncompleteMessage( reason: OrdinaryOpenClawPairingIncompleteReason, ): string { const cause = ORDINARY_OPENCLAW_PAIRING_INCOMPLETE_CAUSES[reason]; - return `OpenClaw onboarding for '${name}' is incomplete because ${cause}. Resume or rerun onboarding.`; + const recovery = + ORDINARY_OPENCLAW_PAIRING_RECOVERY[reason] ?? "Resume or rerun onboarding."; + return `OpenClaw onboarding for '${name}' is incomplete because ${cause}. ${recovery}`; } export const finalizationHandlerDeps = { From c1e3570fc65532e75816c306fdb1a31a804eac9a Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 20:51:39 +0700 Subject: [PATCH 06/40] fix(e2e): preserve local DCode base resolution Signed-off-by: San Dang --- .github/workflows/e2e.yaml | 2 ++ test/e2e/fixtures/phases/onboarding.ts | 17 +++++++----- test/e2e/support/e2e-phase-onboarding.test.ts | 26 +++++++++++++++++++ tools/e2e/operations-workflow-boundary.mts | 4 ++- 4 files changed, 42 insertions(+), 7 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 23af2126a8c..25a04988d85 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -2698,6 +2698,8 @@ jobs: E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_revision }} E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} + # The local path leaves this override empty so the candidate CLI builds + # changed base inputs locally and resolves unchanged inputs normally. NEMOCLAW_LANGCHAIN_DEEPAGENTS_CODE_SANDBOX_BASE_IMAGE_REF: ${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && needs.base-image-publication.outputs.dcode_base_ref || '' }} NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js NEMOCLAW_RUN_LIVE_E2E: "1" diff --git a/test/e2e/fixtures/phases/onboarding.ts b/test/e2e/fixtures/phases/onboarding.ts index f50bd9165d5..a20362e2952 100644 --- a/test/e2e/fixtures/phases/onboarding.ts +++ b/test/e2e/fixtures/phases/onboarding.ts @@ -256,11 +256,16 @@ export class OnboardingPhaseFixture { ); } const sandboxName = sandboxNameFromOptions(environment.onboarding, options); - const baseImageReference = requireDcodeBaseImageReference( - options.dcodeBaseImageReference === undefined - ? process.env - : { [DCODE_BASE_IMAGE_ENV]: options.dcodeBaseImageReference }, - ); + const useCandidateBase = + options.dcodeBaseImageReference === undefined && + process.env.E2E_WORKLOAD_SOURCE === "local-dockerfile"; + const baseImageReference = useCandidateBase + ? undefined + : requireDcodeBaseImageReference( + options.dcodeBaseImageReference === undefined + ? process.env + : { [DCODE_BASE_IMAGE_ENV]: options.dcodeBaseImageReference }, + ); const apiKey = this.secrets.required("NVIDIA_INFERENCE_API_KEY"); this.registerSandboxCleanup(sandboxName); const result = await this.host.nemoclaw([...ONBOARD_ARGS, "--observability"], { @@ -282,7 +287,7 @@ export class OnboardingPhaseFixture { NEMOCLAW_PREFERRED_API: process.env.NEMOCLAW_PREFERRED_API || "openai-completions", NVIDIA_INFERENCE_API_KEY: apiKey, [HOSTED_INFERENCE_CREDENTIAL_ENV]: apiKey, - [DCODE_BASE_IMAGE_ENV]: baseImageReference, + ...(baseImageReference ? { [DCODE_BASE_IMAGE_ENV]: baseImageReference } : {}), }), redactionValues: [apiKey], timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS, diff --git a/test/e2e/support/e2e-phase-onboarding.test.ts b/test/e2e/support/e2e-phase-onboarding.test.ts index bfd6107d8cf..4736e9afded 100644 --- a/test/e2e/support/e2e-phase-onboarding.test.ts +++ b/test/e2e/support/e2e-phase-onboarding.test.ts @@ -254,6 +254,32 @@ describe("onboarding phase fixture", () => { }); }); + it("lets local-Dockerfile Deep Agents Code onboarding resolve its candidate base", async () => { + const runner = new FakeRunner(); + runner.enqueue(shellResult(0, "onboarded\n")); + const secrets = new FakeSecrets({ NVIDIA_INFERENCE_API_KEY: "secret-token" }); + const onboard = new OnboardingPhaseFixture(new HostCliClient(runner), secrets); + + await withProcessEnvironment( + { + E2E_WORKLOAD_SOURCE: "local-dockerfile", + [DCODE_BASE_IMAGE_ENV]: undefined, + }, + () => + onboard.from(ready({ onboarding: "cloud-langchain-deepagents-code" }), { + sandboxName: "e2e-dcode-local", + }), + ); + + expect(runner.calls[0]?.options?.env).toEqual( + expect.objectContaining({ + E2E_WORKLOAD_SOURCE: "local-dockerfile", + NEMOCLAW_AGENT: "langchain-deepagents-code", + }), + ); + expect(runner.calls[0]?.options?.env?.[DCODE_BASE_IMAGE_ENV]).toBeUndefined(); + }); + it("uses the contract-selected Deep Agents Code base image reference instead of the ambient publication index", async () => { const runner = new FakeRunner(); runner.enqueue(shellResult(0, "onboarded\n")); diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index 4e2fd2f4027..9633746dbde 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -770,7 +770,9 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): live.env?.NEMOCLAW_LANGCHAIN_DEEPAGENTS_CODE_SANDBOX_BASE_IMAGE_REF !== "${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && needs.base-image-publication.outputs.dcode_base_ref || '' }}" ) { - errors.push("live DCode must use an immutable base reference only with managed images"); + errors.push( + "live DCode must bind the published base only for managed images and leave local base resolution to the candidate checkout", + ); } const evidence = findStep(live, "Record immutable Deep Agents Code base evidence"); const upload = findStep(live, "Upload E2E artifacts"); From f340c61de8f310acf63d63a1e3fc01a391dce3e6 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 21:09:29 +0700 Subject: [PATCH 07/40] fix(onboard): consume pairing producer receipts Signed-off-by: San Dang --- src/lib/actions/sandbox/auto-pair-warmup.ts | 37 +++++++++------ .../onboard/machine/finalization-deps.test.ts | 37 +++++++++++---- src/lib/onboard/machine/finalization-deps.ts | 46 +++++++++++-------- 3 files changed, 76 insertions(+), 44 deletions(-) diff --git a/src/lib/actions/sandbox/auto-pair-warmup.ts b/src/lib/actions/sandbox/auto-pair-warmup.ts index 52238be69f4..52530f634c1 100644 --- a/src/lib/actions/sandbox/auto-pair-warmup.ts +++ b/src/lib/actions/sandbox/auto-pair-warmup.ts @@ -22,10 +22,10 @@ * * Contract: best-effort, bounded, idempotent. The direct call normally returns * the pending-scope failure after it publishes the request, and its output is - * discarded. The leaf swallows execution failures, and onboarding separately - * observes the canonical pairing state before it reports success. On re-onboard - * where `operator.write` is already paired the call succeeds and the approval - * pass is a no-op. + * discarded. The leaf converts host execution failures to one fixed result, + * and onboarding separately observes the canonical pairing state before it + * reports success. On re-onboard where `operator.write` is already paired the + * call succeeds and the approval pass is a no-op. * * Workaround boundary (NemoClaw#4462): OpenClaw owns device-pairing semantics * and exposes only `devices list/get/approve` — there is no way to pre-grant a @@ -43,6 +43,7 @@ import { WARMUP_SESSION_ID_PREFIX } from "./warmup-session"; // wedged sandbox from blocking onboard or restore. export const WARMUP_TIMEOUT_MS = 30_000; export const WARMUP_PROBE_TIMEOUT_S = 5; +export type SandboxScopeWarmupResult = "executed" | "exec-failed"; // Best-effort in-sandbox request producer. Always exits 0. Use the stored CLI // device credential for the direct `sessions.create` call. Shared gateway @@ -113,7 +114,7 @@ function runSandboxWarmupScript( sandboxName: string, gatewayName: string | undefined, script: string, -): void { +): SandboxScopeWarmupResult { // Lazy require: `adapters/openshell/resolve` pulls in `runner`, whose // load-time `require("./platform")` cannot be resolved by the Vitest TS // loader. Importing it here keeps this module unit-testable in-process. @@ -125,8 +126,8 @@ function runSandboxWarmupScript( require("../../adapters/openshell/resolve") as typeof import("../../adapters/openshell/resolve"); try { const openshellBinary = resolveOpenshell(); - if (!openshellBinary) return; - spawnSync( + if (!openshellBinary) return "exec-failed"; + const result = spawnSync( openshellBinary, sandboxWarmupExecArgs(sandboxName, gatewayName, script), { @@ -136,25 +137,31 @@ function runSandboxWarmupScript( timeout: WARMUP_TIMEOUT_MS, }, ); + return !result.error && result.status === 0 ? "executed" : "exec-failed"; } catch { - /* defense-in-depth — never throw from a warm-up path */ + return "exec-failed"; } } /** * Run the bounded, throwaway scope-upgrade warm-up inside the named sandbox via - * `openshell sandbox exec`. All failure modes (timeout, sandbox-exec errors, - * missing openclaw, gateway unreachable) are swallowed. The finalization - * settlement gate decides readiness from a later canonical observation. + * `openshell sandbox exec`. Host execution failures return one fixed result; + * command output remains discarded. The finalization settlement gate decides + * readiness from a later canonical observation. */ -export function runSandboxScopeWarmupRun(sandboxName: string, gatewayName: string): void { - runSandboxWarmupScript(sandboxName, gatewayName, WARMUP_SCRIPT); +export function runSandboxScopeWarmupRun( + sandboxName: string, + gatewayName: string, +): SandboxScopeWarmupResult { + return runSandboxWarmupScript(sandboxName, gatewayName, WARMUP_SCRIPT); } /** * Attempt to publish a restored clone's write-scope request without an * embedded fallback. Failures remain non-blocking. */ -export function runRestoredSandboxScopeWarmupRun(sandboxName: string): void { - runSandboxWarmupScript(sandboxName, undefined, RESTORED_CLONE_WARMUP_SCRIPT); +export function runRestoredSandboxScopeWarmupRun( + sandboxName: string, +): SandboxScopeWarmupResult { + return runSandboxWarmupScript(sandboxName, undefined, RESTORED_CLONE_WARMUP_SCRIPT); } diff --git a/src/lib/onboard/machine/finalization-deps.test.ts b/src/lib/onboard/machine/finalization-deps.test.ts index e216b72d9d7..cf09e19cf9d 100644 --- a/src/lib/onboard/machine/finalization-deps.test.ts +++ b/src/lib/onboard/machine/finalization-deps.test.ts @@ -49,6 +49,15 @@ const SETTLED: OpenClawPairingSettlementObservation = { deviceIdentitySha256: PAIRING_ONLY.deviceIdentitySha256, }; +const APPROVED_ONE = { + attempted: true, + reported: false, + approved: 0, + receipt: "approved-one", +} as const; + +const APPROVE_FAILED = { ...APPROVED_ONE, receipt: "approve-failed" } as const; + function ordinaryPairingDeps( overrides: Partial[1]> = {}, ) { @@ -59,9 +68,11 @@ function ordinaryPairingDeps( observePairing: vi.fn(() => SETTLED), runWarmup: vi.fn(() => { calls.push("warmup"); + return "executed" as const; }), runApproval: vi.fn(() => { calls.push("approval"); + return APPROVED_ONE; }), withSandboxLock: vi.fn(async (_name, operation) => operation()), withGatewayLock: vi.fn(async (_gatewayName, operation) => operation()), @@ -124,10 +135,12 @@ describe("ordinary OpenClaw pairing settlement", () => { observePairing, runWarmup: vi.fn(() => { scope.calls.push("warmup"); + return "executed" as const; }), runApproval: vi.fn(() => { scope.calls.push("approval"); vi.mocked(scope.deps.observePairing).mockReturnValue(SETTLED); + return APPROVED_ONE; }), }); @@ -140,12 +153,10 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); - it("reports a failed warm-up without attempting pairing approval", async () => { + it("reports a warm-up execution failure receipt without attempting approval", async () => { const scope = ordinaryPairingDeps({ observePairing: vi.fn(() => PAIRING_ONLY), - runWarmup: vi.fn(() => { - throw new Error("secret runtime detail"); - }), + runWarmup: vi.fn(() => "exec-failed" as const), }); await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).resolves.toEqual({ @@ -158,12 +169,10 @@ describe("ordinary OpenClaw pairing settlement", () => { ); }); - it("reports a failed local pairing approval", async () => { + it("reports a local pairing approval failure receipt", async () => { const scope = ordinaryPairingDeps({ observePairing: vi.fn(() => SCOPE_UPGRADE_PENDING), - runApproval: vi.fn(() => { - throw new Error("secret runtime detail"); - }), + runApproval: vi.fn(() => APPROVE_FAILED), }); await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).resolves.toEqual({ @@ -194,9 +203,11 @@ describe("ordinary OpenClaw pairing settlement", () => { }), runWarmup: vi.fn(() => { events.push("warmup"); + return "executed" as const; }), runApproval: vi.fn(() => { events.push("approval"); + return APPROVED_ONE; }), withSandboxLock: vi.fn(async (_name, operation) => { events.push("sandbox-lock:start"); @@ -257,6 +268,7 @@ describe("ordinary OpenClaw pairing settlement", () => { approvalTargets.push(`${currentTarget.lifecycleGeneration}:${gatewayName}`); reportApprovalStarted(); await approvalPending; + return APPROVED_ONE; }), withSandboxLock: (name, operation) => withMcpLifecycleLock(name, operation, lockOptions), withGatewayLock: (gatewayName, operation) => @@ -363,6 +375,7 @@ describe("ordinary OpenClaw pairing settlement", () => { runWarmup: vi.fn(async () => { reportWarmupStarted(); await warmupPending; + return "executed" as const; }), }); @@ -399,6 +412,7 @@ describe("ordinary OpenClaw pairing settlement", () => { runApproval: vi.fn(async () => { reportApprovalStarted(); await approvalPending; + return APPROVED_ONE; }), }); @@ -474,9 +488,11 @@ describe("ordinary OpenClaw pairing settlement", () => { .mockReturnValue(SETTLED), runWarmup: vi.fn(() => { now += WARMUP_TIMEOUT_MS; + return "executed" as const; }), runApproval: vi.fn(() => { now += CONNECT_AUTO_PAIR_TIMEOUT_MS; + return APPROVED_ONE; }), }); @@ -612,8 +628,8 @@ describe("ordinary OpenClaw pairing settlement", () => { .mockReturnValueOnce(PAIRING_ONLY) .mockReturnValueOnce(SCOPE_UPGRADE_PENDING) .mockReturnValueOnce(SETTLED); - const runSandboxScopeWarmupRun = vi.fn(); - const runSandboxAutoPairApprovalPass = vi.fn(); + const runSandboxScopeWarmupRun = vi.fn(() => "executed" as const); + const runSandboxAutoPairApprovalPass = vi.fn(() => APPROVED_ONE); vi.spyOn(finalizationHandlerRuntime, "loadLaunchReadiness").mockReturnValue({ resolveOrdinaryOpenClawPairingTarget: vi.fn(() => PAIRING_TARGET), } as never); @@ -646,6 +662,7 @@ describe("ordinary OpenClaw pairing settlement", () => { }, gatewayName: "nemoclaw", localDeviceOnly: true, + receipt: true, }); }); diff --git a/src/lib/onboard/machine/finalization-deps.ts b/src/lib/onboard/machine/finalization-deps.ts index 862d84fd783..c3683ef7afe 100644 --- a/src/lib/onboard/machine/finalization-deps.ts +++ b/src/lib/onboard/machine/finalization-deps.ts @@ -10,6 +10,8 @@ import { } from "../../actions/sandbox/launch-readiness/openclaw-pairing-qualification"; import type { OpenClawPairingSettlementTarget } from "../../actions/sandbox/launch-readiness"; import { CONNECT_AUTO_PAIR_TIMEOUT_MS } from "../../actions/sandbox/connect-autopair-budget"; +import type { AutoPairApprovalResult } from "../../actions/sandbox/auto-pair-approval"; +import type { SandboxScopeWarmupResult } from "../../actions/sandbox/auto-pair-warmup"; export { OPENCLAW_ONBOARDING_PAIRING_FINAL_OBSERVATION_TIMEOUT_MS, @@ -75,8 +77,14 @@ interface OrdinaryOpenClawPairingSettlementDeps { version: string, stateDirectory: string, ): OpenClawPairingSettlementObservation; - runWarmup(name: string, gatewayName: string): Promise | void; - runApproval(name: string, gatewayName: string): Promise | void; + runWarmup( + name: string, + gatewayName: string, + ): Promise | SandboxScopeWarmupResult; + runApproval( + name: string, + gatewayName: string, + ): Promise | AutoPairApprovalResult; withSandboxLock: SandboxLifecycleLock; withGatewayLock: GatewayRouteLock; now(): number; @@ -168,7 +176,7 @@ function defaultPairingSettlementDeps(): OrdinaryOpenClawPairingSettlementDeps { .observeOrdinaryOpenClawPairingSettlement(...args), runWarmup: (name, gatewayName) => finalizationHandlerRuntime.loadAutoPairWarmup().runSandboxScopeWarmupRun(name, gatewayName), - runApproval: (name, gatewayName) => { + runApproval: (name, gatewayName) => finalizationHandlerRuntime.loadAutoPairApproval().runSandboxAutoPairApprovalPass(name, { budget: { timeoutMs: CONNECT_AUTO_PAIR_TIMEOUT_MS, @@ -178,8 +186,8 @@ function defaultPairingSettlementDeps(): OrdinaryOpenClawPairingSettlementDeps { }, gatewayName, localDeviceOnly: true, - }); - }, + receipt: true, + }), withSandboxLock: (name, operation, options) => finalizationHandlerRuntime .loadSandboxLifecycleLock() @@ -272,16 +280,16 @@ export async function settleOrdinaryOpenClawPairing( // Running the producer before that identity exists can create no // upgrade and leaves an otherwise healthy fresh onboard stuck at // pairing-only (#10014). - let warmupFailed = false; + let warmupResult: SandboxScopeWarmupResult = "exec-failed"; try { - await deps.runWarmup(name, target.gatewayName); + warmupResult = await deps.runWarmup(name, target.gatewayName); } catch { - warmupFailed = true; + // Keep the fixed failure result; producer output is never exposed. } if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } - if (warmupFailed) { + if (warmupResult !== "executed") { return { kind: "incomplete", reason: "warmup-failed" }; } const scopeUpgradeDeadline = Math.min( @@ -319,19 +327,15 @@ export async function settleOrdinaryOpenClawPairing( return { kind: "incomplete", reason: "scope-upgrade-incomplete" }; } - let approvalFailed = false; + let approvalResult: AutoPairApprovalResult | null = null; try { - await deps.runApproval(name, target.gatewayName); + approvalResult = await deps.runApproval(name, target.gatewayName); } catch { - approvalFailed = true; + // A missing receipt is the fixed failure classification below. } if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } - if (approvalFailed) { - return { kind: "incomplete", reason: "approval-failed" }; - } - const finalObservationDeadline = Math.min( settlementDeadline, deps.now() + OPENCLAW_ONBOARDING_PAIRING_FINAL_OBSERVATION_TIMEOUT_MS, @@ -348,9 +352,13 @@ export async function settleOrdinaryOpenClawPairing( if (final.kind === "target-changed") { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } - return final.kind === "observed" - ? { kind: "settled" } - : { kind: "incomplete", reason: "scope-upgrade-incomplete" }; + if (final.kind === "observed") return { kind: "settled" }; + return { + kind: "incomplete", + reason: approvalResult?.receipt === "approved-one" + ? "scope-upgrade-incomplete" + : "approval-failed", + }; }); } catch (error) { if (gatewayBodyEntered) throw error; From c0d08cd8c490447e31a49f1a1536615a6de6274e Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 21:58:26 +0700 Subject: [PATCH 08/40] test(e2e): use valid vLLM storage GPU UUID Signed-off-by: San Dang --- test/platform/images/vllm-docker-storage.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/platform/images/vllm-docker-storage.test.ts b/test/platform/images/vllm-docker-storage.test.ts index fc60c7f1db1..c39d4e233a8 100644 --- a/test/platform/images/vllm-docker-storage.test.ts +++ b/test/platform/images/vllm-docker-storage.test.ts @@ -243,7 +243,7 @@ realDockerTest( case "$#:$1:$2" in 2:--query-gpu=compute_cap:--format=csv,noheader,nounits) printf '9.0\\n' ;; 2:--query-gpu=index,uuid,memory.total,memory.free:--format=csv,noheader,nounits) - printf '0, GPU-storage-proof, 131072, 131072\\n' + printf '0, GPU-00000000-0000-0000-0000-000000000000, 131072, 131072\\n' ;; *) exit 64 ;; esac From 51d093334d4cb76930dd36f7bbea056563458117 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 23:04:51 +0700 Subject: [PATCH 09/40] fix(e2e): use private managed-image catalog writer Signed-off-by: San Dang --- .../support/pr-managed-image-source.test.ts | 20 +++++++++++++++++++ tools/e2e/pr-managed-image-source.mts | 7 ++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/test/e2e/support/pr-managed-image-source.test.ts b/test/e2e/support/pr-managed-image-source.test.ts index 543d1698168..19071397eac 100644 --- a/test/e2e/support/pr-managed-image-source.test.ts +++ b/test/e2e/support/pr-managed-image-source.test.ts @@ -151,6 +151,26 @@ describe("managed-image activation catalog assembly", () => { } }); + it("rejects a symbolic-link catalog output", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-catalog-link-test-")); + try { + const contractPaths = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => { + const contractPath = path.join(directory, `${agent}.json`); + fs.writeFileSync(contractPath, JSON.stringify(contract(agent, index))); + return contractPath; + }); + const targetPath = path.join(directory, "target.json"); + const outputPath = path.join(directory, "catalog.json"); + fs.writeFileSync(targetPath, "unchanged\n"); + fs.symlinkSync(targetPath, outputPath); + + expect(() => writeManagedImageCatalog(contractPaths, CANDIDATE_SHA, outputPath)).toThrow(); + expect(fs.readFileSync(targetPath, "utf8")).toBe("unchanged\n"); + } finally { + fs.rmSync(directory, { force: true, recursive: true }); + } + }); + it.each([ [ "candidate revision", diff --git a/tools/e2e/pr-managed-image-source.mts b/tools/e2e/pr-managed-image-source.mts index 5bc83c9c962..8d2a503b96a 100644 --- a/tools/e2e/pr-managed-image-source.mts +++ b/tools/e2e/pr-managed-image-source.mts @@ -15,6 +15,7 @@ import { githubRequest, parseBaseImagePushPaths, } from "./base-image-publication.mts"; +import { createPrivateRegularFile } from "./private-file.mts"; const REPOSITORY = "NVIDIA/NemoClaw"; const BASE_IMAGE_WORKFLOW_PATH = ".github/workflows/base-image.yaml"; @@ -91,11 +92,7 @@ export function writeManagedImageCatalog( ); const catalog = assembleManagedImageCatalog(contracts, candidateSha); fs.mkdirSync(path.dirname(path.resolve(outputPath)), { mode: 0o700, recursive: true }); - fs.writeFileSync(outputPath, `${JSON.stringify(catalog)}\n`, { - encoding: "utf8", - flag: "wx", - mode: 0o600, - }); + createPrivateRegularFile(outputPath, `${JSON.stringify(catalog)}\n`); } async function readChangedFiles( From b8c4387c465ea8eaf3139fc4ba5ca5d07dda92f6 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 23:20:04 +0700 Subject: [PATCH 10/40] test(e2e): remove duplicate managed-image cases Signed-off-by: San Dang --- test/e2e/support/workload-source-env.test.ts | 21 +++++++------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/test/e2e/support/workload-source-env.test.ts b/test/e2e/support/workload-source-env.test.ts index 0c39a67d9e2..49525067a84 100644 --- a/test/e2e/support/workload-source-env.test.ts +++ b/test/e2e/support/workload-source-env.test.ts @@ -43,18 +43,11 @@ describe("live E2E workload source environment", () => { }); }); - it.each(["managed-image-protected-runtime", "podman-native-cpu", "mxc-runtime-proof"])( - "honors the provider-neutral managed-image source for %s", - (targetId) => { - expect( - resolveLiveE2eWorkloadSourceEnv({ - E2E_TARGET_ID: targetId, - E2E_WORKLOAD_SOURCE: "managed-image", - }), - ).toEqual({ - E2E_TARGET_ID: targetId, - E2E_WORKLOAD_SOURCE: "managed-image", - }); - }, - ); + it("honors the managed-image source", () => { + const input = { + E2E_TARGET_ID: "managed-image-protected-runtime", + E2E_WORKLOAD_SOURCE: "managed-image", + }; + expect(resolveLiveE2eWorkloadSourceEnv(input)).toEqual(input); + }); }); From a1b9a0ab94fb19969880440d3a127bb0d77409b6 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 23:34:42 +0700 Subject: [PATCH 11/40] test(e2e): cover renamed managed-image inputs Signed-off-by: San Dang --- test/e2e/support/pr-managed-image-source.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/e2e/support/pr-managed-image-source.test.ts b/test/e2e/support/pr-managed-image-source.test.ts index 19071397eac..c73d32951fc 100644 --- a/test/e2e/support/pr-managed-image-source.test.ts +++ b/test/e2e/support/pr-managed-image-source.test.ts @@ -93,6 +93,17 @@ describe("PR managed-image source selection", () => { ).resolves.toBe("local-dockerfile"); }); + it("selects a local Dockerfile when a reviewed image input is renamed", async () => { + await expect( + resolvePrManagedImageSource( + selectorInput(), + requestFor([ + { filename: "docs/renamed-base-image.txt", previous_filename: "Dockerfile.base" }, + ]), + ), + ).resolves.toBe("local-dockerfile"); + }); + it("selects a trusted managed image when reviewed image inputs are unchanged", async () => { await expect( resolvePrManagedImageSource(selectorInput(), requestFor([{ filename: "docs/guide.mdx" }])), From 88ab3711c6ef1bf336f905532b4a3b1f94a497c8 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 25 Aug 2026 23:50:13 +0700 Subject: [PATCH 12/40] refactor(e2e): remove unrelated pairing changes Signed-off-by: San Dang --- src/lib/actions/sandbox/auto-pair-warmup.ts | 37 +++--- .../onboard/machine/finalization-deps.test.ts | 75 ++---------- src/lib/onboard/machine/finalization-deps.ts | 115 ++++++------------ 3 files changed, 63 insertions(+), 164 deletions(-) diff --git a/src/lib/actions/sandbox/auto-pair-warmup.ts b/src/lib/actions/sandbox/auto-pair-warmup.ts index 52530f634c1..52238be69f4 100644 --- a/src/lib/actions/sandbox/auto-pair-warmup.ts +++ b/src/lib/actions/sandbox/auto-pair-warmup.ts @@ -22,10 +22,10 @@ * * Contract: best-effort, bounded, idempotent. The direct call normally returns * the pending-scope failure after it publishes the request, and its output is - * discarded. The leaf converts host execution failures to one fixed result, - * and onboarding separately observes the canonical pairing state before it - * reports success. On re-onboard where `operator.write` is already paired the - * call succeeds and the approval pass is a no-op. + * discarded. The leaf swallows execution failures, and onboarding separately + * observes the canonical pairing state before it reports success. On re-onboard + * where `operator.write` is already paired the call succeeds and the approval + * pass is a no-op. * * Workaround boundary (NemoClaw#4462): OpenClaw owns device-pairing semantics * and exposes only `devices list/get/approve` — there is no way to pre-grant a @@ -43,7 +43,6 @@ import { WARMUP_SESSION_ID_PREFIX } from "./warmup-session"; // wedged sandbox from blocking onboard or restore. export const WARMUP_TIMEOUT_MS = 30_000; export const WARMUP_PROBE_TIMEOUT_S = 5; -export type SandboxScopeWarmupResult = "executed" | "exec-failed"; // Best-effort in-sandbox request producer. Always exits 0. Use the stored CLI // device credential for the direct `sessions.create` call. Shared gateway @@ -114,7 +113,7 @@ function runSandboxWarmupScript( sandboxName: string, gatewayName: string | undefined, script: string, -): SandboxScopeWarmupResult { +): void { // Lazy require: `adapters/openshell/resolve` pulls in `runner`, whose // load-time `require("./platform")` cannot be resolved by the Vitest TS // loader. Importing it here keeps this module unit-testable in-process. @@ -126,8 +125,8 @@ function runSandboxWarmupScript( require("../../adapters/openshell/resolve") as typeof import("../../adapters/openshell/resolve"); try { const openshellBinary = resolveOpenshell(); - if (!openshellBinary) return "exec-failed"; - const result = spawnSync( + if (!openshellBinary) return; + spawnSync( openshellBinary, sandboxWarmupExecArgs(sandboxName, gatewayName, script), { @@ -137,31 +136,25 @@ function runSandboxWarmupScript( timeout: WARMUP_TIMEOUT_MS, }, ); - return !result.error && result.status === 0 ? "executed" : "exec-failed"; } catch { - return "exec-failed"; + /* defense-in-depth — never throw from a warm-up path */ } } /** * Run the bounded, throwaway scope-upgrade warm-up inside the named sandbox via - * `openshell sandbox exec`. Host execution failures return one fixed result; - * command output remains discarded. The finalization settlement gate decides - * readiness from a later canonical observation. + * `openshell sandbox exec`. All failure modes (timeout, sandbox-exec errors, + * missing openclaw, gateway unreachable) are swallowed. The finalization + * settlement gate decides readiness from a later canonical observation. */ -export function runSandboxScopeWarmupRun( - sandboxName: string, - gatewayName: string, -): SandboxScopeWarmupResult { - return runSandboxWarmupScript(sandboxName, gatewayName, WARMUP_SCRIPT); +export function runSandboxScopeWarmupRun(sandboxName: string, gatewayName: string): void { + runSandboxWarmupScript(sandboxName, gatewayName, WARMUP_SCRIPT); } /** * Attempt to publish a restored clone's write-scope request without an * embedded fallback. Failures remain non-blocking. */ -export function runRestoredSandboxScopeWarmupRun( - sandboxName: string, -): SandboxScopeWarmupResult { - return runSandboxWarmupScript(sandboxName, undefined, RESTORED_CLONE_WARMUP_SCRIPT); +export function runRestoredSandboxScopeWarmupRun(sandboxName: string): void { + runSandboxWarmupScript(sandboxName, undefined, RESTORED_CLONE_WARMUP_SCRIPT); } diff --git a/src/lib/onboard/machine/finalization-deps.test.ts b/src/lib/onboard/machine/finalization-deps.test.ts index cf09e19cf9d..9cadcb507ea 100644 --- a/src/lib/onboard/machine/finalization-deps.test.ts +++ b/src/lib/onboard/machine/finalization-deps.test.ts @@ -49,15 +49,6 @@ const SETTLED: OpenClawPairingSettlementObservation = { deviceIdentitySha256: PAIRING_ONLY.deviceIdentitySha256, }; -const APPROVED_ONE = { - attempted: true, - reported: false, - approved: 0, - receipt: "approved-one", -} as const; - -const APPROVE_FAILED = { ...APPROVED_ONE, receipt: "approve-failed" } as const; - function ordinaryPairingDeps( overrides: Partial[1]> = {}, ) { @@ -68,11 +59,9 @@ function ordinaryPairingDeps( observePairing: vi.fn(() => SETTLED), runWarmup: vi.fn(() => { calls.push("warmup"); - return "executed" as const; }), runApproval: vi.fn(() => { calls.push("approval"); - return APPROVED_ONE; }), withSandboxLock: vi.fn(async (_name, operation) => operation()), withGatewayLock: vi.fn(async (_gatewayName, operation) => operation()), @@ -124,7 +113,7 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); - it("waits for canonical pairing before running the one request producer (#10014)", async () => { + it("runs the canonical request probe before waiting for fresh pairing (#10014)", async () => { const observePairing = vi .fn(() => SCOPE_UPGRADE_PENDING) .mockImplementationOnce(() => { @@ -135,12 +124,10 @@ describe("ordinary OpenClaw pairing settlement", () => { observePairing, runWarmup: vi.fn(() => { scope.calls.push("warmup"); - return "executed" as const; }), runApproval: vi.fn(() => { scope.calls.push("approval"); vi.mocked(scope.deps.observePairing).mockReturnValue(SETTLED); - return APPROVED_ONE; }), }); @@ -148,42 +135,11 @@ describe("ordinary OpenClaw pairing settlement", () => { kind: "settled", }); - expect(scope.calls).toEqual(["warmup", "approval"]); + expect(scope.calls).toEqual(["warmup", "sleep", "approval"]); expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); - it("reports a warm-up execution failure receipt without attempting approval", async () => { - const scope = ordinaryPairingDeps({ - observePairing: vi.fn(() => PAIRING_ONLY), - runWarmup: vi.fn(() => "exec-failed" as const), - }); - - await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).resolves.toEqual({ - kind: "incomplete", - reason: "warmup-failed", - }); - expect(scope.deps.runApproval).not.toHaveBeenCalled(); - expect(ordinaryOpenClawPairingIncompleteMessage("alpha", "warmup-failed")).toBe( - "OpenClaw onboarding for 'alpha' is incomplete because its scope-upgrade warm-up request failed. Verify the OpenClaw gateway is reachable, then resume or rerun onboarding.", - ); - }); - - it("reports a local pairing approval failure receipt", async () => { - const scope = ordinaryPairingDeps({ - observePairing: vi.fn(() => SCOPE_UPGRADE_PENDING), - runApproval: vi.fn(() => APPROVE_FAILED), - }); - - await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).resolves.toEqual({ - kind: "incomplete", - reason: "approval-failed", - }); - expect(ordinaryOpenClawPairingIncompleteMessage("alpha", "approval-failed")).toBe( - "OpenClaw onboarding for 'alpha' is incomplete because its local pairing approval failed. Verify the pending local pairing request can be approved, then resume or rerun onboarding.", - ); - }); - it("holds lifecycle then gateway-route ownership across the full settlement (#9844)", async () => { const events: string[] = []; const scope = ordinaryPairingDeps({ @@ -203,11 +159,9 @@ describe("ordinary OpenClaw pairing settlement", () => { }), runWarmup: vi.fn(() => { events.push("warmup"); - return "executed" as const; }), runApproval: vi.fn(() => { events.push("approval"); - return APPROVED_ONE; }), withSandboxLock: vi.fn(async (_name, operation) => { events.push("sandbox-lock:start"); @@ -268,7 +222,6 @@ describe("ordinary OpenClaw pairing settlement", () => { approvalTargets.push(`${currentTarget.lifecycleGeneration}:${gatewayName}`); reportApprovalStarted(); await approvalPending; - return APPROVED_ONE; }), withSandboxLock: (name, operation) => withMcpLifecycleLock(name, operation, lockOptions), withGatewayLock: (gatewayName, operation) => @@ -375,7 +328,6 @@ describe("ordinary OpenClaw pairing settlement", () => { runWarmup: vi.fn(async () => { reportWarmupStarted(); await warmupPending; - return "executed" as const; }), }); @@ -412,7 +364,6 @@ describe("ordinary OpenClaw pairing settlement", () => { runApproval: vi.fn(async () => { reportApprovalStarted(); await approvalPending; - return APPROVED_ONE; }), }); @@ -455,7 +406,9 @@ describe("ordinary OpenClaw pairing settlement", () => { throw new Error("not published"); }; const scope = ordinaryPairingDeps({ - observePairing: vi.fn(() => (attempts++ < 10 ? unavailable() : SCOPE_UPGRADE_PENDING)), + observePairing: vi.fn(() => + attempts++ < 10 ? unavailable() : SCOPE_UPGRADE_PENDING, + ), }); await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).resolves.toEqual({ @@ -463,7 +416,7 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "scope-upgrade-incomplete", }); expect(scope.deps.sleep).toHaveBeenCalledTimes(39); - expect(scope.deps.runWarmup).not.toHaveBeenCalled(); + expect(scope.deps.runWarmup).toHaveBeenCalledOnce(); expect(scope.deps.runApproval).toHaveBeenCalledOnce(); }); @@ -483,16 +436,13 @@ describe("ordinary OpenClaw pairing settlement", () => { .mockImplementationOnce(() => { throw new Error("not pending"); }) - .mockReturnValueOnce(PAIRING_ONLY) .mockReturnValueOnce(SCOPE_UPGRADE_PENDING) .mockReturnValue(SETTLED), runWarmup: vi.fn(() => { now += WARMUP_TIMEOUT_MS; - return "executed" as const; }), runApproval: vi.fn(() => { now += CONNECT_AUTO_PAIR_TIMEOUT_MS; - return APPROVED_ONE; }), }); @@ -502,7 +452,7 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); - expect(scope.deps.observePairing).toHaveBeenCalledTimes(5); + expect(scope.deps.observePairing).toHaveBeenCalledTimes(4); expect(now).toBe( OPENCLAW_PAIRING_OBSERVATION_TIMEOUT_MS + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS - @@ -539,11 +489,11 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "pairing-unavailable", }); expect(scope.deps.sleep).not.toHaveBeenCalled(); - expect(scope.deps.runWarmup).not.toHaveBeenCalled(); + expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).not.toHaveBeenCalled(); }); - it("does not run a request producer without a canonical CLI pairing (#9844)", async () => { + it("performs one request-producer write when a canonical CLI pairing never appears (#9844)", async () => { const scope = ordinaryPairingDeps({ observePairing: vi.fn(() => { throw new Error("not published"); @@ -555,7 +505,7 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "pairing-unavailable", }); - expect(scope.deps.runWarmup).not.toHaveBeenCalled(); + expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).not.toHaveBeenCalled(); }); @@ -628,8 +578,8 @@ describe("ordinary OpenClaw pairing settlement", () => { .mockReturnValueOnce(PAIRING_ONLY) .mockReturnValueOnce(SCOPE_UPGRADE_PENDING) .mockReturnValueOnce(SETTLED); - const runSandboxScopeWarmupRun = vi.fn(() => "executed" as const); - const runSandboxAutoPairApprovalPass = vi.fn(() => APPROVED_ONE); + const runSandboxScopeWarmupRun = vi.fn(); + const runSandboxAutoPairApprovalPass = vi.fn(); vi.spyOn(finalizationHandlerRuntime, "loadLaunchReadiness").mockReturnValue({ resolveOrdinaryOpenClawPairingTarget: vi.fn(() => PAIRING_TARGET), } as never); @@ -662,7 +612,6 @@ describe("ordinary OpenClaw pairing settlement", () => { }, gatewayName: "nemoclaw", localDeviceOnly: true, - receipt: true, }); }); diff --git a/src/lib/onboard/machine/finalization-deps.ts b/src/lib/onboard/machine/finalization-deps.ts index c3683ef7afe..55d323f53ea 100644 --- a/src/lib/onboard/machine/finalization-deps.ts +++ b/src/lib/onboard/machine/finalization-deps.ts @@ -10,8 +10,6 @@ import { } from "../../actions/sandbox/launch-readiness/openclaw-pairing-qualification"; import type { OpenClawPairingSettlementTarget } from "../../actions/sandbox/launch-readiness"; import { CONNECT_AUTO_PAIR_TIMEOUT_MS } from "../../actions/sandbox/connect-autopair-budget"; -import type { AutoPairApprovalResult } from "../../actions/sandbox/auto-pair-approval"; -import type { SandboxScopeWarmupResult } from "../../actions/sandbox/auto-pair-warmup"; export { OPENCLAW_ONBOARDING_PAIRING_FINAL_OBSERVATION_TIMEOUT_MS, @@ -38,8 +36,6 @@ export type OrdinaryOpenClawPairingSettlementResult = | "runtime-identity-invalid" | "pairing-lock-unavailable" | "pairing-unavailable" - | "warmup-failed" - | "approval-failed" | "scope-upgrade-incomplete"; }; @@ -55,20 +51,10 @@ const ORDINARY_OPENCLAW_PAIRING_INCOMPLETE_CAUSES: Record< "runtime-identity-invalid": "its recorded OpenClaw runtime identity changed or is invalid", "pairing-lock-unavailable": "NemoClaw could not acquire the pairing settlement locks", "pairing-unavailable": "its canonical CLI device pairing did not appear", - "warmup-failed": "its scope-upgrade warm-up request failed", - "approval-failed": "its local pairing approval failed", "scope-upgrade-incomplete": "its canonical CLI device did not receive the required baseline scopes", }; -const ORDINARY_OPENCLAW_PAIRING_RECOVERY: Partial< - Record -> = { - "warmup-failed": "Verify the OpenClaw gateway is reachable, then resume or rerun onboarding.", - "approval-failed": - "Verify the pending local pairing request can be approved, then resume or rerun onboarding.", -}; - interface OrdinaryOpenClawPairingSettlementDeps { getTarget(name: string): OpenClawPairingSettlementTarget | null; observePairing( @@ -77,14 +63,8 @@ interface OrdinaryOpenClawPairingSettlementDeps { version: string, stateDirectory: string, ): OpenClawPairingSettlementObservation; - runWarmup( - name: string, - gatewayName: string, - ): Promise | SandboxScopeWarmupResult; - runApproval( - name: string, - gatewayName: string, - ): Promise | AutoPairApprovalResult; + runWarmup(name: string, gatewayName: string): Promise | void; + runApproval(name: string, gatewayName: string): Promise | void; withSandboxLock: SandboxLifecycleLock; withGatewayLock: GatewayRouteLock; now(): number; @@ -175,8 +155,10 @@ function defaultPairingSettlementDeps(): OrdinaryOpenClawPairingSettlementDeps { .loadPairingQualification() .observeOrdinaryOpenClawPairingSettlement(...args), runWarmup: (name, gatewayName) => - finalizationHandlerRuntime.loadAutoPairWarmup().runSandboxScopeWarmupRun(name, gatewayName), - runApproval: (name, gatewayName) => + finalizationHandlerRuntime + .loadAutoPairWarmup() + .runSandboxScopeWarmupRun(name, gatewayName), + runApproval: (name, gatewayName) => { finalizationHandlerRuntime.loadAutoPairApproval().runSandboxAutoPairApprovalPass(name, { budget: { timeoutMs: CONNECT_AUTO_PAIR_TIMEOUT_MS, @@ -186,8 +168,8 @@ function defaultPairingSettlementDeps(): OrdinaryOpenClawPairingSettlementDeps { }, gatewayName, localDeviceOnly: true, - receipt: true, - }), + }); + }, withSandboxLock: (name, operation, options) => finalizationHandlerRuntime .loadSandboxLifecycleLock() @@ -240,7 +222,7 @@ export async function settleOrdinaryOpenClawPairing( ); sawCanonicalPairing = true; } catch { - // Pairing may not have appeared yet; the bounded observer handles that path. + // Pairing may not have appeared yet; the producer handles that path. } if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; @@ -250,56 +232,30 @@ export async function settleOrdinaryOpenClawPairing( } if (initial?.state === "settled") return { kind: "settled" }; - const pairingAppearanceDeadline = Math.min( - settlementDeadline, - deps.now() + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS, - ); - let baseline: PairingWaitResult = initial - ? { kind: "observed", value: initial } - : await waitForPairingObservation( - name, - target, - pairingAppearanceDeadline, - (value) => { - sawCanonicalPairing = true; - return true; - }, - deps, - ); - if (baseline.kind === "target-changed") { - return { kind: "incomplete", reason: "runtime-identity-invalid" }; - } - if (baseline.kind === "timeout") { - return { kind: "incomplete", reason: "pairing-unavailable" }; - } - if (baseline.value.state === "settled") return { kind: "settled" }; - - if (baseline.value.state === "pairing-only") { - // Wait for the startup watcher to publish the canonical CLI - // pairing before issuing the one bounded write-scope producer. - // Running the producer before that identity exists can create no - // upgrade and leaves an otherwise healthy fresh onboard stuck at - // pairing-only (#10014). - let warmupResult: SandboxScopeWarmupResult = "exec-failed"; + let baseline: PairingWaitResult; + if (initial?.state === "scope-upgrade-pending") { + baseline = { kind: "observed", value: initial }; + } else { + // A valid non-interactive path can reach finalization before the + // startup watcher publishes its first CLI request. Run the bounded + // direct producer once, then require canonical evidence that its + // exact write upgrade is pending before the approval pass (#10014). try { - warmupResult = await deps.runWarmup(name, target.gatewayName); + await deps.runWarmup(name, target.gatewayName); } catch { - // Keep the fixed failure result; producer output is never exposed. + // The bounded observation below remains fail closed. } if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } - if (warmupResult !== "executed") { - return { kind: "incomplete", reason: "warmup-failed" }; - } - const scopeUpgradeDeadline = Math.min( + const pairingAppearanceDeadline = Math.min( settlementDeadline, deps.now() + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS, ); baseline = await waitForPairingObservation( name, target, - scopeUpgradeDeadline, + pairingAppearanceDeadline, (value) => { sawCanonicalPairing = true; return value.state !== "pairing-only"; @@ -316,7 +272,10 @@ export async function settleOrdinaryOpenClawPairing( reason: sawCanonicalPairing ? "scope-upgrade-incomplete" : "pairing-unavailable", }; } - if (initial && baseline.value.deviceIdentitySha256 !== initial.deviceIdentitySha256) { + if ( + initial && + baseline.value.deviceIdentitySha256 !== initial.deviceIdentitySha256 + ) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } if (baseline.value.state === "settled") return { kind: "settled" }; @@ -327,15 +286,19 @@ export async function settleOrdinaryOpenClawPairing( return { kind: "incomplete", reason: "scope-upgrade-incomplete" }; } - let approvalResult: AutoPairApprovalResult | null = null; + let approvalFailed = false; try { - approvalResult = await deps.runApproval(name, target.gatewayName); + await deps.runApproval(name, target.gatewayName); } catch { - // A missing receipt is the fixed failure classification below. + approvalFailed = true; } if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } + if (approvalFailed) { + return { kind: "incomplete", reason: "scope-upgrade-incomplete" }; + } + const finalObservationDeadline = Math.min( settlementDeadline, deps.now() + OPENCLAW_ONBOARDING_PAIRING_FINAL_OBSERVATION_TIMEOUT_MS, @@ -352,13 +315,9 @@ export async function settleOrdinaryOpenClawPairing( if (final.kind === "target-changed") { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } - if (final.kind === "observed") return { kind: "settled" }; - return { - kind: "incomplete", - reason: approvalResult?.receipt === "approved-one" - ? "scope-upgrade-incomplete" - : "approval-failed", - }; + return final.kind === "observed" + ? { kind: "settled" } + : { kind: "incomplete", reason: "scope-upgrade-incomplete" }; }); } catch (error) { if (gatewayBodyEntered) throw error; @@ -376,9 +335,7 @@ export function ordinaryOpenClawPairingIncompleteMessage( reason: OrdinaryOpenClawPairingIncompleteReason, ): string { const cause = ORDINARY_OPENCLAW_PAIRING_INCOMPLETE_CAUSES[reason]; - const recovery = - ORDINARY_OPENCLAW_PAIRING_RECOVERY[reason] ?? "Resume or rerun onboarding."; - return `OpenClaw onboarding for '${name}' is incomplete because ${cause}. ${recovery}`; + return `OpenClaw onboarding for '${name}' is incomplete because ${cause}. Resume or rerun onboarding.`; } export const finalizationHandlerDeps = { From 4d2df936915ae500d53ade675a762f04ab6d8cbf Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 00:09:10 +0700 Subject: [PATCH 13/40] test(e2e): cover PR revision guards Signed-off-by: San Dang --- .../support/pr-managed-image-source.test.ts | 39 +++++++++++++++---- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/test/e2e/support/pr-managed-image-source.test.ts b/test/e2e/support/pr-managed-image-source.test.ts index c73d32951fc..4517cdd1d06 100644 --- a/test/e2e/support/pr-managed-image-source.test.ts +++ b/test/e2e/support/pr-managed-image-source.test.ts @@ -110,14 +110,39 @@ describe("PR managed-image source selection", () => { ).resolves.toBe("managed-image"); }); - it("rejects PR identity drift before selecting a source", async () => { - const request = requestFor([{ filename: "Dockerfile" }], { - head: { sha: CANDIDATE_SHA, repo: { full_name: "attacker/fork" } }, - }); - - await expect(resolvePrManagedImageSource(selectorInput(), request)).rejects.toThrow( + it.each([ + ["a closed pull request", { state: "closed" }, "pull request state must be open"], + [ + "base commit drift", + { base: { sha: "c".repeat(40), repo: { full_name: "NVIDIA/NemoClaw" } } }, + `pull request base commit must be ${BASE_SHA}`, + ], + [ + "candidate commit drift", + { + head: { + sha: "c".repeat(40), + repo: { full_name: CANDIDATE_REPOSITORY }, + }, + }, + `pull request source commit must be ${CANDIDATE_SHA}`, + ], + [ + "source repository drift", + { head: { sha: CANDIDATE_SHA, repo: { full_name: "attacker/fork" } } }, "pull request source repository must be NVIDIA/NemoClaw", - ); + ], + ])("rejects %s before reading changed files", async (_label, pullOverrides, message) => { + const metadataPath = `/repos/NVIDIA/NemoClaw/pulls/${PR_NUMBER}`; + const requests: string[] = []; + const responses = new Map([[metadataPath, pull(1, pullOverrides)]]); + const request = async (requestPath: string): Promise => { + requests.push(requestPath); + return responses.get(requestPath) ?? unexpectedRequest(requestPath); + }; + + await expect(resolvePrManagedImageSource(selectorInput(), request)).rejects.toThrow(message); + expect(requests).toEqual([metadataPath]); }); it("records PR source reads in the retry inventory", () => { From d73cd20f60bdc7e95c3d2eb602cd7f33edc408d6 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 00:27:51 +0700 Subject: [PATCH 14/40] fix(e2e): qualify local images on arm64 Signed-off-by: San Dang --- .github/workflows/e2e.yaml | 116 +++++++++++++----- .../checks/build-protected-managed-images.sh | 7 +- ...d-image-protected-runtime-workflow.test.ts | 22 ++++ ...otected-managed-image-build-script.test.ts | 21 +++- ...aged-image-multiarch-workflow-boundary.mts | 25 +++- 5 files changed, 152 insertions(+), 39 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 25a04988d85..700fbdd46c8 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -3980,7 +3980,7 @@ jobs: managed-image-multiarch-startup: name: Protected managed-image startup (${{ matrix.platform }}) needs: [base-image-publication, generate-matrix] - if: ${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-multiarch-startup') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime')) }} + if: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-multiarch-startup') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime')) }} runs-on: ${{ matrix.runner }} timeout-minutes: 210 permissions: @@ -4005,6 +4005,7 @@ jobs: E2E_TARGET_ID: "managed-image-multiarch-startup" E2E_AGENT_RUNTIME: "openclaw + hermes + langchain-deepagents-code" E2E_OBSERVABLE_OUTCOME: "Exact managed images start directly on the native architecture" + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} RELEASE_E2E_ACTIVATION_PATH: ci/protected-managed-image-multiarch-activation-v1.json NEMOCLAW_E2E_EXPECTED_SHA: ${{ inputs.checkout_sha }} NEMOCLAW_PROTECTED_MANAGED_IMAGE_HEAD_SHA: ${{ inputs.checkout_sha || github.sha }} @@ -4126,6 +4127,7 @@ jobs: - id: hermes-base name: Resolve reviewed Hermes platform base image + if: ${{ needs.generate-matrix.outputs.workload_source == 'managed-image' }} uses: ./.trusted-hermes-resolver/.github/actions/resolve-reviewed-hermes-platform with: dockerfile-path: agents/hermes/Dockerfile @@ -4149,11 +4151,41 @@ jobs: exit 1 } + - name: Start isolated protected managed-image registry + shell: bash + run: | + set -euo pipefail + if docker container inspect "$NEMOCLAW_PROTECTED_REGISTRY_NAME" >/dev/null 2>&1; then + echo "::error::Protected registry name already exists" >&2 + exit 1 + fi + if curl --fail --silent --show-error http://127.0.0.1:5000/v2/ >/dev/null 2>&1; then + echo "::error::Refusing to reuse an existing localhost:5000 registry" >&2 + exit 1 + fi + docker run --detach \ + --name "$NEMOCLAW_PROTECTED_REGISTRY_NAME" \ + --label "io.nvidia.nemoclaw.e2e-owner=${NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT}" \ + --label "io.nvidia.nemoclaw.e2e-platform=${NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM}" \ + --publish 127.0.0.1:5000:5000 \ + docker.io/library/registry@sha256:a3d8aaa63ed8681a604f1dea0aa03f100d5895b6a58ace528858a7b332415373 + for _ in $(seq 1 30); do + if curl --fail --silent --show-error http://127.0.0.1:5000/v2/ >/dev/null; then + exit 0 + fi + sleep 1 + done + docker logs "$NEMOCLAW_PROTECTED_REGISTRY_NAME" >&2 + exit 1 + - id: bases name: Resolve exact platform base images env: + CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} DCODE_BASE_CONTRACT: ${{ needs.base-image-publication.outputs.dcode_base_contract }} + HERMES_BASE_DIGEST: ${{ steps.hermes-base.outputs.digest }} PLATFORM: ${{ matrix.platform }} + WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} shell: bash run: | set -euo pipefail @@ -4161,6 +4193,52 @@ jobs: work_dir="$(mktemp -d "${RUNNER_TEMP}/nemoclaw-protected-bases.XXXXXX")" trap 'rm -rf -- "$work_dir"' EXIT + build_local_base() { + local output_name="$1" + local dockerfile="$2" + local repository="$3" + local metadata="$work_dir/${output_name}-build.json" + scripts/check-production-build-args.sh -f "$dockerfile" + docker buildx build \ + --file "$dockerfile" \ + --platform "$PLATFORM" \ + --push \ + --provenance=false \ + --sbom=false \ + --metadata-file "$metadata" \ + --tag "${repository}:${CHECKOUT_SHA}" \ + --label "org.opencontainers.image.revision=${CHECKOUT_SHA}" \ + . + local digest + digest="$(jq -er '."containerimage.digest"' "$metadata")" + [[ "$digest" =~ ^sha256:[a-f0-9]{64}$ ]] || { + echo "::error::${output_name} local base build returned an invalid digest" >&2 + exit 1 + } + local reference="${repository}@${digest}" + docker buildx imagetools inspect "$reference" --raw > "$work_dir/${output_name}-local.raw" + [[ "sha256:$(sha256sum "$work_dir/${output_name}-local.raw" | awk '{print $1}')" == "$digest" ]] || { + echo "::error::${output_name} local base bytes do not match the build digest" >&2 + exit 1 + } + printf '%s=%s\n' "$output_name" "$reference" >> "$GITHUB_OUTPUT" + } + + case "$WORKLOAD_SOURCE" in + local-dockerfile) + base_registry="localhost:5000/nemoclaw-managed-protected-base" + build_local_base openclaw Dockerfile.base "${base_registry}/sandbox-base" + build_local_base hermes agents/hermes/Dockerfile.base "${base_registry}/hermes-sandbox-base" + build_local_base dcode agents/langchain-deepagents-code/Dockerfile.base "${base_registry}/langchain-deepagents-code-sandbox-base" + exit 0 + ;; + managed-image) ;; + *) + echo "::error::Protected managed-image workload source is invalid" >&2 + exit 1 + ;; + esac + resolve_base() { local output_name="$1" local alias="$2" @@ -4198,6 +4276,13 @@ jobs: resolve_base openclaw \ ghcr.io/nvidia/nemoclaw/sandbox-base:latest \ ghcr.io/nvidia/nemoclaw/sandbox-base + [[ "$HERMES_BASE_DIGEST" =~ ^sha256:[a-f0-9]{64}$ ]] || { + echo "::error::Hermes reviewed base resolver returned an invalid digest" >&2 + exit 1 + } + printf 'hermes=%s\n' \ + "ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${HERMES_BASE_DIGEST}" \ + >> "$GITHUB_OUTPUT" dcode_reference="$( jq -er --arg platform "$PLATFORM" \ '.platformReferences[$platform]' <<< "$DCODE_BASE_CONTRACT" @@ -4214,37 +4299,10 @@ jobs: } printf 'dcode=%s\n' "$dcode_reference" >> "$GITHUB_OUTPUT" - - name: Start isolated protected managed-image registry - shell: bash - run: | - set -euo pipefail - if docker container inspect "$NEMOCLAW_PROTECTED_REGISTRY_NAME" >/dev/null 2>&1; then - echo "::error::Protected registry name already exists" >&2 - exit 1 - fi - if curl --fail --silent --show-error http://127.0.0.1:5000/v2/ >/dev/null 2>&1; then - echo "::error::Refusing to reuse an existing localhost:5000 registry" >&2 - exit 1 - fi - docker run --detach \ - --name "$NEMOCLAW_PROTECTED_REGISTRY_NAME" \ - --label "io.nvidia.nemoclaw.e2e-owner=${NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT}" \ - --label "io.nvidia.nemoclaw.e2e-platform=${NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM}" \ - --publish 127.0.0.1:5000:5000 \ - docker.io/library/registry@sha256:a3d8aaa63ed8681a604f1dea0aa03f100d5895b6a58ace528858a7b332415373 - for _ in $(seq 1 30); do - if curl --fail --silent --show-error http://127.0.0.1:5000/v2/ >/dev/null; then - exit 0 - fi - sleep 1 - done - docker logs "$NEMOCLAW_PROTECTED_REGISTRY_NAME" >&2 - exit 1 - - name: Build exact all-agent protected managed images env: BASE_DCODE: ${{ steps.bases.outputs.dcode }} - BASE_HERMES: ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.hermes-base.outputs.digest }} + BASE_HERMES: ${{ steps.bases.outputs.hermes }} BASE_OPENCLAW: ${{ steps.bases.outputs.openclaw }} CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} shell: bash diff --git a/scripts/checks/build-protected-managed-images.sh b/scripts/checks/build-protected-managed-images.sh index d7cde196dac..c6ffb919794 100755 --- a/scripts/checks/build-protected-managed-images.sh +++ b/scripts/checks/build-protected-managed-images.sh @@ -88,9 +88,10 @@ esac target_arch="${platform#linux/}" npm_target_os="linux" npm_target_libc="glibc" -[[ "$openclaw_base" =~ ^ghcr[.]io/nvidia/nemoclaw/sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage -[[ "$hermes_base" =~ ^ghcr[.]io/nvidia/nemoclaw/hermes-sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage -[[ "$dcode_base" =~ ^ghcr[.]io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage +base_prefix='(ghcr[.]io/nvidia/nemoclaw|localhost:5000/nemoclaw-managed-protected-base)' +[[ "$openclaw_base" =~ ^${base_prefix}/sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage +[[ "$hermes_base" =~ ^${base_prefix}/hermes-sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage +[[ "$dcode_base" =~ ^${base_prefix}/langchain-deepagents-code-sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage [[ "$source_root" == /* && "$source_root" != *$'\n'* && -d "$source_root" && ! -L "$source_root" ]] || usage source_root="$(cd -- "$source_root" && pwd -P)" seed_helper="$source_root/scripts/checks/materialize-locked-npm-cache-seed.mts" diff --git a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts index 6b0df9b13fc..ab9a6b26a9c 100644 --- a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts +++ b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts @@ -381,6 +381,28 @@ describe("protected managed-image runtime workflow", () => { ); }); + it("rejects excluding local Dockerfile sources from native candidate qualification", () => { + const value = workflow(); + multiarchJob(value).if = String(multiarchJob(value).if).replace( + "github.repository == 'NVIDIA/NemoClaw'", + "needs.generate-matrix.outputs.workload_source == 'managed-image' && github.repository == 'NVIDIA/NemoClaw'", + ); + + expect(validateManagedImageMultiarchWorkflow(value)).toContain( + "managed-image-multiarch-startup must use the trusted execution plan", + ); + }); + + it("rejects removing local multiarch base builds", () => { + const value = workflow(); + const bases = namedMultiarchStep(value, "Resolve exact platform base images"); + bases.run = String(bases.run).replace("local-dockerfile)", "candidate-images)"); + + expect(validateManagedImageMultiarchWorkflow(value)).toContain( + "managed-image-multiarch-startup step 'Resolve exact platform base images' must include local-dockerfile)", + ); + }); + it("requires the validated base publication before protected multiarch startup", () => { const value = workflow(); multiarchJob(value).needs = "generate-matrix"; diff --git a/test/platform/images/protected-managed-image-build-script.test.ts b/test/platform/images/protected-managed-image-build-script.test.ts index 749b4641ce2..0cf1c8616b5 100644 --- a/test/platform/images/protected-managed-image-build-script.test.ts +++ b/test/platform/images/protected-managed-image-build-script.test.ts @@ -220,6 +220,7 @@ function runBuild( sourceRoot: string, extraArgs: readonly string[] = [], platform = "linux/amd64", + baseRegistry = "ghcr.io/nvidia/nemoclaw", ) { const output = path.join(testRoot, "contracts.json"); return spawnSync( @@ -235,11 +236,11 @@ function runBuild( "--platform", platform, "--openclaw-base", - `ghcr.io/nvidia/nemoclaw/sandbox-base@sha256:${DIGEST}`, + `${baseRegistry}/sandbox-base@sha256:${DIGEST}`, "--hermes-base", - `ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@sha256:${DIGEST}`, + `${baseRegistry}/hermes-sandbox-base@sha256:${DIGEST}`, "--dcode-base", - `ghcr.io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@sha256:${DIGEST}`, + `${baseRegistry}/langchain-deepagents-code-sandbox-base@sha256:${DIGEST}`, "--source-root", sourceRoot, ...extraArgs, @@ -360,6 +361,20 @@ describe("protected managed-image build-cache boundary", () => { }); }); + it("accepts exact bases from the isolated local registry", () => { + stubBuildInvocation(); + + const result = runBuild( + REPO_ROOT, + [], + "linux/arm64", + "localhost:5000/nemoclaw-managed-protected-base", + ); + + expect(result.status, result.stderr).toBe(0); + expect(recordedBuildInvocations()).toHaveLength(3); + }); + it("binds every protected build to the selected target architecture", () => { stubBuildInvocation(); diff --git a/tools/e2e/managed-image-multiarch-workflow-boundary.mts b/tools/e2e/managed-image-multiarch-workflow-boundary.mts index 798529adc11..2a298f0cc07 100644 --- a/tools/e2e/managed-image-multiarch-workflow-boundary.mts +++ b/tools/e2e/managed-image-multiarch-workflow-boundary.mts @@ -29,7 +29,7 @@ type WorkflowStep = WorkflowRecord & { const JOB_ID = PROTECTED_MANAGED_IMAGE_MULTIARCH_JOB_ID; const PROTECTED_RUNTIME_JOB_ID = "managed-image-protected-runtime"; -const SELECTOR = `\${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), '${JOB_ID}') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), '${PROTECTED_RUNTIME_JOB_ID}')) }}`; +const SELECTOR = `\${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), '${JOB_ID}') || contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), '${PROTECTED_RUNTIME_JOB_ID}')) }}`; const ACTIVATION_PATH = PROTECTED_MANAGED_IMAGE_ACTIVATION_PATH; const DIRECT_TEST_PATH = "test/e2e/live/managed-image-multiarch-startup.test.ts"; const REGISTRY_IMAGE = @@ -155,6 +155,7 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): "${{ github.workspace }}/e2e-artifacts/live/managed-image-multiarch-startup/${{ matrix.shard }}", E2E_JOB: "1", E2E_TARGET_ID: JOB_ID, + E2E_WORKLOAD_SOURCE: "${{ needs.generate-matrix.outputs.workload_source }}", NEMOCLAW_E2E_EXPECTED_SHA: "${{ inputs.checkout_sha }}", NEMOCLAW_E2E_SHARD: "${{ matrix.shard }}", NEMOCLAW_PROTECTED_MANAGED_IMAGE_BASE_SHA: @@ -267,6 +268,9 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): ]); const hermesBase = requireStep(errors, steps, "Resolve reviewed Hermes platform base image"); + if (hermesBase?.if !== "${{ needs.generate-matrix.outputs.workload_source == 'managed-image' }}") { + errors.push(`${JOB_ID} must resolve the reviewed Hermes base only for managed images`); + } if (hermesBase?.uses !== REVIEWED_HERMES_PLATFORM_ACTION) { errors.push(`${JOB_ID} must use the shared reviewed Hermes platform resolver`); } @@ -292,16 +296,30 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): const bases = requireStep(errors, steps, "Resolve exact platform base images"); requireValues(errors, `${JOB_ID} exact base resolution`, record(bases?.env), { + CHECKOUT_SHA: "${{ inputs.checkout_sha || github.sha }}", DCODE_BASE_CONTRACT: "${{ needs.base-image-publication.outputs.dcode_base_contract }}", + HERMES_BASE_DIGEST: "${{ steps.hermes-base.outputs.digest }}", PLATFORM: "${{ matrix.platform }}", + WORKLOAD_SOURCE: "${{ needs.generate-matrix.outputs.workload_source }}", }); requireFragments(errors, bases, [ 'arch="${PLATFORM#linux/}"', + 'case "$WORKLOAD_SOURCE" in', + "local-dockerfile)", + "build_local_base openclaw Dockerfile.base", + "build_local_base hermes agents/hermes/Dockerfile.base", + "build_local_base dcode agents/langchain-deepagents-code/Dockerfile.base", + '--platform "$PLATFORM"', + '--tag "${repository}:${CHECKOUT_SHA}"', + '--label "org.opencontainers.image.revision=${CHECKOUT_SHA}"', + 'digest="$(jq -er \'."containerimage.digest"\' "$metadata")"', + 'reference="${repository}@${digest}"', 'docker buildx imagetools inspect "$alias" --raw', '.platform.os == "linux" and .platform.architecture == $arch', 'reference="${repository}@${digest}"', '"sha256:$(sha256sum "$exact_raw" | awk \'{print $1}\')" == "$digest"', "ghcr.io/nvidia/nemoclaw/sandbox-base:latest", + '"ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${HERMES_BASE_DIGEST}"', "'.platformReferences[$platform]' <<< \"$DCODE_BASE_CONTRACT\"", 'docker buildx imagetools inspect "$dcode_reference" --raw', '"sha256:$(sha256sum "$work_dir/dcode-exact.raw" | awk \'{print $1}\')" == "$dcode_digest"', @@ -340,8 +358,7 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): '--dcode-base "$BASE_DCODE"', ]); requireValues(errors, `${JOB_ID} protected build bases`, record(build?.env), { - BASE_HERMES: - "ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.hermes-base.outputs.digest }}", + BASE_HERMES: "${{ steps.bases.outputs.hermes }}", }); const direct = requireStep(errors, steps, "Run every exact managed-image contract directly"); @@ -406,8 +423,8 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): "Validate candidate activation contract", "Resolve reviewed Hermes platform base image", "Remove trusted Hermes resolver checkout", - "Resolve exact platform base images", "Start isolated protected managed-image registry", + "Resolve exact platform base images", "Build exact all-agent protected managed images", "Run every exact managed-image contract directly", "Remove isolated protected managed-image registry", From 80f0abadde9625ac7d7882b54b176aa1e8f8c3a8 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 00:40:18 +0700 Subject: [PATCH 15/40] test(e2e): set multiarch workload source Signed-off-by: San Dang --- .../protected-managed-image-contract.test.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/test/platform/images/protected-managed-image-contract.test.ts b/test/platform/images/protected-managed-image-contract.test.ts index 6eedf5a21e4..cb853d869cc 100644 --- a/test/platform/images/protected-managed-image-contract.test.ts +++ b/test/platform/images/protected-managed-image-contract.test.ts @@ -58,6 +58,17 @@ const PLATFORM_DIGESTS = { } as const; const DCODE_BASE_REF = `ghcr.io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@${PLATFORM_DIGESTS.dcode}`; +const EXPECTED_BASE_OUTPUTS = { + "managed-image-multiarch-startup": { + dcode: DCODE_BASE_REF, + hermes: `ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${PLATFORM_DIGESTS.hermes}`, + openclaw: `ghcr.io/nvidia/nemoclaw/sandbox-base@${PLATFORM_DIGESTS.openclaw}`, + }, + "managed-image-protected-runtime": { + dcode: DCODE_BASE_REF, + openclaw: `ghcr.io/nvidia/nemoclaw/sandbox-base@${PLATFORM_DIGESTS.openclaw}`, + }, +} as const; const E2E_WORKFLOW = YAML.parse( readFileSync(path.join(ROOT, ".github", "workflows", "e2e.yaml"), "utf8"), ) as { @@ -125,14 +136,17 @@ printf '%s %s\n' "$digest" "$1" encoding: "utf8", env: { ...process.env, + CHECKOUT_SHA: HEAD_SHA, DCODE_BASE_CONTRACT: JSON.stringify({ platformReferences: { "linux/amd64": DCODE_BASE_REF }, }), DCODE_BASE_REF, GITHUB_OUTPUT: outputPath, + HERMES_BASE_DIGEST: PLATFORM_DIGESTS.hermes, PATH: `${fakeBin}:${process.env.PATH ?? ""}`, PLATFORM: "linux/amd64", RUNNER_TEMP: runnerTemp, + WORKLOAD_SOURCE: "managed-image", }, }); return { @@ -185,10 +199,7 @@ describe("protected managed-image build contract", () => { const { result, output } = runBaseResolution(jobId, stepName); expect(result.status, result.stderr).toBe(0); expect(Object.fromEntries(output.trim().split("\n").map((line) => line.split("=")))).toEqual( - { - dcode: `ghcr.io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@${PLATFORM_DIGESTS.dcode}`, - openclaw: `ghcr.io/nvidia/nemoclaw/sandbox-base@${PLATFORM_DIGESTS.openclaw}`, - }, + EXPECTED_BASE_OUTPUTS[jobId as keyof typeof EXPECTED_BASE_OUTPUTS], ); }); From 6b980cc9d79afbd0c26ed8e31c6994cc25b1fc6e Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 07:18:19 +0700 Subject: [PATCH 16/40] fix(onboard): restore local build fallback Signed-off-by: San Dang --- .../onboard-orchestration.test.ts | 12 ++++++++-- .../managed-workload/onboard-orchestration.ts | 22 +++++++++---------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts index 73ddb90eacc..de26cfec30f 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts @@ -173,13 +173,21 @@ describe("managed workload onboard orchestration", () => { ).toBe(false); }); - it("rejects an unavailable catalog for stock managed-image onboarding", async () => { + it("uses the Dockerfile when the stock managed-image catalog is unavailable", async () => { const { runtime } = createFreshOnboardingRuntime( {}, { stockManagedRuntime: true, unavailableCatalog: true }, ); - await expect(runtime.ensurePreparedWorkload()).rejects.toThrow("registry offline"); + await expect(runtime.ensurePreparedWorkload()).resolves.toMatchObject({ + source: { + kind: "legacy-dockerfile", + dockerfilePath: "agents/openclaw/Dockerfile", + reason: "contract-unavailable", + }, + release: null, + fallbackDiagnostic: expect.stringContaining("registry offline"), + }); }); it("rejects an unavailable catalog for explicit temporary managed-image onboarding", async () => { diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index b0e6d6ac59c..2c6b9d7b47f 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -20,10 +20,7 @@ import { } from "../docker-gpu-route"; import type { HermesDashboardOnboardState } from "../hermes-dashboard"; import type { InitialSandboxPolicy } from "../initial-policy"; -import { - isShippedManagedImageAgent, - managedImageRuntimeIdentity, -} from "../managed-image/contract"; +import { isShippedManagedImageAgent, managedImageRuntimeIdentity } from "../managed-image/contract"; import { type BuiltManagedStartupOnboardProfile, buildManagedStartupOnboardProfile, @@ -221,14 +218,15 @@ export function createManagedWorkloadOnboardRuntime( input.computePlan, ); const strictManagedRuntime = input.tempManagedRuntime || input.managedWorkloadRebuild !== null; - const runtimeCapabilities = - strictManagedRuntime || input.stockManagedRuntime - ? discoveredRuntimeCapabilities - : { - ...discoveredRuntimeCapabilities, - managedImageSelectionPolicy: "prefer-managed" as const, - managedImages: null, - }; + const runtimeCapabilities = strictManagedRuntime + ? discoveredRuntimeCapabilities + : { + ...discoveredRuntimeCapabilities, + managedImageSelectionPolicy: "prefer-managed" as const, + managedImages: input.stockManagedRuntime + ? discoveredRuntimeCapabilities.managedImages + : null, + }; const runtimeProvider = resolveRuntimeProviderBundle( input.computePlan.driverName, CURRENT_RUNTIME_PROVIDER_BUNDLES, From 65ed831a59edc77df4b44d7c0943f101e4bb1a3d Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 07:32:03 +0700 Subject: [PATCH 17/40] fix(e2e): harden managed image selection Signed-off-by: San Dang --- .github/workflows/base-image.yaml | 2 + .github/workflows/e2e.yaml | 2 +- .../support/base-image-publication.test.ts | 2 + .../dockerhub-auth-workflow-boundary.test.ts | 15 ++++++++ .../support/pr-managed-image-source.test.ts | 37 ++++++++++++++++++- tools/e2e/workflow-boundary.mts | 7 +++- 6 files changed, 60 insertions(+), 5 deletions(-) diff --git a/.github/workflows/base-image.yaml b/.github/workflows/base-image.yaml index c06f4ce4d88..0edcff9b007 100644 --- a/.github/workflows/base-image.yaml +++ b/.github/workflows/base-image.yaml @@ -42,6 +42,8 @@ on: - "src/lib/actions/sandbox/openshell-child-visible-credentials.v*.json" - "src/lib/core/json-types.ts" - "src/lib/core/ports.ts" + - "src/lib/hermes-managed-route.ts" + - "src/lib/inference/managed-dcode/identity.ts" - "src/lib/messaging/**" - "src/lib/onboard/managed-bootstrap/envelope.ts" - "src/lib/onboard/managed-startup/**" diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 700fbdd46c8..4a91ff39cbe 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -2814,7 +2814,7 @@ jobs: - name: Run live E2E tests env: E2E_TARGET_ID: ${{ matrix.id }} - NVIDIA_INFERENCE_API_KEY: ${{ secrets.NVIDIA_INFERENCE_API_KEY }} + NVIDIA_INFERENCE_API_KEY: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.NVIDIA_INFERENCE_API_KEY || '' }} TARGET_ID: ${{ matrix.id }} run: | set -euo pipefail diff --git a/test/e2e/support/base-image-publication.test.ts b/test/e2e/support/base-image-publication.test.ts index 85c109f4439..db1bdae2641 100644 --- a/test/e2e/support/base-image-publication.test.ts +++ b/test/e2e/support/base-image-publication.test.ts @@ -194,6 +194,8 @@ describe("base-image publication evidence", () => { "nemoclaw-blueprint/**", "scripts/**", "src/lib/actions/sandbox/openshell-child-visible-credentials.v*.json", + "src/lib/hermes-managed-route.ts", + "src/lib/inference/managed-dcode/identity.ts", "src/lib/messaging/**", "src/lib/tool-disclosure.ts", "tools/mcp-tool-discovery-runtime/**", diff --git a/test/e2e/support/dockerhub-auth-workflow-boundary.test.ts b/test/e2e/support/dockerhub-auth-workflow-boundary.test.ts index 8dafbad1f32..ee803d68c8b 100644 --- a/test/e2e/support/dockerhub-auth-workflow-boundary.test.ts +++ b/test/e2e/support/dockerhub-auth-workflow-boundary.test.ts @@ -349,6 +349,21 @@ describe("shared Docker Hub authentication workflow boundary (#6961)", () => { ); }); + it("rejects an inference credential mapped to candidate code without authorization", () => { + const errors = validateMutation((workflow) => { + const run = namedStep(workflow.jobs.live, "Run live E2E tests"); + expect(run).toBeDefined(); + run!.env = { + ...run!.env, + NVIDIA_INFERENCE_API_KEY: "${{ secrets.NVIDIA_INFERENCE_API_KEY }}", + }; + }); + + expect(errors).toContain( + "live E2E step must guard NVIDIA_INFERENCE_API_KEY behind a main run or an authorized NVIDIA-owned PR dispatch", + ); + }); + it("rejects uniform unsafe cleanup drift without trusting the live job as canonical", () => { const workflow = loadWorkflow(); const requiredJobs = imageJobNames(workflow); diff --git a/test/e2e/support/pr-managed-image-source.test.ts b/test/e2e/support/pr-managed-image-source.test.ts index 4517cdd1d06..e3425cf3d3f 100644 --- a/test/e2e/support/pr-managed-image-source.test.ts +++ b/test/e2e/support/pr-managed-image-source.test.ts @@ -87,9 +87,18 @@ function selectorInput() { } describe("PR managed-image source selection", () => { - it("selects a local Dockerfile when a reviewed image input changes", async () => { + it.each([ + "Dockerfile", + "Dockerfile.base", + "agents/hermes/Dockerfile.base", + "agents/langchain-deepagents-code/Dockerfile.base", + "agents/pi/Dockerfile.base", + "src/lib/hermes-managed-route.ts", + "src/lib/inference/managed-dcode/identity.ts", + "tools/mcp-tool-discovery-runtime/reviewed-runtime-bundle/managed-startup-image-runtime.bundle", + ])("selects a local Dockerfile when reviewed image input %s changes", async (filename) => { await expect( - resolvePrManagedImageSource(selectorInput(), requestFor([{ filename: "Dockerfile.base" }])), + resolvePrManagedImageSource(selectorInput(), requestFor([{ filename }])), ).resolves.toBe("local-dockerfile"); }); @@ -110,6 +119,30 @@ describe("PR managed-image source selection", () => { ).resolves.toBe("managed-image"); }); + it("selects a local Dockerfile when a reviewed image input appears on page two", async () => { + const metadataPath = `/repos/NVIDIA/NemoClaw/pulls/${PR_NUMBER}`; + const pageOnePath = `${metadataPath}/files?per_page=100&page=1`; + const pageTwoPath = `${metadataPath}/files?per_page=100&page=2`; + const requests: string[] = []; + const responses = new Map([ + [metadataPath, pull(101)], + [ + pageOnePath, + Array.from({ length: 100 }, (_, index) => ({ filename: `docs/guide-${index}.mdx` })), + ], + [pageTwoPath, [{ filename: "Dockerfile.base" }]], + ]); + const request = async (requestPath: string): Promise => { + requests.push(requestPath); + return responses.get(requestPath) ?? unexpectedRequest(requestPath); + }; + + await expect(resolvePrManagedImageSource(selectorInput(), request)).resolves.toBe( + "local-dockerfile", + ); + expect(requests).toContain(pageTwoPath); + }); + it.each([ ["a closed pull request", { state: "closed" }, "pull request state must be open"], [ diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 5135fb845f3..ecde159d448 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -222,6 +222,7 @@ const GUARDED_DOCKER_HUB_AUTH_REQUIRED = `\${{ ${TRUSTED_DOCKER_HUB_PREDICATE} & const GUARDED_DOCKER_HUB_USERNAME = `\${{ ${TRUSTED_DOCKER_HUB_PREDICATE} && secrets.DOCKERHUB_USERNAME || '' }}`; const GUARDED_DOCKER_HUB_TOKEN = `\${{ ${TRUSTED_DOCKER_HUB_PREDICATE} && secrets.DOCKERHUB_TOKEN || '' }}`; const GUARDED_HERMES_E2E_INFERENCE_KEY = `\${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && (inputs.inference_mode || 'mock') != 'mock' && secrets.NVIDIA_INFERENCE_API_KEY || '' }}`; +const GUARDED_LIVE_E2E_INFERENCE_KEY = `\${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.NVIDIA_INFERENCE_API_KEY || '' }}`; const RUNNER_ROUTING_OUTPUT = "${{ steps.runner_routing.outputs.runner_routing }}"; const RUNNER_ROUTING_STEP_NAME = "Build trusted larger-runner routing"; const RUNNER_ROUTING_SCRIPT = [ @@ -3018,8 +3019,10 @@ export function validateE2eWorkflow(workflowValue: unknown): string[] { if (runVitestEnv.TARGET_ID !== "${{ matrix.id }}") { errors.push("live E2E step must pass matrix.id through TARGET_ID env"); } - if (runVitestEnv.NVIDIA_INFERENCE_API_KEY !== "${{ secrets.NVIDIA_INFERENCE_API_KEY }}") { - errors.push("live E2E step must receive NVIDIA_INFERENCE_API_KEY from secrets"); + if (runVitestEnv.NVIDIA_INFERENCE_API_KEY !== GUARDED_LIVE_E2E_INFERENCE_KEY) { + errors.push( + "live E2E step must guard NVIDIA_INFERENCE_API_KEY behind a main run or an authorized NVIDIA-owned PR dispatch", + ); } requireRunContains(errors, runVitest, "tools/e2e/live-vitest-invocation.mts run --test-path"); requireRunContains(errors, runVitest, "test/e2e/live/registry-targets.test.ts"); From 39d60e437cc52e2152c35184ad3b9e1eddf0c7ec Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 07:59:49 +0700 Subject: [PATCH 18/40] fix(e2e): qualify local images on protected runtime Signed-off-by: San Dang --- .github/workflows/e2e.yaml | 2 +- .../managed-image-protected-runtime-workflow.test.ts | 12 ++++++++++++ ...ged-image-protected-runtime-workflow-boundary.mts | 2 +- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 4a91ff39cbe..ace21183642 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -4722,7 +4722,7 @@ jobs: managed-image-protected-runtime: name: Protected managed-image GPU and local inference needs: [base-image-publication, generate-matrix, managed-image-multiarch-startup] - if: ${{ always() && needs.generate-matrix.outputs.workload_source == 'managed-image' && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }} + if: ${{ always() && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }} runs-on: linux-amd64-gpu-rtxpro6000-latest-1 timeout-minutes: 300 permissions: diff --git a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts index ab9a6b26a9c..b1a24aaccba 100644 --- a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts +++ b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts @@ -393,6 +393,18 @@ describe("protected managed-image runtime workflow", () => { ); }); + it("rejects excluding local Dockerfile sources from protected runtime qualification", () => { + const value = workflow(); + runtimeJob(value).if = String(runtimeJob(value).if).replace( + "github.repository == 'NVIDIA/NemoClaw'", + "needs.generate-matrix.outputs.workload_source == 'managed-image' && github.repository == 'NVIDIA/NemoClaw'", + ); + + expect(validateManagedImageProtectedRuntimeWorkflow(value)).toContain( + "managed-image-protected-runtime must use the trusted execution plan", + ); + }); + it("rejects removing local multiarch base builds", () => { const value = workflow(); const bases = namedMultiarchStep(value, "Resolve exact platform base images"); diff --git a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts index 0e8d6de8c75..e7031afd020 100644 --- a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts +++ b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts @@ -14,7 +14,7 @@ type WorkflowStep = WorkflowRecord & { const JOB_ID = "managed-image-protected-runtime"; const SELECTOR = - "${{ always() && needs.generate-matrix.outputs.workload_source == 'managed-image' && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }}"; + "${{ always() && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }}"; const ACTIVATION_PATH = "ci/protected-managed-image-runtime-activation-v1.json"; const LIVE_TEST_PATH = "test/e2e/live/managed-image-protected-runtime.test.ts"; const REGISTRY_IMAGE = From b188ad68309f48cf0bf673ce387ac35973bcb810 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 08:48:16 +0700 Subject: [PATCH 19/40] fix(mcp): wait for final provider revision --- .../actions/sandbox/mcp-bridge-add-restart.ts | 14 ++++++-- .../sandbox/mcp-bridge-provider-readiness.ts | 33 ++++++++++++++++-- .../sandbox/mcp-bridge-provider.test.ts | 34 +++++++++++++++++++ .../actions/sandbox/mcp-bridge-provider.ts | 1 + src/lib/actions/sandbox/mcp-bridge-restart.ts | 14 ++++++-- test/mcp/mcp-add-crash-consistency.test.ts | 27 +++++++++++++++ 6 files changed, 115 insertions(+), 8 deletions(-) diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index f8bcd7a5ff6..1d0838d0c9e 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -35,6 +35,7 @@ import { assertMcpProviderRecoverable, assertNoProviderCredentialCollisions, attachProvider, + credentialRevisionForProviderResourceVersion, deleteProvider, detachMissingProviderReference, detachProvider, @@ -435,18 +436,23 @@ async function addMcpBridgeUnlocked( providerAttachAttempted = true; attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, target); + let expectedCredentialRevision; if (Object.hasOwn(adapterEnvValues, entry.env[0])) { // OpenShell 0.0.106 can miss a credential update published before the // bound policy generation. Republish while that policy is active and // before the first readiness exec; the exact provider identity is // rechecked before and after this update-only mutation. - upsertMcpProvider(entry.providerName ?? "", options.env, { + const republished = upsertMcpProvider(entry.providerName ?? "", options.env, { allowExisting: true, expectedProviderId: entry.providerId, requireExisting: true, }); + expectedCredentialRevision = credentialRevisionForProviderResourceVersion( + republished.inspection.resourceVersion, + ); } const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { + expectedRevision: expectedCredentialRevision, ...(providerResult.action === "updated" ? { previousRevision: previousCredentialRevision, @@ -473,7 +479,11 @@ async function addMcpBridgeUnlocked( expectedProviderId: entry.providerId, requireExisting: true, }); - if (republished.action !== "updated") refreshMcpProviderEnvironment(entry); + const synchronized = + republished.action === "updated" + ? republished.inspection + : refreshMcpProviderEnvironment(entry); + return credentialRevisionForProviderResourceVersion(synchronized.resourceVersion); }, }); // The adapter was proven absent above, so cleanup is safe even when a diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts index 60eeadb8e73..6bcabf73f4c 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts @@ -13,6 +13,7 @@ import { import { executeSandboxExecCommand } from "./process-recovery"; const MCP_CREDENTIAL_REVISION_OBSERVATION_RE = /^(?:absent|canonical|v[0-9]{1,20})$/; +const MCP_ATTACHED_CREDENTIAL_REVISION_RE = /^v[0-9]{1,20}$/; export type McpCredentialRevisionObservation = "absent" | "canonical" | `v${number}`; export type McpAttachedCredentialRevision = Exclude< @@ -20,6 +21,15 @@ export type McpAttachedCredentialRevision = Exclude< "absent" | "canonical" >; +export function credentialRevisionForProviderResourceVersion( + resourceVersion: number | null, +): McpAttachedCredentialRevision { + if (!Number.isSafeInteger(resourceVersion) || (resourceVersion ?? 0) < 1) { + throw new McpBridgeError("OpenShell provider metadata has no valid credential revision."); + } + return `v${String(resourceVersion)}` as McpAttachedCredentialRevision; +} + type McpCredentialRevisionAttempt = | { kind: "observation"; observation: McpCredentialRevisionObservation } | { kind: "transport-unavailable" } @@ -147,8 +157,9 @@ export function waitForAttachedMcpCredential( sandboxName: string, entry: McpBridgeEntry, options: { + expectedRevision?: McpAttachedCredentialRevision; previousRevision?: McpCredentialRevisionObservation; - refreshAfterObservedAbsence?: () => void; + refreshAfterObservedAbsence?: () => McpAttachedCredentialRevision | void; } = {}, ): McpAttachedCredentialRevision { assertAuthenticatedBridgeEntry(entry); @@ -159,6 +170,12 @@ export function waitForAttachedMcpCredential( ) { throw new McpBridgeError("Invalid prior MCP credential revision observation."); } + if ( + options.expectedRevision !== undefined && + !MCP_ATTACHED_CREDENTIAL_REVISION_RE.test(options.expectedRevision) + ) { + throw new McpBridgeError("Invalid expected MCP credential revision."); + } const timeoutSeconds = Number.parseInt( process.env.NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS ?? "30", 10, @@ -166,6 +183,7 @@ export function waitForAttachedMcpCredential( let refreshedAfterObservedAbsence = false; let lastAttempt: McpCredentialRevisionAttempt = { kind: "transport-unavailable" }; let attachedRevision: McpAttachedCredentialRevision | undefined; + let expectedRevision = options.expectedRevision; const ready = waitForMcpBridgeCondition( () => { // Each exec is a fresh OpenShell process. Only the bounded placeholder @@ -180,7 +198,14 @@ export function waitForAttachedMcpCredential( options.refreshAfterObservedAbsence ) { refreshedAfterObservedAbsence = true; - options.refreshAfterObservedAbsence(); + const refreshedRevision = options.refreshAfterObservedAbsence(); + if ( + refreshedRevision !== undefined && + !MCP_ATTACHED_CREDENTIAL_REVISION_RE.test(refreshedRevision) + ) { + throw new McpBridgeError("Invalid refreshed MCP credential revision."); + } + expectedRevision = refreshedRevision ?? expectedRevision; attempt = tryObserveMcpCredentialRevision(sandboxName, envName); lastAttempt = attempt; } @@ -193,7 +218,9 @@ export function waitForAttachedMcpCredential( observation !== null && observation !== "absent" && observation !== "canonical" && - (options.previousRevision === undefined || observation !== options.previousRevision); + (expectedRevision !== undefined + ? observation === expectedRevision + : options.previousRevision === undefined || observation !== options.previousRevision); if (attached) attachedRevision = observation; return attached; }, diff --git a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts index 5bbdc2af88c..bde0b8dbe0a 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts @@ -21,6 +21,7 @@ import { } from "./mcp-bridge-provider-inspection"; import { assertMcpProviderRecoverable, + credentialRevisionForProviderResourceVersion, observeMcpCredentialRevision, refreshMcpProviderEnvironment, waitForAttachedMcpCredential, @@ -83,6 +84,16 @@ Provider: expect(output).not.toMatch(/\[[0-9;]*m/); }); + it("maps a valid provider resource version to its credential revision", () => { + expect(credentialRevisionForProviderResourceVersion(12)).toBe("v12"); + expect(() => credentialRevisionForProviderResourceVersion(null)).toThrow( + "OpenShell provider metadata has no valid credential revision.", + ); + expect(() => credentialRevisionForProviderResourceVersion(0)).toThrow( + "OpenShell provider metadata has no valid credential revision.", + ); + }); + it("accepts an exact legacy generic provider only for cleanup", () => { const inspection = { exists: true, @@ -615,4 +626,27 @@ alpha-mcp-slack generic 1 0 ); expect(exec).toHaveBeenCalledTimes(1); }); + + it("waits for the credential revision from the final provider publication", () => { + const entry = { + server: "github", + agent: "openclaw", + adapter: "mcporter", + url: "https://mcp.example.test/mcp", + env: ["GITHUB_TOKEN"], + providerName: "alpha-mcp-github-0123456789abcdef", + providerId: "11111111-2222-4333-8444-555555555555", + policyName: "mcp-bridge-github", + addedAt: "2026-06-01T00:00:00.000Z", + }; + const exec = vi + .spyOn(processRecovery, "executeSandboxExecCommand") + .mockReturnValueOnce({ status: 0, stdout: "v11", stderr: "" }) + .mockReturnValueOnce({ status: 0, stdout: "v12", stderr: "" }); + + expect( + waitForAttachedMcpCredential("alpha", entry, { expectedRevision: "v12" }), + ).toBe("v12"); + expect(exec).toHaveBeenCalledTimes(2); + }); }); diff --git a/src/lib/actions/sandbox/mcp-bridge-provider.ts b/src/lib/actions/sandbox/mcp-bridge-provider.ts index 42b991c6b10..5f0a3fe9c93 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider.ts @@ -38,6 +38,7 @@ export type { McpCredentialRevisionObservation } from "./mcp-bridge-provider-rea export { buildMcpCredentialDetachedCommand, buildMcpCredentialRevisionObservationCommand, + credentialRevisionForProviderResourceVersion, observeMcpCredentialRevision, waitForAttachedMcpCredential, waitForDetachedMcpCredential, diff --git a/src/lib/actions/sandbox/mcp-bridge-restart.ts b/src/lib/actions/sandbox/mcp-bridge-restart.ts index bdee7dee3bf..da326ecfb29 100644 --- a/src/lib/actions/sandbox/mcp-bridge-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-restart.ts @@ -14,6 +14,7 @@ import { assertNoAttachedProviderCredentialCollisions, assertNoProviderCredentialCollisions, attachProvider, + credentialRevisionForProviderResourceVersion, detachMissingProviderReference, ensureMcpBridgeProviderProfile, refreshMcpProviderEnvironment, @@ -172,8 +173,11 @@ async function restartMcpBridgeUnlocked(sandboxName: string, server?: string): P } attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, target); - refreshMcpProviderEnvironment(entry); + const synchronizedProvider = refreshMcpProviderEnvironment(entry); const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { + expectedRevision: credentialRevisionForProviderResourceVersion( + synchronizedProvider.resourceVersion, + ), ...(providerResult.action === "updated" ? { previousRevision: previousCredentialRevision } : {}), @@ -241,8 +245,12 @@ export async function restoreExistingMcpBridgeRuntime( }); attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, resolvedTargetPins(resolvedByServer, entry)); - refreshMcpProviderEnvironment(entry); - const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry); + const synchronizedProvider = refreshMcpProviderEnvironment(entry); + const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { + expectedRevision: credentialRevisionForProviderResourceVersion( + synchronizedProvider.resourceVersion, + ), + }); const adapter = (entry.adapter as AgentMcpAdapter | undefined) ?? defaultAdapter; registerAgentAdapter( sandboxName, diff --git a/test/mcp/mcp-add-crash-consistency.test.ts b/test/mcp/mcp-add-crash-consistency.test.ts index a9099784655..675258c2bac 100644 --- a/test/mcp/mcp-add-crash-consistency.test.ts +++ b/test/mcp/mcp-add-crash-consistency.test.ts @@ -18,6 +18,7 @@ type CrashBoundary = | "credential-collision" | "credential-command-race" | "credential-projection-coalesced" + | "credential-projection-delayed-final" | "credential-projection-delayed-hostless" | "registered-credential-collision" | "registered-late-collision" @@ -45,6 +46,7 @@ const path = require("node:path"); const crashAfter = ${JSON.stringify(crashAfter)}; if ( crashAfter === "credential-projection-coalesced" || + crashAfter === "credential-projection-delayed-final" || crashAfter === "credential-projection-delayed-hostless" ) { process.env.NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS = "2"; @@ -66,6 +68,7 @@ let credentialRepublishBeforeObservationCountThisProcess = 0; let credentialRepublishAfterAbsenceCountThisProcess = 0; let credentialFreeRefreshBeforeObservationCountThisProcess = 0; let credentialFreeRefreshAfterAbsenceCountThisProcess = 0; +let credentialObservationCountThisProcess = 0; const registry = require("./src/lib/state/registry.js"); const providerCommands = require("./src/lib/adapters/openshell/provider-command.js"); @@ -258,6 +261,14 @@ processRecovery.executeSandboxExecCommand = (_sandbox, command) => { stderr: "", }; } + if (crashAfter === "credential-projection-delayed-final" && isObservation) { + credentialObservationCountThisProcess += 1; + return { + status: 0, + stdout: credentialObservationCountThisProcess === 1 ? "v1" : "v" + providerVersion(), + stderr: "", + }; + } return { status: crashAfter === "preupdate-observation-forbidden" && isPreupdateObservation ? 1 : 0, stdout: isObservation ? (marked("updated") ? "v" + providerVersion() : marked("provider") ? "v1" : "absent") : "", @@ -270,6 +281,9 @@ processRecovery.executeSandboxCommand = (_sandbox, command) => { } if (command.includes("config' 'add") || command.includes('"config", "add"')) { mark("adapter"); + if (command.includes("openshell:resolve:env:v2_FAKE_MCP_SECRET")) { + mark("adapter-final-revision"); + } if (crashAfter === "adapter") process.exit(86); return { status: 0, stdout: "", stderr: "" }; } @@ -711,6 +725,19 @@ describe("MCP add crash consistency", () => { } }); + it("registers the revision from the final provider publication", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-add-final-revision-")); + try { + const result = runAddProcess(home, "credential-projection-delayed-final"); + + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(fs.existsSync(path.join(home, "adapter-final-revision.marker"))).toBe(true); + expect(readBridge(home).addState).toBeUndefined(); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("resumes an exact provider without a host credential or prior revision observation", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-add-reuse-no-observation-")); try { From 12fe0e8b27ec851eadeeaf06c475a6c37c727e4b Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 09:08:23 +0700 Subject: [PATCH 20/40] fix(e2e): resolve local Dockerfile from agent Signed-off-by: San Dang --- .../sandbox/mcp-bridge-input-targets.test.ts | 2 +- test/e2e/fixtures/workload-source-env.ts | 28 ++++----- test/e2e/support/workload-source-env.test.ts | 57 ++++++++++++++++++- 3 files changed, 66 insertions(+), 21 deletions(-) diff --git a/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts b/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts index c709c629d56..7d9309a30a9 100644 --- a/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts @@ -191,7 +191,7 @@ replace(provider, "upsertMcpProvider", () => ({ action: "created", inspection: { credentialKeys: ["LOCAL_MCP_TOKEN"], exists: true, - id: "11111111-2222-4333-8444-555555555555", resourceVersion: "1", type: "nemoclaw-mcp-v1", + id: "11111111-2222-4333-8444-555555555555", resourceVersion: 1, type: "nemoclaw-mcp-v1", }, })); replace(provider, "attachProvider", () => {}); diff --git a/test/e2e/fixtures/workload-source-env.ts b/test/e2e/fixtures/workload-source-env.ts index b745516a4e3..5a2693b1462 100644 --- a/test/e2e/fixtures/workload-source-env.ts +++ b/test/e2e/fixtures/workload-source-env.ts @@ -1,23 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import path from "node:path"; +import { loadAgent } from "../../../src/lib/agent/defs.ts"; -import { REPO_ROOT } from "./paths.ts"; - -const LOCAL_DOCKERFILE_BY_AGENT = { - openclaw: "Dockerfile", - hermes: "agents/hermes/Dockerfile", - "langchain-deepagents-code": "agents/langchain-deepagents-code/Dockerfile", - pi: "agents/pi/Dockerfile", -} as const; - -type LocalDockerfileAgent = keyof typeof LOCAL_DOCKERFILE_BY_AGENT; - -function localDockerfileAgent(env: NodeJS.ProcessEnv): LocalDockerfileAgent { - const agent = env.NEMOCLAW_AGENT ?? "openclaw"; - if (agent in LOCAL_DOCKERFILE_BY_AGENT) return agent as LocalDockerfileAgent; - return "openclaw"; +function localDockerfilePath(env: NodeJS.ProcessEnv): string { + const agent = loadAgent(env.NEMOCLAW_AGENT ?? "openclaw", env); + const dockerfilePath = agent.dockerfilePath ?? agent.legacyPaths?.dockerfile; + if (!dockerfilePath) { + throw new Error(`Agent '${agent.name}' has no Dockerfile for local E2E workload source.`); + } + return dockerfilePath; } /** @@ -32,9 +24,9 @@ export function resolveLiveE2eWorkloadSourceEnv(input: NodeJS.ProcessEnv): NodeJ const source = input.E2E_WORKLOAD_SOURCE ?? process.env.E2E_WORKLOAD_SOURCE; if (!targetId || source !== "local-dockerfile") return input; if (input.NEMOCLAW_FROM_DOCKERFILE) return input; - const agent = localDockerfileAgent({ ...process.env, ...input }); + const dockerfilePath = localDockerfilePath({ ...process.env, ...input }); return { ...input, - NEMOCLAW_FROM_DOCKERFILE: path.join(REPO_ROOT, LOCAL_DOCKERFILE_BY_AGENT[agent]), + NEMOCLAW_FROM_DOCKERFILE: dockerfilePath, }; } diff --git a/test/e2e/support/workload-source-env.test.ts b/test/e2e/support/workload-source-env.test.ts index 49525067a84..28007a06bde 100644 --- a/test/e2e/support/workload-source-env.test.ts +++ b/test/e2e/support/workload-source-env.test.ts @@ -1,21 +1,29 @@ // 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 { afterEach, describe, expect, it, vi } from "vitest"; +import { AGENTS_DIR } from "../../../src/lib/agent/defs.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; import { resolveLiveE2eWorkloadSourceEnv } from "../fixtures/workload-source-env.ts"; describe("live E2E workload source environment", () => { - afterEach(() => vi.unstubAllEnvs()); + const temporaryAgentDirectories: string[] = []; + + afterEach(() => { + vi.unstubAllEnvs(); + while (temporaryAgentDirectories.length > 0) { + fs.rmSync(temporaryAgentDirectories.pop() ?? "", { force: true, recursive: true }); + } + }); it.each([ ["openclaw", "Dockerfile"], ["hermes", "agents/hermes/Dockerfile"], ["langchain-deepagents-code", "agents/langchain-deepagents-code/Dockerfile"], - ["pi", "agents/pi/Dockerfile"], ])("uses the candidate Dockerfile for %s", (agent, dockerfile) => { expect( resolveLiveE2eWorkloadSourceEnv({ @@ -28,6 +36,51 @@ describe("live E2E workload source environment", () => { }); }); + it("uses the qualified Pi candidate Dockerfile", () => { + expect( + resolveLiveE2eWorkloadSourceEnv({ + E2E_TARGET_ID: "pi-agent-qualification", + E2E_WORKLOAD_SOURCE: "local-dockerfile", + NEMOCLAW_AGENT: "pi", + NEMOCLAW_CANDIDATE_AGENTS: "1", + NEMOCLAW_CANDIDATE_QUALIFICATION_RECEIPT: path.join( + REPO_ROOT, + "ci/pi-agent-qualification-v1-linux-amd64.json", + ), + }), + ).toMatchObject({ + NEMOCLAW_FROM_DOCKERFILE: path.join(REPO_ROOT, "agents/pi/Dockerfile"), + }); + }); + + it("rejects an unknown local-build agent", () => { + expect(() => + resolveLiveE2eWorkloadSourceEnv({ + E2E_TARGET_ID: "full-e2e", + E2E_WORKLOAD_SOURCE: "local-dockerfile", + NEMOCLAW_AGENT: "not-an-agent", + }), + ).toThrow("Agent 'not-an-agent' not found"); + }); + + it("rejects a selected agent without a Dockerfile", () => { + const agentDirectory = fs.mkdtempSync(path.join(AGENTS_DIR, "e2e-no-dockerfile-")); + temporaryAgentDirectories.push(agentDirectory); + const agentName = path.basename(agentDirectory); + fs.writeFileSync( + path.join(agentDirectory, "manifest.yaml"), + `name: ${agentName}\ndisplay_name: E2E no Dockerfile\n`, + ); + + expect(() => + resolveLiveE2eWorkloadSourceEnv({ + E2E_TARGET_ID: "full-e2e", + E2E_WORKLOAD_SOURCE: "local-dockerfile", + NEMOCLAW_AGENT: agentName, + }), + ).toThrow(`Agent '${agentName}' has no Dockerfile for local E2E workload source.`); + }); + it("leaves an unspecified source on the product's default workload path", () => { const input = { E2E_TARGET_ID: "full-e2e", NEMOCLAW_AGENT: "openclaw" }; expect(resolveLiveE2eWorkloadSourceEnv(input)).toEqual(input); From 087f361a67ed8f725a9d7c1e1c256156ae6e9948 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 09:47:20 +0700 Subject: [PATCH 21/40] fix(onboard): wait for canonical pairing before warmup Signed-off-by: San Dang --- .../onboard/machine/finalization-deps.test.ts | 19 ++++--- src/lib/onboard/machine/finalization-deps.ts | 53 ++++++++++++------- 2 files changed, 44 insertions(+), 28 deletions(-) diff --git a/src/lib/onboard/machine/finalization-deps.test.ts b/src/lib/onboard/machine/finalization-deps.test.ts index 9cadcb507ea..21aff1c9e09 100644 --- a/src/lib/onboard/machine/finalization-deps.test.ts +++ b/src/lib/onboard/machine/finalization-deps.test.ts @@ -113,7 +113,7 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); - it("runs the canonical request probe before waiting for fresh pairing (#10014)", async () => { + it("waits for canonical pairing before running the one request producer (#10014)", async () => { const observePairing = vi .fn(() => SCOPE_UPGRADE_PENDING) .mockImplementationOnce(() => { @@ -135,7 +135,7 @@ describe("ordinary OpenClaw pairing settlement", () => { kind: "settled", }); - expect(scope.calls).toEqual(["warmup", "sleep", "approval"]); + expect(scope.calls).toEqual(["warmup", "approval"]); expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); @@ -406,9 +406,7 @@ describe("ordinary OpenClaw pairing settlement", () => { throw new Error("not published"); }; const scope = ordinaryPairingDeps({ - observePairing: vi.fn(() => - attempts++ < 10 ? unavailable() : SCOPE_UPGRADE_PENDING, - ), + observePairing: vi.fn(() => (attempts++ < 10 ? unavailable() : SCOPE_UPGRADE_PENDING)), }); await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).resolves.toEqual({ @@ -416,7 +414,7 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "scope-upgrade-incomplete", }); expect(scope.deps.sleep).toHaveBeenCalledTimes(39); - expect(scope.deps.runWarmup).toHaveBeenCalledOnce(); + expect(scope.deps.runWarmup).not.toHaveBeenCalled(); expect(scope.deps.runApproval).toHaveBeenCalledOnce(); }); @@ -436,6 +434,7 @@ describe("ordinary OpenClaw pairing settlement", () => { .mockImplementationOnce(() => { throw new Error("not pending"); }) + .mockReturnValueOnce(PAIRING_ONLY) .mockReturnValueOnce(SCOPE_UPGRADE_PENDING) .mockReturnValue(SETTLED), runWarmup: vi.fn(() => { @@ -452,7 +451,7 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); - expect(scope.deps.observePairing).toHaveBeenCalledTimes(4); + expect(scope.deps.observePairing).toHaveBeenCalledTimes(5); expect(now).toBe( OPENCLAW_PAIRING_OBSERVATION_TIMEOUT_MS + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS - @@ -489,11 +488,11 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "pairing-unavailable", }); expect(scope.deps.sleep).not.toHaveBeenCalled(); - expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); + expect(scope.deps.runWarmup).not.toHaveBeenCalled(); expect(scope.deps.runApproval).not.toHaveBeenCalled(); }); - it("performs one request-producer write when a canonical CLI pairing never appears (#9844)", async () => { + it("does not run a request producer without a canonical CLI pairing (#9844)", async () => { const scope = ordinaryPairingDeps({ observePairing: vi.fn(() => { throw new Error("not published"); @@ -505,7 +504,7 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "pairing-unavailable", }); - expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); + expect(scope.deps.runWarmup).not.toHaveBeenCalled(); expect(scope.deps.runApproval).not.toHaveBeenCalled(); }); diff --git a/src/lib/onboard/machine/finalization-deps.ts b/src/lib/onboard/machine/finalization-deps.ts index 55d323f53ea..c4f51c32bf5 100644 --- a/src/lib/onboard/machine/finalization-deps.ts +++ b/src/lib/onboard/machine/finalization-deps.ts @@ -155,9 +155,7 @@ function defaultPairingSettlementDeps(): OrdinaryOpenClawPairingSettlementDeps { .loadPairingQualification() .observeOrdinaryOpenClawPairingSettlement(...args), runWarmup: (name, gatewayName) => - finalizationHandlerRuntime - .loadAutoPairWarmup() - .runSandboxScopeWarmupRun(name, gatewayName), + finalizationHandlerRuntime.loadAutoPairWarmup().runSandboxScopeWarmupRun(name, gatewayName), runApproval: (name, gatewayName) => { finalizationHandlerRuntime.loadAutoPairApproval().runSandboxAutoPairApprovalPass(name, { budget: { @@ -222,7 +220,7 @@ export async function settleOrdinaryOpenClawPairing( ); sawCanonicalPairing = true; } catch { - // Pairing may not have appeared yet; the producer handles that path. + // Pairing may not have appeared yet; the bounded observer handles that path. } if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; @@ -232,14 +230,36 @@ export async function settleOrdinaryOpenClawPairing( } if (initial?.state === "settled") return { kind: "settled" }; - let baseline: PairingWaitResult; - if (initial?.state === "scope-upgrade-pending") { - baseline = { kind: "observed", value: initial }; - } else { - // A valid non-interactive path can reach finalization before the - // startup watcher publishes its first CLI request. Run the bounded - // direct producer once, then require canonical evidence that its - // exact write upgrade is pending before the approval pass (#10014). + const pairingAppearanceDeadline = Math.min( + settlementDeadline, + deps.now() + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS, + ); + let baseline: PairingWaitResult = initial + ? { kind: "observed", value: initial } + : await waitForPairingObservation( + name, + target, + pairingAppearanceDeadline, + (value) => { + sawCanonicalPairing = true; + return true; + }, + deps, + ); + if (baseline.kind === "target-changed") { + return { kind: "incomplete", reason: "runtime-identity-invalid" }; + } + if (baseline.kind === "timeout") { + return { kind: "incomplete", reason: "pairing-unavailable" }; + } + if (baseline.value.state === "settled") return { kind: "settled" }; + + if (baseline.value.state === "pairing-only") { + // Wait for the startup watcher to publish the canonical CLI + // pairing before issuing the one bounded write-scope producer. + // Running the producer before that identity exists can create no + // upgrade and leaves an otherwise healthy fresh onboard stuck at + // pairing-only (#10014). try { await deps.runWarmup(name, target.gatewayName); } catch { @@ -248,14 +268,14 @@ export async function settleOrdinaryOpenClawPairing( if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } - const pairingAppearanceDeadline = Math.min( + const scopeUpgradeDeadline = Math.min( settlementDeadline, deps.now() + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS, ); baseline = await waitForPairingObservation( name, target, - pairingAppearanceDeadline, + scopeUpgradeDeadline, (value) => { sawCanonicalPairing = true; return value.state !== "pairing-only"; @@ -272,10 +292,7 @@ export async function settleOrdinaryOpenClawPairing( reason: sawCanonicalPairing ? "scope-upgrade-incomplete" : "pairing-unavailable", }; } - if ( - initial && - baseline.value.deviceIdentitySha256 !== initial.deviceIdentitySha256 - ) { + if (initial && baseline.value.deviceIdentitySha256 !== initial.deviceIdentitySha256) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } if (baseline.value.state === "settled") return { kind: "settled" }; From b49077afe1bd941446b9a46e5197b2a0193be591 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 09:48:23 +0700 Subject: [PATCH 22/40] docs(e2e): qualify GitHub rate-limit retries Signed-off-by: San Dang --- test/e2e/RETRY_INVENTORY.md | 2 +- test/e2e/support/pr-managed-image-source.test.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/test/e2e/RETRY_INVENTORY.md b/test/e2e/RETRY_INVENTORY.md index e1a1218cbac..58eb70556df 100644 --- a/test/e2e/RETRY_INVENTORY.md +++ b/test/e2e/RETRY_INVENTORY.md @@ -16,7 +16,7 @@ Exhaustion remains failed. | `workflow-main-observer` | Completed `E2E main` run; `tools/e2e/main-run-retry.mts`, `.github/workflows/e2e-main-retry.yaml` | Any failed job | 0 automatic reruns | Not established at workflow scope | Test owner | `failed-no-retry`, `ignored`, `passed-first-attempt`, or `passed-after-retry` for a later manually requested rerun | Failed job names, non-skipped job count, runner minutes, and source SHA for each attempt | Broad rerun removed; operation-level evidence is required | | `hosted-runner-recovery` | Confirmed GitHub-hosted runner loss; `tools/e2e/hosted-runner-recovery.mts`, `tools/e2e/hosted-runner-loss*.mts` | Authenticated runner-allocation or internal-runner evidence that remains identical across 2 consecutive reads | 2 immediate evidence reads and at most 1 recovery request; no delay | GitHub reruns a workflow attempt | GitHub Actions | Dedicated runner-loss classifications | Source and recovery run links plus authenticated job evidence | External owner; governed by #7146, not this policy | | `pr-rerun-reconciliation` | PR E2E dispatch reconciliation; `tools/e2e/pr-e2e-dispatch-reconciliation.mts`, `tools/e2e/pr-e2e-retry-receipt.mts` | Trusted dispatch receipt state | Contract-defined single reconciliation | Reconciles workflow and commit identity before action | GitHub Actions | Receipt-specific terminal states | Signed workflow identity and receipt | External scope; governed by #7206 | -| `github-publication-read` | Publication and PR metadata reads; `tools/e2e/base-image-publication.mts`, `tools/e2e/pr-managed-image-source.mts` | Fetch error, 408, rate limit, or 5xx | 3 attempts; Retry-After/rate-limit reset or linear delay capped at 10s | Read-only | GitHub API | Returned publication or workload-source selection on success; thrown terminal HTTP/fetch error on failure or exhaustion | Caller records the publication selection or PR workload source; terminal errors identify exhausted fetch or HTTP status without response content | Eligible bounded read; existing implementation retained | +| `github-publication-read` | Publication and PR metadata reads; `tools/e2e/base-image-publication.mts`, `tools/e2e/pr-managed-image-source.mts` | Fetch error, HTTP 408, HTTP 5xx, HTTP 429, or HTTP 403 with `x-ratelimit-remaining: 0` | 3 attempts; Retry-After/rate-limit reset or linear delay capped at 10s | Read-only | GitHub API | Returned publication or workload-source selection on success; thrown terminal HTTP/fetch error on failure or exhaustion | Caller records the publication selection or PR workload source; terminal errors identify exhausted fetch or HTTP status without response content | Eligible bounded read; existing implementation retained | | `ghcr-pr-exact-digest-visibility` | Anonymous pull after same-repository PR publication; `scripts/checks/pull-public-exact-digest.sh`, `.github/workflows/managed-images.yaml` | Final nonempty Docker output line is exactly `ERROR: : not found`; every other Docker failure is terminal | 5 attempts; exponential 2s, 4s, 8s, then 16s | Read-only registry request for one immutable digest; any local image-cache write repeats the same content-addressed result | GHCR | `passed-first-attempt`, `passed-after-retry`, `failed-no-retry`, or `exhausted` | Sanitized outcome, attempt number, total attempts, retry delay or Docker exit status; raw Docker output, credentials, and environment values are excluded | Eligible bounded external read after the independently fetched manifest bytes match the publication digest; every non-exact failure remains terminal and no workflow rerun occurs | | `protected-managed-image-buildkit-transport` | One agent's exact protected managed-image `docker buildx build`; `scripts/checks/build-protected-managed-images.sh` | Final nonempty line exactly matches BuildKit's `ERROR: failed to build: failed to solve: stream error: stream ID ; INTERNAL_ERROR; received from peer`; every near-match and other Docker failure is terminal | 2 attempts; fixed 2s delay | Before retry, a read-only local registry `HEAD` request confirms that the isolated revision tag is absent. The script then repeats the same agent, inputs, revision tag, and content-addressed push. A present tag or any inconclusive registry result is terminal. Existing digest, registry-byte, and image-contract checks still gate success. | BuildKit transport | `passed-first-attempt`, `passed-after-retry`, `failed-no-retry`, or `exhausted` | Existing Docker attempt output remains in the job log. Sanitized job-log annotations retain the agent, attempt, outcome, retry delay or Docker exit status, failure class, and revision-tag state without image content. | Eligible bounded operation retry for the exact pre-export transport failure observed in #9763; repeated exact failure remains failed and no workflow rerun occurs | | `protected-managed-image-npm-registry-dns` | One agent's exact protected managed-image `docker buildx build`; `scripts/checks/build-protected-managed-images.sh` | One attempt line has an optional BuildKit step prefix, an elapsed-time field, and exact text `ERROR: curl failed: curl: (6) Could not resolve host: registry.npmjs.org`; every other curl exit, host, and near-match is terminal | 2 attempts; fixed 2s delay | Before retry, a read-only local registry `HEAD` request confirms that the isolated revision tag is absent. The script then repeats the same agent, inputs, revision tag, and content-addressed push. A present tag or any inconclusive registry result is terminal. Existing digest, registry-byte, and image-contract checks still gate success. | npm registry DNS | `passed-first-attempt`, `passed-after-retry`, `failed-no-retry`, or `exhausted` | Existing Docker attempt output remains in the job log. Sanitized job-log annotations retain the agent, attempt, outcome, retry delay or Docker exit status, failure class, and revision-tag state without image content. | Eligible bounded operation retry for the exact pre-export DNS failure observed in run 32621454757, job 97154036894; repeated exact failure remains failed and no workflow rerun occurs | diff --git a/test/e2e/support/pr-managed-image-source.test.ts b/test/e2e/support/pr-managed-image-source.test.ts index e3425cf3d3f..4599f955fce 100644 --- a/test/e2e/support/pr-managed-image-source.test.ts +++ b/test/e2e/support/pr-managed-image-source.test.ts @@ -188,6 +188,7 @@ describe("PR managed-image source selection", () => { expect(row).toContain("tools/e2e/pr-managed-image-source.mts"); expect(row).toContain("PR metadata reads"); expect(row).toContain("workload-source selection"); + expect(row).toContain("HTTP 429, or HTTP 403 with `x-ratelimit-remaining: 0`"); }); }); From 82206e4072267a9a887aeba0fdd859cba6c1c2ea Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 10:02:20 +0700 Subject: [PATCH 23/40] chore(mcp): leave provider revision fix to owning PR Signed-off-by: San Dang --- .../actions/sandbox/mcp-bridge-add-restart.ts | 14 ++------ .../sandbox/mcp-bridge-provider-readiness.ts | 33 ++---------------- .../sandbox/mcp-bridge-provider.test.ts | 34 ------------------- .../actions/sandbox/mcp-bridge-provider.ts | 1 - src/lib/actions/sandbox/mcp-bridge-restart.ts | 14 ++------ test/mcp/mcp-add-crash-consistency.test.ts | 27 --------------- 6 files changed, 8 insertions(+), 115 deletions(-) diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index 1d0838d0c9e..f8bcd7a5ff6 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -35,7 +35,6 @@ import { assertMcpProviderRecoverable, assertNoProviderCredentialCollisions, attachProvider, - credentialRevisionForProviderResourceVersion, deleteProvider, detachMissingProviderReference, detachProvider, @@ -436,23 +435,18 @@ async function addMcpBridgeUnlocked( providerAttachAttempted = true; attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, target); - let expectedCredentialRevision; if (Object.hasOwn(adapterEnvValues, entry.env[0])) { // OpenShell 0.0.106 can miss a credential update published before the // bound policy generation. Republish while that policy is active and // before the first readiness exec; the exact provider identity is // rechecked before and after this update-only mutation. - const republished = upsertMcpProvider(entry.providerName ?? "", options.env, { + upsertMcpProvider(entry.providerName ?? "", options.env, { allowExisting: true, expectedProviderId: entry.providerId, requireExisting: true, }); - expectedCredentialRevision = credentialRevisionForProviderResourceVersion( - republished.inspection.resourceVersion, - ); } const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { - expectedRevision: expectedCredentialRevision, ...(providerResult.action === "updated" ? { previousRevision: previousCredentialRevision, @@ -479,11 +473,7 @@ async function addMcpBridgeUnlocked( expectedProviderId: entry.providerId, requireExisting: true, }); - const synchronized = - republished.action === "updated" - ? republished.inspection - : refreshMcpProviderEnvironment(entry); - return credentialRevisionForProviderResourceVersion(synchronized.resourceVersion); + if (republished.action !== "updated") refreshMcpProviderEnvironment(entry); }, }); // The adapter was proven absent above, so cleanup is safe even when a diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts index 6bcabf73f4c..60eeadb8e73 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts @@ -13,7 +13,6 @@ import { import { executeSandboxExecCommand } from "./process-recovery"; const MCP_CREDENTIAL_REVISION_OBSERVATION_RE = /^(?:absent|canonical|v[0-9]{1,20})$/; -const MCP_ATTACHED_CREDENTIAL_REVISION_RE = /^v[0-9]{1,20}$/; export type McpCredentialRevisionObservation = "absent" | "canonical" | `v${number}`; export type McpAttachedCredentialRevision = Exclude< @@ -21,15 +20,6 @@ export type McpAttachedCredentialRevision = Exclude< "absent" | "canonical" >; -export function credentialRevisionForProviderResourceVersion( - resourceVersion: number | null, -): McpAttachedCredentialRevision { - if (!Number.isSafeInteger(resourceVersion) || (resourceVersion ?? 0) < 1) { - throw new McpBridgeError("OpenShell provider metadata has no valid credential revision."); - } - return `v${String(resourceVersion)}` as McpAttachedCredentialRevision; -} - type McpCredentialRevisionAttempt = | { kind: "observation"; observation: McpCredentialRevisionObservation } | { kind: "transport-unavailable" } @@ -157,9 +147,8 @@ export function waitForAttachedMcpCredential( sandboxName: string, entry: McpBridgeEntry, options: { - expectedRevision?: McpAttachedCredentialRevision; previousRevision?: McpCredentialRevisionObservation; - refreshAfterObservedAbsence?: () => McpAttachedCredentialRevision | void; + refreshAfterObservedAbsence?: () => void; } = {}, ): McpAttachedCredentialRevision { assertAuthenticatedBridgeEntry(entry); @@ -170,12 +159,6 @@ export function waitForAttachedMcpCredential( ) { throw new McpBridgeError("Invalid prior MCP credential revision observation."); } - if ( - options.expectedRevision !== undefined && - !MCP_ATTACHED_CREDENTIAL_REVISION_RE.test(options.expectedRevision) - ) { - throw new McpBridgeError("Invalid expected MCP credential revision."); - } const timeoutSeconds = Number.parseInt( process.env.NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS ?? "30", 10, @@ -183,7 +166,6 @@ export function waitForAttachedMcpCredential( let refreshedAfterObservedAbsence = false; let lastAttempt: McpCredentialRevisionAttempt = { kind: "transport-unavailable" }; let attachedRevision: McpAttachedCredentialRevision | undefined; - let expectedRevision = options.expectedRevision; const ready = waitForMcpBridgeCondition( () => { // Each exec is a fresh OpenShell process. Only the bounded placeholder @@ -198,14 +180,7 @@ export function waitForAttachedMcpCredential( options.refreshAfterObservedAbsence ) { refreshedAfterObservedAbsence = true; - const refreshedRevision = options.refreshAfterObservedAbsence(); - if ( - refreshedRevision !== undefined && - !MCP_ATTACHED_CREDENTIAL_REVISION_RE.test(refreshedRevision) - ) { - throw new McpBridgeError("Invalid refreshed MCP credential revision."); - } - expectedRevision = refreshedRevision ?? expectedRevision; + options.refreshAfterObservedAbsence(); attempt = tryObserveMcpCredentialRevision(sandboxName, envName); lastAttempt = attempt; } @@ -218,9 +193,7 @@ export function waitForAttachedMcpCredential( observation !== null && observation !== "absent" && observation !== "canonical" && - (expectedRevision !== undefined - ? observation === expectedRevision - : options.previousRevision === undefined || observation !== options.previousRevision); + (options.previousRevision === undefined || observation !== options.previousRevision); if (attached) attachedRevision = observation; return attached; }, diff --git a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts index bde0b8dbe0a..5bbdc2af88c 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts @@ -21,7 +21,6 @@ import { } from "./mcp-bridge-provider-inspection"; import { assertMcpProviderRecoverable, - credentialRevisionForProviderResourceVersion, observeMcpCredentialRevision, refreshMcpProviderEnvironment, waitForAttachedMcpCredential, @@ -84,16 +83,6 @@ Provider: expect(output).not.toMatch(/\[[0-9;]*m/); }); - it("maps a valid provider resource version to its credential revision", () => { - expect(credentialRevisionForProviderResourceVersion(12)).toBe("v12"); - expect(() => credentialRevisionForProviderResourceVersion(null)).toThrow( - "OpenShell provider metadata has no valid credential revision.", - ); - expect(() => credentialRevisionForProviderResourceVersion(0)).toThrow( - "OpenShell provider metadata has no valid credential revision.", - ); - }); - it("accepts an exact legacy generic provider only for cleanup", () => { const inspection = { exists: true, @@ -626,27 +615,4 @@ alpha-mcp-slack generic 1 0 ); expect(exec).toHaveBeenCalledTimes(1); }); - - it("waits for the credential revision from the final provider publication", () => { - const entry = { - server: "github", - agent: "openclaw", - adapter: "mcporter", - url: "https://mcp.example.test/mcp", - env: ["GITHUB_TOKEN"], - providerName: "alpha-mcp-github-0123456789abcdef", - providerId: "11111111-2222-4333-8444-555555555555", - policyName: "mcp-bridge-github", - addedAt: "2026-06-01T00:00:00.000Z", - }; - const exec = vi - .spyOn(processRecovery, "executeSandboxExecCommand") - .mockReturnValueOnce({ status: 0, stdout: "v11", stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: "v12", stderr: "" }); - - expect( - waitForAttachedMcpCredential("alpha", entry, { expectedRevision: "v12" }), - ).toBe("v12"); - expect(exec).toHaveBeenCalledTimes(2); - }); }); diff --git a/src/lib/actions/sandbox/mcp-bridge-provider.ts b/src/lib/actions/sandbox/mcp-bridge-provider.ts index 5f0a3fe9c93..42b991c6b10 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider.ts @@ -38,7 +38,6 @@ export type { McpCredentialRevisionObservation } from "./mcp-bridge-provider-rea export { buildMcpCredentialDetachedCommand, buildMcpCredentialRevisionObservationCommand, - credentialRevisionForProviderResourceVersion, observeMcpCredentialRevision, waitForAttachedMcpCredential, waitForDetachedMcpCredential, diff --git a/src/lib/actions/sandbox/mcp-bridge-restart.ts b/src/lib/actions/sandbox/mcp-bridge-restart.ts index da326ecfb29..bdee7dee3bf 100644 --- a/src/lib/actions/sandbox/mcp-bridge-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-restart.ts @@ -14,7 +14,6 @@ import { assertNoAttachedProviderCredentialCollisions, assertNoProviderCredentialCollisions, attachProvider, - credentialRevisionForProviderResourceVersion, detachMissingProviderReference, ensureMcpBridgeProviderProfile, refreshMcpProviderEnvironment, @@ -173,11 +172,8 @@ async function restartMcpBridgeUnlocked(sandboxName: string, server?: string): P } attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, target); - const synchronizedProvider = refreshMcpProviderEnvironment(entry); + refreshMcpProviderEnvironment(entry); const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { - expectedRevision: credentialRevisionForProviderResourceVersion( - synchronizedProvider.resourceVersion, - ), ...(providerResult.action === "updated" ? { previousRevision: previousCredentialRevision } : {}), @@ -245,12 +241,8 @@ export async function restoreExistingMcpBridgeRuntime( }); attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, resolvedTargetPins(resolvedByServer, entry)); - const synchronizedProvider = refreshMcpProviderEnvironment(entry); - const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { - expectedRevision: credentialRevisionForProviderResourceVersion( - synchronizedProvider.resourceVersion, - ), - }); + refreshMcpProviderEnvironment(entry); + const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry); const adapter = (entry.adapter as AgentMcpAdapter | undefined) ?? defaultAdapter; registerAgentAdapter( sandboxName, diff --git a/test/mcp/mcp-add-crash-consistency.test.ts b/test/mcp/mcp-add-crash-consistency.test.ts index 675258c2bac..a9099784655 100644 --- a/test/mcp/mcp-add-crash-consistency.test.ts +++ b/test/mcp/mcp-add-crash-consistency.test.ts @@ -18,7 +18,6 @@ type CrashBoundary = | "credential-collision" | "credential-command-race" | "credential-projection-coalesced" - | "credential-projection-delayed-final" | "credential-projection-delayed-hostless" | "registered-credential-collision" | "registered-late-collision" @@ -46,7 +45,6 @@ const path = require("node:path"); const crashAfter = ${JSON.stringify(crashAfter)}; if ( crashAfter === "credential-projection-coalesced" || - crashAfter === "credential-projection-delayed-final" || crashAfter === "credential-projection-delayed-hostless" ) { process.env.NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS = "2"; @@ -68,7 +66,6 @@ let credentialRepublishBeforeObservationCountThisProcess = 0; let credentialRepublishAfterAbsenceCountThisProcess = 0; let credentialFreeRefreshBeforeObservationCountThisProcess = 0; let credentialFreeRefreshAfterAbsenceCountThisProcess = 0; -let credentialObservationCountThisProcess = 0; const registry = require("./src/lib/state/registry.js"); const providerCommands = require("./src/lib/adapters/openshell/provider-command.js"); @@ -261,14 +258,6 @@ processRecovery.executeSandboxExecCommand = (_sandbox, command) => { stderr: "", }; } - if (crashAfter === "credential-projection-delayed-final" && isObservation) { - credentialObservationCountThisProcess += 1; - return { - status: 0, - stdout: credentialObservationCountThisProcess === 1 ? "v1" : "v" + providerVersion(), - stderr: "", - }; - } return { status: crashAfter === "preupdate-observation-forbidden" && isPreupdateObservation ? 1 : 0, stdout: isObservation ? (marked("updated") ? "v" + providerVersion() : marked("provider") ? "v1" : "absent") : "", @@ -281,9 +270,6 @@ processRecovery.executeSandboxCommand = (_sandbox, command) => { } if (command.includes("config' 'add") || command.includes('"config", "add"')) { mark("adapter"); - if (command.includes("openshell:resolve:env:v2_FAKE_MCP_SECRET")) { - mark("adapter-final-revision"); - } if (crashAfter === "adapter") process.exit(86); return { status: 0, stdout: "", stderr: "" }; } @@ -725,19 +711,6 @@ describe("MCP add crash consistency", () => { } }); - it("registers the revision from the final provider publication", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-add-final-revision-")); - try { - const result = runAddProcess(home, "credential-projection-delayed-final"); - - expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); - expect(fs.existsSync(path.join(home, "adapter-final-revision.marker"))).toBe(true); - expect(readBridge(home).addState).toBeUndefined(); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); - it("resumes an exact provider without a host credential or prior revision observation", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-add-reuse-no-observation-")); try { From 66fd3ed33534befb4203256c35ba4006d4f80d04 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 10:03:27 +0700 Subject: [PATCH 24/40] chore(onboard): leave pairing settlement unchanged Signed-off-by: San Dang --- .../onboard/machine/finalization-deps.test.ts | 19 +++---- src/lib/onboard/machine/finalization-deps.ts | 53 +++++++------------ 2 files changed, 28 insertions(+), 44 deletions(-) diff --git a/src/lib/onboard/machine/finalization-deps.test.ts b/src/lib/onboard/machine/finalization-deps.test.ts index 21aff1c9e09..9cadcb507ea 100644 --- a/src/lib/onboard/machine/finalization-deps.test.ts +++ b/src/lib/onboard/machine/finalization-deps.test.ts @@ -113,7 +113,7 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); - it("waits for canonical pairing before running the one request producer (#10014)", async () => { + it("runs the canonical request probe before waiting for fresh pairing (#10014)", async () => { const observePairing = vi .fn(() => SCOPE_UPGRADE_PENDING) .mockImplementationOnce(() => { @@ -135,7 +135,7 @@ describe("ordinary OpenClaw pairing settlement", () => { kind: "settled", }); - expect(scope.calls).toEqual(["warmup", "approval"]); + expect(scope.calls).toEqual(["warmup", "sleep", "approval"]); expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); }); @@ -406,7 +406,9 @@ describe("ordinary OpenClaw pairing settlement", () => { throw new Error("not published"); }; const scope = ordinaryPairingDeps({ - observePairing: vi.fn(() => (attempts++ < 10 ? unavailable() : SCOPE_UPGRADE_PENDING)), + observePairing: vi.fn(() => + attempts++ < 10 ? unavailable() : SCOPE_UPGRADE_PENDING, + ), }); await expect(settleOrdinaryOpenClawPairing("alpha", scope.deps)).resolves.toEqual({ @@ -414,7 +416,7 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "scope-upgrade-incomplete", }); expect(scope.deps.sleep).toHaveBeenCalledTimes(39); - expect(scope.deps.runWarmup).not.toHaveBeenCalled(); + expect(scope.deps.runWarmup).toHaveBeenCalledOnce(); expect(scope.deps.runApproval).toHaveBeenCalledOnce(); }); @@ -434,7 +436,6 @@ describe("ordinary OpenClaw pairing settlement", () => { .mockImplementationOnce(() => { throw new Error("not pending"); }) - .mockReturnValueOnce(PAIRING_ONLY) .mockReturnValueOnce(SCOPE_UPGRADE_PENDING) .mockReturnValue(SETTLED), runWarmup: vi.fn(() => { @@ -451,7 +452,7 @@ describe("ordinary OpenClaw pairing settlement", () => { expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); - expect(scope.deps.observePairing).toHaveBeenCalledTimes(5); + expect(scope.deps.observePairing).toHaveBeenCalledTimes(4); expect(now).toBe( OPENCLAW_PAIRING_OBSERVATION_TIMEOUT_MS + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS - @@ -488,11 +489,11 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "pairing-unavailable", }); expect(scope.deps.sleep).not.toHaveBeenCalled(); - expect(scope.deps.runWarmup).not.toHaveBeenCalled(); + expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).not.toHaveBeenCalled(); }); - it("does not run a request producer without a canonical CLI pairing (#9844)", async () => { + it("performs one request-producer write when a canonical CLI pairing never appears (#9844)", async () => { const scope = ordinaryPairingDeps({ observePairing: vi.fn(() => { throw new Error("not published"); @@ -504,7 +505,7 @@ describe("ordinary OpenClaw pairing settlement", () => { reason: "pairing-unavailable", }); - expect(scope.deps.runWarmup).not.toHaveBeenCalled(); + expect(scope.deps.runWarmup).toHaveBeenCalledExactlyOnceWith("alpha", "nemoclaw"); expect(scope.deps.runApproval).not.toHaveBeenCalled(); }); diff --git a/src/lib/onboard/machine/finalization-deps.ts b/src/lib/onboard/machine/finalization-deps.ts index c4f51c32bf5..55d323f53ea 100644 --- a/src/lib/onboard/machine/finalization-deps.ts +++ b/src/lib/onboard/machine/finalization-deps.ts @@ -155,7 +155,9 @@ function defaultPairingSettlementDeps(): OrdinaryOpenClawPairingSettlementDeps { .loadPairingQualification() .observeOrdinaryOpenClawPairingSettlement(...args), runWarmup: (name, gatewayName) => - finalizationHandlerRuntime.loadAutoPairWarmup().runSandboxScopeWarmupRun(name, gatewayName), + finalizationHandlerRuntime + .loadAutoPairWarmup() + .runSandboxScopeWarmupRun(name, gatewayName), runApproval: (name, gatewayName) => { finalizationHandlerRuntime.loadAutoPairApproval().runSandboxAutoPairApprovalPass(name, { budget: { @@ -220,7 +222,7 @@ export async function settleOrdinaryOpenClawPairing( ); sawCanonicalPairing = true; } catch { - // Pairing may not have appeared yet; the bounded observer handles that path. + // Pairing may not have appeared yet; the producer handles that path. } if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; @@ -230,36 +232,14 @@ export async function settleOrdinaryOpenClawPairing( } if (initial?.state === "settled") return { kind: "settled" }; - const pairingAppearanceDeadline = Math.min( - settlementDeadline, - deps.now() + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS, - ); - let baseline: PairingWaitResult = initial - ? { kind: "observed", value: initial } - : await waitForPairingObservation( - name, - target, - pairingAppearanceDeadline, - (value) => { - sawCanonicalPairing = true; - return true; - }, - deps, - ); - if (baseline.kind === "target-changed") { - return { kind: "incomplete", reason: "runtime-identity-invalid" }; - } - if (baseline.kind === "timeout") { - return { kind: "incomplete", reason: "pairing-unavailable" }; - } - if (baseline.value.state === "settled") return { kind: "settled" }; - - if (baseline.value.state === "pairing-only") { - // Wait for the startup watcher to publish the canonical CLI - // pairing before issuing the one bounded write-scope producer. - // Running the producer before that identity exists can create no - // upgrade and leaves an otherwise healthy fresh onboard stuck at - // pairing-only (#10014). + let baseline: PairingWaitResult; + if (initial?.state === "scope-upgrade-pending") { + baseline = { kind: "observed", value: initial }; + } else { + // A valid non-interactive path can reach finalization before the + // startup watcher publishes its first CLI request. Run the bounded + // direct producer once, then require canonical evidence that its + // exact write upgrade is pending before the approval pass (#10014). try { await deps.runWarmup(name, target.gatewayName); } catch { @@ -268,14 +248,14 @@ export async function settleOrdinaryOpenClawPairing( if (!samePairingTarget(target, deps.getTarget(name))) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } - const scopeUpgradeDeadline = Math.min( + const pairingAppearanceDeadline = Math.min( settlementDeadline, deps.now() + OPENCLAW_ONBOARDING_PAIRING_TIMEOUT_MS, ); baseline = await waitForPairingObservation( name, target, - scopeUpgradeDeadline, + pairingAppearanceDeadline, (value) => { sawCanonicalPairing = true; return value.state !== "pairing-only"; @@ -292,7 +272,10 @@ export async function settleOrdinaryOpenClawPairing( reason: sawCanonicalPairing ? "scope-upgrade-incomplete" : "pairing-unavailable", }; } - if (initial && baseline.value.deviceIdentitySha256 !== initial.deviceIdentitySha256) { + if ( + initial && + baseline.value.deviceIdentitySha256 !== initial.deviceIdentitySha256 + ) { return { kind: "incomplete", reason: "runtime-identity-invalid" }; } if (baseline.value.state === "settled") return { kind: "settled" }; From b6f45b2ddd160f5fab029e0f45afebc100c6e24b Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 10:22:53 +0700 Subject: [PATCH 25/40] fix(e2e): preserve local base identity on GPU Signed-off-by: San Dang --- .github/workflows/e2e.yaml | 188 +++++++++++++++--- test/e2e/README.md | 21 +- ...d-image-protected-runtime-workflow.test.ts | 25 ++- ...aged-image-multiarch-workflow-boundary.mts | 12 +- ...ge-protected-runtime-workflow-boundary.mts | 34 +++- 5 files changed, 232 insertions(+), 48 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index b588f5cfc98..625387afc2b 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -4014,6 +4014,7 @@ jobs: NEMOCLAW_PROTECTED_MANAGED_IMAGE_BASE_SHA: ${{ inputs.base_sha || github.event.before || github.sha }} NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE: ${{ github.workspace }}/.protected-managed-image-build-cache/${{ matrix.shard }} NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE_ARTIFACT: protected-managed-image-build-cache-${{ github.run_id }}-${{ inputs.checkout_sha || github.sha }} + NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT: ${{ github.workspace }}/.protected-managed-image-build-cache/${{ matrix.shard }}/local-bases.json NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT: protected-${{ github.run_id }}-${{ github.run_attempt }} NEMOCLAW_PROTECTED_MANAGED_IMAGE_CONTRACT: ${{ github.workspace }}/e2e-artifacts/live/managed-image-multiarch-startup/${{ matrix.shard }}/contracts.json NEMOCLAW_PROTECTED_MANAGED_IMAGE_EVIDENCE: ${{ github.workspace }}/e2e-artifacts/live/managed-image-multiarch-startup/${{ matrix.shard }}/evidence.json @@ -4199,6 +4200,12 @@ jobs: local dockerfile="$2" local repository="$3" local metadata="$work_dir/${output_name}-build.json" + local cache_args=() + if [[ "$PLATFORM" == "linux/amd64" ]]; then + local cache_destination="$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/local-bases/${output_name}" + install -d -m 0700 "$(dirname "$cache_destination")" + cache_args=(--cache-to "type=local,dest=${cache_destination},mode=max") + fi scripts/check-production-build-args.sh -f "$dockerfile" docker buildx build \ --file "$dockerfile" \ @@ -4209,6 +4216,7 @@ jobs: --metadata-file "$metadata" \ --tag "${repository}:${CHECKOUT_SHA}" \ --label "org.opencontainers.image.revision=${CHECKOUT_SHA}" \ + "${cache_args[@]}" \ . local digest digest="$(jq -er '."containerimage.digest"' "$metadata")" @@ -4231,6 +4239,29 @@ jobs: build_local_base openclaw Dockerfile.base "${base_registry}/sandbox-base" build_local_base hermes agents/hermes/Dockerfile.base "${base_registry}/hermes-sandbox-base" build_local_base dcode agents/langchain-deepagents-code/Dockerfile.base "${base_registry}/langchain-deepagents-code-sandbox-base" + if [[ "$PLATFORM" == "linux/amd64" ]]; then + install -d -m 0700 "$(dirname "$NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT")" + jq -n \ + --arg dcode "$(jq -er '."containerimage.digest"' "$work_dir/dcode-build.json")" \ + --arg hermes "$(jq -er '."containerimage.digest"' "$work_dir/hermes-build.json")" \ + --arg openclaw "$(jq -er '."containerimage.digest"' "$work_dir/openclaw-build.json")" \ + --arg platform "$PLATFORM" \ + --arg revision "$CHECKOUT_SHA" \ + '{ + kind: "nemoclaw-protected-local-bases-v1", + revision: $revision, + platform: $platform, + bases: { + openclaw: {dockerfile: "Dockerfile.base", digest: $openclaw}, + hermes: {dockerfile: "agents/hermes/Dockerfile.base", digest: $hermes}, + dcode: {dockerfile: "agents/langchain-deepagents-code/Dockerfile.base", digest: $dcode} + } + }' > "${NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT}.tmp" + chmod 0600 "${NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT}.tmp" + mv \ + "${NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT}.tmp" \ + "$NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT" + fi exit 0 ;; managed-image) ;; @@ -4706,8 +4737,11 @@ jobs: # sourceBoundary: The hosted amd64 lane builds the exact candidate. It adds # every reachable Linux x64 glibc registry archive from the candidate # lockfile to the same-run cache artifact. The GPU lane verifies the manifest, - # lock digest, archive set, and - # each SHA-512 integrity before the candidate build can consume the seed. + # lock digest, archive set, and each SHA-512 integrity before the candidate + # build can consume the seed. For local Dockerfile selection, the artifact + # also carries each candidate base digest and BuildKit cache. The GPU lane + # rebuilds those bases without network access and requires exact digest + # equality before it builds or qualifies the managed images. # BuildKit records can accelerate the rebuild, while the seed makes a missing # npm layer reproducible without weakening the fail-closed network boundary. # whyNotBuildCacheOnly: Protected runs 31156103003, 31158136234, and @@ -4735,7 +4769,7 @@ jobs: E2E_AGENT_RUNTIME: "openclaw + hermes + langchain-deepagents-code" E2E_OBSERVABLE_OUTCOME: "Protected GPU runtime supports Ollama vLLM NIM rollback and cleanup" E2E_ENVIRONMENT_OR_INFERENCE_ENDPOINT: "NVIDIA GPU runner; local and hosted inference services" - E2E_WORKLOAD_SOURCE: "managed-image" + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} RELEASE_E2E_ACTIVATION_PATH: ci/protected-managed-image-runtime-activation-v1.json NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js NEMOCLAW_E2E_EXPECTED_SHA: ${{ inputs.checkout_sha }} @@ -4745,6 +4779,7 @@ jobs: NEMOCLAW_PROTECTED_MANAGED_IMAGE_BASE_SHA: ${{ inputs.base_sha || github.event.before || github.sha }} NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE: ${{ github.workspace }}/.protected-managed-image-build-cache/linux-amd64 NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE_ARTIFACT: protected-managed-image-build-cache-${{ github.run_id }}-${{ inputs.checkout_sha || github.sha }} + NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT: ${{ github.workspace }}/.protected-managed-image-build-cache/linux-amd64/local-bases.json NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT: protected-${{ github.run_id }}-${{ github.run_attempt }} NEMOCLAW_PROTECTED_MANAGED_IMAGE_CONTRACT: ${{ github.workspace }}/e2e-artifacts/live/managed-image-protected-runtime/contracts.json NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM: linux/amd64 @@ -4848,8 +4883,36 @@ jobs: } install -d -m 0700 "$E2E_ARTIFACT_DIR" + - name: Start isolated protected runtime registry + shell: bash + run: | + set -euo pipefail + if docker container inspect "$NEMOCLAW_PROTECTED_REGISTRY_NAME" >/dev/null 2>&1; then + echo "::error::Protected runtime registry name already exists" >&2 + exit 1 + fi + if curl --fail --silent --show-error http://127.0.0.1:5000/v2/ >/dev/null 2>&1; then + echo "::error::Refusing to reuse an existing localhost:5000 registry" >&2 + exit 1 + fi + docker run --detach \ + --name "$NEMOCLAW_PROTECTED_REGISTRY_NAME" \ + --label "io.nvidia.nemoclaw.e2e-owner=${NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT}" \ + --label "io.nvidia.nemoclaw.e2e-platform=linux/amd64" \ + --publish 127.0.0.1:5000:5000 \ + docker.io/library/registry@sha256:a3d8aaa63ed8681a604f1dea0aa03f100d5895b6a58ace528858a7b332415373 + for _ in $(seq 1 30); do + if curl --fail --silent --show-error http://127.0.0.1:5000/v2/ >/dev/null; then + exit 0 + fi + sleep 1 + done + docker logs "$NEMOCLAW_PROTECTED_REGISTRY_NAME" >&2 + exit 1 + - id: runtime-hermes-base name: Resolve reviewed Hermes runtime base image + if: ${{ needs.generate-matrix.outputs.workload_source == 'managed-image' }} uses: ./.github/actions/resolve-reviewed-hermes-platform with: dockerfile-path: .candidate-runtime/agents/hermes/Dockerfile @@ -4858,13 +4921,57 @@ jobs: - id: runtime-bases name: Resolve exact amd64 runtime base images env: + CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} DCODE_BASE_REF: ${{ needs.base-image-publication.outputs.dcode_base_ref }} + HERMES_BASE_DIGEST: ${{ steps.runtime-hermes-base.outputs.digest }} + WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} shell: bash run: | set -euo pipefail + candidate_root="$GITHUB_WORKSPACE/.candidate-runtime" work_dir="$(mktemp -d "${RUNNER_TEMP}/nemoclaw-runtime-bases.XXXXXX")" trap 'rm -rf -- "$work_dir"' EXIT + rebuild_local_base() { + local output_name="$1" + local dockerfile="$2" + local repository="$3" + local expected_digest + expected_digest="$(jq -er --arg name "$output_name" '.bases[$name].digest' "$NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT")" + local cache_source="$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/local-bases/${output_name}" + [[ -d "$cache_source" && ! -L "$cache_source" && -f "$cache_source/index.json" && ! -L "$cache_source/index.json" ]] || { + echo "::error::${output_name} local base cache is missing or invalid" >&2 + exit 1 + } + local metadata="$work_dir/${output_name}-build.json" + scripts/check-production-build-args.sh -f "$candidate_root/$dockerfile" + docker buildx build \ + --file "$candidate_root/$dockerfile" \ + --platform linux/amd64 \ + --push \ + --provenance=false \ + --sbom=false \ + --network=none \ + --cache-from "type=local,src=${cache_source}" \ + --metadata-file "$metadata" \ + --tag "${repository}:${CHECKOUT_SHA}" \ + --label "org.opencontainers.image.revision=${CHECKOUT_SHA}" \ + "$candidate_root" + local actual_digest + actual_digest="$(jq -er '."containerimage.digest"' "$metadata")" + [[ "$actual_digest" == "$expected_digest" ]] || { + echo "::error::${output_name} protected runtime base digest does not match the hosted candidate build" >&2 + exit 1 + } + local reference="${repository}@${actual_digest}" + docker buildx imagetools inspect "$reference" --raw > "$work_dir/${output_name}-local.raw" + [[ "sha256:$(sha256sum "$work_dir/${output_name}-local.raw" | awk '{print $1}')" == "$actual_digest" ]] || { + echo "::error::${output_name} protected runtime base bytes do not match the candidate digest" >&2 + exit 1 + } + printf '%s=%s\n' "$output_name" "$reference" >> "$GITHUB_OUTPUT" + } + resolve_base() { local output_name="$1" local alias="$2" @@ -4899,9 +5006,55 @@ jobs: printf '%s=%s\n' "$output_name" "$reference" >> "$GITHUB_OUTPUT" } + case "$WORKLOAD_SOURCE" in + local-dockerfile) + [[ -f "$NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT" && ! -L "$NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT" ]] || { + echo "::error::Protected local base identity contract is missing or invalid" >&2 + exit 1 + } + jq -e --arg revision "$CHECKOUT_SHA" ' + (keys | sort) == ["bases", "kind", "platform", "revision"] and + .kind == "nemoclaw-protected-local-bases-v1" and + .revision == $revision and + .platform == "linux/amd64" and + (.bases | keys | sort) == ["dcode", "hermes", "openclaw"] and + .bases.openclaw.dockerfile == "Dockerfile.base" and + .bases.hermes.dockerfile == "agents/hermes/Dockerfile.base" and + .bases.dcode.dockerfile == "agents/langchain-deepagents-code/Dockerfile.base" and + all(.bases[]; + (keys | sort) == ["digest", "dockerfile"] and + (.digest | test("^sha256:[a-f0-9]{64}$")) + ) + ' "$NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT" >/dev/null || { + echo "::error::Protected local base identity contract does not match the candidate" >&2 + exit 1 + } + base_registry="localhost:5000/nemoclaw-managed-protected-base" + rebuild_local_base openclaw Dockerfile.base "${base_registry}/sandbox-base" + rebuild_local_base hermes agents/hermes/Dockerfile.base "${base_registry}/hermes-sandbox-base" + rebuild_local_base dcode agents/langchain-deepagents-code/Dockerfile.base "${base_registry}/langchain-deepagents-code-sandbox-base" + install -m 0600 \ + "$NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT" \ + "$E2E_ARTIFACT_DIR/local-bases.json" + exit 0 + ;; + managed-image) ;; + *) + echo "::error::Protected runtime workload source is invalid" >&2 + exit 1 + ;; + esac + resolve_base openclaw \ ghcr.io/nvidia/nemoclaw/sandbox-base:latest \ ghcr.io/nvidia/nemoclaw/sandbox-base + [[ "$HERMES_BASE_DIGEST" =~ ^sha256:[a-f0-9]{64}$ ]] || { + echo "::error::Hermes reviewed runtime base resolver returned an invalid digest" >&2 + exit 1 + } + printf 'hermes=%s\n' \ + "ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${HERMES_BASE_DIGEST}" \ + >> "$GITHUB_OUTPUT" [[ "$DCODE_BASE_REF" =~ ^ghcr[.]io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@sha256:[a-f0-9]{64}$ ]] || { echo "::error::dcode base publication returned an invalid exact reference" >&2 exit 1 @@ -4914,37 +5067,10 @@ jobs: } printf 'dcode=%s\n' "$DCODE_BASE_REF" >> "$GITHUB_OUTPUT" - - name: Start isolated protected runtime registry - shell: bash - run: | - set -euo pipefail - if docker container inspect "$NEMOCLAW_PROTECTED_REGISTRY_NAME" >/dev/null 2>&1; then - echo "::error::Protected runtime registry name already exists" >&2 - exit 1 - fi - if curl --fail --silent --show-error http://127.0.0.1:5000/v2/ >/dev/null 2>&1; then - echo "::error::Refusing to reuse an existing localhost:5000 registry" >&2 - exit 1 - fi - docker run --detach \ - --name "$NEMOCLAW_PROTECTED_REGISTRY_NAME" \ - --label "io.nvidia.nemoclaw.e2e-owner=${NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT}" \ - --label "io.nvidia.nemoclaw.e2e-platform=linux/amd64" \ - --publish 127.0.0.1:5000:5000 \ - docker.io/library/registry@sha256:a3d8aaa63ed8681a604f1dea0aa03f100d5895b6a58ace528858a7b332415373 - for _ in $(seq 1 30); do - if curl --fail --silent --show-error http://127.0.0.1:5000/v2/ >/dev/null; then - exit 0 - fi - sleep 1 - done - docker logs "$NEMOCLAW_PROTECTED_REGISTRY_NAME" >&2 - exit 1 - - name: Build exact all-agent protected runtime images env: BASE_DCODE: ${{ steps.runtime-bases.outputs.dcode }} - BASE_HERMES: ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.runtime-hermes-base.outputs.digest }} + BASE_HERMES: ${{ steps.runtime-bases.outputs.hermes }} BASE_OPENCLAW: ${{ steps.runtime-bases.outputs.openclaw }} CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} shell: bash diff --git a/test/e2e/README.md b/test/e2e/README.md index 10d2ebde31a..4f7a2f87125 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -90,16 +90,17 @@ After the checks pass, the action restores root `dist/` and `nemoclaw/dist/share If the version command fails, the action stops before the live test runs. This boundary keeps candidate source separate from the trusted workflow implementation. -For a same-repository PR that changes a managed-image workflow path, the trusted planner also -requires one successful `Images / Build, Test, and Publish Managed Images` run for the candidate commit. Before candidate -checkout, the planner downloads the three nonexpired contract artifacts by immutable artifact ID. -It verifies each artifact digest, producer run, attempt, and candidate commit. The planner rejects a -missing, incomplete, or mixed all-agent publication before E2E jobs start. - -The planner adds the exact all-agent catalog to `dist/` after the candidate CLI build completes. -Each live E2E consumer verifies that the catalog source revision matches `checkout_sha`. A PR that -does not change a managed-image workflow path keeps the released catalog behavior. The GitHub token -is available only to the trusted planner job and is not included in the candidate CLI artifact. +For a manual PR run, the trusted planner compares the changed files with the +base-image and managed-image input paths. When those inputs are unchanged, the +run uses the applicable trusted managed-image publication from `main`. When any +input changed, the run builds the candidate Dockerfiles locally instead of +waiting for a candidate publication. + +The native startup jobs build the local candidate bases for each platform. The +AMD64 producer passes their exact digests and build caches to the protected GPU +job. That job rebuilds with networking disabled and rejects any digest mismatch +before it runs Ollama, NIM, or vLLM qualification. The GitHub token is available +only to the trusted planner and is not included in the candidate CLI artifact. The same-repository `Images / Build, Test, and Publish Managed Images` PR workflow also runs the OpenClaw managed-image MCP discovery and lifecycle scope in two independent matrix jobs. Each job assembles one exact candidate diff --git a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts index b1a24aaccba..3d4e8539d82 100644 --- a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts +++ b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts @@ -54,7 +54,7 @@ describe("protected managed-image runtime workflow", () => { expect(validateManagedImageProtectedRuntimeWorkflow(workflow())).toEqual([]); }); - it("accepts the hosted build-cache handoff to the protected runtime job", () => { + it("accepts the hosted cache and local-base identity handoff", () => { const value = workflow(); expect(validateManagedImageMultiarchWorkflow(value)).toEqual([]); @@ -371,6 +371,29 @@ describe("protected managed-image runtime workflow", () => { ); }); + it("rejects a protected local-base rebuild without exact producer digest equality", () => { + const value = workflow(); + const bases = namedStep(value, "Resolve exact amd64 runtime base images"); + bases.run = String(bases.run).replace('[[ "$actual_digest" == "$expected_digest" ]]', ""); + + expect(validateManagedImageProtectedRuntimeWorkflow(value)).toContain( + 'managed-image-protected-runtime step \'Resolve exact amd64 runtime base images\' must include [[ "$actual_digest" == "$expected_digest" ]]', + ); + }); + + it("requires the hosted producer to publish the local-base identity contract", () => { + const value = workflow(); + const bases = namedMultiarchStep(value, "Resolve exact platform base images"); + bases.run = String(bases.run).replace( + 'kind: "nemoclaw-protected-local-bases-v1"', + 'kind: "unbound-local-bases"', + ); + + expect(validateManagedImageMultiarchWorkflow(value)).toContain( + "managed-image-multiarch-startup step 'Resolve exact platform base images' must include kind: \"nemoclaw-protected-local-bases-v1\"", + ); + }); + it("rejects a hosted producer that is not selected with protected runtime", () => { const value = workflow(); multiarchJob(value).if = diff --git a/tools/e2e/managed-image-multiarch-workflow-boundary.mts b/tools/e2e/managed-image-multiarch-workflow-boundary.mts index 2a298f0cc07..fbcb9f32bfa 100644 --- a/tools/e2e/managed-image-multiarch-workflow-boundary.mts +++ b/tools/e2e/managed-image-multiarch-workflow-boundary.mts @@ -164,6 +164,8 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): "${{ github.workspace }}/.protected-managed-image-build-cache/${{ matrix.shard }}", NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE_ARTIFACT: "protected-managed-image-build-cache-${{ github.run_id }}-${{ inputs.checkout_sha || github.sha }}", + NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT: + "${{ github.workspace }}/.protected-managed-image-build-cache/${{ matrix.shard }}/local-bases.json", NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT: "protected-${{ github.run_id }}-${{ github.run_attempt }}", NEMOCLAW_PROTECTED_MANAGED_IMAGE_HEAD_SHA: "${{ inputs.checkout_sha || github.sha }}", @@ -268,7 +270,9 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): ]); const hermesBase = requireStep(errors, steps, "Resolve reviewed Hermes platform base image"); - if (hermesBase?.if !== "${{ needs.generate-matrix.outputs.workload_source == 'managed-image' }}") { + if ( + hermesBase?.if !== "${{ needs.generate-matrix.outputs.workload_source == 'managed-image' }}" + ) { errors.push(`${JOB_ID} must resolve the reviewed Hermes base only for managed images`); } if (hermesBase?.uses !== REVIEWED_HERMES_PLATFORM_ACTION) { @@ -306,17 +310,21 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): 'arch="${PLATFORM#linux/}"', 'case "$WORKLOAD_SOURCE" in', "local-dockerfile)", + "Protected managed-image workload source is invalid", "build_local_base openclaw Dockerfile.base", "build_local_base hermes agents/hermes/Dockerfile.base", "build_local_base dcode agents/langchain-deepagents-code/Dockerfile.base", '--platform "$PLATFORM"', + "--push", + '--cache-to "type=local,dest=${cache_destination},mode=max"', '--tag "${repository}:${CHECKOUT_SHA}"', '--label "org.opencontainers.image.revision=${CHECKOUT_SHA}"', 'digest="$(jq -er \'."containerimage.digest"\' "$metadata")"', 'reference="${repository}@${digest}"', + 'kind: "nemoclaw-protected-local-bases-v1"', + '"${NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT}.tmp"', 'docker buildx imagetools inspect "$alias" --raw', '.platform.os == "linux" and .platform.architecture == $arch', - 'reference="${repository}@${digest}"', '"sha256:$(sha256sum "$exact_raw" | awk \'{print $1}\')" == "$digest"', "ghcr.io/nvidia/nemoclaw/sandbox-base:latest", '"ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${HERMES_BASE_DIGEST}"', diff --git a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts index e7031afd020..ffb0a3e8291 100644 --- a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts +++ b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts @@ -122,7 +122,7 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR E2E_ARTIFACT_DIR: "${{ github.workspace }}/e2e-artifacts/live/managed-image-protected-runtime", E2E_JOB: "1", E2E_TARGET_ID: JOB_ID, - E2E_WORKLOAD_SOURCE: "managed-image", + E2E_WORKLOAD_SOURCE: "${{ needs.generate-matrix.outputs.workload_source }}", RELEASE_E2E_ACTIVATION_PATH: ACTIVATION_PATH, NEMOCLAW_E2E_EXPECTED_SHA: "${{ inputs.checkout_sha }}", NEMOCLAW_E2E_SHARD: "linux-amd64-gpu", @@ -134,6 +134,8 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR "${{ github.workspace }}/.protected-managed-image-build-cache/linux-amd64", NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE_ARTIFACT: "protected-managed-image-build-cache-${{ github.run_id }}-${{ inputs.checkout_sha || github.sha }}", + NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT: + "${{ github.workspace }}/.protected-managed-image-build-cache/linux-amd64/local-bases.json", NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT: "protected-${{ github.run_id }}-${{ github.run_attempt }}", NEMOCLAW_PROTECTED_MANAGED_IMAGE_CONTRACT: @@ -264,6 +266,11 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR workflowSteps, "Resolve reviewed Hermes runtime base image", ); + if ( + hermesBase?.if !== "${{ needs.generate-matrix.outputs.workload_source == 'managed-image' }}" + ) { + errors.push(`${JOB_ID} must resolve the reviewed Hermes base only for managed images`); + } if (hermesBase?.uses !== REVIEWED_HERMES_PLATFORM_ACTION) { errors.push(`${JOB_ID} must use the shared reviewed Hermes platform resolver`); } @@ -274,9 +281,29 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR const bases = requireStep(errors, workflowSteps, "Resolve exact amd64 runtime base images"); requireValues(errors, `${JOB_ID} runtime base env`, record(bases?.env), { + CHECKOUT_SHA: "${{ inputs.checkout_sha || github.sha }}", DCODE_BASE_REF: "${{ needs.base-image-publication.outputs.dcode_base_ref }}", + HERMES_BASE_DIGEST: "${{ steps.runtime-hermes-base.outputs.digest }}", + WORKLOAD_SOURCE: "${{ needs.generate-matrix.outputs.workload_source }}", }); requireFragments(errors, bases, [ + 'case "$WORKLOAD_SOURCE" in', + "local-dockerfile)", + "Protected runtime workload source is invalid", + '[[ -f "$NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT" && ! -L "$NEMOCLAW_PROTECTED_LOCAL_BASE_CONTRACT" ]]', + 'kind == "nemoclaw-protected-local-bases-v1"', + ".revision == $revision", + '--file "$candidate_root/$dockerfile"', + "--platform linux/amd64", + "--push", + "--network=none", + '--cache-from "type=local,src=${cache_source}"', + 'actual_digest="$(jq -er \'."containerimage.digest"\' "$metadata")"', + '[[ "$actual_digest" == "$expected_digest" ]]', + "rebuild_local_base openclaw Dockerfile.base", + "rebuild_local_base hermes agents/hermes/Dockerfile.base", + "rebuild_local_base dcode agents/langchain-deepagents-code/Dockerfile.base", + '"$E2E_ARTIFACT_DIR/local-bases.json"', 'docker buildx imagetools inspect "$alias" --raw', '.platform.os == "linux" and .platform.architecture == "amd64"', 'reference="${repository}@${digest}"', @@ -319,8 +346,7 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR '--dcode-base "$BASE_DCODE"', ]); requireValues(errors, `${JOB_ID} protected runtime build bases`, record(build?.env), { - BASE_HERMES: - "ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.runtime-hermes-base.outputs.digest }}", + BASE_HERMES: "${{ steps.runtime-bases.outputs.hermes }}", }); const install = requireStep(errors, workflowSteps, "Install OpenShell CLI"); @@ -382,9 +408,9 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR "Download exact protected runtime build cache", "Prepare E2E workspace", "Validate protected runtime activation contract", + "Start isolated protected runtime registry", "Resolve reviewed Hermes runtime base image", "Resolve exact amd64 runtime base images", - "Start isolated protected runtime registry", "Build exact all-agent protected runtime images", "Install OpenShell CLI", "Run all-agent GPU, local inference, rollback, and cleanup qualification", From 272b372649b18cddece6e2851ab0baa0ad761539 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 10:30:01 +0700 Subject: [PATCH 26/40] fix(e2e): keep workload selection acyclic Signed-off-by: San Dang --- .github/workflows/e2e.yaml | 1 - .../support/base-image-publication-workflow-boundary.test.ts | 4 ++++ tools/e2e/operations-workflow-boundary.mts | 1 - 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 625387afc2b..5d4498d86e6 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -96,7 +96,6 @@ env: jobs: base-image-publication: - needs: generate-matrix runs-on: ubuntu-latest timeout-minutes: 55 outputs: diff --git a/test/e2e/support/base-image-publication-workflow-boundary.test.ts b/test/e2e/support/base-image-publication-workflow-boundary.test.ts index 0d298d8176f..40abe0847af 100644 --- a/test/e2e/support/base-image-publication-workflow-boundary.test.ts +++ b/test/e2e/support/base-image-publication-workflow-boundary.test.ts @@ -258,6 +258,10 @@ describe("base-image publication workflow boundary (#7372)", () => { "node tools/e2e/dcode-base-image-contract.mts contract.json"), ], ["step count", (value) => gateSteps(value).push({ name: "Unreviewed step", run: "true" })], + [ + "publication dependency cycle", + (value) => (value.jobs["base-image-publication"].needs = "generate-matrix"), + ], ["matrix publication dependency", (value) => (value.jobs["generate-matrix"].needs = [])], [ "matrix workload source", diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index 3bb249237e1..9633746dbde 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -596,7 +596,6 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): const errors: string[] = []; const job = workflow.jobs["base-image-publication"] ?? {}; const expectedJob = { - needs: "generate-matrix", "runs-on": "ubuntu-latest", "timeout-minutes": 55, outputs: { From f560f03d6d2b3443616a148fc6a7340a3e5169db Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 11:20:10 +0700 Subject: [PATCH 27/40] fix(ci): resolve managed image verification failures --- .../actions/sandbox/mcp-bridge-add-restart.ts | 22 +++++++++- .../sandbox/mcp-bridge-provider-readiness.ts | 29 ++++++++++++-- .../sandbox/mcp-bridge-provider.test.ts | 40 ++++++++++++++++++- .../actions/sandbox/mcp-bridge-provider.ts | 1 + src/lib/actions/sandbox/mcp-bridge-restart.ts | 14 +++++-- test/e2e/fixtures/workload-source-env.ts | 23 +++++++++-- .../protected-managed-image-contract.test.ts | 2 + 7 files changed, 119 insertions(+), 12 deletions(-) diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index f8bcd7a5ff6..4fd18e50861 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -40,6 +40,7 @@ import { detachProvider, ensureMcpBridgeProviderProfile, inspectMcpProvider, + mcpCredentialRevisionForProviderResourceVersion, type McpCredentialRevisionObservation, observeMcpCredentialRevision, providerMatchesCredential, @@ -435,16 +436,26 @@ async function addMcpBridgeUnlocked( providerAttachAttempted = true; attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, target); + let expectedCredentialRevision = mcpCredentialRevisionForProviderResourceVersion( + providerResult.inspection.resourceVersion, + ); if (Object.hasOwn(adapterEnvValues, entry.env[0])) { // OpenShell 0.0.106 can miss a credential update published before the // bound policy generation. Republish while that policy is active and // before the first readiness exec; the exact provider identity is // rechecked before and after this update-only mutation. - upsertMcpProvider(entry.providerName ?? "", options.env, { + const republished = upsertMcpProvider(entry.providerName ?? "", options.env, { allowExisting: true, expectedProviderId: entry.providerId, requireExisting: true, }); + const publishedProvider = + republished.action === "updated" + ? republished.inspection + : refreshMcpProviderEnvironment(entry); + expectedCredentialRevision = mcpCredentialRevisionForProviderResourceVersion( + publishedProvider.resourceVersion, + ); } const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { ...(providerResult.action === "updated" @@ -452,6 +463,7 @@ async function addMcpBridgeUnlocked( previousRevision: previousCredentialRevision, } : {}), + expectedRevision: expectedCredentialRevision, // A no-field provider update advances only the provider resource version. // If the credential remains available, republish it after observing an // absence; otherwise, a hostless recovery advances the provider revision. @@ -473,7 +485,13 @@ async function addMcpBridgeUnlocked( expectedProviderId: entry.providerId, requireExisting: true, }); - if (republished.action !== "updated") refreshMcpProviderEnvironment(entry); + const publishedProvider = + republished.action === "updated" + ? republished.inspection + : refreshMcpProviderEnvironment(entry); + return mcpCredentialRevisionForProviderResourceVersion( + publishedProvider.resourceVersion, + ); }, }); // The adapter was proven absent above, so cleanup is safe even when a diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts index 60eeadb8e73..ad9abfff396 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts @@ -20,6 +20,17 @@ export type McpAttachedCredentialRevision = Exclude< "absent" | "canonical" >; +export function mcpCredentialRevisionForProviderResourceVersion( + resourceVersion: number | null, +): McpAttachedCredentialRevision { + if (!Number.isSafeInteger(resourceVersion) || Number(resourceVersion) < 1) { + throw new McpBridgeError( + "OpenShell did not return a valid MCP provider resource version for credential synchronization.", + ); + } + return `v${String(resourceVersion)}` as McpAttachedCredentialRevision; +} + type McpCredentialRevisionAttempt = | { kind: "observation"; observation: McpCredentialRevisionObservation } | { kind: "transport-unavailable" } @@ -148,7 +159,8 @@ export function waitForAttachedMcpCredential( entry: McpBridgeEntry, options: { previousRevision?: McpCredentialRevisionObservation; - refreshAfterObservedAbsence?: () => void; + expectedRevision?: McpAttachedCredentialRevision; + refreshAfterObservedAbsence?: () => McpAttachedCredentialRevision | void; } = {}, ): McpAttachedCredentialRevision { assertAuthenticatedBridgeEntry(entry); @@ -164,6 +176,10 @@ export function waitForAttachedMcpCredential( 10, ); let refreshedAfterObservedAbsence = false; + let expectedRevision = options.expectedRevision; + if (expectedRevision !== undefined && !/^v[0-9]{1,20}$/u.test(expectedRevision)) { + throw new McpBridgeError("Invalid expected MCP credential revision."); + } let lastAttempt: McpCredentialRevisionAttempt = { kind: "transport-unavailable" }; let attachedRevision: McpAttachedCredentialRevision | undefined; const ready = waitForMcpBridgeCondition( @@ -180,7 +196,13 @@ export function waitForAttachedMcpCredential( options.refreshAfterObservedAbsence ) { refreshedAfterObservedAbsence = true; - options.refreshAfterObservedAbsence(); + const refreshedRevision = options.refreshAfterObservedAbsence(); + if (refreshedRevision !== undefined) { + if (!/^v[0-9]{1,20}$/u.test(refreshedRevision)) { + throw new McpBridgeError("Invalid refreshed MCP credential revision."); + } + expectedRevision = refreshedRevision; + } attempt = tryObserveMcpCredentialRevision(sandboxName, envName); lastAttempt = attempt; } @@ -193,7 +215,8 @@ export function waitForAttachedMcpCredential( observation !== null && observation !== "absent" && observation !== "canonical" && - (options.previousRevision === undefined || observation !== options.previousRevision); + (options.previousRevision === undefined || observation !== options.previousRevision) && + (expectedRevision === undefined || observation === expectedRevision); if (attached) attachedRevision = observation; return attached; }, diff --git a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts index 5bbdc2af88c..487c3167aa3 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts @@ -21,6 +21,7 @@ import { } from "./mcp-bridge-provider-inspection"; import { assertMcpProviderRecoverable, + mcpCredentialRevisionForProviderResourceVersion, observeMcpCredentialRevision, refreshMcpProviderEnvironment, waitForAttachedMcpCredential, @@ -378,6 +379,32 @@ alpha-mcp-slack generic 1 0 expect(revision).toBe("v11"); }); + it("waits for the final published provider revision", () => { + const exec = vi + .spyOn(processRecovery, "executeSandboxExecCommand") + .mockReturnValueOnce({ status: 0, stdout: "v11", stderr: "" }) + .mockReturnValue({ status: 0, stdout: "v12", stderr: "" }); + + const revision = waitForAttachedMcpCredential( + "alpha", + { + server: "github", + agent: "openclaw", + adapter: "mcporter", + url: "https://mcp.example.test/mcp", + env: ["GITHUB_TOKEN"], + providerName: "alpha-mcp-github-0123456789abcdef", + providerId: "11111111-2222-4333-8444-555555555555", + policyName: "mcp-bridge-github", + addedAt: "2026-06-01T00:00:00.000Z", + }, + { expectedRevision: "v12" }, + ); + + expect(exec).toHaveBeenCalledTimes(2); + expect(revision).toBe("v12"); + }); + it("does not accept an identityless placeholder as attachment readiness", () => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ @@ -418,9 +445,10 @@ alpha-mcp-slack generic 1 0 .spyOn(processRecovery, "executeSandboxExecCommand") .mockReturnValueOnce({ status: 0, stdout: "absent", stderr: "" }) .mockReturnValueOnce({ status: 0, stdout: "v12", stderr: "" }); - const refreshAfterObservedAbsence = vi.fn(); + const refreshAfterObservedAbsence = vi.fn(() => "v12" as const); const revision = waitForAttachedMcpCredential("alpha", entry, { + expectedRevision: "v11", refreshAfterObservedAbsence, }); @@ -429,6 +457,16 @@ alpha-mcp-slack generic 1 0 expect(revision).toBe("v12"); }); + it("derives the bounded credential revision from the published provider", () => { + expect(mcpCredentialRevisionForProviderResourceVersion(12)).toBe("v12"); + expect(() => mcpCredentialRevisionForProviderResourceVersion(null)).toThrow( + /valid MCP provider resource version/, + ); + expect(() => mcpCredentialRevisionForProviderResourceVersion(0)).toThrow( + /valid MCP provider resource version/, + ); + }); + it("does not repeat the refresh when the credential remains absent (#9764)", () => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ diff --git a/src/lib/actions/sandbox/mcp-bridge-provider.ts b/src/lib/actions/sandbox/mcp-bridge-provider.ts index 42b991c6b10..19fc292aa77 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider.ts @@ -38,6 +38,7 @@ export type { McpCredentialRevisionObservation } from "./mcp-bridge-provider-rea export { buildMcpCredentialDetachedCommand, buildMcpCredentialRevisionObservationCommand, + mcpCredentialRevisionForProviderResourceVersion, observeMcpCredentialRevision, waitForAttachedMcpCredential, waitForDetachedMcpCredential, diff --git a/src/lib/actions/sandbox/mcp-bridge-restart.ts b/src/lib/actions/sandbox/mcp-bridge-restart.ts index bdee7dee3bf..1e5ca5b7f43 100644 --- a/src/lib/actions/sandbox/mcp-bridge-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-restart.ts @@ -16,6 +16,7 @@ import { attachProvider, detachMissingProviderReference, ensureMcpBridgeProviderProfile, + mcpCredentialRevisionForProviderResourceVersion, refreshMcpProviderEnvironment, type McpCredentialRevisionObservation, type McpProviderInspection, @@ -172,11 +173,14 @@ async function restartMcpBridgeUnlocked(sandboxName: string, server?: string): P } attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, target); - refreshMcpProviderEnvironment(entry); + const publishedProvider = refreshMcpProviderEnvironment(entry); const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { ...(providerResult.action === "updated" ? { previousRevision: previousCredentialRevision } : {}), + expectedRevision: mcpCredentialRevisionForProviderResourceVersion( + publishedProvider.resourceVersion, + ), }); registerAgentAdapter( sandboxName, @@ -241,8 +245,12 @@ export async function restoreExistingMcpBridgeRuntime( }); attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, resolvedTargetPins(resolvedByServer, entry)); - refreshMcpProviderEnvironment(entry); - const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry); + const publishedProvider = refreshMcpProviderEnvironment(entry); + const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { + expectedRevision: mcpCredentialRevisionForProviderResourceVersion( + publishedProvider.resourceVersion, + ), + }); const adapter = (entry.adapter as AgentMcpAdapter | undefined) ?? defaultAdapter; registerAgentAdapter( sandboxName, diff --git a/test/e2e/fixtures/workload-source-env.ts b/test/e2e/fixtures/workload-source-env.ts index 5a2693b1462..0e567fddc08 100644 --- a/test/e2e/fixtures/workload-source-env.ts +++ b/test/e2e/fixtures/workload-source-env.ts @@ -2,9 +2,26 @@ // SPDX-License-Identifier: Apache-2.0 import { loadAgent } from "../../../src/lib/agent/defs.ts"; +import { + CANDIDATE_AGENT_FEATURE_ENV, + CANDIDATE_QUALIFICATION_RECEIPT_ENV, +} from "../../../src/lib/agent/candidate.ts"; +import { CUA_FEATURE_ENV } from "../../../src/lib/cua/feature.ts"; -function localDockerfilePath(env: NodeJS.ProcessEnv): string { - const agent = loadAgent(env.NEMOCLAW_AGENT ?? "openclaw", env); +function agentSelectionEnv(input: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + return { + [CANDIDATE_AGENT_FEATURE_ENV]: + input[CANDIDATE_AGENT_FEATURE_ENV] ?? process.env[CANDIDATE_AGENT_FEATURE_ENV], + [CANDIDATE_QUALIFICATION_RECEIPT_ENV]: + input[CANDIDATE_QUALIFICATION_RECEIPT_ENV] ?? + process.env[CANDIDATE_QUALIFICATION_RECEIPT_ENV], + [CUA_FEATURE_ENV]: input[CUA_FEATURE_ENV] ?? process.env[CUA_FEATURE_ENV], + }; +} + +function localDockerfilePath(input: NodeJS.ProcessEnv): string { + const agentName = input.NEMOCLAW_AGENT ?? process.env.NEMOCLAW_AGENT ?? "openclaw"; + const agent = loadAgent(agentName, agentSelectionEnv(input)); const dockerfilePath = agent.dockerfilePath ?? agent.legacyPaths?.dockerfile; if (!dockerfilePath) { throw new Error(`Agent '${agent.name}' has no Dockerfile for local E2E workload source.`); @@ -24,7 +41,7 @@ export function resolveLiveE2eWorkloadSourceEnv(input: NodeJS.ProcessEnv): NodeJ const source = input.E2E_WORKLOAD_SOURCE ?? process.env.E2E_WORKLOAD_SOURCE; if (!targetId || source !== "local-dockerfile") return input; if (input.NEMOCLAW_FROM_DOCKERFILE) return input; - const dockerfilePath = localDockerfilePath({ ...process.env, ...input }); + const dockerfilePath = localDockerfilePath(input); return { ...input, NEMOCLAW_FROM_DOCKERFILE: dockerfilePath, diff --git a/test/platform/images/protected-managed-image-contract.test.ts b/test/platform/images/protected-managed-image-contract.test.ts index cb853d869cc..e15e7edfa56 100644 --- a/test/platform/images/protected-managed-image-contract.test.ts +++ b/test/platform/images/protected-managed-image-contract.test.ts @@ -66,6 +66,7 @@ const EXPECTED_BASE_OUTPUTS = { }, "managed-image-protected-runtime": { dcode: DCODE_BASE_REF, + hermes: `ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${PLATFORM_DIGESTS.hermes}`, openclaw: `ghcr.io/nvidia/nemoclaw/sandbox-base@${PLATFORM_DIGESTS.openclaw}`, }, } as const; @@ -142,6 +143,7 @@ printf '%s %s\n' "$digest" "$1" }), DCODE_BASE_REF, GITHUB_OUTPUT: outputPath, + GITHUB_WORKSPACE: fixture, HERMES_BASE_DIGEST: PLATFORM_DIGESTS.hermes, PATH: `${fakeBin}:${process.env.PATH ?? ""}`, PLATFORM: "linux/amd64", From 6b5759447e54d74db6a14ab67ed045955813833e Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 11:22:39 +0700 Subject: [PATCH 28/40] test(ci): remove duplicate advisor watch trigger --- test/helpers/vitest-watch-triggers.ts | 1 - test/repository/vitest-watch-triggers.test.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts index e7347a66d0f..88cde7585cb 100644 --- a/test/helpers/vitest-watch-triggers.ts +++ b/test/helpers/vitest-watch-triggers.ts @@ -321,7 +321,6 @@ export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ pattern: /(?:^|\/)\.github\/workflows\/pr-review-advisor\.yaml$/, testsToRun: runTests( "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts", - "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts", ), }, { diff --git a/test/repository/vitest-watch-triggers.test.ts b/test/repository/vitest-watch-triggers.test.ts index bb08e8b1149..ba05c49c492 100644 --- a/test/repository/vitest-watch-triggers.test.ts +++ b/test/repository/vitest-watch-triggers.test.ts @@ -333,7 +333,6 @@ describe("Vitest opaque-input watch triggers", () => { ]); expect(triggeredBy(".github/workflows/pr-review-advisor.yaml")).toEqual([ "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts", - "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts", ]); expect(triggeredBy("tools/pr-review-advisor/openshell-policy.yaml")).toEqual([ "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts", From 993c194de871d54a15f1aaf5aae26c114c267481 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 11:45:59 +0700 Subject: [PATCH 29/40] chore(mcp): remove unrelated credential revision fix --- .../actions/sandbox/mcp-bridge-add-restart.ts | 22 +--------- .../sandbox/mcp-bridge-provider-readiness.ts | 29 ++------------ .../sandbox/mcp-bridge-provider.test.ts | 40 +------------------ .../actions/sandbox/mcp-bridge-provider.ts | 1 - src/lib/actions/sandbox/mcp-bridge-restart.ts | 14 ++----- 5 files changed, 9 insertions(+), 97 deletions(-) diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index 4fd18e50861..f8bcd7a5ff6 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -40,7 +40,6 @@ import { detachProvider, ensureMcpBridgeProviderProfile, inspectMcpProvider, - mcpCredentialRevisionForProviderResourceVersion, type McpCredentialRevisionObservation, observeMcpCredentialRevision, providerMatchesCredential, @@ -436,26 +435,16 @@ async function addMcpBridgeUnlocked( providerAttachAttempted = true; attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, target); - let expectedCredentialRevision = mcpCredentialRevisionForProviderResourceVersion( - providerResult.inspection.resourceVersion, - ); if (Object.hasOwn(adapterEnvValues, entry.env[0])) { // OpenShell 0.0.106 can miss a credential update published before the // bound policy generation. Republish while that policy is active and // before the first readiness exec; the exact provider identity is // rechecked before and after this update-only mutation. - const republished = upsertMcpProvider(entry.providerName ?? "", options.env, { + upsertMcpProvider(entry.providerName ?? "", options.env, { allowExisting: true, expectedProviderId: entry.providerId, requireExisting: true, }); - const publishedProvider = - republished.action === "updated" - ? republished.inspection - : refreshMcpProviderEnvironment(entry); - expectedCredentialRevision = mcpCredentialRevisionForProviderResourceVersion( - publishedProvider.resourceVersion, - ); } const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { ...(providerResult.action === "updated" @@ -463,7 +452,6 @@ async function addMcpBridgeUnlocked( previousRevision: previousCredentialRevision, } : {}), - expectedRevision: expectedCredentialRevision, // A no-field provider update advances only the provider resource version. // If the credential remains available, republish it after observing an // absence; otherwise, a hostless recovery advances the provider revision. @@ -485,13 +473,7 @@ async function addMcpBridgeUnlocked( expectedProviderId: entry.providerId, requireExisting: true, }); - const publishedProvider = - republished.action === "updated" - ? republished.inspection - : refreshMcpProviderEnvironment(entry); - return mcpCredentialRevisionForProviderResourceVersion( - publishedProvider.resourceVersion, - ); + if (republished.action !== "updated") refreshMcpProviderEnvironment(entry); }, }); // The adapter was proven absent above, so cleanup is safe even when a diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts index ad9abfff396..60eeadb8e73 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts @@ -20,17 +20,6 @@ export type McpAttachedCredentialRevision = Exclude< "absent" | "canonical" >; -export function mcpCredentialRevisionForProviderResourceVersion( - resourceVersion: number | null, -): McpAttachedCredentialRevision { - if (!Number.isSafeInteger(resourceVersion) || Number(resourceVersion) < 1) { - throw new McpBridgeError( - "OpenShell did not return a valid MCP provider resource version for credential synchronization.", - ); - } - return `v${String(resourceVersion)}` as McpAttachedCredentialRevision; -} - type McpCredentialRevisionAttempt = | { kind: "observation"; observation: McpCredentialRevisionObservation } | { kind: "transport-unavailable" } @@ -159,8 +148,7 @@ export function waitForAttachedMcpCredential( entry: McpBridgeEntry, options: { previousRevision?: McpCredentialRevisionObservation; - expectedRevision?: McpAttachedCredentialRevision; - refreshAfterObservedAbsence?: () => McpAttachedCredentialRevision | void; + refreshAfterObservedAbsence?: () => void; } = {}, ): McpAttachedCredentialRevision { assertAuthenticatedBridgeEntry(entry); @@ -176,10 +164,6 @@ export function waitForAttachedMcpCredential( 10, ); let refreshedAfterObservedAbsence = false; - let expectedRevision = options.expectedRevision; - if (expectedRevision !== undefined && !/^v[0-9]{1,20}$/u.test(expectedRevision)) { - throw new McpBridgeError("Invalid expected MCP credential revision."); - } let lastAttempt: McpCredentialRevisionAttempt = { kind: "transport-unavailable" }; let attachedRevision: McpAttachedCredentialRevision | undefined; const ready = waitForMcpBridgeCondition( @@ -196,13 +180,7 @@ export function waitForAttachedMcpCredential( options.refreshAfterObservedAbsence ) { refreshedAfterObservedAbsence = true; - const refreshedRevision = options.refreshAfterObservedAbsence(); - if (refreshedRevision !== undefined) { - if (!/^v[0-9]{1,20}$/u.test(refreshedRevision)) { - throw new McpBridgeError("Invalid refreshed MCP credential revision."); - } - expectedRevision = refreshedRevision; - } + options.refreshAfterObservedAbsence(); attempt = tryObserveMcpCredentialRevision(sandboxName, envName); lastAttempt = attempt; } @@ -215,8 +193,7 @@ export function waitForAttachedMcpCredential( observation !== null && observation !== "absent" && observation !== "canonical" && - (options.previousRevision === undefined || observation !== options.previousRevision) && - (expectedRevision === undefined || observation === expectedRevision); + (options.previousRevision === undefined || observation !== options.previousRevision); if (attached) attachedRevision = observation; return attached; }, diff --git a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts index 487c3167aa3..5bbdc2af88c 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts @@ -21,7 +21,6 @@ import { } from "./mcp-bridge-provider-inspection"; import { assertMcpProviderRecoverable, - mcpCredentialRevisionForProviderResourceVersion, observeMcpCredentialRevision, refreshMcpProviderEnvironment, waitForAttachedMcpCredential, @@ -379,32 +378,6 @@ alpha-mcp-slack generic 1 0 expect(revision).toBe("v11"); }); - it("waits for the final published provider revision", () => { - const exec = vi - .spyOn(processRecovery, "executeSandboxExecCommand") - .mockReturnValueOnce({ status: 0, stdout: "v11", stderr: "" }) - .mockReturnValue({ status: 0, stdout: "v12", stderr: "" }); - - const revision = waitForAttachedMcpCredential( - "alpha", - { - server: "github", - agent: "openclaw", - adapter: "mcporter", - url: "https://mcp.example.test/mcp", - env: ["GITHUB_TOKEN"], - providerName: "alpha-mcp-github-0123456789abcdef", - providerId: "11111111-2222-4333-8444-555555555555", - policyName: "mcp-bridge-github", - addedAt: "2026-06-01T00:00:00.000Z", - }, - { expectedRevision: "v12" }, - ); - - expect(exec).toHaveBeenCalledTimes(2); - expect(revision).toBe("v12"); - }); - it("does not accept an identityless placeholder as attachment readiness", () => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ @@ -445,10 +418,9 @@ alpha-mcp-slack generic 1 0 .spyOn(processRecovery, "executeSandboxExecCommand") .mockReturnValueOnce({ status: 0, stdout: "absent", stderr: "" }) .mockReturnValueOnce({ status: 0, stdout: "v12", stderr: "" }); - const refreshAfterObservedAbsence = vi.fn(() => "v12" as const); + const refreshAfterObservedAbsence = vi.fn(); const revision = waitForAttachedMcpCredential("alpha", entry, { - expectedRevision: "v11", refreshAfterObservedAbsence, }); @@ -457,16 +429,6 @@ alpha-mcp-slack generic 1 0 expect(revision).toBe("v12"); }); - it("derives the bounded credential revision from the published provider", () => { - expect(mcpCredentialRevisionForProviderResourceVersion(12)).toBe("v12"); - expect(() => mcpCredentialRevisionForProviderResourceVersion(null)).toThrow( - /valid MCP provider resource version/, - ); - expect(() => mcpCredentialRevisionForProviderResourceVersion(0)).toThrow( - /valid MCP provider resource version/, - ); - }); - it("does not repeat the refresh when the credential remains absent (#9764)", () => { vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1"); const exec = vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({ diff --git a/src/lib/actions/sandbox/mcp-bridge-provider.ts b/src/lib/actions/sandbox/mcp-bridge-provider.ts index 19fc292aa77..42b991c6b10 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider.ts @@ -38,7 +38,6 @@ export type { McpCredentialRevisionObservation } from "./mcp-bridge-provider-rea export { buildMcpCredentialDetachedCommand, buildMcpCredentialRevisionObservationCommand, - mcpCredentialRevisionForProviderResourceVersion, observeMcpCredentialRevision, waitForAttachedMcpCredential, waitForDetachedMcpCredential, diff --git a/src/lib/actions/sandbox/mcp-bridge-restart.ts b/src/lib/actions/sandbox/mcp-bridge-restart.ts index 1e5ca5b7f43..bdee7dee3bf 100644 --- a/src/lib/actions/sandbox/mcp-bridge-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-restart.ts @@ -16,7 +16,6 @@ import { attachProvider, detachMissingProviderReference, ensureMcpBridgeProviderProfile, - mcpCredentialRevisionForProviderResourceVersion, refreshMcpProviderEnvironment, type McpCredentialRevisionObservation, type McpProviderInspection, @@ -173,14 +172,11 @@ async function restartMcpBridgeUnlocked(sandboxName: string, server?: string): P } attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, target); - const publishedProvider = refreshMcpProviderEnvironment(entry); + refreshMcpProviderEnvironment(entry); const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { ...(providerResult.action === "updated" ? { previousRevision: previousCredentialRevision } : {}), - expectedRevision: mcpCredentialRevisionForProviderResourceVersion( - publishedProvider.resourceVersion, - ), }); registerAgentAdapter( sandboxName, @@ -245,12 +241,8 @@ export async function restoreExistingMcpBridgeRuntime( }); attachProvider(sandboxName, entry); applyGeneratedPolicy(sandboxName, entry, resolvedTargetPins(resolvedByServer, entry)); - const publishedProvider = refreshMcpProviderEnvironment(entry); - const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, { - expectedRevision: mcpCredentialRevisionForProviderResourceVersion( - publishedProvider.resourceVersion, - ), - }); + refreshMcpProviderEnvironment(entry); + const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry); const adapter = (entry.adapter as AgentMcpAdapter | undefined) ?? defaultAdapter; registerAgentAdapter( sandboxName, From 9259f231d4fc88037ee6554a104b31e988ec5ec6 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 11:47:55 +0700 Subject: [PATCH 30/40] chore(ci): leave advisor trigger fix to owner --- test/helpers/vitest-watch-triggers.ts | 1 + test/repository/vitest-watch-triggers.test.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts index 88cde7585cb..e7347a66d0f 100644 --- a/test/helpers/vitest-watch-triggers.ts +++ b/test/helpers/vitest-watch-triggers.ts @@ -321,6 +321,7 @@ export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ pattern: /(?:^|\/)\.github\/workflows\/pr-review-advisor\.yaml$/, testsToRun: runTests( "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts", + "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts", ), }, { diff --git a/test/repository/vitest-watch-triggers.test.ts b/test/repository/vitest-watch-triggers.test.ts index ba05c49c492..bb08e8b1149 100644 --- a/test/repository/vitest-watch-triggers.test.ts +++ b/test/repository/vitest-watch-triggers.test.ts @@ -333,6 +333,7 @@ describe("Vitest opaque-input watch triggers", () => { ]); expect(triggeredBy(".github/workflows/pr-review-advisor.yaml")).toEqual([ "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts", + "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts", ]); expect(triggeredBy("tools/pr-review-advisor/openshell-policy.yaml")).toEqual([ "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts", From 649968be2fb971f589aeda8f73bce74cb7984622 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 26 Aug 2026 14:01:43 +0700 Subject: [PATCH 31/40] fix(e2e): bind workload selection to commit trees Signed-off-by: San Dang --- test/e2e/README.md | 10 +- test/e2e/RETRY_INVENTORY.md | 2 +- .../support/pr-managed-image-source.test.ts | 110 ++++++++++++----- tools/e2e/pr-managed-image-source.mts | 111 ++++++++++++------ 4 files changed, 158 insertions(+), 75 deletions(-) diff --git a/test/e2e/README.md b/test/e2e/README.md index badd92d2447..479a4403b39 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -90,11 +90,11 @@ After the checks pass, the action restores root `dist/` and `nemoclaw/dist/share If the version command fails, the action stops before the live test runs. This boundary keeps candidate source separate from the trusted workflow implementation. -For a manual PR run, the trusted planner compares the changed files with the -base-image and managed-image input paths. When those inputs are unchanged, the -run uses the applicable trusted managed-image publication from `main`. When any -input changed, the run builds the candidate Dockerfiles locally instead of -waiting for a candidate publication. +For a manual PR run, the trusted planner compares the immutable base and +candidate commit trees with the base-image and managed-image input paths. When +those inputs are unchanged, the run uses the applicable trusted managed-image +publication from `main`. When any input changed, the run builds the candidate +Dockerfiles locally instead of waiting for a candidate publication. The native startup jobs build the local candidate bases for each platform. The AMD64 producer passes their exact digests and build caches to the protected GPU diff --git a/test/e2e/RETRY_INVENTORY.md b/test/e2e/RETRY_INVENTORY.md index c457cb36282..7e8ac0d96c2 100644 --- a/test/e2e/RETRY_INVENTORY.md +++ b/test/e2e/RETRY_INVENTORY.md @@ -16,7 +16,7 @@ Exhaustion remains failed. | `workflow-main-observer` | Completed `E2E main` run; `tools/e2e/main-run-retry.mts`, `.github/workflows/e2e-main-retry.yaml` | Any failed job | 0 automatic reruns | Not established at workflow scope | Test owner | `failed-no-retry`, `ignored`, `passed-first-attempt`, or `passed-after-retry` for a later manually requested rerun | Failed job names, non-skipped job count, runner minutes, and source SHA for each attempt | Broad rerun removed; operation-level evidence is required | | `hosted-runner-recovery` | Confirmed GitHub-hosted runner loss; `tools/e2e/hosted-runner-recovery.mts`, `tools/e2e/hosted-runner-loss*.mts` | Authenticated runner-allocation or internal-runner evidence that remains identical across 2 consecutive reads | 2 immediate evidence reads and at most 1 recovery request; no delay | GitHub reruns a workflow attempt | GitHub Actions | Dedicated runner-loss classifications | Source and recovery run links plus authenticated job evidence | External owner; governed by #7146, not this policy | | `pr-rerun-reconciliation` | PR E2E dispatch reconciliation; `tools/e2e/pr-e2e-dispatch-reconciliation.mts`, `tools/e2e/pr-e2e-retry-receipt.mts` | Trusted dispatch receipt state | Contract-defined single reconciliation | Reconciles workflow and commit identity before action | GitHub Actions | Receipt-specific terminal states | Signed workflow identity and receipt | External scope; governed by #7206 | -| `github-publication-read` | Publication and PR metadata reads; `tools/e2e/base-image-publication.mts`, `tools/e2e/pr-managed-image-source.mts` | Fetch error, HTTP 408, HTTP 5xx, HTTP 429, or HTTP 403 with `x-ratelimit-remaining: 0` | 3 attempts; Retry-After/rate-limit reset or linear delay capped at 10s | Read-only | GitHub API | Returned publication or workload-source selection on success; thrown terminal HTTP/fetch error on failure or exhaustion | Caller records the publication selection or PR workload source; terminal errors identify exhausted fetch or HTTP status without response content | Eligible bounded read; existing implementation retained | +| `github-publication-read` | Publication reads, PR metadata reads, and immutable commit-tree reads; `tools/e2e/base-image-publication.mts`, `tools/e2e/pr-managed-image-source.mts` | Fetch error, HTTP 408, HTTP 5xx, HTTP 429, or HTTP 403 with `x-ratelimit-remaining: 0` | 3 attempts; Retry-After/rate-limit reset or linear delay capped at 10s | Read-only | GitHub API | Returned publication or workload-source selection on success; thrown terminal HTTP/fetch error on failure or exhaustion | Caller records the publication selection or PR workload source; terminal errors identify exhausted fetch or HTTP status without response content | Eligible bounded read; existing implementation retained | | `ghcr-pr-exact-digest-visibility` | Anonymous pull after same-repository PR publication; `scripts/checks/pull-public-exact-digest.sh`, `.github/workflows/managed-images.yaml` | Final nonempty Docker output line is exactly `ERROR: : not found`; every other Docker failure is terminal | 5 attempts; exponential 2s, 4s, 8s, then 16s | Read-only registry request for one immutable digest; any local image-cache write repeats the same content-addressed result | GHCR | `passed-first-attempt`, `passed-after-retry`, `failed-no-retry`, or `exhausted` | Sanitized outcome, attempt number, total attempts, retry delay or Docker exit status; raw Docker output, credentials, and environment values are excluded | Eligible bounded external read after the independently fetched manifest bytes match the publication digest; every non-exact failure remains terminal and no workflow rerun occurs | | `protected-managed-image-buildkit-transport` | One agent's exact protected managed-image `docker buildx build`; `scripts/checks/build-protected-managed-images.sh` | Final nonempty line exactly matches BuildKit's `ERROR: failed to build: failed to solve: stream error: stream ID ; INTERNAL_ERROR; received from peer`; every near-match and other Docker failure is terminal | 2 attempts; fixed 2s delay | Before retry, a read-only local registry `HEAD` request confirms that the isolated revision tag is absent. The script then repeats the same agent, inputs, revision tag, and content-addressed push. A present tag or any inconclusive registry result is terminal. Existing digest, registry-byte, and image-contract checks still gate success. | BuildKit transport | `passed-first-attempt`, `passed-after-retry`, `failed-no-retry`, or `exhausted` | Existing Docker attempt output remains in the job log. Sanitized job-log annotations retain the agent, attempt, outcome, retry delay or Docker exit status, failure class, and revision-tag state without image content. | Eligible bounded operation retry for the exact pre-export transport failure observed in #9763; repeated exact failure remains failed and no workflow rerun occurs | | `protected-managed-image-npm-registry-dns` | One agent's exact protected managed-image `docker buildx build`; `scripts/checks/build-protected-managed-images.sh` | One attempt line has an optional BuildKit step prefix, an elapsed-time field, and exact text `ERROR: curl failed: curl: (6) Could not resolve host: registry.npmjs.org`; every other curl exit, host, and near-match is terminal | 2 attempts; fixed 2s delay | Before retry, a read-only local registry `HEAD` request confirms that the isolated revision tag is absent. The script then repeats the same agent, inputs, revision tag, and content-addressed push. A present tag or any inconclusive registry result is terminal. Existing digest, registry-byte, and image-contract checks still gate success. | npm registry DNS | `passed-first-attempt`, `passed-after-retry`, `failed-no-retry`, or `exhausted` | Existing Docker attempt output remains in the job log. Sanitized job-log annotations retain the agent, attempt, outcome, retry delay or Docker exit status, failure class, and revision-tag state without image content. | Eligible bounded operation retry for the exact pre-export DNS failure observed in run 32621454757, job 97154036894; repeated exact failure remains failed and no workflow rerun occurs | diff --git a/test/e2e/support/pr-managed-image-source.test.ts b/test/e2e/support/pr-managed-image-source.test.ts index 4599f955fce..1d093b023d9 100644 --- a/test/e2e/support/pr-managed-image-source.test.ts +++ b/test/e2e/support/pr-managed-image-source.test.ts @@ -25,6 +25,9 @@ import { const BASE_SHA = "b".repeat(40); const CANDIDATE_SHA = "a".repeat(40); +const DRIFT_SHA = "c".repeat(40); +const BASE_TREE_SHA = "1".repeat(40); +const CANDIDATE_TREE_SHA = "2".repeat(40); const PR_NUMBER = 10_113; const CANDIDATE_REPOSITORY = "NVIDIA/NemoClaw"; @@ -63,13 +66,41 @@ function unexpectedRequest(requestPath: string): never { throw new Error(`unexpected request ${requestPath}`); } -function requestFor( - files: Array<{ filename: string; previous_filename?: string }>, +function requestForChanges( + changes: Array<{ filename: string; previous_filename?: string }>, pullOverrides: Record = {}, ) { + const baseEntries = changes.map((change) => ({ + mode: "100644", + path: change.previous_filename ?? change.filename, + sha: "3".repeat(40), + type: "blob", + })); + const candidateEntries = changes.map((change) => ({ + mode: "100644", + path: change.filename, + sha: "4".repeat(40), + type: "blob", + })); const responses = new Map([ - [`/repos/NVIDIA/NemoClaw/pulls/${PR_NUMBER}`, pull(files.length, pullOverrides)], - [`/repos/NVIDIA/NemoClaw/pulls/${PR_NUMBER}/files?per_page=100&page=1`, files], + [`/repos/NVIDIA/NemoClaw/pulls/${PR_NUMBER}`, pull(changes.length, pullOverrides)], + [`/repos/NVIDIA/NemoClaw/pulls/${PR_NUMBER}/files?per_page=100&page=1`, changes], + [ + `/repos/NVIDIA/NemoClaw/git/commits/${BASE_SHA}`, + { sha: BASE_SHA, tree: { sha: BASE_TREE_SHA } }, + ], + [ + `/repos/NVIDIA/NemoClaw/git/trees/${BASE_TREE_SHA}?recursive=1`, + { sha: BASE_TREE_SHA, tree: baseEntries, truncated: false }, + ], + [ + `/repos/${CANDIDATE_REPOSITORY}/git/commits/${CANDIDATE_SHA}`, + { sha: CANDIDATE_SHA, tree: { sha: CANDIDATE_TREE_SHA } }, + ], + [ + `/repos/${CANDIDATE_REPOSITORY}/git/trees/${CANDIDATE_TREE_SHA}?recursive=1`, + { sha: CANDIDATE_TREE_SHA, tree: candidateEntries, truncated: false }, + ], ]); return async (requestPath: string): Promise => responses.get(requestPath) ?? unexpectedRequest(requestPath); @@ -98,7 +129,7 @@ describe("PR managed-image source selection", () => { "tools/mcp-tool-discovery-runtime/reviewed-runtime-bundle/managed-startup-image-runtime.bundle", ])("selects a local Dockerfile when reviewed image input %s changes", async (filename) => { await expect( - resolvePrManagedImageSource(selectorInput(), requestFor([{ filename }])), + resolvePrManagedImageSource(selectorInput(), requestForChanges([{ filename }])), ).resolves.toBe("local-dockerfile"); }); @@ -106,7 +137,7 @@ describe("PR managed-image source selection", () => { await expect( resolvePrManagedImageSource( selectorInput(), - requestFor([ + requestForChanges([ { filename: "docs/renamed-base-image.txt", previous_filename: "Dockerfile.base" }, ]), ), @@ -115,32 +146,64 @@ describe("PR managed-image source selection", () => { it("selects a trusted managed image when reviewed image inputs are unchanged", async () => { await expect( - resolvePrManagedImageSource(selectorInput(), requestFor([{ filename: "docs/guide.mdx" }])), + resolvePrManagedImageSource( + selectorInput(), + requestForChanges([{ filename: "docs/guide.mdx" }]), + ), ).resolves.toBe("managed-image"); }); - it("selects a local Dockerfile when a reviewed image input appears on page two", async () => { + it("keeps classification bound to immutable commits during A-to-B-to-A PR drift", async () => { const metadataPath = `/repos/NVIDIA/NemoClaw/pulls/${PR_NUMBER}`; - const pageOnePath = `${metadataPath}/files?per_page=100&page=1`; - const pageTwoPath = `${metadataPath}/files?per_page=100&page=2`; + const mutableFilesPath = `${metadataPath}/files?per_page=100&page=1`; + const immutableRequest = requestForChanges([{ filename: "Dockerfile.base" }]); const requests: string[] = []; - const responses = new Map([ - [metadataPath, pull(101)], + const observedPrHeads = [CANDIDATE_SHA]; + const requestHandlers = new Map Promise | unknown>([ + [ + metadataPath, + async () => { + const response = await immutableRequest(metadataPath); + observedPrHeads.push(DRIFT_SHA); + return response; + }, + ], + [mutableFilesPath, () => [{ filename: "docs/guide.mdx" }]], [ - pageOnePath, - Array.from({ length: 100 }, (_, index) => ({ filename: `docs/guide-${index}.mdx` })), + `/repos/${CANDIDATE_REPOSITORY}/git/commits/${CANDIDATE_SHA}`, + async () => { + observedPrHeads.push(CANDIDATE_SHA); + return immutableRequest(`/repos/${CANDIDATE_REPOSITORY}/git/commits/${CANDIDATE_SHA}`); + }, ], - [pageTwoPath, [{ filename: "Dockerfile.base" }]], ]); const request = async (requestPath: string): Promise => { requests.push(requestPath); - return responses.get(requestPath) ?? unexpectedRequest(requestPath); + const handler = requestHandlers.get(requestPath); + return handler ? handler() : immutableRequest(requestPath); }; await expect(resolvePrManagedImageSource(selectorInput(), request)).resolves.toBe( "local-dockerfile", ); - expect(requests).toContain(pageTwoPath); + expect(observedPrHeads).toEqual([CANDIDATE_SHA, DRIFT_SHA, CANDIDATE_SHA]); + expect(requests).not.toContain(mutableFilesPath); + expect(requests).toContain( + `/repos/${CANDIDATE_REPOSITORY}/git/trees/${CANDIDATE_TREE_SHA}?recursive=1`, + ); + }); + + it("rejects a truncated immutable candidate tree", async () => { + const candidateTreePath = `/repos/${CANDIDATE_REPOSITORY}/git/trees/${CANDIDATE_TREE_SHA}?recursive=1`; + const immutableRequest = requestForChanges([{ filename: "docs/guide.mdx" }]); + const request = async (requestPath: string): Promise => + requestPath === candidateTreePath + ? { sha: CANDIDATE_TREE_SHA, tree: [], truncated: true } + : immutableRequest(requestPath); + + await expect(resolvePrManagedImageSource(selectorInput(), request)).rejects.toThrow( + "PR candidate commit tree is truncated", + ); }); it.each([ @@ -177,19 +240,6 @@ describe("PR managed-image source selection", () => { await expect(resolvePrManagedImageSource(selectorInput(), request)).rejects.toThrow(message); expect(requests).toEqual([metadataPath]); }); - - it("records PR source reads in the retry inventory", () => { - const row = fs - .readFileSync("test/e2e/RETRY_INVENTORY.md", "utf8") - .split("\n") - .find((line) => line.startsWith("| `github-publication-read` |")); - - expect(row).toContain("tools/e2e/base-image-publication.mts"); - expect(row).toContain("tools/e2e/pr-managed-image-source.mts"); - expect(row).toContain("PR metadata reads"); - expect(row).toContain("workload-source selection"); - expect(row).toContain("HTTP 429, or HTTP 403 with `x-ratelimit-remaining: 0`"); - }); }); describe("managed-image activation catalog assembly", () => { diff --git a/tools/e2e/pr-managed-image-source.mts b/tools/e2e/pr-managed-image-source.mts index 8d2a503b96a..c57279989af 100644 --- a/tools/e2e/pr-managed-image-source.mts +++ b/tools/e2e/pr-managed-image-source.mts @@ -19,10 +19,10 @@ import { createPrivateRegularFile } from "./private-file.mts"; const REPOSITORY = "NVIDIA/NemoClaw"; const BASE_IMAGE_WORKFLOW_PATH = ".github/workflows/base-image.yaml"; -const MAX_CHANGED_FILES = 3_000; -const PAGE_SIZE = 100; +const MAX_COMMIT_TREE_ENTRIES = 100_000; const SHA_PATTERN = /^[0-9a-f]{40}$/u; const REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u; +const TREE_ENTRY_TYPES = new Set(["blob", "commit", "tree"]); type JsonRecord = Record; @@ -46,6 +46,13 @@ function exactString(value: unknown, expected: string, label: string): void { if (value !== expected) throw new Error(`${label} must be ${expected}`); } +function sha(value: unknown, label: string): string { + if (typeof value !== "string" || !SHA_PATTERN.test(value)) { + throw new Error(`${label} must be a lowercase 40-character SHA`); + } + return value; +} + /** Assemble one all-agent catalog for the managed-image workflow's activation check. */ export function assembleManagedImageCatalog( values: readonly unknown[], @@ -95,41 +102,71 @@ export function writeManagedImageCatalog( createPrivateRegularFile(outputPath, `${JSON.stringify(catalog)}\n`); } -async function readChangedFiles( - prNumber: number, - count: number, +async function readCommitTree( + repository: string, + revision: string, + label: string, request: (path: string) => Promise, -): Promise { - if (!Number.isSafeInteger(count) || count < 0 || count > MAX_CHANGED_FILES) { - throw new Error("PR changed-file count is invalid"); - } - const files: string[] = []; - let listedFiles = 0; - for (let page = 1; listedFiles < count; page += 1) { - if (page > Math.ceil(MAX_CHANGED_FILES / PAGE_SIZE)) { - throw new Error("PR changed-file pagination exceeded the safety cap"); +): Promise> { + const commit = record( + await request(`/repos/${repository}/git/commits/${revision}`), + `${label} commit`, + ); + exactString(commit.sha, revision, `${label} commit SHA`); + const treeSha = sha(record(commit.tree, `${label} commit tree`).sha, `${label} tree SHA`); + const payload = record( + await request(`/repos/${repository}/git/trees/${treeSha}?recursive=1`), + `${label} tree`, + ); + exactString(payload.sha, treeSha, `${label} tree SHA`); + if (payload.truncated !== false) { + throw new Error(`${label} commit tree is truncated`); + } + if (!Array.isArray(payload.tree) || payload.tree.length > MAX_COMMIT_TREE_ENTRIES) { + throw new Error(`${label} commit tree is invalid or exceeds the entry limit`); + } + + const entries = new Map(); + for (const value of payload.tree) { + const entry = record(value, `${label} tree entry`); + if (typeof entry.path !== "string" || entry.path.length === 0) { + throw new Error(`${label} tree entry path is invalid`); } - const payload = await request( - `/repos/${REPOSITORY}/pulls/${prNumber}/files?per_page=${PAGE_SIZE}&page=${page}`, - ); - if (!Array.isArray(payload) || payload.length === 0 || payload.length > PAGE_SIZE) { - throw new Error("PR changed-file page is invalid or incomplete"); + if (typeof entry.type !== "string" || !TREE_ENTRY_TYPES.has(entry.type)) { + throw new Error(`${label} tree entry type is invalid`); } - for (const value of payload) { - const file = record(value, "PR changed file"); - if (typeof file.filename !== "string") throw new Error("PR changed-file name is invalid"); - files.push(file.filename); - if (file.previous_filename !== undefined) { - if (typeof file.previous_filename !== "string") { - throw new Error("PR previous changed-file name is invalid"); - } - files.push(file.previous_filename); - } - listedFiles += 1; + if (typeof entry.mode !== "string" || !/^[0-7]{6}$/u.test(entry.mode)) { + throw new Error(`${label} tree entry mode is invalid`); } + const entrySha = sha(entry.sha, `${label} tree entry SHA`); + if (entry.type === "tree") continue; + if (entries.has(entry.path)) throw new Error(`${label} commit tree contains duplicate paths`); + entries.set(entry.path, `${entry.mode}:${entry.type}:${entrySha}`); } - if (listedFiles !== count) throw new Error("PR changed-file listing is incomplete"); - return [...new Set(files)]; + return entries; +} + +async function readChangedFiles( + input: { + readonly baseSha: string; + readonly candidateRepository: string; + readonly candidateSha: string; + }, + request: (path: string) => Promise, +): Promise { + const baseTree = await readCommitTree(REPOSITORY, input.baseSha, "PR base", request); + const candidateTree = await readCommitTree( + input.candidateRepository, + input.candidateSha, + "PR candidate", + request, + ); + const changedFiles: string[] = []; + for (const changedPath of new Set([...baseTree.keys(), ...candidateTree.keys()])) { + if (baseTree.get(changedPath) === candidateTree.get(changedPath)) continue; + changedFiles.push(changedPath); + } + return changedFiles; } function validatePr( @@ -139,7 +176,7 @@ function validatePr( readonly candidateRepository: string; readonly candidateSha: string; }, -): number { +): void { const pull = record(payload, "pull request"); exactString(pull.state, "open", "pull request state"); const base = record(pull.base, "pull request base"); @@ -156,7 +193,6 @@ function validatePr( expected.candidateRepository, "pull request source repository", ); - return positiveInteger(pull.changed_files, "PR changed-file count"); } /** Select a trusted managed image or the candidate's local Dockerfile path. */ @@ -179,11 +215,8 @@ export async function resolvePrManagedImageSource( } positiveInteger(input.prNumber, "PR number"); if (!input.token) throw new Error("GITHUB_TOKEN is required"); - const changedCount = validatePr( - await request(`/repos/${REPOSITORY}/pulls/${input.prNumber}`), - input, - ); - const changedFiles = await readChangedFiles(input.prNumber, changedCount, request); + validatePr(await request(`/repos/${REPOSITORY}/pulls/${input.prNumber}`), input); + const changedFiles = await readChangedFiles(input, request); const patterns = parseBaseImagePushPaths(input.workflowSource); return baseImageInputsChanged(changedFiles, patterns) ? "local-dockerfile" : "managed-image"; } From e1b853132a6ca51af474c87ee1a447a47c8cbbdc Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 28 Aug 2026 17:52:02 +0700 Subject: [PATCH 32/40] refactor(e2e): remove unused PR image catalog path Signed-off-by: San Dang --- .github/workflows/e2e-standard-profile.yaml | 42 --- .github/workflows/e2e.yaml | 57 ++-- .../pr-managed-image-publication.test.ts | 188 +------------ tools/e2e/mcp-workflow-boundary.mts | 8 +- tools/e2e/operations-workflow-boundary.mts | 28 +- tools/e2e/pr-managed-image-publication.mts | 261 +----------------- .../standard-profile-workflow-boundary.mts | 43 +-- 7 files changed, 54 insertions(+), 573 deletions(-) diff --git a/.github/workflows/e2e-standard-profile.yaml b/.github/workflows/e2e-standard-profile.yaml index 6d9e64cb1ac..53c7c5d8e08 100644 --- a/.github/workflows/e2e-standard-profile.yaml +++ b/.github/workflows/e2e-standard-profile.yaml @@ -21,9 +21,6 @@ on: cli_artifact_provenance: required: true type: string - managed_image_catalog: - required: true - type: string managed_image_revision: required: true type: string @@ -404,45 +401,6 @@ jobs: with: provenance-json: ${{ inputs.cli_artifact_provenance }} - - name: Materialize temporary managed-image catalog - if: ${{ inputs.managed_image_catalog != '' }} - shell: /bin/bash --noprofile --norc -e -o pipefail {0} - env: - CANDIDATE_SHA: ${{ inputs.candidate_sha }} - MANAGED_IMAGE_CATALOG: ${{ inputs.managed_image_catalog }} - RESTORE_CLI: ${{ inputs.restore_cli && 'true' || 'false' }} - run: | - set -euo pipefail - catalog_path="${RUNNER_TEMP}/e2e-managed-image-catalog.json" - jq -e --arg revision "$CANDIDATE_SHA" ' - type == "object" and length > 0 and - all(.[]; - .source.revision == $revision and - (.source.release | type == "string" and length > 0) and - (.source.cohort | type == "string" and length > 0) - ) and - ([.[].source.release] | unique | length) == 1 and - ([.[].source.cohort] | unique | length) == 1 - ' <<<"$MANAGED_IMAGE_CATALOG" >/dev/null || { - echo "::error::managed-image catalog source identity does not match the candidate" >&2 - exit 1 - } - if [[ "$RESTORE_CLI" == "true" ]]; then - candidate_release="v$(jq -r '.nemoclawVersion' dist/build-identity.json)" - jq -e --arg release "$candidate_release" ' - all(.[]; .source.release == $release) - ' <<<"$MANAGED_IMAGE_CATALOG" >/dev/null || { - echo "::error::managed-image catalog release does not match the restored CLI" >&2 - exit 1 - } - fi - jq -c . <<<"$MANAGED_IMAGE_CATALOG" >"$catalog_path" - [[ -s "$catalog_path" && ! -L "$catalog_path" ]] || { - echo "::error::temporary managed-image catalog is invalid" >&2 - exit 1 - } - printf 'NEMOCLAW_E2E_MANAGED_IMAGE_CATALOG=%s\n' "$catalog_path" >>"$GITHUB_ENV" - - name: Install reviewed cloudflared if: ${{ inputs.cloudflared }} shell: /bin/bash --noprofile --norc -e -o pipefail {0} diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 51020b43f17..0752770b662 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -2721,8 +2721,8 @@ jobs: include: ${{ fromJSON(needs.generate-matrix.outputs.matrix) }} env: E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} NEMOCLAW_LANGCHAIN_DEEPAGENTS_CODE_SANDBOX_BASE_IMAGE_REF: ${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && needs.base-image-publication.outputs.dcode_base_ref || '' }} NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js @@ -3013,9 +3013,8 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - managed_image_receipt: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: no provider credential target_id: ${{ matrix.target_id }} @@ -3056,9 +3055,8 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - managed_image_receipt: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: NVIDIA API key target_id: ${{ matrix.target_id }} @@ -3100,9 +3098,8 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - managed_image_receipt: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: NVIDIA inference API key target_id: ${{ matrix.target_id }} @@ -3144,9 +3141,8 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - managed_image_receipt: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: GitHub read token target_id: ${{ matrix.target_id }} @@ -3188,9 +3184,8 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - managed_image_receipt: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: Brave and NVIDIA inference API keys target_id: ${{ matrix.target_id }} @@ -3320,8 +3315,8 @@ jobs: agent_runtime: langchain-deepagents-code coverage_variant: deepagents env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "mcp-bridge" @@ -3655,8 +3650,8 @@ jobs: # MCP lifecycle without sharing destructive sandbox state. timeout-minutes: 90 env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "openshell-credential-generation-window" @@ -3830,8 +3825,8 @@ jobs: agent_runtime: langchain-deepagents-code coverage_variant: deepagents env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "mcp-bridge-dev" @@ -5001,8 +4996,8 @@ jobs: runs-on: ${{ fromJSON(needs.generate-matrix.outputs.runner_routing)['hermes-e2e'] }} timeout-minutes: 85 env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "hermes-e2e" @@ -5111,8 +5106,8 @@ jobs: observable_outcome: "Compatibility-only GPU startup reaches the stable Ready route" coverage_variant: compatibility-only env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "hermes-gpu-startup" @@ -5418,8 +5413,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 70 env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "cloud-onboard" @@ -5545,8 +5540,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 90 env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "messaging-providers" diff --git a/test/e2e/support/pr-managed-image-publication.test.ts b/test/e2e/support/pr-managed-image-publication.test.ts index 18eb4bc35d9..0d70f0f2cce 100644 --- a/test/e2e/support/pr-managed-image-publication.test.ts +++ b/test/e2e/support/pr-managed-image-publication.test.ts @@ -1,90 +1,16 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - import { describe, expect, it } from "vitest"; -import { - MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, - MANAGED_IMAGE_CONTRACT_VERSION, - MANAGED_IMAGE_REPOSITORIES, - MANAGED_IMAGE_SOURCE_REPOSITORY, - MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, - type ManagedImageAgent, - type ManagedImageContractV1, - SHIPPED_MANAGED_IMAGE_AGENTS, -} from "../../../src/lib/onboard/managed-image/contract"; -import { - assembleManagedImageCatalog, - main, - managedImagePublicationRequired, - parseManagedImagePullRequestPaths, - selectManagedImagePublicationRun, -} from "../../../tools/e2e/pr-managed-image-publication.mts"; - -const CANDIDATE_SHA = "a".repeat(40); -const PR_NUMBER = 8746; -const WORKFLOW_ID = 12345; - -function contract(agent: ManagedImageAgent, index: number): ManagedImageContractV1 { - const image = MANAGED_IMAGE_REPOSITORIES[agent]; - const digest = `sha256:${String(index + 1).repeat(64)}` as const; - return { - contractVersion: MANAGED_IMAGE_CONTRACT_VERSION, - agent, - platform: "linux/amd64", - image, - digest, - reference: `${image}@${digest}`, - source: { - repository: MANAGED_IMAGE_SOURCE_REPOSITORY, - revision: CANDIDATE_SHA, - release: "v0.0.110", - cohort: "ghrun-32144654845-1", - }, - startupProfileContractVersion: MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, - capabilityContractVersion: MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, - }; -} - -function run(overrides: Record = {}): unknown { - return { - total_count: 1, - workflow_runs: [ - { - id: 32144654845, - run_attempt: 1, - workflow_id: WORKFLOW_ID, - name: "Images / Build, Test, and Publish Managed Images", - path: ".github/workflows/managed-images.yaml", - event: "pull_request", - head_sha: CANDIDATE_SHA, - status: "completed", - conclusion: "success", - repository: { full_name: "NVIDIA/NemoClaw" }, - head_repository: { full_name: "NVIDIA/NemoClaw" }, - pull_requests: [{ number: PR_NUMBER }], - ...overrides, - }, - ], - }; -} +import { managedImagePublicationRequired } from "../../../tools/e2e/pr-managed-image-publication.mts"; -describe("exact PR managed-image publication (#8746, #9464)", () => { - it("derives applicability from the trusted managed-image workflow", () => { - const patterns = parseManagedImagePullRequestPaths( - fs.readFileSync(".github/workflows/managed-images.yaml", "utf8"), - ); +describe("PR managed-image source selection", () => { + it("matches only reviewed image input paths", () => { + const patterns = ["Dockerfile", "agents/**", "src/lib/actions/sandbox/mcp-bridge-*.ts"]; - expect( - managedImagePublicationRequired(["src/lib/onboard/workload/preparation.ts"], patterns), - ).toBe(true); - expect( - managedImagePublicationRequired(["tools/mcp-tool-discovery-runtime/server.mts"], patterns), - ).toBe(true); + expect(managedImagePublicationRequired(["Dockerfile"], patterns)).toBe(true); + expect(managedImagePublicationRequired(["agents/hermes/Dockerfile"], patterns)).toBe(true); expect( managedImagePublicationRequired( ["src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.ts"], @@ -96,106 +22,4 @@ describe("exact PR managed-image publication (#8746, #9464)", () => { managedImagePublicationRequired(["src/lib/onboard/file.ts\nother"], patterns), ).toThrow("changed-file path is invalid"); }); - - it("rejects an unreviewed path-filter glob", () => { - expect(() => - parseManagedImagePullRequestPaths(` -on: - pull_request: - paths: - - ".github/workflows/managed-images.yaml" - - "src/**/nested/**" -`), - ).toThrow("unsupported glob"); - }); - - it("selects one successful workflow run for the candidate commit", () => { - expect( - selectManagedImagePublicationRun(run(), { - headSha: CANDIDATE_SHA, - prNumber: PR_NUMBER, - workflowId: WORKFLOW_ID, - }), - ).toEqual({ id: 32144654845, attempt: 1, headSha: CANDIDATE_SHA }); - }); - - it.each([ - ["pending", { status: "in_progress", conclusion: null }, "must complete successfully"], - ["failed", { conclusion: "failure" }, "must complete successfully"], - ["different commit", { head_sha: "b".repeat(40) }, "commit must be"], - ["different PR", { pull_requests: [{ number: 9464 }] }, "PR number"], - ])("rejects a %s publication run", (_label, overrides, message) => { - expect(() => - selectManagedImagePublicationRun(run(overrides), { - headSha: CANDIDATE_SHA, - prNumber: PR_NUMBER, - workflowId: WORKFLOW_ID, - }), - ).toThrow(message); - }); - - it("assembles one exact all-agent catalog", () => { - const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map(contract); - - expect(assembleManagedImageCatalog(contracts, CANDIDATE_SHA)).toEqual( - Object.fromEntries(contracts.map((value) => [value.agent, value])), - ); - }); - - it("writes a validated catalog through the shared assembly command", async () => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-catalog-test-")); - try { - const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => { - const contractPath = path.join(directory, `${agent}.json`); - fs.writeFileSync(contractPath, JSON.stringify(contract(agent, index))); - return contractPath; - }); - const outputPath = path.join(directory, "catalog.json"); - - await main(["assemble", CANDIDATE_SHA, outputPath, ...contracts], {}); - - expect(JSON.parse(fs.readFileSync(outputPath, "utf8"))).toEqual( - Object.fromEntries( - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => [agent, contract(agent, index)]), - ), - ); - expect(fs.statSync(outputPath).mode & 0o777).toBe(0o600); - } finally { - fs.rmSync(directory, { force: true, recursive: true }); - } - }); - - it.each([ - [ - "candidate revision", - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => - index === 0 - ? { - ...contract(agent, index), - source: { ...contract(agent, index).source, revision: "b".repeat(40) }, - } - : contract(agent, index), - ), - "candidate commit", - ], - [ - "publication cohort", - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => - index === 0 - ? { - ...contract(agent, index), - source: { ...contract(agent, index).source, cohort: "ghrun-32144654845-2" }, - } - : contract(agent, index), - ), - "publication cohort", - ], - [ - "agent set", - [contract("openclaw", 0), contract("openclaw", 0), contract("hermes", 1)], - "every shipped agent", - ], - ])("rejects mixed %s authority", (_label, contracts, message) => { - expect(() => assembleManagedImageCatalog(contracts, CANDIDATE_SHA)).toThrow(message); - }); }); diff --git a/tools/e2e/mcp-workflow-boundary.mts b/tools/e2e/mcp-workflow-boundary.mts index 6a1a924707c..db252b05c6c 100644 --- a/tools/e2e/mcp-workflow-boundary.mts +++ b/tools/e2e/mcp-workflow-boundary.mts @@ -169,13 +169,13 @@ function validateJobIdentity( requireEqual( errors, env.E2E_MANAGED_IMAGE_REVISION, - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}", + "${{ needs.base-image-publication.outputs.managed_image_revision }}", `${jobName} must receive the selected managed-image cohort revision`, ); requireEqual( errors, env.E2E_MANAGED_IMAGE_COHORT_RECEIPT, - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }}", + "${{ needs.base-image-publication.outputs.managed_image_receipt }}", `${jobName} must receive the complete selected managed-image cohort receipt`, ); requireEqual( @@ -883,9 +883,9 @@ function validateCredentialWindowJob( const env = asRecord(job.env); const expectedEnv = { E2E_MANAGED_IMAGE_REVISION: - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}", + "${{ needs.base-image-publication.outputs.managed_image_revision }}", E2E_MANAGED_IMAGE_COHORT_RECEIPT: - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }}", + "${{ needs.base-image-publication.outputs.managed_image_receipt }}", E2E_WORKLOAD_SOURCE: "${{ needs.generate-matrix.outputs.workload_source }}", E2E_JOB: "1", E2E_TARGET_ID: CREDENTIAL_WINDOW_JOB, diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index fde1127f608..6cbc18ccb2d 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -772,19 +772,15 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): } if ( cloudOnboard.env?.E2E_MANAGED_IMAGE_REVISION !== - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}" + "${{ needs.base-image-publication.outputs.managed_image_revision }}" ) { - errors.push( - "cloud-onboard must use the selected managed-image revision when no exact PR catalog is present", - ); + errors.push("cloud-onboard must use the selected managed-image revision"); } if ( live.env?.E2E_MANAGED_IMAGE_REVISION !== - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}" + "${{ needs.base-image-publication.outputs.managed_image_revision }}" ) { - errors.push( - "live stock onboarding must use the selected managed-image revision when no exact PR catalog is present", - ); + errors.push("live stock onboarding must use the selected managed-image revision"); } for (const jobName of [ "catalogue-standard", @@ -799,17 +795,9 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): } if ( catalogue.with?.managed_image_revision !== - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}" - ) { - errors.push( - `${jobName} must use the selected managed-image revision when no exact PR catalog is present`, - ); - } - if ( - catalogue.with?.managed_image_catalog !== - "${{ needs.generate-matrix.outputs.managed_image_catalog }}" + "${{ needs.base-image-publication.outputs.managed_image_revision }}" ) { - errors.push(`${jobName} must pass the selected exact PR managed-image catalog`); + errors.push(`${jobName} must use the selected managed-image revision`); } } if ( @@ -872,9 +860,9 @@ const STOCK_ONBOARDING_CATALOGUE_JOBS = [ ] as const; const MANAGED_IMAGE_REVISION_EXPRESSION = - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}"; + "${{ needs.base-image-publication.outputs.managed_image_revision }}"; const MANAGED_IMAGE_RECEIPT_EXPRESSION = - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }}"; + "${{ needs.base-image-publication.outputs.managed_image_receipt }}"; /** Require publication success and one exact cohort revision for every stock onboarding job. */ export function validateStockOnboardingPublicationBoundary( diff --git a/tools/e2e/pr-managed-image-publication.mts b/tools/e2e/pr-managed-image-publication.mts index 01556218da3..682821f40ef 100644 --- a/tools/e2e/pr-managed-image-publication.mts +++ b/tools/e2e/pr-managed-image-publication.mts @@ -2,30 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; -import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import YAML from "yaml"; - -import { - parseManagedImageContractV1, - SHIPPED_MANAGED_IMAGE_AGENTS, - type ManagedImageContractCatalog, - type ManagedImageContractV1, -} from "../../src/lib/onboard/managed-image/contract.ts"; import { githubRequest, parseBaseImagePushPaths } from "./base-image-publication.mts"; -import { - bindNamedExactArtifact, - downloadBoundArtifact, - materializeContractArchive, -} from "./exact-artifact-download.mts"; const REPOSITORY = "NVIDIA/NemoClaw"; const BASE_IMAGE_WORKFLOW_PATH = ".github/workflows/base-image.yaml"; -const WORKFLOW_PATH = ".github/workflows/managed-images.yaml"; -const WORKFLOW_FILE = "managed-images.yaml"; -const WORKFLOW_NAME = "Images / Build, Test, and Publish Managed Images"; const MAX_CHANGED_FILES = 3_000; const PAGE_SIZE = 100; const SHA_PATTERN = /^[0-9a-f]{40}$/u; @@ -34,12 +17,6 @@ const SAFE_PATH_PATTERN = /^[A-Za-z0-9._/*-]+$/u; type JsonRecord = Record; -export interface ManagedImagePublicationRun { - readonly id: number; - readonly attempt: number; - readonly headSha: string; -} - export interface PrChangedFilesInput { readonly baseSha: string; readonly candidateRepository: string; @@ -91,31 +68,7 @@ function compileManagedImagePath(pattern: string): RegExp { throw new Error(`managed-image PR path '${pattern}' uses an unsupported glob`); } -/** Read the managed-image workflow path filter from the trusted workflow source. */ -export function parseManagedImagePullRequestPaths(source: string): string[] { - const workflow = record(YAML.parse(source), "managed-image workflow"); - const triggers = record(workflow.on, "managed-image workflow on block"); - const pullRequest = record(triggers.pull_request, "managed-image pull_request trigger"); - if (!Array.isArray(pullRequest.paths) || pullRequest.paths.length === 0) { - throw new Error("managed-image pull_request trigger must declare paths"); - } - const paths = pullRequest.paths.map((value) => { - if (typeof value !== "string" || value.length === 0 || value.trim() !== value) { - throw new Error("managed-image PR paths must be non-empty strings"); - } - compileManagedImagePath(value); - return value; - }); - if (new Set(paths).size !== paths.length) { - throw new Error("managed-image PR paths must be unique"); - } - if (!paths.includes(WORKFLOW_PATH)) { - throw new Error(`managed-image PR paths must include ${WORKFLOW_PATH}`); - } - return paths; -} - -/** Determine whether changed PR files require exact managed-image publication. */ +/** Determine whether changed PR files require local candidate image builds. */ export function managedImagePublicationRequired( changedFiles: readonly string[], patterns: readonly string[], @@ -140,118 +93,6 @@ export function managedImagePublicationRequired( return false; } -/** Select the unique successful managed-image workflow run for one PR commit. */ -export function selectManagedImagePublicationRun( - payload: unknown, - expected: { readonly headSha: string; readonly prNumber: number; readonly workflowId: number }, -): ManagedImagePublicationRun { - if (!SHA_PATTERN.test(expected.headSha)) throw new Error("candidate SHA is invalid"); - positiveInteger(expected.prNumber, "PR number"); - positiveInteger(expected.workflowId, "managed-image workflow id"); - const response = record(payload, "managed-image workflow runs"); - if (response.total_count !== 1 || !Array.isArray(response.workflow_runs)) { - throw new Error("exact managed-image workflow run is missing or ambiguous"); - } - if (response.workflow_runs.length !== 1) { - throw new Error("exact managed-image workflow run listing is incomplete"); - } - const run = record(response.workflow_runs[0], "managed-image workflow run"); - const id = positiveInteger(run.id, "managed-image workflow run id"); - const attempt = positiveInteger(run.run_attempt, "managed-image workflow run attempt"); - if (run.workflow_id !== expected.workflowId) { - throw new Error("managed-image workflow run does not match the trusted workflow"); - } - exactString(run.name, WORKFLOW_NAME, "managed-image workflow run name"); - exactString(run.path, WORKFLOW_PATH, "managed-image workflow run path"); - exactString(run.event, "pull_request", "managed-image workflow run event"); - exactString(run.head_sha, expected.headSha, "managed-image workflow run commit"); - exactString( - record(run.repository, "managed-image workflow repository").full_name, - REPOSITORY, - "managed-image workflow repository", - ); - exactString( - record(run.head_repository, "managed-image workflow source repository").full_name, - REPOSITORY, - "managed-image workflow source repository", - ); - if ( - !Array.isArray(run.pull_requests) || - run.pull_requests.length !== 1 || - record(run.pull_requests[0], "managed-image workflow pull request").number !== expected.prNumber - ) { - throw new Error("managed-image workflow run does not match the PR number"); - } - if (run.status !== "completed" || run.conclusion !== "success") { - throw new Error( - `managed-image workflow for candidate ${expected.headSha} must complete successfully before live E2E`, - ); - } - return { id, attempt, headSha: expected.headSha }; -} - -/** Assemble one all-agent catalog and reject mixed publication authority. */ -export function assembleManagedImageCatalog( - values: readonly unknown[], - candidateSha: string, -): ManagedImageContractCatalog { - if (!SHA_PATTERN.test(candidateSha)) throw new Error("candidate SHA is invalid"); - if (values.length !== SHIPPED_MANAGED_IMAGE_AGENTS.length) { - throw new Error( - `exact PR managed-image publication requires ${SHIPPED_MANAGED_IMAGE_AGENTS.length} contracts`, - ); - } - const contracts = values.map((value) => - parseManagedImageContractV1(value, undefined, "linux/amd64"), - ); - const byAgent = new Map(contracts.map((contract) => [contract.agent, contract])); - if ( - byAgent.size !== SHIPPED_MANAGED_IMAGE_AGENTS.length || - SHIPPED_MANAGED_IMAGE_AGENTS.some((agent) => !byAgent.has(agent)) - ) { - throw new Error("exact PR managed-image publication must contain every shipped agent once"); - } - const revisions = new Set(contracts.map((contract) => contract.source.revision)); - const releases = new Set(contracts.map((contract) => contract.source.release)); - const cohorts = new Set(contracts.map((contract) => contract.source.cohort)); - if (!revisions.has(candidateSha) || revisions.size !== 1) { - throw new Error("exact PR managed-image contracts do not match the candidate commit"); - } - if (releases.size !== 1 || cohorts.size !== 1) { - throw new Error("exact PR managed-image contracts do not form one publication cohort"); - } - return Object.fromEntries( - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent) => [agent, byAgent.get(agent)!]), - ); -} - -/** Write one validated exact-candidate catalog from local contract paths. */ -export function writeManagedImageCatalog( - contractPaths: readonly string[], - candidateSha: string, - outputPath: string, -): void { - const contracts = contractPaths.map( - (contractPath) => JSON.parse(fs.readFileSync(contractPath, "utf8")) as unknown, - ); - const catalog = assembleManagedImageCatalog(contracts, candidateSha); - fs.mkdirSync(path.dirname(path.resolve(outputPath)), { mode: 0o700, recursive: true }); - fs.writeFileSync(outputPath, `${JSON.stringify(catalog)}\n`, { - encoding: "utf8", - flag: "wx", - mode: 0o600, - }); -} - -function validateWorkflow(payload: unknown): number { - const workflow = record(payload, "managed-image workflow"); - const id = positiveInteger(workflow.id, "managed-image workflow id"); - exactString(workflow.name, WORKFLOW_NAME, "managed-image workflow name"); - exactString(workflow.path, WORKFLOW_PATH, "managed-image workflow path"); - exactString(workflow.state, "active", "managed-image workflow state"); - return id; -} - async function readChangedFiles( prNumber: number, count: number, @@ -367,112 +208,24 @@ export async function resolvePrManagedImageSource( : "managed-image"; } -/** Resolve and download the exact all-agent catalog before candidate code executes. */ -export async function resolvePrManagedImageCatalog( - input: { - readonly baseSha: string; - readonly candidateRepository: string; - readonly candidateSha: string; - readonly outputPath: string; - readonly prNumber: number; - readonly token: string; - readonly workflowSource: string; - }, - request: (path: string) => Promise = (apiPath) => githubRequest(apiPath, input.token), -): Promise<"not-required" | "written"> { - if (input.candidateRepository !== REPOSITORY) return "not-required"; - if (!input.token) throw new Error("GITHUB_TOKEN is required"); - const changedFiles = await readPrChangedFiles(input, request); - const patterns = parseManagedImagePullRequestPaths(input.workflowSource); - if (!managedImagePublicationRequired(changedFiles, patterns)) return "not-required"; - - const workflowId = validateWorkflow( - await request(`/repos/${REPOSITORY}/actions/workflows/${WORKFLOW_FILE}`), - ); - const runs = await request( - `/repos/${REPOSITORY}/actions/workflows/${WORKFLOW_FILE}/runs?event=pull_request&head_sha=${input.candidateSha}&per_page=100`, - ); - const run = selectManagedImagePublicationRun(runs, { - headSha: input.candidateSha, - prNumber: input.prNumber, - workflowId, - }); - - const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-managed-catalog-")); - try { - const contracts: ManagedImageContractV1[] = []; - for (const agent of SHIPPED_MANAGED_IMAGE_AGENTS) { - const name = `managed-pr-contract-${run.id}-${run.attempt}-${agent}`; - const metadata = await request( - `/repos/${REPOSITORY}/actions/runs/${run.id}/artifacts?name=${encodeURIComponent(name)}&per_page=100`, - ); - const identity = bindNamedExactArtifact( - metadata, - { - headSha: run.headSha, - runAttempt: run.attempt, - runId: run.id, - }, - name, - ); - const archive = await downloadBoundArtifact(identity, input.token); - const contractPath = materializeContractArchive(archive, path.join(tempDirectory, agent)); - contracts.push( - JSON.parse(fs.readFileSync(contractPath, "utf8")) as unknown as ManagedImageContractV1, - ); - } - const catalog = assembleManagedImageCatalog(contracts, input.candidateSha); - fs.mkdirSync(path.dirname(path.resolve(input.outputPath)), { mode: 0o700, recursive: true }); - fs.writeFileSync(input.outputPath, `${JSON.stringify(catalog)}\n`, { - encoding: "utf8", - flag: "wx", - mode: 0o600, - }); - return "written"; - } finally { - fs.rmSync(tempDirectory, { force: true, recursive: true }); - } -} - function requiredInteger(value: string | undefined, label: string): number { if (!value || !/^[1-9][0-9]*$/u.test(value)) throw new Error(`${label} is required`); return positiveInteger(Number(value), label); } export async function main(argv = process.argv.slice(2), env = process.env): Promise { - if (argv.length === 1 && argv[0] === "select-source") { - const source = await resolvePrManagedImageSource({ - baseSha: env.BASE_SHA ?? "", - candidateRepository: env.CANDIDATE_REPOSITORY ?? "", - candidateSha: env.CANDIDATE_SHA ?? "", - prNumber: requiredInteger(env.PR_NUMBER, "PR_NUMBER"), - token: env.GITHUB_TOKEN ?? "", - workflowSource: fs.readFileSync(BASE_IMAGE_WORKFLOW_PATH, "utf8"), - }); - process.stdout.write(`${source}\n`); - return; - } - if (argv[0] === "assemble") { - if (argv.length < 4) { - throw new Error("expected candidate SHA, output path, and managed-image contract paths"); - } - writeManagedImageCatalog(argv.slice(3), argv[1], argv[2]); - console.log("pr-managed-image-catalog outcome=assembled"); - return; + if (argv.length !== 1 || argv[0] !== "select-source") { + throw new Error("expected select-source"); } - if (argv.length !== 1) throw new Error("expected one managed-image catalog output path"); - const candidateSha = env.CANDIDATE_SHA ?? ""; - if (!candidateSha) return; - const result = await resolvePrManagedImageCatalog({ + const source = await resolvePrManagedImageSource({ baseSha: env.BASE_SHA ?? "", candidateRepository: env.CANDIDATE_REPOSITORY ?? "", - candidateSha, - outputPath: argv[0], + candidateSha: env.CANDIDATE_SHA ?? "", prNumber: requiredInteger(env.PR_NUMBER, "PR_NUMBER"), token: env.GITHUB_TOKEN ?? "", - workflowSource: fs.readFileSync(WORKFLOW_PATH, "utf8"), + workflowSource: fs.readFileSync(BASE_IMAGE_WORKFLOW_PATH, "utf8"), }); - console.log(`pr-managed-image-catalog outcome=${result}`); + process.stdout.write(`${source}\n`); } if (path.resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) { diff --git a/tools/e2e/standard-profile-workflow-boundary.mts b/tools/e2e/standard-profile-workflow-boundary.mts index 7056e2a95a8..e21d9ec04f2 100644 --- a/tools/e2e/standard-profile-workflow-boundary.mts +++ b/tools/e2e/standard-profile-workflow-boundary.mts @@ -163,11 +163,8 @@ function validateProfileCallers(errors: string[], workflow: WorkflowRecord): voi risk_signal_correlation_id: "${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }}", cli_artifact_provenance: "${{ needs.generate-matrix.outputs.cli_artifact_provenance }}", - managed_image_catalog: "${{ needs.generate-matrix.outputs.managed_image_catalog }}", - managed_image_revision: - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}", - managed_image_receipt: - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }}", + managed_image_revision: "${{ needs.base-image-publication.outputs.managed_image_revision }}", + managed_image_receipt: "${{ needs.base-image-publication.outputs.managed_image_receipt }}", workload_source: "${{ needs.generate-matrix.outputs.workload_source }}", credential_boundary: contract.credentialBoundary, catalogue_id: "${{ matrix.id }}", @@ -216,7 +213,6 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi risk_signal_expected_sha: "string", risk_signal_correlation_id: "string", cli_artifact_provenance: "string", - managed_image_catalog: "string", managed_image_revision: "string", managed_image_receipt: "string", workload_source: "string", @@ -313,7 +309,6 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi "Install target host dependencies", "Prepare E2E workspace", "Restore exact-commit CLI artifact", - "Materialize temporary managed-image catalog", "Install reviewed cloudflared", "Add swap for Hermes image rebuild", "Initialize runner comparison telemetry", @@ -464,38 +459,6 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi ) { errors.push("standard E2E profile must restore the planned exact-commit CLI artifact"); } - const managedCatalog = requireStep( - errors, - workflowSteps, - "Materialize temporary managed-image catalog", - ); - const managedCatalogRun = String(managedCatalog?.run ?? ""); - if ( - managedCatalog?.if !== "${{ inputs.managed_image_catalog != '' }}" || - managedCatalog.shell !== EXECUTION_PLAN_SHELL || - !isDeepStrictEqual(record(managedCatalog.env), { - CANDIDATE_SHA: "${{ inputs.candidate_sha }}", - MANAGED_IMAGE_CATALOG: "${{ inputs.managed_image_catalog }}", - RESTORE_CLI: "${{ inputs.restore_cli && 'true' || 'false' }}", - }) || - !managedCatalogRun.includes(".source.revision == $revision") || - !managedCatalogRun.includes("[.[].source.release] | unique | length") || - !managedCatalogRun.includes("[.[].source.cohort] | unique | length") || - !managedCatalogRun.includes('[[ "$RESTORE_CLI" == "true" ]]') || - !managedCatalogRun.includes(".source.release == $release") || - !managedCatalogRun.includes( - "managed-image catalog source identity does not match the candidate", - ) || - !managedCatalogRun.includes("managed-image catalog release does not match the restored CLI") || - !managedCatalogRun.includes("NEMOCLAW_E2E_MANAGED_IMAGE_CATALOG") || - managedCatalogRun.includes("NEMOCLAW_E2E_EXACT_RELEASE") || - managedCatalogRun.includes(".source.release = $release") || - workflowSteps.indexOf(managedCatalog ?? {}) !== workflowSteps.indexOf(restore ?? {}) + 1 - ) { - errors.push( - "standard E2E profile must materialize only the exact-candidate managed-image catalog", - ); - } const cloudflared = requireStep(errors, workflowSteps, "Install reviewed cloudflared"); const cloudflaredRun = String(cloudflared?.run ?? ""); if ( @@ -513,7 +476,7 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi !cloudflaredRun.includes('dpkg-deb -f "${cloudflared_deb}" Package') || !cloudflaredRun.includes('"${architecture}" != "amd64"') || cloudflaredRun.includes("command -v cloudflared") || - workflowSteps.indexOf(cloudflared ?? {}) !== workflowSteps.indexOf(managedCatalog ?? {}) + 1 + workflowSteps.indexOf(cloudflared ?? {}) !== workflowSteps.indexOf(restore ?? {}) + 1 ) { errors.push("standard E2E profile must install only the reviewed cloudflared package"); } From a2b575e43506b29fcfd6ad32f576d69e6c123930 Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 28 Aug 2026 18:07:03 +0700 Subject: [PATCH 33/40] fix(e2e): retain managed image catalog assembler Signed-off-by: San Dang --- tools/e2e/base-image-publication.mts | 27 ++++++ tools/e2e/pr-managed-image-publication.mts | 107 ++++++++++++++------- 2 files changed, 99 insertions(+), 35 deletions(-) diff --git a/tools/e2e/base-image-publication.mts b/tools/e2e/base-image-publication.mts index 8d0f6935969..b1302e5333e 100644 --- a/tools/e2e/base-image-publication.mts +++ b/tools/e2e/base-image-publication.mts @@ -206,6 +206,33 @@ function parseQuotedPath(raw: string, lineNumber: number): string { return value; } +/** Match one validated base-image workflow path without duplicating its glob semantics. */ +export function matchesBaseImagePushPath(pattern: string, changedPath: string): boolean { + if ( + changedPath.length === 0 || + changedPath.length > 4_096 || + /[\0\r\n]/u.test(changedPath) || + changedPath.startsWith("/") || + changedPath.includes("//") || + changedPath.split("/").some((segment) => segment === "" || segment === "." || segment === "..") + ) { + throw new Error("base-image changed path is invalid"); + } + const matcher = REVIEWED_PATH_GLOBS.get(pattern); + if (matcher) return matcher.test(changedPath); + if ( + !SAFE_PATH_PATTERN.test(pattern) || + pattern.startsWith("/") || + pattern.startsWith("-") || + pattern.startsWith(":") || + pattern.includes("//") || + pattern.split("/").some((segment) => segment === "" || segment === "." || segment === "..") + ) { + throw new Error("base-image push pattern is not reviewed"); + } + return pattern === changedPath; +} + /** * Read the controlled path list without requiring a dependency install in the * preflight job. Deliberately reject YAML features such as flow lists, aliases, diff --git a/tools/e2e/pr-managed-image-publication.mts b/tools/e2e/pr-managed-image-publication.mts index 682821f40ef..ae51085b55d 100644 --- a/tools/e2e/pr-managed-image-publication.mts +++ b/tools/e2e/pr-managed-image-publication.mts @@ -5,7 +5,16 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { githubRequest, parseBaseImagePushPaths } from "./base-image-publication.mts"; +import { + parseManagedImageContractV1, + SHIPPED_MANAGED_IMAGE_AGENTS, + type ManagedImageContractCatalog, +} from "../../src/lib/onboard/managed-image/contract.ts"; +import { + githubRequest, + matchesBaseImagePushPath, + parseBaseImagePushPaths, +} from "./base-image-publication.mts"; const REPOSITORY = "NVIDIA/NemoClaw"; const BASE_IMAGE_WORKFLOW_PATH = ".github/workflows/base-image.yaml"; @@ -13,7 +22,6 @@ const MAX_CHANGED_FILES = 3_000; const PAGE_SIZE = 100; const SHA_PATTERN = /^[0-9a-f]{40}$/u; const REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u; -const SAFE_PATH_PATTERN = /^[A-Za-z0-9._/*-]+$/u; type JsonRecord = Record; @@ -44,30 +52,6 @@ function exactString(value: unknown, expected: string, label: string): void { if (value !== expected) throw new Error(`${label} must be ${expected}`); } -function compileManagedImagePath(pattern: string): RegExp { - if ( - !SAFE_PATH_PATTERN.test(pattern) || - pattern.startsWith("/") || - pattern.includes("//") || - pattern.split("/").some((segment) => segment === "" || segment === "." || segment === "..") - ) { - throw new Error(`managed-image PR path '${pattern}' is invalid`); - } - const stars = [...pattern.matchAll(/\*/gu)].map((match) => match.index); - if (stars.length === 0) { - return new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}$`, "u"); - } - if (pattern.endsWith("/**") && stars.length === 2) { - const prefix = pattern.slice(0, -3).replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); - return new RegExp(`^${prefix}/.+$`, "u"); - } - if (stars.length === 1) { - const escaped = pattern.replace(/[.+?^${}()|[\]\\]/gu, "\\$&").replaceAll("*", "[^/]*"); - return new RegExp(`^${escaped}$`, "u"); - } - throw new Error(`managed-image PR path '${pattern}' uses an unsupported glob`); -} - /** Determine whether changed PR files require local candidate image builds. */ export function managedImagePublicationRequired( changedFiles: readonly string[], @@ -76,7 +60,6 @@ export function managedImagePublicationRequired( if (changedFiles.length > MAX_CHANGED_FILES * 2) { throw new Error(`PR changed-path count exceeds ${MAX_CHANGED_FILES * 2}`); } - const matchers = patterns.map(compileManagedImagePath); for (const file of changedFiles) { if ( file.length === 0 || @@ -88,11 +71,62 @@ export function managedImagePublicationRequired( ) { throw new Error("PR changed-file path is invalid"); } - if (matchers.some((matcher) => matcher.test(file))) return true; + if (patterns.some((pattern) => matchesBaseImagePushPath(pattern, file))) return true; } return false; } +function assembleManagedImageCatalog( + values: readonly unknown[], + candidateSha: string, +): ManagedImageContractCatalog { + if (!SHA_PATTERN.test(candidateSha)) throw new Error("candidate SHA is invalid"); + if (values.length !== SHIPPED_MANAGED_IMAGE_AGENTS.length) { + throw new Error( + `exact PR managed-image publication requires ${SHIPPED_MANAGED_IMAGE_AGENTS.length} contracts`, + ); + } + const contracts = values.map((value) => + parseManagedImageContractV1(value, undefined, "linux/amd64"), + ); + const byAgent = new Map(contracts.map((contract) => [contract.agent, contract])); + if ( + byAgent.size !== SHIPPED_MANAGED_IMAGE_AGENTS.length || + SHIPPED_MANAGED_IMAGE_AGENTS.some((agent) => !byAgent.has(agent)) + ) { + throw new Error("exact PR managed-image publication must contain every shipped agent once"); + } + const revisions = new Set(contracts.map((contract) => contract.source.revision)); + const releases = new Set(contracts.map((contract) => contract.source.release)); + const cohorts = new Set(contracts.map((contract) => contract.source.cohort)); + if (!revisions.has(candidateSha) || revisions.size !== 1) { + throw new Error("exact PR managed-image contracts do not match the candidate commit"); + } + if (releases.size !== 1 || cohorts.size !== 1) { + throw new Error("exact PR managed-image contracts do not form one publication cohort"); + } + return Object.fromEntries( + SHIPPED_MANAGED_IMAGE_AGENTS.map((agent) => [agent, byAgent.get(agent)!]), + ); +} + +function writeManagedImageCatalog( + contractPaths: readonly string[], + candidateSha: string, + outputPath: string, +): void { + const contracts = contractPaths.map( + (contractPath) => JSON.parse(fs.readFileSync(contractPath, "utf8")) as unknown, + ); + const catalog = assembleManagedImageCatalog(contracts, candidateSha); + fs.mkdirSync(path.dirname(path.resolve(outputPath)), { mode: 0o700, recursive: true }); + fs.writeFileSync(outputPath, `${JSON.stringify(catalog)}\n`, { + encoding: "utf8", + flag: "wx", + mode: 0o600, + }); +} + async function readChangedFiles( prNumber: number, count: number, @@ -177,9 +211,7 @@ export async function readPrChangedFiles( } if ( !REPOSITORY_PATTERN.test(input.candidateRepository) || - input.candidateRepository - .split("/") - .some((segment) => segment === "." || segment === "..") + input.candidateRepository.split("/").some((segment) => segment === "." || segment === "..") ) { throw new Error("candidate repository is invalid"); } @@ -197,8 +229,7 @@ export async function resolvePrManagedImageSource( readonly token: string; readonly workflowSource: string; }, - request: (apiPath: string) => Promise = (apiPath) => - githubRequest(apiPath, input.token), + request: (apiPath: string) => Promise = (apiPath) => githubRequest(apiPath, input.token), ): Promise { if (!input.token) throw new Error("GITHUB_TOKEN is required"); const changedFiles = await readPrChangedFiles(input, request); @@ -214,9 +245,15 @@ function requiredInteger(value: string | undefined, label: string): number { } export async function main(argv = process.argv.slice(2), env = process.env): Promise { - if (argv.length !== 1 || argv[0] !== "select-source") { - throw new Error("expected select-source"); + if (argv[0] === "assemble") { + if (argv.length < 4) { + throw new Error("expected candidate SHA, output path, and managed-image contract paths"); + } + writeManagedImageCatalog(argv.slice(3), argv[1], argv[2]); + console.log("pr-managed-image-catalog outcome=assembled"); + return; } + if (argv.length !== 1 || argv[0] !== "select-source") throw new Error("expected select-source"); const source = await resolvePrManagedImageSource({ baseSha: env.BASE_SHA ?? "", candidateRepository: env.CANDIDATE_REPOSITORY ?? "", From 0847dd91949bf949bea5a223ed144c31064cb21c Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 28 Aug 2026 18:13:48 +0700 Subject: [PATCH 34/40] refactor(e2e): remove obsolete DCode publication path Signed-off-by: San Dang --- .../support/pr-dcode-base-publication.test.ts | 214 ---------- tools/e2e/pr-dcode-base-publication.mts | 367 ------------------ 2 files changed, 581 deletions(-) delete mode 100644 test/e2e/support/pr-dcode-base-publication.test.ts delete mode 100644 tools/e2e/pr-dcode-base-publication.mts diff --git a/test/e2e/support/pr-dcode-base-publication.test.ts b/test/e2e/support/pr-dcode-base-publication.test.ts deleted file mode 100644 index f6c185b9665..00000000000 --- a/test/e2e/support/pr-dcode-base-publication.test.ts +++ /dev/null @@ -1,214 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { createHash } from "node:crypto"; - -import { describe, expect, it, vi } from "vitest"; - -import { - MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, - MANAGED_IMAGE_CONTRACT_VERSION, - MANAGED_IMAGE_REPOSITORIES, - MANAGED_IMAGE_SOURCE_REPOSITORY, - MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, - SHIPPED_MANAGED_IMAGE_AGENTS, - type ManagedImageAgent, - type ManagedImageContractV1, -} from "../../../src/lib/onboard/managed-image/contract.ts"; -import { - buildDockerInspectionEnvironment, - readDcodeBaseResolution, - resolvePrDcodeBasePublication, -} from "../../../tools/e2e/pr-dcode-base-publication.mts"; - -const CANDIDATE_SHA = "a".repeat(40); -const BASE_SOURCE_SHA = "b".repeat(40); -const COHORT = "ghrun-32841372913-1"; -const BASE_IMAGE = "ghcr.io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base"; -const BASE_DIGEST = `sha256:${"c".repeat(64)}`; -const BASE_REFERENCE = `${BASE_IMAGE}@${BASE_DIGEST}`; -const MANAGED_DIGEST = `sha256:${"d".repeat(64)}`; -const DCODE_IMAGE = MANAGED_IMAGE_REPOSITORIES["langchain-deepagents-code"]; -const DCODE_REFERENCE = `${DCODE_IMAGE}@${MANAGED_DIGEST}`; - -function contract(agent: ManagedImageAgent, index: number): ManagedImageContractV1 { - const image = MANAGED_IMAGE_REPOSITORIES[agent]; - const digest: ManagedImageContractV1["digest"] = - agent === "langchain-deepagents-code" - ? (MANAGED_DIGEST as ManagedImageContractV1["digest"]) - : (`sha256:${String(index + 1).repeat(64)}` as const); - return { - contractVersion: MANAGED_IMAGE_CONTRACT_VERSION, - agent, - platform: "linux/amd64", - image, - digest, - reference: `${image}@${digest}`, - source: { - repository: MANAGED_IMAGE_SOURCE_REPOSITORY, - revision: CANDIDATE_SHA, - release: "v0.0.113", - cohort: COHORT, - }, - startupProfileContractVersion: MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, - capabilityContractVersion: MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, - }; -} - -function catalog(): string { - return JSON.stringify( - Object.fromEntries( - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => [agent, contract(agent, index)]), - ), - ); -} - -function baseResolution(overrides: Record = {}): Record { - const value = { - schema: 1, - key: "", - imageName: BASE_IMAGE, - ref: BASE_REFERENCE, - digest: BASE_DIGEST, - source: "override", - sourceRevision: BASE_SOURCE_SHA, - imageId: `sha256:${"e".repeat(64)}`, - os: "linux", - architecture: "amd64", - glibcVersion: "2.39", - requireOpenshellSandboxAbi: true, - minGlibcVersion: "2.39", - ...overrides, - }; - value.key = createHash("sha256") - .update(JSON.stringify({ ...value, key: "" })) - .digest("hex"); - return value; -} - -function inspection(resolution = baseResolution()): unknown { - const encoded = Buffer.from(JSON.stringify(resolution)).toString("base64url"); - return [ - { - Architecture: "amd64", - Os: "linux", - RepoDigests: [DCODE_REFERENCE], - Config: { - Labels: { - "com.nvidia.nemoclaw.base-resolution": encoded, - "com.nvidia.nemoclaw.base-resolution-key": resolution.key, - "io.nvidia.nemoclaw.agent": "langchain-deepagents-code", - "io.nvidia.nemoclaw.managed-image.cohort": COHORT, - "io.nvidia.nemoclaw.managed-image.contract": "1", - "io.nvidia.nemoclaw.managed-image.platform": "linux/amd64", - "org.opencontainers.image.revision": CANDIDATE_SHA, - "org.opencontainers.image.version": "v0.0.113", - }, - }, - }, - ]; -} - -const publication = { - id: 32832002443, - attempt: 1, - workflowId: 194842001, - headSha: BASE_SOURCE_SHA, - status: "completed", - conclusion: "success", - url: "https://github.com/NVIDIA/NemoClaw/actions/runs/32832002443", -}; - -describe("exact PR Deep Agents Code base publication pairing", () => { - it("keeps controller credentials out of Docker inspection subprocesses", () => { - expect( - buildDockerInspectionEnvironment({ - DOCKER_HOST: "unix:///var/run/docker.sock", - GITHUB_TOKEN: "github-secret", - LC_ALL: "C.UTF-8", - NVIDIA_API_KEY: "nvidia-secret", - PATH: "/usr/bin:/bin", - }), - ).toEqual({ - DOCKER_HOST: "unix:///var/run/docker.sock", - LC_ALL: "C.UTF-8", - PATH: "/usr/bin:/bin", - }); - }); - - it("selects the trusted publication for the base source revision recorded by the exact PR managed image", async () => { - const inspectManagedImage = vi.fn(() => inspection()); - const resolvePublication = vi.fn(async () => publication); - - await expect( - resolvePrDcodeBasePublication( - { candidateSha: CANDIDATE_SHA, catalog: catalog(), token: "test-token" }, - { inspectManagedImage, resolvePublication }, - ), - ).resolves.toEqual({ baseReference: BASE_REFERENCE, run: publication }); - expect(inspectManagedImage).toHaveBeenCalledWith(DCODE_REFERENCE); - expect(resolvePublication).toHaveBeenCalledWith(BASE_SOURCE_SHA); - }); - - it("accepts the fixed base-resolution key for the producer field order", () => { - const expectedResolutionHash = - "083e317cc6f3dd2a14a4f2c7a52c3cbd40864b35c8182df2a6546e3b6f4236a1"; - const resolution = { - schema: 1, - key: expectedResolutionHash, - imageName: BASE_IMAGE, - ref: BASE_REFERENCE, - digest: BASE_DIGEST, - source: "override", - sourceRevision: BASE_SOURCE_SHA, - imageId: `sha256:${"e".repeat(64)}`, - os: "linux", - architecture: "amd64", - glibcVersion: "2.39", - requireOpenshellSandboxAbi: true, - minGlibcVersion: "2.39", - }; - - expect( - readDcodeBaseResolution( - inspection(resolution), - contract("langchain-deepagents-code", 2), - CANDIDATE_SHA, - ), - ).toEqual({ reference: BASE_REFERENCE, sourceRevision: BASE_SOURCE_SHA }); - }); - - it("rejects a base-resolution key that does not bind the recorded fields", () => { - const resolution = baseResolution(); - resolution.key = "f".repeat(64); - - expect(() => - readDcodeBaseResolution( - inspection(resolution), - contract("langchain-deepagents-code", 2), - CANDIDATE_SHA, - ), - ).toThrow("base resolution key is invalid"); - }); - - it("rejects a trusted publication from a different base source revision", async () => { - await expect( - resolvePrDcodeBasePublication( - { candidateSha: CANDIDATE_SHA, catalog: catalog(), token: "test-token" }, - { - inspectManagedImage: () => inspection(), - resolvePublication: async () => ({ ...publication, headSha: "f".repeat(40) }), - }, - ), - ).rejects.toThrow("does not match the managed image binding"); - }); - - it("rejects an image inspection that is not bound to the exact managed-image reference", () => { - const value = inspection() as Array>; - value[0]!.RepoDigests = [`${DCODE_IMAGE}@sha256:${"f".repeat(64)}`]; - - expect(() => - readDcodeBaseResolution(value, contract("langchain-deepagents-code", 2), CANDIDATE_SHA), - ).toThrow("does not match its exact reference"); - }); -}); diff --git a/tools/e2e/pr-dcode-base-publication.mts b/tools/e2e/pr-dcode-base-publication.mts deleted file mode 100644 index 145f2d7b3c3..00000000000 --- a/tools/e2e/pr-dcode-base-publication.mts +++ /dev/null @@ -1,367 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { createHash } from "node:crypto"; -import { execFileSync } from "node:child_process"; -import { appendFileSync } from "node:fs"; -import { fileURLToPath } from "node:url"; -import path from "node:path"; - -import { - MANAGED_IMAGE_REPOSITORIES, - parseManagedImageContractV1, - SHIPPED_MANAGED_IMAGE_AGENTS, - type ManagedImageContractCatalog, - type ManagedImageContractV1, -} from "../../src/lib/onboard/managed-image/contract.ts"; -import { - githubRequest, - type PublicationRun, - waitForBaseImagePublication, - writePublicationRunOutputs, -} from "./base-image-publication.mts"; - -const REPOSITORY = "NVIDIA/NemoClaw"; -const AGENT = "langchain-deepagents-code"; -const BASE_IMAGE = "ghcr.io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base"; -const BASE_RESOLUTION_KEY_LABEL = "com.nvidia.nemoclaw.base-resolution-key"; -const BASE_RESOLUTION_LABEL = "com.nvidia.nemoclaw.base-resolution"; -const SHA_PATTERN = /^[0-9a-f]{40}$/u; -const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/u; -const KEY_PATTERN = /^[0-9a-f]{64}$/u; -const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u; -const MAX_CATALOG_BYTES = 64 * 1024; -const MAX_RESOLUTION_BYTES = 8 * 1024; -const DOCKER_ENV_NAMES = new Set([ - "DOCKER_HOST", - "HOME", - "HTTPS_PROXY", - "HTTP_PROXY", - "LANG", - "NODE_EXTRA_CA_CERTS", - "NO_PROXY", - "PATH", - "SSL_CERT_DIR", - "SSL_CERT_FILE", - "TEMP", - "TMP", - "TMPDIR", - "https_proxy", - "http_proxy", - "no_proxy", -]); -const DOCKER_ENV_PREFIXES = ["LC_", "XDG_"] as const; - -type JsonRecord = Record; - -export interface DcodeBaseResolution { - readonly reference: string; - readonly sourceRevision: string; -} - -export interface PrDcodeBasePublication { - readonly baseReference: string; - readonly run: PublicationRun; -} - -export interface PrDcodeBasePublicationDependencies { - readonly inspectManagedImage?: (reference: string) => unknown; - readonly resolvePublication?: (sourceRevision: string) => Promise; -} - -function record(value: unknown, label: string): JsonRecord { - if (!value || typeof value !== "object" || Array.isArray(value)) { - throw new Error(`${label} must be a JSON object`); - } - return value as JsonRecord; -} - -function exactKeys(value: JsonRecord, expected: readonly string[], label: string): void { - if (JSON.stringify(Object.keys(value).sort()) !== JSON.stringify([...expected].sort())) { - throw new Error(`${label} has unexpected fields`); - } -} - -function parseCatalog(raw: string, candidateSha: string): ManagedImageContractV1 { - if (!SHA_PATTERN.test(candidateSha)) throw new Error("candidate SHA is invalid"); - if (!raw || Buffer.byteLength(raw) > MAX_CATALOG_BYTES) { - throw new Error("exact PR managed-image catalog is missing or oversized"); - } - let parsed: unknown; - try { - parsed = JSON.parse(raw) as unknown; - } catch { - throw new Error("exact PR managed-image catalog is invalid JSON"); - } - const catalog = record(parsed, "exact PR managed-image catalog"); - exactKeys(catalog, SHIPPED_MANAGED_IMAGE_AGENTS, "exact PR managed-image catalog"); - const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent) => - parseManagedImageContractV1(catalog[agent], agent, "linux/amd64"), - ); - if ( - new Set(contracts.map((contract) => contract.source.revision)).size !== 1 || - contracts[0]?.source.revision !== candidateSha - ) { - throw new Error("exact PR managed-image contracts do not match the candidate commit"); - } - if ( - new Set(contracts.map((contract) => contract.source.release)).size !== 1 || - new Set(contracts.map((contract) => contract.source.cohort)).size !== 1 - ) { - throw new Error("exact PR managed-image contracts do not form one publication cohort"); - } - const assembled = Object.fromEntries( - contracts.map((contract) => [contract.agent, contract]), - ) as ManagedImageContractCatalog; - return parseManagedImageContractV1(assembled[AGENT], AGENT, "linux/amd64"); -} - -/** Limit controller data exposed to the Docker image inspection subprocess. */ -export function buildDockerInspectionEnvironment( - environment: NodeJS.ProcessEnv, -): NodeJS.ProcessEnv { - return Object.fromEntries( - Object.entries(environment).filter( - ([name, value]) => - value !== undefined && - (DOCKER_ENV_NAMES.has(name) || - DOCKER_ENV_PREFIXES.some((prefix) => name.startsWith(prefix))), - ), - ); -} - -function defaultInspectManagedImage(reference: string): unknown { - const env = buildDockerInspectionEnvironment(process.env); - execFileSync("docker", ["pull", "--platform", "linux/amd64", reference], { - encoding: "utf8", - env, - killSignal: "SIGKILL", - maxBuffer: 4 * 1024 * 1024, - stdio: ["ignore", "ignore", "pipe"], - timeout: 600_000, - }); - return JSON.parse( - execFileSync("docker", ["image", "inspect", reference], { - encoding: "utf8", - env, - killSignal: "SIGKILL", - maxBuffer: 4 * 1024 * 1024, - stdio: ["ignore", "pipe", "pipe"], - timeout: 30_000, - }), - ) as unknown; -} - -function parseResolutionLabel(raw: string): JsonRecord { - if ( - !BASE64URL_PATTERN.test(raw) || - raw.length > MAX_RESOLUTION_BYTES || - Buffer.from(raw, "base64url").toString("base64url") !== raw - ) { - throw new Error("Deep Agents Code managed image base resolution label is invalid"); - } - try { - return record( - JSON.parse(Buffer.from(raw, "base64url").toString("utf8")) as unknown, - "Deep Agents Code managed image base resolution", - ); - } catch (error) { - if (error instanceof Error && error.message.includes("must be a JSON object")) throw error; - throw new Error("Deep Agents Code managed image base resolution label is invalid JSON"); - } -} - -/** Bind the exact PR managed image to the base reference recorded by its trusted producer. */ -export function readDcodeBaseResolution( - inspection: unknown, - contract: ManagedImageContractV1, - candidateSha: string, -): DcodeBaseResolution { - if ( - contract.agent !== AGENT || - contract.image !== MANAGED_IMAGE_REPOSITORIES[AGENT] || - contract.platform !== "linux/amd64" || - contract.source.revision !== candidateSha - ) { - throw new Error("Deep Agents Code managed-image contract does not match the candidate"); - } - if (!Array.isArray(inspection) || inspection.length !== 1) { - throw new Error("Deep Agents Code managed image inspection must contain one image"); - } - const image = record(inspection[0], "Deep Agents Code managed image inspection"); - if ( - image.Os !== "linux" || - image.Architecture !== "amd64" || - !Array.isArray(image.RepoDigests) || - !image.RepoDigests.includes(contract.reference) - ) { - throw new Error("Deep Agents Code managed image inspection does not match its exact reference"); - } - const labels = record( - record(image.Config, "Deep Agents Code managed image configuration").Labels, - "Deep Agents Code managed image labels", - ); - const rawResolution = labels[BASE_RESOLUTION_LABEL]; - const resolutionKey = labels[BASE_RESOLUTION_KEY_LABEL]; - if ( - labels["io.nvidia.nemoclaw.agent"] !== AGENT || - labels["io.nvidia.nemoclaw.managed-image.contract"] !== "1" || - labels["io.nvidia.nemoclaw.managed-image.platform"] !== "linux/amd64" || - labels["io.nvidia.nemoclaw.managed-image.cohort"] !== contract.source.cohort || - labels["org.opencontainers.image.revision"] !== candidateSha || - labels["org.opencontainers.image.version"] !== contract.source.release || - typeof rawResolution !== "string" || - typeof resolutionKey !== "string" - ) { - throw new Error("Deep Agents Code managed image labels do not match its exact contract"); - } - - const resolution = parseResolutionLabel(rawResolution); - exactKeys( - resolution, - [ - "architecture", - "digest", - "glibcVersion", - "imageId", - "imageName", - "key", - "minGlibcVersion", - "os", - "ref", - "requireOpenshellSandboxAbi", - "schema", - "source", - "sourceRevision", - ], - "Deep Agents Code managed image base resolution", - ); - const sourceRevision = resolution.sourceRevision; - const digest = resolution.digest; - const reference = resolution.ref; - if ( - resolution.schema !== 1 || - resolution.imageName !== BASE_IMAGE || - typeof digest !== "string" || - !DIGEST_PATTERN.test(digest) || - reference !== `${BASE_IMAGE}@${digest}` || - resolution.source !== "override" || - typeof sourceRevision !== "string" || - !SHA_PATTERN.test(sourceRevision) || - resolution.os !== "linux" || - resolution.architecture !== "amd64" || - typeof resolution.imageId !== "string" || - !DIGEST_PATTERN.test(resolution.imageId) || - typeof resolution.glibcVersion !== "string" || - !/^[0-9]+[.][0-9]+$/u.test(resolution.glibcVersion) || - resolution.minGlibcVersion !== "2.39" || - resolution.requireOpenshellSandboxAbi !== true || - typeof resolution.key !== "string" || - !KEY_PATTERN.test(resolution.key) || - resolution.key !== resolutionKey - ) { - throw new Error("Deep Agents Code managed image base resolution is invalid"); - } - const canonical = { - schema: 1, - key: "", - imageName: BASE_IMAGE, - ref: reference, - digest, - source: "override", - sourceRevision, - imageId: resolution.imageId, - os: "linux", - architecture: "amd64", - glibcVersion: resolution.glibcVersion, - requireOpenshellSandboxAbi: true, - minGlibcVersion: "2.39", - }; - const expectedKey = createHash("sha256").update(JSON.stringify(canonical)).digest("hex"); - if (resolution.key !== expectedKey) { - throw new Error("Deep Agents Code managed image base resolution key is invalid"); - } - return { reference, sourceRevision }; -} - -async function defaultResolvePublication( - sourceRevision: string, - token: string, -): Promise { - return waitForBaseImagePublication({ - history: { - expectedSha: sourceRevision, - relevantSha: sourceRevision, - relevantDistance: 0, - distanceBySha: new Map([[sourceRevision, 0]]), - }, - request: (apiPath) => githubRequest(apiPath, token), - requireWorkflowSuccess: true, - waitMs: 60_000, - pollMs: 5_000, - }); -} - -/** Resolve one trusted base publication for the source revision recorded by the exact PR managed image. */ -export async function resolvePrDcodeBasePublication( - input: { - readonly candidateSha: string; - readonly catalog: string; - readonly token: string; - }, - dependencies: PrDcodeBasePublicationDependencies = {}, -): Promise { - const contract = parseCatalog(input.catalog, input.candidateSha); - const inspection = (dependencies.inspectManagedImage ?? defaultInspectManagedImage)( - contract.reference, - ); - const resolution = readDcodeBaseResolution(inspection, contract, input.candidateSha); - const run = await ( - dependencies.resolvePublication ?? - ((sourceRevision) => defaultResolvePublication(sourceRevision, input.token)) - )(resolution.sourceRevision); - if (run.headSha !== resolution.sourceRevision) { - throw new Error("trusted base-image publication does not match the managed image binding"); - } - return { baseReference: resolution.reference, run }; -} - -export async function main(argv = process.argv.slice(2), env = process.env): Promise { - if (argv.length !== 0) throw new Error("expected no arguments"); - const candidateSha = env.CANDIDATE_SHA ?? ""; - const workflowSha = env.GITHUB_SHA ?? ""; - if ( - env.GITHUB_ACTIONS !== "true" || - env.GITHUB_EVENT_NAME !== "workflow_dispatch" || - env.GITHUB_REPOSITORY !== REPOSITORY || - env.CANDIDATE_REPOSITORY !== REPOSITORY || - !SHA_PATTERN.test(candidateSha) || - !SHA_PATTERN.test(workflowSha) || - candidateSha === workflowSha - ) { - throw new Error( - "Deep Agents Code base publication selection requires a trusted manual PR run for NVIDIA/NemoClaw", - ); - } - const token = env.GITHUB_TOKEN ?? ""; - if (!token || token.includes("\r") || token.includes("\n")) { - throw new Error("GITHUB_TOKEN must be a non-empty single-line value"); - } - const result = await resolvePrDcodeBasePublication({ - candidateSha, - catalog: env.MANAGED_IMAGE_CATALOG ?? "", - token, - }); - const outputPath = env.GITHUB_OUTPUT ?? ""; - writePublicationRunOutputs(outputPath, result.run); - appendFileSync(outputPath, `base_ref=${result.baseReference}\n`, "utf8"); -} - -if (path.resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) { - main().catch((error: unknown) => { - console.error( - error instanceof Error ? error.message : "unknown PR Deep Agents Code base publication error", - ); - process.exitCode = 1; - }); -} From 20a39f13c3a1d9545e1f7bb60a187a89d6bcf6ee Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 28 Aug 2026 18:21:56 +0700 Subject: [PATCH 35/40] fix(e2e): retain trusted base for local builds Signed-off-by: San Dang --- .github/workflows/e2e.yaml | 9 +++------ tools/e2e/operations-workflow-boundary.mts | 10 ++++------ 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 0752770b662..77e02864a2a 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -181,14 +181,13 @@ jobs: printf 'workload_source=%s\n' "$workload_source" >>"$GITHUB_OUTPUT" - id: publication - name: Select complete base and managed-image publication - if: ${{ inputs.pr_number == '' || steps.select_pr_source.outputs.workload_source == 'managed-image' }} + name: Select base and optional managed-image publication env: EXPECTED_SHA: ${{ steps.publication_mode.outputs.expected_sha }} GITHUB_TOKEN: ${{ github.token }} PUBLICATION_HISTORY_ALLOW_NON_HEAD: ${{ steps.publication_mode.outputs.allow_non_head }} - REQUIRE_MANAGED_IMAGE_PUBLICATION: "1" - SELECT_NEAREST_SUCCESSFUL_PUBLICATION: ${{ steps.publication_mode.outputs.select_nearest_successful }} + REQUIRE_MANAGED_IMAGE_PUBLICATION: ${{ steps.select_pr_source.outputs.workload_source == 'local-dockerfile' && '0' || '1' }} + SELECT_NEAREST_SUCCESSFUL_PUBLICATION: ${{ steps.select_pr_source.outputs.workload_source == 'local-dockerfile' && '0' || steps.publication_mode.outputs.select_nearest_successful }} shell: bash run: | set -euo pipefail @@ -201,7 +200,6 @@ jobs: node --experimental-strip-types --no-warnings tools/e2e/base-image-publication.mts --wait-seconds "$wait_seconds" --poll-seconds 30 - name: Download immutable Deep Agents Code base contract - if: ${{ inputs.pr_number == '' || steps.select_pr_source.outputs.workload_source == 'managed-image' }} env: GITHUB_TOKEN: ${{ github.token }} PUBLICATION_HEAD_SHA: ${{ steps.publication.outputs.head_sha }} @@ -211,7 +209,6 @@ jobs: - id: validate_dcode_base name: Validate immutable Deep Agents Code base - if: ${{ inputs.pr_number == '' || steps.select_pr_source.outputs.workload_source == 'managed-image' }} env: PUBLICATION_HEAD_SHA: ${{ steps.publication.outputs.head_sha }} PUBLICATION_RUN_ATTEMPT: ${{ steps.publication.outputs.run_attempt }} diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index 6cbc18ccb2d..6ac3012b727 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -676,16 +676,16 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): }, { id: "publication", - name: "Select complete base and managed-image publication", - if: MANAGED_SOURCE_CONDITION, + name: "Select base and optional managed-image publication", env: { EXPECTED_SHA: "${{ steps.publication_mode.outputs.expected_sha }}", GITHUB_TOKEN: "${{ github.token }}", PUBLICATION_HISTORY_ALLOW_NON_HEAD: "${{ steps.publication_mode.outputs.allow_non_head }}", - REQUIRE_MANAGED_IMAGE_PUBLICATION: "1", + REQUIRE_MANAGED_IMAGE_PUBLICATION: + "${{ steps.select_pr_source.outputs.workload_source == 'local-dockerfile' && '0' || '1' }}", SELECT_NEAREST_SUCCESSFUL_PUBLICATION: - "${{ steps.publication_mode.outputs.select_nearest_successful }}", + "${{ steps.select_pr_source.outputs.workload_source == 'local-dockerfile' && '0' || steps.publication_mode.outputs.select_nearest_successful }}", }, shell: "bash", run: [ @@ -702,7 +702,6 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): }, { name: "Download immutable Deep Agents Code base contract", - if: MANAGED_SOURCE_CONDITION, env: { GITHUB_TOKEN: "${{ github.token }}", PUBLICATION_HEAD_SHA: "${{ steps.publication.outputs.head_sha }}", @@ -714,7 +713,6 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): { id: "validate_dcode_base", name: "Validate immutable Deep Agents Code base", - if: MANAGED_SOURCE_CONDITION, env: { PUBLICATION_HEAD_SHA: "${{ steps.publication.outputs.head_sha }}", PUBLICATION_RUN_ATTEMPT: "${{ steps.publication.outputs.run_attempt }}", From fecee106ed726b8060071c96d4b51856288b4bc4 Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 28 Aug 2026 18:29:29 +0700 Subject: [PATCH 36/40] refactor(e2e): remove unused publication outputs Signed-off-by: San Dang --- .github/workflows/e2e.yaml | 4 ---- tools/e2e/operations-workflow-boundary.mts | 5 ----- 2 files changed, 9 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 77e02864a2a..abe6ef5f356 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -101,12 +101,8 @@ jobs: outputs: dcode_base_contract: ${{ steps.validate_dcode_base.outputs.contract }} dcode_base_ref: ${{ steps.validate_dcode_base.outputs.base_ref }} - managed_image_artifact_provenance: ${{ steps.download_managed_cohort.outputs.provenance }} - managed_image_cohort: ${{ steps.validate_managed_cohort.outputs.cohort }} managed_image_receipt: ${{ steps.validate_managed_cohort.outputs.receipt }} managed_image_revision: ${{ steps.validate_managed_cohort.outputs.revision }} - managed_image_run_attempt: ${{ steps.validate_managed_cohort.outputs.run_attempt }} - managed_image_run_id: ${{ steps.validate_managed_cohort.outputs.run_id }} workload_source: ${{ steps.select_pr_source.outputs.workload_source || 'managed-image' }} permissions: actions: read diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index 6ac3012b727..693277df2e5 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -605,14 +605,9 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): outputs: { dcode_base_contract: "${{ steps.validate_dcode_base.outputs.contract }}", dcode_base_ref: "${{ steps.validate_dcode_base.outputs.base_ref }}", - managed_image_artifact_provenance: - "${{ steps.download_managed_cohort.outputs.provenance }}", - managed_image_cohort: "${{ steps.validate_managed_cohort.outputs.cohort }}", managed_image_receipt: "${{ steps.validate_managed_cohort.outputs.receipt }}", managed_image_revision: "${{ steps.validate_managed_cohort.outputs.revision }}", - managed_image_run_attempt: "${{ steps.validate_managed_cohort.outputs.run_attempt }}", - managed_image_run_id: "${{ steps.validate_managed_cohort.outputs.run_id }}", workload_source: "${{ steps.select_pr_source.outputs.workload_source || 'managed-image' }}", }, permissions: { From 5994ff0406dd9189e83227ae501db510f401b839 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 29 Aug 2026 11:30:47 +0700 Subject: [PATCH 37/40] fix(e2e): bind image selection to commit trees Signed-off-by: San Dang --- .../pr-managed-image-publication.test.ts | 131 +++++++++++-- tools/e2e/base-image-publication.mts | 35 +++- tools/e2e/pr-managed-image-publication.mts | 178 +++++++++--------- 3 files changed, 235 insertions(+), 109 deletions(-) diff --git a/test/e2e/support/pr-managed-image-publication.test.ts b/test/e2e/support/pr-managed-image-publication.test.ts index 0d70f0f2cce..88282cd2333 100644 --- a/test/e2e/support/pr-managed-image-publication.test.ts +++ b/test/e2e/support/pr-managed-image-publication.test.ts @@ -1,25 +1,124 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; -import { managedImagePublicationRequired } from "../../../tools/e2e/pr-managed-image-publication.mts"; +import { githubRequest } from "../../../tools/e2e/base-image-publication.mts"; +import { resolvePrManagedImageSource } from "../../../tools/e2e/pr-managed-image-publication.mts"; + +const BASE_SHA = "b".repeat(40); +const CANDIDATE_SHA = "a".repeat(40); +const BASE_TREE_SHA = "1".repeat(40); +const CANDIDATE_TREE_SHA = "2".repeat(40); +const PR_NUMBER = 10_263; +const CANONICAL_REPOSITORY = "NVIDIA/NemoClaw"; +const WORKFLOW_SOURCE = `on: + push: + branches: [main] + paths: + - ".github/workflows/base-image.yaml" + - "Dockerfile.base" + workflow_dispatch: +jobs: {} +`; + +function treeEntry(path: string, sha: string) { + return { mode: "100644", path, sha, type: "blob" }; +} + +function requestFor(candidateRepository: string, imageChanged: boolean) { + const baseEntries = [ + treeEntry("Dockerfile.base", "3".repeat(40)), + treeEntry("docs/guide.mdx", "4".repeat(40)), + ]; + const candidateEntries = [ + treeEntry("Dockerfile.base", (imageChanged ? "5" : "3").repeat(40)), + treeEntry("docs/guide.mdx", "4".repeat(40)), + ]; + const responses = new Map([ + [ + `/repos/${CANONICAL_REPOSITORY}/pulls/${PR_NUMBER}`, + { + state: "open", + changed_files: 1, + base: { sha: BASE_SHA, repo: { full_name: CANONICAL_REPOSITORY } }, + head: { sha: CANDIDATE_SHA, repo: { full_name: candidateRepository } }, + }, + ], + [ + `/repos/${CANONICAL_REPOSITORY}/pulls/${PR_NUMBER}/files?per_page=100&page=1`, + [{ filename: "docs/guide.mdx" }], + ], + [ + `/repos/${CANONICAL_REPOSITORY}/git/commits/${BASE_SHA}`, + { sha: BASE_SHA, tree: { sha: BASE_TREE_SHA } }, + ], + [ + `/repos/${CANONICAL_REPOSITORY}/git/trees/${BASE_TREE_SHA}?recursive=1`, + { sha: BASE_TREE_SHA, tree: baseEntries, truncated: false }, + ], + [ + `/repos/${candidateRepository}/git/commits/${CANDIDATE_SHA}`, + { sha: CANDIDATE_SHA, tree: { sha: CANDIDATE_TREE_SHA } }, + ], + [ + `/repos/${candidateRepository}/git/trees/${CANDIDATE_TREE_SHA}?recursive=1`, + { sha: CANDIDATE_TREE_SHA, tree: candidateEntries, truncated: false }, + ], + ]); + return async (requestPath: string): Promise => + responses.get(requestPath) ?? Promise.reject(new Error(`unexpected request ${requestPath}`)); +} + +function selectorInput(candidateRepository: string) { + return { + baseSha: BASE_SHA, + candidateRepository, + candidateSha: CANDIDATE_SHA, + prNumber: PR_NUMBER, + token: "test-token", + workflowSource: WORKFLOW_SOURCE, + }; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); describe("PR managed-image source selection", () => { - it("matches only reviewed image input paths", () => { - const patterns = ["Dockerfile", "agents/**", "src/lib/actions/sandbox/mcp-bridge-*.ts"]; - - expect(managedImagePublicationRequired(["Dockerfile"], patterns)).toBe(true); - expect(managedImagePublicationRequired(["agents/hermes/Dockerfile"], patterns)).toBe(true); - expect( - managedImagePublicationRequired( - ["src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.ts"], - patterns, + it("keeps source selection bound to commit A during A-to-B-to-A PR drift", async () => { + await expect( + resolvePrManagedImageSource( + selectorInput(CANONICAL_REPOSITORY), + requestFor(CANONICAL_REPOSITORY, true), ), - ).toBe(true); - expect(managedImagePublicationRequired(["docs/My Guide.md"], patterns)).toBe(false); - expect(() => - managedImagePublicationRequired(["src/lib/onboard/file.ts\nother"], patterns), - ).toThrow("changed-file path is invalid"); + ).resolves.toBe("local-dockerfile"); + }); + + it("reads a validated external candidate repository through the default request policy", async () => { + const candidateRepository = "external-contributor/NemoClaw"; + const request = requestFor(candidateRepository, false); + vi.stubGlobal("fetch", async (input: string) => { + const url = new URL(input); + return new Response(JSON.stringify(await request(`${url.pathname}${url.search}`)), { + status: 200, + }); + }); + + await expect(resolvePrManagedImageSource(selectorInput(candidateRepository))).resolves.toBe( + "managed-image", + ); + }); + + it("rejects a GitHub request outside the canonical and candidate repositories", async () => { + await expect( + githubRequest(`/repos/other-owner/other-repository/git/commits/${CANDIDATE_SHA}`, "token", { + additionalRepository: "external-contributor/NemoClaw", + attempts: 1, + fetchImpl: async () => { + throw new Error("must not fetch"); + }, + }), + ).rejects.toThrow("GitHub API path must stay within an allowed repository"); }); }); diff --git a/tools/e2e/base-image-publication.mts b/tools/e2e/base-image-publication.mts index b1302e5333e..1a71d44c74f 100644 --- a/tools/e2e/base-image-publication.mts +++ b/tools/e2e/base-image-publication.mts @@ -20,6 +20,7 @@ const RUN_URL_ROOT = `https://github.com/${REPOSITORY}/actions/runs`; const WORKFLOW_URL = `https://github.com/${REPOSITORY}/blob/${MAIN_BRANCH}/${WORKFLOW_PATH}`; const PAGE_SIZE = 100; const MAX_API_PAGES = 10; +const MAX_CHANGED_PATHS = 6_000; const PAGINATION_ATTEMPTS = 3; const REQUEST_ATTEMPTS = 3; const REQUEST_TIMEOUT_MS = 20_000; @@ -134,6 +135,7 @@ export function writePublicationRunOutputs(path: string, run: PublicationRun): v } export interface GithubRequestOptions { + additionalRepository?: string; fetchImpl?: (input: string, init: RequestInit) => Promise; sleep?: (milliseconds: number) => Promise; now?: () => number; @@ -233,6 +235,22 @@ export function matchesBaseImagePushPath(pattern: string, changedPath: string): return pattern === changedPath; } +/** Determine whether reviewed base-image inputs contain a changed repository path. */ +export function baseImageInputsChanged( + changedFiles: readonly string[], + reviewedPaths: readonly string[], +): boolean { + if (changedFiles.length > MAX_CHANGED_PATHS) { + throw new Error(`PR changed-path count exceeds ${MAX_CHANGED_PATHS}`); + } + for (const changedFile of changedFiles) { + if (reviewedPaths.some((reviewedPath) => matchesBaseImagePushPath(reviewedPath, changedFile))) { + return true; + } + } + return false; +} + /** * Read the controlled path list without requiring a dependency install in the * preflight job. Deliberately reject YAML features such as flow lists, aliases, @@ -764,8 +782,21 @@ export async function githubRequest( token: string, options: GithubRequestOptions = {}, ): Promise { - if (!path.startsWith(`/repos/${REPOSITORY}/`) || path.includes("\r") || path.includes("\n")) { - throw new Error("GitHub API path must stay within the canonical NemoClaw repository"); + const additionalRepository = options.additionalRepository; + if ( + additionalRepository !== undefined && + (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(additionalRepository) || + additionalRepository.split("/").some((segment) => segment === "." || segment === "..")) + ) { + throw new Error("additional GitHub API repository is invalid"); + } + const allowedRepositories = [REPOSITORY, ...(additionalRepository ? [additionalRepository] : [])]; + if ( + path.includes("\r") || + path.includes("\n") || + !allowedRepositories.some((repository) => path.startsWith(`/repos/${repository}/`)) + ) { + throw new Error("GitHub API path must stay within an allowed repository"); } const fetchImpl = options.fetchImpl ?? fetch; const sleep = diff --git a/tools/e2e/pr-managed-image-publication.mts b/tools/e2e/pr-managed-image-publication.mts index ae51085b55d..8c6f6b8f9c6 100644 --- a/tools/e2e/pr-managed-image-publication.mts +++ b/tools/e2e/pr-managed-image-publication.mts @@ -11,27 +11,20 @@ import { type ManagedImageContractCatalog, } from "../../src/lib/onboard/managed-image/contract.ts"; import { + baseImageInputsChanged, githubRequest, - matchesBaseImagePushPath, parseBaseImagePushPaths, } from "./base-image-publication.mts"; const REPOSITORY = "NVIDIA/NemoClaw"; const BASE_IMAGE_WORKFLOW_PATH = ".github/workflows/base-image.yaml"; -const MAX_CHANGED_FILES = 3_000; -const PAGE_SIZE = 100; +const MAX_COMMIT_TREE_ENTRIES = 100_000; const SHA_PATTERN = /^[0-9a-f]{40}$/u; const REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u; +const TREE_ENTRY_TYPES = new Set(["blob", "commit", "tree"]); type JsonRecord = Record; -export interface PrChangedFilesInput { - readonly baseSha: string; - readonly candidateRepository: string; - readonly candidateSha: string; - readonly prNumber: number; -} - export type PrManagedImageSource = "local-dockerfile" | "managed-image"; function record(value: unknown, label: string): JsonRecord { @@ -52,30 +45,6 @@ function exactString(value: unknown, expected: string, label: string): void { if (value !== expected) throw new Error(`${label} must be ${expected}`); } -/** Determine whether changed PR files require local candidate image builds. */ -export function managedImagePublicationRequired( - changedFiles: readonly string[], - patterns: readonly string[], -): boolean { - if (changedFiles.length > MAX_CHANGED_FILES * 2) { - throw new Error(`PR changed-path count exceeds ${MAX_CHANGED_FILES * 2}`); - } - for (const file of changedFiles) { - if ( - file.length === 0 || - file.length > 4_096 || - /[\0\r\n]/u.test(file) || - file.startsWith("/") || - file.includes("//") || - file.split("/").some((segment) => segment === "" || segment === "." || segment === "..") - ) { - throw new Error("PR changed-file path is invalid"); - } - if (patterns.some((pattern) => matchesBaseImagePushPath(pattern, file))) return true; - } - return false; -} - function assembleManagedImageCatalog( values: readonly unknown[], candidateSha: string, @@ -127,43 +96,78 @@ function writeManagedImageCatalog( }); } -async function readChangedFiles( - prNumber: number, - count: number, +function sha(value: unknown, label: string): string { + if (typeof value !== "string" || !SHA_PATTERN.test(value)) { + throw new Error(`${label} must be a lowercase 40-character SHA`); + } + return value; +} + +async function readCommitTree( + repository: string, + revision: string, + label: string, request: (path: string) => Promise, -): Promise { - if (!Number.isSafeInteger(count) || count < 0 || count > MAX_CHANGED_FILES) { - throw new Error("PR changed-file count is invalid"); +): Promise> { + const commit = record( + await request(`/repos/${repository}/git/commits/${revision}`), + `${label} commit`, + ); + exactString(commit.sha, revision, `${label} commit SHA`); + const treeSha = sha(record(commit.tree, `${label} commit tree`).sha, `${label} tree SHA`); + const payload = record( + await request(`/repos/${repository}/git/trees/${treeSha}?recursive=1`), + `${label} tree`, + ); + exactString(payload.sha, treeSha, `${label} tree SHA`); + if (payload.truncated !== false) { + throw new Error(`${label} commit tree is truncated`); + } + if (!Array.isArray(payload.tree) || payload.tree.length > MAX_COMMIT_TREE_ENTRIES) { + throw new Error(`${label} commit tree is invalid or exceeds the entry limit`); } - const files: string[] = []; - let listedFiles = 0; - for (let page = 1; listedFiles < count; page += 1) { - if (page > Math.ceil(MAX_CHANGED_FILES / PAGE_SIZE)) { - throw new Error("PR changed-file pagination exceeded the safety cap"); + + const entries = new Map(); + for (const value of payload.tree) { + const entry = record(value, `${label} tree entry`); + if (typeof entry.path !== "string" || entry.path.length === 0) { + throw new Error(`${label} tree entry path is invalid`); } - const payload = await request( - `/repos/${REPOSITORY}/pulls/${prNumber}/files?per_page=${PAGE_SIZE}&page=${page}`, - ); - if (!Array.isArray(payload) || payload.length === 0 || payload.length > PAGE_SIZE) { - throw new Error("PR changed-file page is invalid or incomplete"); + if (typeof entry.type !== "string" || !TREE_ENTRY_TYPES.has(entry.type)) { + throw new Error(`${label} tree entry type is invalid`); } - for (const value of payload) { - const file = record(value, "PR changed file"); - if (typeof file.filename !== "string") throw new Error("PR changed-file name is invalid"); - files.push(file.filename); - if (file.previous_filename !== undefined) { - if (typeof file.previous_filename !== "string") { - throw new Error("PR previous changed-file name is invalid"); - } - files.push(file.previous_filename); - } - listedFiles += 1; + if (typeof entry.mode !== "string" || !/^[0-7]{6}$/u.test(entry.mode)) { + throw new Error(`${label} tree entry mode is invalid`); } + const entrySha = sha(entry.sha, `${label} tree entry SHA`); + if (entry.type === "tree") continue; + if (entries.has(entry.path)) throw new Error(`${label} commit tree contains duplicate paths`); + entries.set(entry.path, `${entry.mode}:${entry.type}:${entrySha}`); } - if (listedFiles !== count) { - throw new Error("PR changed-file listing is incomplete"); + return entries; +} + +async function readChangedFiles( + input: { + readonly baseSha: string; + readonly candidateRepository: string; + readonly candidateSha: string; + }, + request: (path: string) => Promise, +): Promise { + const baseTree = await readCommitTree(REPOSITORY, input.baseSha, "PR base", request); + const candidateTree = await readCommitTree( + input.candidateRepository, + input.candidateSha, + "PR candidate", + request, + ); + const changedFiles: string[] = []; + for (const changedPath of new Set([...baseTree.keys(), ...candidateTree.keys()])) { + if (baseTree.get(changedPath) === candidateTree.get(changedPath)) continue; + changedFiles.push(changedPath); } - return [...new Set(files)]; + return changedFiles; } function validatePr( @@ -172,9 +176,8 @@ function validatePr( readonly baseSha: string; readonly candidateRepository: string; readonly candidateSha: string; - readonly prNumber: number; }, -): number { +): void { const pull = record(payload, "pull request"); exactString(pull.state, "open", "pull request state"); exactString( @@ -198,14 +201,23 @@ function validatePr( expected.candidateRepository, "pull request source repository", ); - return positiveInteger(pull.changed_files, "PR changed-file count"); } -/** Read one validated PR change set from the canonical pull-request API. */ -export async function readPrChangedFiles( - input: PrChangedFilesInput, - request: (path: string) => Promise, -): Promise { +/** Select a trusted managed image or the candidate Dockerfile path. */ +export async function resolvePrManagedImageSource( + input: { + readonly baseSha: string; + readonly candidateRepository: string; + readonly candidateSha: string; + readonly prNumber: number; + readonly token: string; + readonly workflowSource: string; + }, + request: (apiPath: string) => Promise = (apiPath) => + githubRequest(apiPath, input.token, { + additionalRepository: input.candidateRepository, + }), +): Promise { if (!SHA_PATTERN.test(input.baseSha) || !SHA_PATTERN.test(input.candidateSha)) { throw new Error("PR base and candidate SHAs are required"); } @@ -216,27 +228,11 @@ export async function readPrChangedFiles( throw new Error("candidate repository is invalid"); } positiveInteger(input.prNumber, "PR number"); - const changedCount = validatePr( - await request(`/repos/${REPOSITORY}/pulls/${input.prNumber}`), - input, - ); - return readChangedFiles(input.prNumber, changedCount, request); -} - -/** Select a trusted managed image or the candidate Dockerfile path. */ -export async function resolvePrManagedImageSource( - input: PrChangedFilesInput & { - readonly token: string; - readonly workflowSource: string; - }, - request: (apiPath: string) => Promise = (apiPath) => githubRequest(apiPath, input.token), -): Promise { if (!input.token) throw new Error("GITHUB_TOKEN is required"); - const changedFiles = await readPrChangedFiles(input, request); + validatePr(await request(`/repos/${REPOSITORY}/pulls/${input.prNumber}`), input); + const changedFiles = await readChangedFiles(input, request); const patterns = parseBaseImagePushPaths(input.workflowSource); - return managedImagePublicationRequired(changedFiles, patterns) - ? "local-dockerfile" - : "managed-image"; + return baseImageInputsChanged(changedFiles, patterns) ? "local-dockerfile" : "managed-image"; } function requiredInteger(value: string | undefined, label: string): number { From 6f7f0975bcb2eafa67bcf06e4e5acdc86061a93d Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 29 Aug 2026 12:00:09 +0700 Subject: [PATCH 38/40] test(e2e): map live helpers to existing coverage Signed-off-by: San Dang --- test/e2e/mock-parity.json | 8 ++++++-- ...ntime-compatible-anthropic-progress.test.ts | 18 +++++++++++++----- .../support/dashboard-connect-handoff.test.ts | 16 +++++++++++++--- test/e2e/support/managed-image-receipt.test.ts | 9 ++++++--- .../pr-managed-image-publication.test.ts | 5 ----- tools/e2e/pr-managed-image-publication.mts | 2 +- 6 files changed, 39 insertions(+), 19 deletions(-) diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 353a81479c8..d848bd0dc8b 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -138,13 +138,15 @@ }, { "live": "test/e2e/live/full-e2e.test.ts", + "liveSources": ["test/e2e/live/full-e2e-workload-evidence.ts"], "fast": [ "test/e2e/support/hosted-inference.test.ts", "test/e2e/support/full-e2e-inference-probe.test.ts", "test/e2e/support/launch-agent-turn.test.ts", "test/e2e/support/onboard-performance.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", - "test/e2e/support/e2e-clients.test.ts" + "test/e2e/support/e2e-clients.test.ts", + "test/e2e/support/managed-image-receipt.test.ts" ] }, { @@ -243,7 +245,8 @@ }, { "live": "test/e2e/live/dashboard-remote-bind.test.ts", - "liveOnlyReason": "Requires a real OpenShell dashboard forward on a remote Brev host to prove all-interface bind behavior after background connect." + "liveSources": ["test/e2e/live/dashboard-connect-handoff.ts"], + "fast": ["test/e2e/support/dashboard-connect-handoff.test.ts"] }, { "live": "test/e2e/live/sandbox-rlimits-connect.test.ts", @@ -312,6 +315,7 @@ }, { "live": "test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts", + "liveSources": ["test/e2e/live/bedrock-runtime-compatible-anthropic-raw-command.ts"], "fast": [ "test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", diff --git a/test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts b/test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts index 228d6faad16..2544621a856 100644 --- a/test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts +++ b/test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts @@ -54,8 +54,10 @@ afterEach(async () => { }); describe("Bedrock raw-command progress", () => { - it("reports timestamp-only output activity without forwarding child payloads", async () => { + it("applies the local Dockerfile and reports timestamp-only output activity", async () => { const secret = "opaque-bedrock-progress-secret"; + const expectedDockerfile = path.resolve("Dockerfile"); + const expectedOutput = `${secret}:${expectedDockerfile}`; const artifacts = await artifactSink("bedrock-progress-output"); const observation = progressProbe(); const { progress } = observation; @@ -64,19 +66,25 @@ describe("Bedrock raw-command progress", () => { process.execPath, [ "-e", - "process.stdout.write(process.env.BEDROCK_TEST_SECRET); process.stderr.write('stderr-ready')", + "process.stdout.write(`${process.env.BEDROCK_TEST_SECRET}:${process.env.NEMOCLAW_FROM_DOCKERFILE}`); process.stderr.write('stderr-ready')", ], { artifactName: "bedrock-progress-output", artifacts, - env: { ...process.env, BEDROCK_TEST_SECRET: secret }, + env: { + ...process.env, + BEDROCK_TEST_SECRET: secret, + E2E_TARGET_ID: "bedrock-runtime-compatible-anthropic", + E2E_WORKLOAD_SOURCE: "local-dockerfile", + NEMOCLAW_AGENT: "openclaw", + }, progress, redactionValues: [secret], }, ); expect(result.exitCode).toBe(0); - expect(result.stdout).toBe(secret); + expect(result.stdout).toBe(expectedOutput); observation.timers[0]?.(); expect(observation.lines.at(-1)).toContain("no active command"); expect(observation.lines).toEqual( @@ -95,7 +103,7 @@ describe("Bedrock raw-command progress", () => { path.join(artifacts.rootDir, "raw-shell/bedrock-progress-output.stdout.txt"), "utf8", ), - ).resolves.toBe("[REDACTED]"); + ).resolves.toBe(`[REDACTED]:${expectedDockerfile}`); }); it("emits an immediate content-free timeout event and closes command activity", async () => { diff --git a/test/e2e/support/dashboard-connect-handoff.test.ts b/test/e2e/support/dashboard-connect-handoff.test.ts index f259301ec46..b6673db0d8c 100644 --- a/test/e2e/support/dashboard-connect-handoff.test.ts +++ b/test/e2e/support/dashboard-connect-handoff.test.ts @@ -37,15 +37,25 @@ async function stopFixtureProcess(pid: number): Promise { expect(processExists(pid)).toBe(false); } -test("accepts a normally completed connect when the forward is already healthy", async ({ +test("accepts a normally completed connect with the local Dockerfile workload", async ({ artifacts, progress, }) => { const result = await runDashboardConnectUntilForwardHandoff({ artifacts, - command: [process.execPath, "-e", "process.exit(0)"], + command: [ + process.execPath, + "-e", + "process.exit(process.env.NEMOCLAW_FROM_DOCKERFILE === process.argv[1] ? 0 : 1)", + path.resolve("Dockerfile"), + ], dashboardPort: DASHBOARD_PORT, - env: process.env, + env: { + ...process.env, + E2E_TARGET_ID: "dashboard-remote-bind", + E2E_WORKLOAD_SOURCE: "local-dockerfile", + NEMOCLAW_AGENT: "openclaw", + }, progress, sandboxName: SANDBOX_NAME, timeoutMs: 2_000, diff --git a/test/e2e/support/managed-image-receipt.test.ts b/test/e2e/support/managed-image-receipt.test.ts index 5cc0e85ccfd..09e9c72a7ed 100644 --- a/test/e2e/support/managed-image-receipt.test.ts +++ b/test/e2e/support/managed-image-receipt.test.ts @@ -173,12 +173,15 @@ describe("stock E2E managed-image receipt assertion", () => { ).toMatchObject({ agent: "openclaw", sourceRevision: REVISION }); }); - it("uses the trusted candidate catalog for full E2E workload evidence", () => { + it("records local Dockerfile evidence without a managed-image receipt", () => { const home = writeRegistry(managedReceipt()); expect( - readFullE2eColdWorkloadEvidence(SANDBOX_NAME, false, candidateCatalogEnvironment(home)), - ).toMatchObject({ kind: "managed-image", sourceRevision: REVISION }); + readFullE2eColdWorkloadEvidence(SANDBOX_NAME, false, { + ...candidateCatalogEnvironment(home), + E2E_WORKLOAD_SOURCE: "local-dockerfile", + }), + ).toMatchObject({ kind: "legacy-dockerfile" }); }); it("rejects a candidate catalog whose source revision differs from the exact candidate revision", () => { diff --git a/test/e2e/support/pr-managed-image-publication.test.ts b/test/e2e/support/pr-managed-image-publication.test.ts index 88282cd2333..2a6188ed8c6 100644 --- a/test/e2e/support/pr-managed-image-publication.test.ts +++ b/test/e2e/support/pr-managed-image-publication.test.ts @@ -40,15 +40,10 @@ function requestFor(candidateRepository: string, imageChanged: boolean) { `/repos/${CANONICAL_REPOSITORY}/pulls/${PR_NUMBER}`, { state: "open", - changed_files: 1, base: { sha: BASE_SHA, repo: { full_name: CANONICAL_REPOSITORY } }, head: { sha: CANDIDATE_SHA, repo: { full_name: candidateRepository } }, }, ], - [ - `/repos/${CANONICAL_REPOSITORY}/pulls/${PR_NUMBER}/files?per_page=100&page=1`, - [{ filename: "docs/guide.mdx" }], - ], [ `/repos/${CANONICAL_REPOSITORY}/git/commits/${BASE_SHA}`, { sha: BASE_SHA, tree: { sha: BASE_TREE_SHA } }, diff --git a/tools/e2e/pr-managed-image-publication.mts b/tools/e2e/pr-managed-image-publication.mts index 8c6f6b8f9c6..4b8d32b0851 100644 --- a/tools/e2e/pr-managed-image-publication.mts +++ b/tools/e2e/pr-managed-image-publication.mts @@ -203,7 +203,7 @@ function validatePr( ); } -/** Select a trusted managed image or the candidate Dockerfile path. */ +/** Select the managed-image or local-Dockerfile source for a validated PR. */ export async function resolvePrManagedImageSource( input: { readonly baseSha: string; From d9331e3fc97dfea4f092bdf11062792771cb0e52 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 29 Aug 2026 12:09:37 +0700 Subject: [PATCH 39/40] test(onboard): remove duplicate activation case Signed-off-by: San Dang --- .../managed-workload/onboard-orchestration.test.ts | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts index c07a4e5d510..080b6666916 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts @@ -183,16 +183,6 @@ describe("managed workload onboard orchestration", () => { ).toBe(false); }); - it("keeps stock managed images required during providerless interceptor creation (#9833)", () => { - expect( - shouldActivateStockManagedRuntime({ - portableLifecycle: false, - hermesPortableLifecycle: false, - agentName: "openclaw", - }), - ).toBe(true); - }); - it("uses the Dockerfile when the stock managed-image catalog is unavailable", async () => { const { runtime } = createFreshOnboardingRuntime( {}, From 53fc625fe13f3c40d7fbfcf6c8a273d869041c5f Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 31 Aug 2026 08:05:45 -0700 Subject: [PATCH 40/40] fix(e2e): restore workload source contract Signed-off-by: Carlos Villela --- .github/workflows/e2e.yaml | 108 ++-- .../managed-workload/onboard-orchestration.ts | 15 +- test/e2e/README.md | 25 +- test/e2e/mock-parity.json | 4 +- .../pr-managed-image-publication.test.ts | 525 +++--------------- .../e2e/mcp-dev-workflow-boundary-digests.mts | 2 + tools/e2e/mcp-workflow-boundary.mts | 19 +- tools/e2e/operations-workflow-boundary.mts | 73 ++- tools/e2e/pr-managed-image-publication.mts | 301 ++-------- 9 files changed, 289 insertions(+), 783 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index fb51b28309e..4d13174838c 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -161,15 +161,13 @@ jobs: outputs: dcode_base_contract: ${{ steps.validate_dcode_base.outputs.contract }} dcode_base_ref: ${{ steps.validate_dcode_base.outputs.base_ref }} - managed_image_artifact_provenance: ${{ steps.download_managed_cohort.outputs.provenance }} - managed_image_cohort: ${{ steps.validate_managed_cohort.outputs.cohort }} managed_image_receipt: ${{ steps.validate_managed_cohort.outputs.receipt }} managed_image_revision: ${{ steps.validate_managed_cohort.outputs.revision }} - managed_image_run_attempt: ${{ steps.validate_managed_cohort.outputs.run_attempt }} - managed_image_run_id: ${{ steps.validate_managed_cohort.outputs.run_id }} + workload_source: ${{ steps.select_pr_source.outputs.workload_source || 'managed-image' }} permissions: actions: read contents: read + pull-requests: read steps: - id: publication_mode name: Classify base-image publication requirement @@ -219,14 +217,33 @@ jobs: with: node-version: 22 + - id: select_pr_source + name: Select PR workload source + if: ${{ inputs.pr_number != '' }} + env: + BASE_SHA: ${{ inputs.base_sha }} + CANDIDATE_REPOSITORY: ${{ inputs.checkout_repository }} + CANDIDATE_SHA: ${{ inputs.checkout_sha }} + GITHUB_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.pr_number }} + shell: bash + run: | + set -euo pipefail + workload_source="$(node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-publication.mts select-source)" + case "$workload_source" in + managed-image|local-dockerfile) ;; + *) echo "::error::PR workload source is invalid" >&2; exit 1 ;; + esac + printf 'workload_source=%s\n' "$workload_source" >>"$GITHUB_OUTPUT" + - id: publication - name: Select complete base and managed-image publication + name: Select base and optional managed-image publication env: EXPECTED_SHA: ${{ steps.publication_mode.outputs.expected_sha }} GITHUB_TOKEN: ${{ github.token }} PUBLICATION_HISTORY_ALLOW_NON_HEAD: ${{ steps.publication_mode.outputs.allow_non_head }} - REQUIRE_MANAGED_IMAGE_PUBLICATION: "1" - SELECT_NEAREST_SUCCESSFUL_PUBLICATION: ${{ steps.publication_mode.outputs.select_nearest_successful }} + REQUIRE_MANAGED_IMAGE_PUBLICATION: ${{ steps.select_pr_source.outputs.workload_source == 'local-dockerfile' && '0' || '1' }} + SELECT_NEAREST_SUCCESSFUL_PUBLICATION: ${{ steps.select_pr_source.outputs.workload_source == 'local-dockerfile' && '0' || steps.publication_mode.outputs.select_nearest_successful }} shell: bash run: | set -euo pipefail @@ -256,6 +273,7 @@ jobs: - id: download_managed_cohort name: Download immutable managed-image cohort contract + if: ${{ inputs.pr_number == '' || steps.select_pr_source.outputs.workload_source == 'managed-image' }} env: GITHUB_TOKEN: ${{ github.token }} PUBLICATION_ARTIFACT_KIND: managed-image-cohort @@ -266,6 +284,7 @@ jobs: - id: validate_managed_cohort name: Validate immutable managed-image cohort contract + if: ${{ inputs.pr_number == '' || steps.select_pr_source.outputs.workload_source == 'managed-image' }} env: PUBLICATION_HEAD_SHA: ${{ steps.publication.outputs.head_sha }} PUBLICATION_RUN_ATTEMPT: ${{ steps.publication.outputs.run_attempt }} @@ -282,6 +301,7 @@ jobs: pull-requests: read outputs: cli_artifact_provenance: ${{ steps.record_cli_artifact.outputs.provenance }} + workload_source: ${{ needs.base-image-publication.outputs.workload_source }} e2e_credentials_allowed: ${{ steps.e2e_credentials.outputs.allowed }} managed_image_catalog: ${{ steps.resolve_pr_managed_image_catalog.outputs.catalog }} matrix: ${{ steps.matrix.outputs.matrix }} @@ -2821,9 +2841,10 @@ jobs: include: ${{ fromJSON(needs.generate-matrix.outputs.matrix) }} env: E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} - NEMOCLAW_LANGCHAIN_DEEPAGENTS_CODE_SANDBOX_BASE_IMAGE_REF: ${{ needs.base-image-publication.outputs.dcode_base_ref }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} + NEMOCLAW_LANGCHAIN_DEEPAGENTS_CODE_SANDBOX_BASE_IMAGE_REF: ${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && needs.base-image-publication.outputs.dcode_base_ref || '' }} NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js NEMOCLAW_RUN_LIVE_E2E: "1" NEMOCLAW_E2E_USE_HOSTED_INFERENCE: "1" @@ -2879,7 +2900,7 @@ jobs: build-cli: "false" - name: Record immutable Deep Agents Code base evidence - if: ${{ matrix.id == 'ubuntu-repo-cloud-langchain-deepagents-code' }} + if: ${{ matrix.id == 'ubuntu-repo-cloud-langchain-deepagents-code' && needs.generate-matrix.outputs.workload_source == 'managed-image' }} env: BASE_CONTRACT: ${{ needs.base-image-publication.outputs.dcode_base_contract }} CANDIDATE_SHA: ${{ inputs.checkout_sha || github.sha }} @@ -3112,9 +3133,9 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - managed_image_receipt: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: no provider credential target_id: ${{ matrix.target_id }} catalogue_id: ${{ matrix.id }} @@ -3154,9 +3175,9 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - managed_image_receipt: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: NVIDIA API key target_id: ${{ matrix.target_id }} catalogue_id: ${{ matrix.id }} @@ -3197,9 +3218,9 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - managed_image_receipt: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: NVIDIA inference API key target_id: ${{ matrix.target_id }} catalogue_id: ${{ matrix.id }} @@ -3240,9 +3261,9 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - managed_image_receipt: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: GitHub read token target_id: ${{ matrix.target_id }} catalogue_id: ${{ matrix.id }} @@ -3283,9 +3304,9 @@ jobs: risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} - managed_image_catalog: ${{ needs.generate-matrix.outputs.managed_image_catalog }} - managed_image_revision: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - managed_image_receipt: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} credential_boundary: Brave and NVIDIA inference API keys target_id: ${{ matrix.target_id }} catalogue_id: ${{ matrix.id }} @@ -3479,8 +3500,9 @@ jobs: agent_runtime: langchain-deepagents-code coverage_variant: deepagents env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "mcp-bridge" E2E_OBSERVABLE_OUTCOME: "Stable OpenShell MCP bridge reaches tools and inference" @@ -3813,8 +3835,9 @@ jobs: # MCP lifecycle without sharing destructive sandbox state. timeout-minutes: 90 env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "openshell-credential-generation-window" E2E_AGENT_RUNTIME: "openclaw" @@ -3987,8 +4010,9 @@ jobs: agent_runtime: langchain-deepagents-code coverage_variant: deepagents env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "mcp-bridge-dev" E2E_OBSERVABLE_OUTCOME: "Development OpenShell MCP bridge reaches tools and inference" @@ -5157,8 +5181,9 @@ jobs: runs-on: ${{ fromJSON(needs.generate-matrix.outputs.runner_routing)['hermes-e2e'] }} timeout-minutes: 85 env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "hermes-e2e" E2E_AGENT_RUNTIME: "hermes" @@ -5266,8 +5291,9 @@ jobs: observable_outcome: "Compatibility-only GPU startup reaches the stable Ready route" coverage_variant: compatibility-only env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "hermes-gpu-startup" E2E_AGENT_RUNTIME: "hermes" @@ -5572,8 +5598,9 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 70 env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "cloud-onboard" E2E_AGENT_RUNTIME: "openclaw" @@ -5698,8 +5725,9 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 90 env: - E2E_MANAGED_IMAGE_REVISION: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }} - E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }} + E2E_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + E2E_MANAGED_IMAGE_COHORT_RECEIPT: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + E2E_WORKLOAD_SOURCE: ${{ needs.generate-matrix.outputs.workload_source }} E2E_JOB: "1" E2E_TARGET_ID: "messaging-providers" E2E_AGENT_RUNTIME: "openclaw" diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index 25ba9ca4995..0f0d5fde99c 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -231,14 +231,13 @@ export function createManagedWorkloadOnboardRuntime( input.tempManagedRuntime || input.tempManagedRuntimeCatalog !== null || input.managedWorkloadRebuild !== null; - const runtimeCapabilities = - strictManagedRuntime || input.stockManagedRuntime - ? discoveredRuntimeCapabilities - : { - ...discoveredRuntimeCapabilities, - managedImageSelectionPolicy: "prefer-managed" as const, - managedImages: null, - }; + const runtimeCapabilities = strictManagedRuntime + ? discoveredRuntimeCapabilities + : { + ...discoveredRuntimeCapabilities, + managedImageSelectionPolicy: "prefer-managed" as const, + managedImages: input.stockManagedRuntime ? discoveredRuntimeCapabilities.managedImages : null, + }; const runtimeProvider = resolveRuntimeProviderBundle( input.computePlan.driverName, CURRENT_RUNTIME_PROVIDER_BUNDLES, diff --git a/test/e2e/README.md b/test/e2e/README.md index e9731f8e034..01b5aac2984 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -99,20 +99,17 @@ Agents Code on `linux/amd64` and `linux/arm64` before it emits `managed_image_re `generate-matrix` and every stock-onboarding job depend on this job, so a missing, failed, incomplete, or mixed publication starts no onboarding consumer. -For a same-repository PR that changes a managed-image workflow path, the trusted planner also -requires one successful `Images / Build, Test, and Publish Managed Images` run for the candidate -commit. Before candidate checkout, the planner downloads the three nonexpired contract artifacts by -immutable artifact ID. -It verifies each artifact digest, producer run, attempt, and candidate commit. The planner rejects a -missing, incomplete, or mixed all-agent publication before E2E jobs start. - -The planner adds the all-agent catalog to `dist/` after the candidate CLI build completes. -Each live E2E consumer verifies that the catalog source revision matches `checkout_sha`. A PR that -does not change a managed-image workflow path receives the selected base publication through -`E2E_MANAGED_IMAGE_REVISION` and the complete cohort receipt. Every stock-onboarding test asserts -its durable `managed-image` receipt against either the exact candidate catalog or the selected base -cohort before later probes. The GitHub token is available only to the trusted planner job and is not -included in the candidate CLI artifact. +For a manual same-repository PR run, the trusted planner compares the immutable base and candidate +commit trees with the reviewed base-image and managed-image input paths. When those inputs are +unchanged, the run uses the applicable trusted managed-image publication from the PR base history. +When any input changed, the run selects `local-dockerfile` and builds the candidate Dockerfiles +locally instead of waiting for a candidate publication. + +The selected source is passed to every stock-onboarding consumer. Managed-image runs receive the +selected base revision and complete cohort receipt. Local-Dockerfile runs resolve the shipped agent +Dockerfile at the final process boundary and require the resulting durable receipt to identify that +source. The GitHub token remains available only to the trusted planner and is not included in the +candidate CLI artifact. The same-repository `Images / Build, Test, and Publish Managed Images` PR workflow also runs the OpenClaw managed-image MCP discovery and lifecycle scope in two independent matrix jobs. Each job diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index ef5f24f6ded..549583ff712 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -144,9 +144,9 @@ { "live": "test/e2e/live/full-e2e.test.ts", "liveSources": [ - "test/e2e/live/full-e2e-workload-evidence.ts", "test/e2e/live/agent-turn-latency-helpers.ts", - "test/e2e/live/full-e2e-inference-probe.ts" + "test/e2e/live/full-e2e-inference-probe.ts", + "test/e2e/live/full-e2e-workload-evidence.ts" ], "fast": [ "test/e2e/support/hosted-inference.test.ts", diff --git a/test/e2e/support/pr-managed-image-publication.test.ts b/test/e2e/support/pr-managed-image-publication.test.ts index 7c8b27d3f9e..2a6188ed8c6 100644 --- a/test/e2e/support/pr-managed-image-publication.test.ts +++ b/test/e2e/support/pr-managed-image-publication.test.ts @@ -1,468 +1,119 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { createHash } from "node:crypto"; -import { spawnSync } from "node:child_process"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; -import { describe, expect, it } from "vitest"; -import YAML from "yaml"; - -import { - MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, - MANAGED_IMAGE_CONTRACT_VERSION, - MANAGED_IMAGE_REPOSITORIES, - MANAGED_IMAGE_SOURCE_REPOSITORY, - MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, - type ManagedImageAgent, - type ManagedImageContractV1, - SHIPPED_MANAGED_IMAGE_AGENTS, -} from "../../../src/lib/onboard/managed-image/contract"; -import { - assembleManagedImageCatalog, - main, - managedImagePublicationRequired, - parseManagedImagePullRequestPaths, - resolvePrManagedImageCatalog, - selectManagedImagePublicationRun, -} from "../../../tools/e2e/pr-managed-image-publication.mts"; -import { - readE2eOperationsWorkflow, - validateE2eOperationsWorkflow, -} from "../../../tools/e2e/operations-workflow-boundary.mts"; +import { githubRequest } from "../../../tools/e2e/base-image-publication.mts"; +import { resolvePrManagedImageSource } from "../../../tools/e2e/pr-managed-image-publication.mts"; const BASE_SHA = "b".repeat(40); const CANDIDATE_SHA = "a".repeat(40); -const BASE_TREE_SHA = "c".repeat(40); -const CANDIDATE_TREE_SHA = "d".repeat(40); -const PR_NUMBER = 8746; -const WORKFLOW_ID = 12345; -const MANAGED_IMAGE_WORKFLOW = fs.readFileSync(".github/workflows/managed-images.yaml", "utf8"); - -function contract(agent: ManagedImageAgent, index: number): ManagedImageContractV1 { - const image = MANAGED_IMAGE_REPOSITORIES[agent]; - const digest = `sha256:${String(index + 1).repeat(64)}` as const; - return { - contractVersion: MANAGED_IMAGE_CONTRACT_VERSION, - agent, - platform: "linux/amd64", - image, - digest, - reference: `${image}@${digest}`, - source: { - repository: MANAGED_IMAGE_SOURCE_REPOSITORY, - revision: CANDIDATE_SHA, - release: "v0.0.110", - cohort: "ghrun-32144654845-1", - }, - startupProfileContractVersion: MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, - capabilityContractVersion: MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, - }; +const BASE_TREE_SHA = "1".repeat(40); +const CANDIDATE_TREE_SHA = "2".repeat(40); +const PR_NUMBER = 10_263; +const CANONICAL_REPOSITORY = "NVIDIA/NemoClaw"; +const WORKFLOW_SOURCE = `on: + push: + branches: [main] + paths: + - ".github/workflows/base-image.yaml" + - "Dockerfile.base" + workflow_dispatch: +jobs: {} +`; + +function treeEntry(path: string, sha: string) { + return { mode: "100644", path, sha, type: "blob" }; } -function run(overrides: Record = {}): unknown { - return { - total_count: 1, - workflow_runs: [ +function requestFor(candidateRepository: string, imageChanged: boolean) { + const baseEntries = [ + treeEntry("Dockerfile.base", "3".repeat(40)), + treeEntry("docs/guide.mdx", "4".repeat(40)), + ]; + const candidateEntries = [ + treeEntry("Dockerfile.base", (imageChanged ? "5" : "3").repeat(40)), + treeEntry("docs/guide.mdx", "4".repeat(40)), + ]; + const responses = new Map([ + [ + `/repos/${CANONICAL_REPOSITORY}/pulls/${PR_NUMBER}`, { - id: 32144654845, - run_attempt: 1, - workflow_id: WORKFLOW_ID, - name: "Images / Build, Test, and Publish Managed Images", - path: ".github/workflows/managed-images.yaml", - event: "pull_request", - head_sha: CANDIDATE_SHA, - status: "completed", - conclusion: "success", - repository: { full_name: "NVIDIA/NemoClaw" }, - head_repository: { full_name: "NVIDIA/NemoClaw" }, - pull_requests: [{ number: PR_NUMBER }], - ...overrides, + state: "open", + base: { sha: BASE_SHA, repo: { full_name: CANONICAL_REPOSITORY } }, + head: { sha: CANDIDATE_SHA, repo: { full_name: candidateRepository } }, }, ], - }; -} - -function exactCommitRequest(changedPath: string, onUnexpected: (apiPath: string) => unknown) { - const baseBlob = "1".repeat(40); - const candidateBlob = "2".repeat(40); - return async (apiPath: string): Promise => { - switch (apiPath) { - case `/repos/NVIDIA/NemoClaw/pulls/${PR_NUMBER}`: - return { - state: "open", - base: { sha: BASE_SHA, repo: { full_name: "NVIDIA/NemoClaw" } }, - head: { sha: CANDIDATE_SHA, repo: { full_name: "NVIDIA/NemoClaw" } }, - }; - case `/repos/NVIDIA/NemoClaw/git/commits/${BASE_SHA}`: - return { sha: BASE_SHA, tree: { sha: BASE_TREE_SHA } }; - case `/repos/NVIDIA/NemoClaw/git/commits/${CANDIDATE_SHA}`: - return { sha: CANDIDATE_SHA, tree: { sha: CANDIDATE_TREE_SHA } }; - case `/repos/NVIDIA/NemoClaw/git/trees/${BASE_TREE_SHA}?recursive=1`: - return { - sha: BASE_TREE_SHA, - truncated: false, - tree: [{ path: changedPath, mode: "100644", type: "blob", sha: baseBlob }], - }; - case `/repos/NVIDIA/NemoClaw/git/trees/${CANDIDATE_TREE_SHA}?recursive=1`: - return { - sha: CANDIDATE_TREE_SHA, - truncated: false, - tree: [{ path: changedPath, mode: "100644", type: "blob", sha: candidateBlob }], - }; - default: - return onUnexpected(apiPath); - } - }; -} - -describe("exact PR managed-image publication (#8746, #9464)", () => { - it("derives applicability from the trusted managed-image workflow", () => { - const patterns = parseManagedImagePullRequestPaths( - fs.readFileSync(".github/workflows/managed-images.yaml", "utf8"), - ); - - expect( - managedImagePublicationRequired(["src/lib/onboard/workload/preparation.ts"], patterns), - ).toBe(true); - expect( - managedImagePublicationRequired(["tools/mcp-tool-discovery-runtime/server.mts"], patterns), - ).toBe(true); - expect( - managedImagePublicationRequired( - ["src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.ts"], - patterns, - ), - ).toBe(true); - expect(managedImagePublicationRequired(["docs/My Guide.md"], patterns)).toBe(false); - expect(() => - managedImagePublicationRequired(["src/lib/onboard/file.ts\nother"], patterns), - ).toThrow("changed-file path is invalid"); - }); - - it("rejects an unreviewed path-filter glob", () => { - expect(() => - parseManagedImagePullRequestPaths(` -on: - pull_request: - paths: - - ".github/workflows/managed-images.yaml" - - "src/**/nested/**" -`), - ).toThrow("unsupported glob"); - }); - - it("classifies immutable commit trees without reading the mutable PR file listing", async () => { - const requests: string[] = []; - const request = exactCommitRequest("docs/upgrade.md", (apiPath) => { - requests.push(apiPath); - throw new Error(`unexpected request: ${apiPath}`); - }); - - await expect( - resolvePrManagedImageCatalog( - { - baseSha: BASE_SHA, - candidateRepository: "NVIDIA/NemoClaw", - candidateSha: CANDIDATE_SHA, - outputPath: path.join(os.tmpdir(), "unused-pr-managed-image-catalog.json"), - prNumber: PR_NUMBER, - token: "test-token", - workflowSource: MANAGED_IMAGE_WORKFLOW, - }, - async (apiPath) => { - requests.push(apiPath); - return request(apiPath); - }, - ), - ).resolves.toBe("not-required"); - expect(requests).toContain(`/repos/NVIDIA/NemoClaw/git/commits/${BASE_SHA}`); - expect(requests).toContain(`/repos/NVIDIA/NemoClaw/git/commits/${CANDIDATE_SHA}`); - expect(requests.some((apiPath) => apiPath.includes(`/pulls/${PR_NUMBER}/files`))).toBe(false); - }); - - it("requires exact publication after an immutable managed-image input change", async () => { - const request = exactCommitRequest("agents/hermes/plugin/__init__.py", (apiPath) => { - throw new Error(`publication lookup reached: ${apiPath}`); - }); - - await expect( - resolvePrManagedImageCatalog( - { - baseSha: BASE_SHA, - candidateRepository: "NVIDIA/NemoClaw", - candidateSha: CANDIDATE_SHA, - outputPath: path.join(os.tmpdir(), "unused-pr-managed-image-catalog.json"), - prNumber: PR_NUMBER, - token: "test-token", - workflowSource: MANAGED_IMAGE_WORKFLOW, - }, - request, - ), - ).rejects.toThrow("publication lookup reached: /repos/NVIDIA/NemoClaw/actions/workflows"); - }); - - it("rejects a truncated immutable commit tree", async () => { - const request = exactCommitRequest("docs/upgrade.md", (apiPath) => { - throw new Error(`unexpected request: ${apiPath}`); - }); - const truncatedTreePath = `/repos/NVIDIA/NemoClaw/git/trees/${BASE_TREE_SHA}?recursive=1`; - const substitutedResponses = new Map([ - [ - truncatedTreePath, - { - sha: BASE_TREE_SHA, - truncated: true, - tree: [ - { - path: "docs/upgrade.md", - mode: "100644", - type: "blob", - sha: "1".repeat(40), - }, - ], - }, - ], - ]); - await expect( - resolvePrManagedImageCatalog( - { - baseSha: BASE_SHA, - candidateRepository: "NVIDIA/NemoClaw", - candidateSha: CANDIDATE_SHA, - outputPath: path.join(os.tmpdir(), "unused-pr-managed-image-catalog.json"), - prNumber: PR_NUMBER, - token: "test-token", - workflowSource: MANAGED_IMAGE_WORKFLOW, - }, - async (apiPath) => substitutedResponses.get(apiPath) ?? request(apiPath), - ), - ).rejects.toThrow("PR base commit tree is truncated"); - }); - - it.each([ [ - "duplicate directories", - [ - { path: "agents", mode: "040000", type: "tree", sha: "1".repeat(40) }, - { path: "agents", mode: "040000", type: "tree", sha: "2".repeat(40) }, - ], + `/repos/${CANONICAL_REPOSITORY}/git/commits/${BASE_SHA}`, + { sha: BASE_SHA, tree: { sha: BASE_TREE_SHA } }, ], [ - "directory and file collisions", - [ - { path: "agents", mode: "040000", type: "tree", sha: "1".repeat(40) }, - { path: "agents", mode: "100644", type: "blob", sha: "2".repeat(40) }, - ], + `/repos/${CANONICAL_REPOSITORY}/git/trees/${BASE_TREE_SHA}?recursive=1`, + { sha: BASE_TREE_SHA, tree: baseEntries, truncated: false }, ], - ])("rejects %s in an immutable commit tree", async (_description, tree) => { - const request = exactCommitRequest("docs/upgrade.md", (apiPath) => { - throw new Error(`unexpected request: ${apiPath}`); - }); - const baseTreePath = `/repos/NVIDIA/NemoClaw/git/trees/${BASE_TREE_SHA}?recursive=1`; + [ + `/repos/${candidateRepository}/git/commits/${CANDIDATE_SHA}`, + { sha: CANDIDATE_SHA, tree: { sha: CANDIDATE_TREE_SHA } }, + ], + [ + `/repos/${candidateRepository}/git/trees/${CANDIDATE_TREE_SHA}?recursive=1`, + { sha: CANDIDATE_TREE_SHA, tree: candidateEntries, truncated: false }, + ], + ]); + return async (requestPath: string): Promise => + responses.get(requestPath) ?? Promise.reject(new Error(`unexpected request ${requestPath}`)); +} - await expect( - resolvePrManagedImageCatalog( - { - baseSha: BASE_SHA, - candidateRepository: "NVIDIA/NemoClaw", - candidateSha: CANDIDATE_SHA, - outputPath: path.join(os.tmpdir(), "unused-pr-managed-image-catalog.json"), - prNumber: PR_NUMBER, - token: "test-token", - workflowSource: MANAGED_IMAGE_WORKFLOW, - }, - async (apiPath) => - apiPath === baseTreePath - ? { sha: BASE_TREE_SHA, truncated: false, tree } - : request(apiPath), - ), - ).rejects.toThrow("PR base commit tree contains duplicate paths"); - }); +function selectorInput(candidateRepository: string) { + return { + baseSha: BASE_SHA, + candidateRepository, + candidateSha: CANDIDATE_SHA, + prNumber: PR_NUMBER, + token: "test-token", + workflowSource: WORKFLOW_SOURCE, + }; +} - it.each([ - ["blob", "040000"], - ["commit", "100644"], - ["tree", "100755"], - ])("rejects an immutable %s entry with Git mode %s", async (type, mode) => { - const request = exactCommitRequest("docs/upgrade.md", (apiPath) => { - throw new Error(`unexpected request: ${apiPath}`); - }); - const baseTreePath = `/repos/NVIDIA/NemoClaw/git/trees/${BASE_TREE_SHA}?recursive=1`; +afterEach(() => { + vi.unstubAllGlobals(); +}); +describe("PR managed-image source selection", () => { + it("keeps source selection bound to commit A during A-to-B-to-A PR drift", async () => { await expect( - resolvePrManagedImageCatalog( - { - baseSha: BASE_SHA, - candidateRepository: "NVIDIA/NemoClaw", - candidateSha: CANDIDATE_SHA, - outputPath: path.join(os.tmpdir(), "unused-pr-managed-image-catalog.json"), - prNumber: PR_NUMBER, - token: "test-token", - workflowSource: MANAGED_IMAGE_WORKFLOW, - }, - async (apiPath) => - apiPath === baseTreePath - ? { - sha: BASE_TREE_SHA, - truncated: false, - tree: [{ path: "agents", mode, type, sha: "1".repeat(40) }], - } - : request(apiPath), + resolvePrManagedImageSource( + selectorInput(CANONICAL_REPOSITORY), + requestFor(CANONICAL_REPOSITORY, true), ), - ).rejects.toThrow("PR base tree entry mode is invalid"); + ).resolves.toBe("local-dockerfile"); }); - it("rejects a manual PR catalog without a trusted pre-checkout producer", () => { - const workflow = readE2eOperationsWorkflow(); - delete workflow.jobs["generate-matrix"].outputs?.managed_image_catalog; + it("reads a validated external candidate repository through the default request policy", async () => { + const candidateRepository = "external-contributor/NemoClaw"; + const request = requestFor(candidateRepository, false); + vi.stubGlobal("fetch", async (input: string) => { + const url = new URL(input); + return new Response(JSON.stringify(await request(`${url.pathname}${url.search}`)), { + status: 200, + }); + }); - expect(validateE2eOperationsWorkflow(workflow)).toContain( - "Manual PR managed-image catalog must be authenticated before candidate checkout", + await expect(resolvePrManagedImageSource(selectorInput(candidateRepository))).resolves.toBe( + "managed-image", ); }); - it("rejects a candidate mutation of the authenticated managed-image catalog", () => { - const workflow = YAML.parse(fs.readFileSync(".github/workflows/e2e.yaml", "utf8")); - const packageCli = workflow.jobs["generate-matrix"].steps.find( - (step: Record) => step.name === "Package exact-commit CLI", - ); - const stagingMatch = packageCli.run.match( - /# BEGIN exact managed-image catalog staging\n([\s\S]*?)# END exact managed-image catalog staging/u, - ); - const stagingSource = stagingMatch?.[1] ?? ""; - - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-catalog-stage-test-")); - try { - fs.mkdirSync(path.join(directory, "dist"), { mode: 0o700 }); - const trustedCatalog = JSON.stringify( - Object.fromEntries( - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => [agent, contract(agent, index)]), - ), - ); - const trustedDigest = createHash("sha256") - .update(`${trustedCatalog}\n`, "utf8") - .digest("hex"); - fs.writeFileSync( - path.join(directory, "pr-managed-image-catalog.json"), - '{"candidateMutation":true}\n', - { mode: 0o600 }, - ); - const scriptPath = path.join(directory, "stage-managed-image-catalog.sh"); - fs.writeFileSync(scriptPath, `set -euo pipefail\n${stagingSource}`, { mode: 0o700 }); - - const result = spawnSync("/bin/bash", ["--noprofile", "--norc", scriptPath], { - cwd: directory, - encoding: "utf8", - env: { - MANAGED_IMAGE_CATALOG: trustedCatalog, - MANAGED_IMAGE_CATALOG_SHA256: trustedDigest, - PATH: "/usr/bin:/bin:/usr/sbin:/sbin", - RUNNER_TEMP: directory, + it("rejects a GitHub request outside the canonical and candidate repositories", async () => { + await expect( + githubRequest(`/repos/other-owner/other-repository/git/commits/${CANDIDATE_SHA}`, "token", { + additionalRepository: "external-contributor/NemoClaw", + attempts: 1, + fetchImpl: async () => { + throw new Error("must not fetch"); }, - }); - - expect(result.status).not.toBe(0); - expect(result.stderr).toContain( - "trusted PR managed-image catalog changed after authentication", - ); - expect(fs.existsSync(path.join(directory, "dist/e2e-managed-image-catalog.json"))).toBe( - false, - ); - } finally { - fs.rmSync(directory, { force: true, recursive: true }); - } - }); - - it("selects one successful workflow run for the candidate commit", () => { - expect( - selectManagedImagePublicationRun(run(), { - headSha: CANDIDATE_SHA, - prNumber: PR_NUMBER, - workflowId: WORKFLOW_ID, - }), - ).toEqual({ id: 32144654845, attempt: 1, headSha: CANDIDATE_SHA }); - }); - - it.each([ - ["pending", { status: "in_progress", conclusion: null }, "must complete successfully"], - ["failed", { conclusion: "failure" }, "must complete successfully"], - ["different commit", { head_sha: "b".repeat(40) }, "commit must be"], - ["different PR", { pull_requests: [{ number: 9464 }] }, "PR number"], - ])("rejects a %s publication run", (_label, overrides, message) => { - expect(() => - selectManagedImagePublicationRun(run(overrides), { - headSha: CANDIDATE_SHA, - prNumber: PR_NUMBER, - workflowId: WORKFLOW_ID, }), - ).toThrow(message); - }); - - it("assembles one exact all-agent catalog", () => { - const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map(contract); - - expect(assembleManagedImageCatalog(contracts, CANDIDATE_SHA)).toEqual( - Object.fromEntries(contracts.map((value) => [value.agent, value])), - ); - }); - - it("writes a validated catalog through the shared assembly command", async () => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-catalog-test-")); - try { - const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => { - const contractPath = path.join(directory, `${agent}.json`); - fs.writeFileSync(contractPath, JSON.stringify(contract(agent, index))); - return contractPath; - }); - const outputPath = path.join(directory, "catalog.json"); - - await main(["assemble", CANDIDATE_SHA, outputPath, ...contracts], {}); - - expect(JSON.parse(fs.readFileSync(outputPath, "utf8"))).toEqual( - Object.fromEntries( - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => [agent, contract(agent, index)]), - ), - ); - expect(fs.statSync(outputPath).mode & 0o777).toBe(0o600); - } finally { - fs.rmSync(directory, { force: true, recursive: true }); - } - }); - - it.each([ - [ - "candidate revision", - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => - index === 0 - ? { - ...contract(agent, index), - source: { ...contract(agent, index).source, revision: "b".repeat(40) }, - } - : contract(agent, index), - ), - "candidate commit", - ], - [ - "publication cohort", - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => - index === 0 - ? { - ...contract(agent, index), - source: { ...contract(agent, index).source, cohort: "ghrun-32144654845-2" }, - } - : contract(agent, index), - ), - "publication cohort", - ], - [ - "agent set", - [contract("openclaw", 0), contract("openclaw", 0), contract("hermes", 1)], - "every shipped agent", - ], - ])("rejects mixed %s authority", (_label, contracts, message) => { - expect(() => assembleManagedImageCatalog(contracts, CANDIDATE_SHA)).toThrow(message); + ).rejects.toThrow("GitHub API path must stay within an allowed repository"); }); }); diff --git a/tools/e2e/mcp-dev-workflow-boundary-digests.mts b/tools/e2e/mcp-dev-workflow-boundary-digests.mts index 0f36f01e81c..c8ffe4734eb 100644 --- a/tools/e2e/mcp-dev-workflow-boundary-digests.mts +++ b/tools/e2e/mcp-dev-workflow-boundary-digests.mts @@ -5,6 +5,8 @@ import { createHash } from "node:crypto"; export const MCP_DEV_WORKFLOW_EXECUTION_CONTEXT_SHA256 = "052c49d5e8688266dbf38fa911733132d33e4470a29a61deb6e7a11067737559"; +export const MCP_DEV_JOB_EXECUTION_CONTEXT_SHA256 = + "63fdbb0b1d775e0f06cb31adc36d992b79bf75866a51038e3faa87849f2545e4"; export const MCP_DEV_TRUSTED_NODE_SETUP_CONTENT_SHA256 = "504821ad93c57971d0281ef1130ed6008fadd331bd56acb1a6b5e6a3358f3e49"; export const MCP_DEV_TRUSTED_PREFIX_CONTENT_SHA256 = diff --git a/tools/e2e/mcp-workflow-boundary.mts b/tools/e2e/mcp-workflow-boundary.mts index f8d27680e8d..e5775bebc62 100644 --- a/tools/e2e/mcp-workflow-boundary.mts +++ b/tools/e2e/mcp-workflow-boundary.mts @@ -11,6 +11,7 @@ import { } from "./upload-e2e-artifacts-workflow-boundary.mts"; import { contentSha256, + MCP_DEV_JOB_EXECUTION_CONTEXT_SHA256, MCP_DEV_POST_INSTALL_TRANSITION_CONTENT_SHA256, MCP_DEV_TRUSTED_NODE_SETUP_CONTENT_SHA256, MCP_DEV_TRUSTED_PREFIX_CONTENT_SHA256, @@ -283,17 +284,13 @@ function validateJobSecurity( job: UnknownRecord, canonicalDockerAuth: UnknownRecord, ): void { - const environment = asRecord(job.env); - if ( - jobName === "mcp-bridge-dev" && - (Object.hasOwn(environment, "NODE_OPTIONS") || - ["BASH_ENV", "ENV"].some( - (name) => Object.hasOwn(environment, name) && environment[name] !== "/dev/null", - )) - ) { - errors.push( - "mcp-bridge-dev must preserve its reviewed job execution context before candidate activation", - ); + if (jobName === "mcp-bridge-dev") { + const { steps: _jobSteps, ...jobExecutionContext } = job; + if (contentSha256(jobExecutionContext) !== MCP_DEV_JOB_EXECUTION_CONTEXT_SHA256) { + errors.push( + "mcp-bridge-dev must preserve its reviewed job execution context before candidate activation", + ); + } } const permissions = asRecord(job.permissions); if (Object.keys(permissions).sort().join(",") !== "contents" || permissions.contents !== "read") { diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index 5a7bf57ae7f..07d1b7c3384 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -34,6 +34,8 @@ const LIVE_VITEST_HELPER = "tools/e2e/live-vitest-invocation.mts run --test-path const E2E_ARTIFACT_ACTION = "NVIDIA/NemoClaw/.github/actions/upload-e2e-artifacts@"; const COLD_ONBOARD_PERFORMANCE_EVIDENCE_PATH = "e2e-artifacts/live/${{ matrix.id }}/onboard-progress-budget.json"; +const MANAGED_SOURCE_CONDITION = + "${{ inputs.pr_number == '' || steps.select_pr_source.outputs.workload_source == 'managed-image' }}"; const PUBLICATION_CLASSIFIER_SCRIPT = [ "set -euo pipefail", @@ -660,16 +662,14 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): outputs: { dcode_base_contract: "${{ steps.validate_dcode_base.outputs.contract }}", dcode_base_ref: "${{ steps.validate_dcode_base.outputs.base_ref }}", - managed_image_artifact_provenance: "${{ steps.download_managed_cohort.outputs.provenance }}", - managed_image_cohort: "${{ steps.validate_managed_cohort.outputs.cohort }}", managed_image_receipt: "${{ steps.validate_managed_cohort.outputs.receipt }}", managed_image_revision: "${{ steps.validate_managed_cohort.outputs.revision }}", - managed_image_run_attempt: "${{ steps.validate_managed_cohort.outputs.run_attempt }}", - managed_image_run_id: "${{ steps.validate_managed_cohort.outputs.run_id }}", + workload_source: "${{ steps.select_pr_source.outputs.workload_source || 'managed-image' }}", }, permissions: { actions: "read", contents: "read", + "pull-requests": "read", }, steps: [ { @@ -702,17 +702,41 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): "node-version": 22, }, }, + { + id: "select_pr_source", + name: "Select PR workload source", + if: "${{ inputs.pr_number != '' }}", + env: { + BASE_SHA: "${{ inputs.base_sha }}", + CANDIDATE_REPOSITORY: "${{ inputs.checkout_repository }}", + CANDIDATE_SHA: "${{ inputs.checkout_sha }}", + GITHUB_TOKEN: "${{ github.token }}", + PR_NUMBER: "${{ inputs.pr_number }}", + }, + shell: "bash", + run: [ + "set -euo pipefail", + 'workload_source="$(node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-publication.mts select-source)"', + 'case "$workload_source" in', + " managed-image|local-dockerfile) ;;", + ' *) echo "::error::PR workload source is invalid" >&2; exit 1 ;;', + "esac", + 'printf \'workload_source=%s\\n\' "$workload_source" >>"$GITHUB_OUTPUT"', + "", + ].join("\n"), + }, { id: "publication", - name: "Select complete base and managed-image publication", + name: "Select base and optional managed-image publication", env: { EXPECTED_SHA: "${{ steps.publication_mode.outputs.expected_sha }}", GITHUB_TOKEN: "${{ github.token }}", PUBLICATION_HISTORY_ALLOW_NON_HEAD: "${{ steps.publication_mode.outputs.allow_non_head }}", - REQUIRE_MANAGED_IMAGE_PUBLICATION: "1", + REQUIRE_MANAGED_IMAGE_PUBLICATION: + "${{ steps.select_pr_source.outputs.workload_source == 'local-dockerfile' && '0' || '1' }}", SELECT_NEAREST_SUCCESSFUL_PUBLICATION: - "${{ steps.publication_mode.outputs.select_nearest_successful }}", + "${{ steps.select_pr_source.outputs.workload_source == 'local-dockerfile' && '0' || steps.publication_mode.outputs.select_nearest_successful }}", }, shell: "bash", run: [ @@ -750,6 +774,7 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): { id: "download_managed_cohort", name: "Download immutable managed-image cohort contract", + if: MANAGED_SOURCE_CONDITION, env: { GITHUB_TOKEN: "${{ github.token }}", PUBLICATION_ARTIFACT_KIND: "managed-image-cohort", @@ -762,6 +787,7 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): { id: "validate_managed_cohort", name: "Validate immutable managed-image cohort contract", + if: MANAGED_SOURCE_CONDITION, env: { PUBLICATION_HEAD_SHA: "${{ steps.publication.outputs.head_sha }}", PUBLICATION_RUN_ATTEMPT: "${{ steps.publication.outputs.run_attempt }}", @@ -795,19 +821,15 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): } if ( cloudOnboard.env?.E2E_MANAGED_IMAGE_REVISION !== - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}" + "${{ needs.base-image-publication.outputs.managed_image_revision }}" ) { - errors.push( - "cloud-onboard must use the selected managed-image revision when no exact PR catalog is present", - ); + errors.push("cloud-onboard must use the selected managed-image revision"); } if ( live.env?.E2E_MANAGED_IMAGE_REVISION !== - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}" + "${{ needs.base-image-publication.outputs.managed_image_revision }}" ) { - errors.push( - "live stock onboarding must use the selected managed-image revision when no exact PR catalog is present", - ); + errors.push("live stock onboarding must use the selected managed-image revision"); } for (const jobName of [ "catalogue-standard", @@ -822,22 +844,14 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): } if ( catalogue.with?.managed_image_revision !== - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}" - ) { - errors.push( - `${jobName} must use the selected managed-image revision when no exact PR catalog is present`, - ); - } - if ( - catalogue.with?.managed_image_catalog !== - "${{ needs.generate-matrix.outputs.managed_image_catalog }}" + "${{ needs.base-image-publication.outputs.managed_image_revision }}" ) { - errors.push(`${jobName} must pass the selected exact PR managed-image catalog`); + errors.push(`${jobName} must use the selected managed-image revision`); } } if ( live.env?.NEMOCLAW_LANGCHAIN_DEEPAGENTS_CODE_SANDBOX_BASE_IMAGE_REF !== - "${{ needs.base-image-publication.outputs.dcode_base_ref }}" + "${{ needs.generate-matrix.outputs.workload_source == 'managed-image' && needs.base-image-publication.outputs.dcode_base_ref || '' }}" ) { errors.push("live DCode must use the selected immutable base reference"); } @@ -849,7 +863,8 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): .filter(Boolean); const liveSteps = live.steps ?? []; if ( - evidence.if !== "${{ matrix.id == 'ubuntu-repo-cloud-langchain-deepagents-code' }}" || + evidence.if !== + "${{ matrix.id == 'ubuntu-repo-cloud-langchain-deepagents-code' && needs.generate-matrix.outputs.workload_source == 'managed-image' }}" || evidence.env?.BASE_CONTRACT !== "${{ needs.base-image-publication.outputs.dcode_base_contract }}" || !String(evidence.run ?? "").includes("dcode-base-image.json") || @@ -894,9 +909,9 @@ const STOCK_ONBOARDING_CATALOGUE_JOBS = [ ] as const; const MANAGED_IMAGE_REVISION_EXPRESSION = - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_revision || '' }}"; + "${{ needs.base-image-publication.outputs.managed_image_revision }}"; const MANAGED_IMAGE_RECEIPT_EXPRESSION = - "${{ needs.generate-matrix.outputs.managed_image_catalog == '' && needs.base-image-publication.outputs.managed_image_receipt || '' }}"; + "${{ needs.base-image-publication.outputs.managed_image_receipt }}"; /** Require publication success and one exact cohort revision for every stock onboarding job. */ export function validateStockOnboardingPublicationBoundary(workflow: OperationsWorkflow): string[] { diff --git a/tools/e2e/pr-managed-image-publication.mts b/tools/e2e/pr-managed-image-publication.mts index a187981050a..4b8d32b0851 100644 --- a/tools/e2e/pr-managed-image-publication.mts +++ b/tools/e2e/pr-managed-image-publication.mts @@ -2,46 +2,30 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; -import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import YAML from "yaml"; - import { parseManagedImageContractV1, SHIPPED_MANAGED_IMAGE_AGENTS, type ManagedImageContractCatalog, - type ManagedImageContractV1, } from "../../src/lib/onboard/managed-image/contract.ts"; -import { githubRequest } from "./base-image-publication.mts"; import { - bindNamedExactArtifact, - downloadBoundArtifact, - materializeContractArchive, -} from "./exact-artifact-download.mts"; + baseImageInputsChanged, + githubRequest, + parseBaseImagePushPaths, +} from "./base-image-publication.mts"; const REPOSITORY = "NVIDIA/NemoClaw"; -const WORKFLOW_PATH = ".github/workflows/managed-images.yaml"; -const WORKFLOW_FILE = "managed-images.yaml"; -const WORKFLOW_NAME = "Images / Build, Test, and Publish Managed Images"; -const MAX_CHANGED_FILES = 3_000; +const BASE_IMAGE_WORKFLOW_PATH = ".github/workflows/base-image.yaml"; const MAX_COMMIT_TREE_ENTRIES = 100_000; const SHA_PATTERN = /^[0-9a-f]{40}$/u; -const SAFE_PATH_PATTERN = /^[A-Za-z0-9._/*-]+$/u; -const TREE_ENTRY_MODES = new Map([ - ["blob", new Set(["100644", "100755", "120000"])], - ["commit", new Set(["160000"])], - ["tree", new Set(["040000"])], -]); +const REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u; +const TREE_ENTRY_TYPES = new Set(["blob", "commit", "tree"]); type JsonRecord = Record; -export interface ManagedImagePublicationRun { - readonly id: number; - readonly attempt: number; - readonly headSha: string; -} +export type PrManagedImageSource = "local-dockerfile" | "managed-image"; function record(value: unknown, label: string): JsonRecord { if (!value || typeof value !== "object" || Array.isArray(value)) { @@ -61,138 +45,7 @@ function exactString(value: unknown, expected: string, label: string): void { if (value !== expected) throw new Error(`${label} must be ${expected}`); } -function sha(value: unknown, label: string): string { - if (typeof value !== "string" || !SHA_PATTERN.test(value)) { - throw new Error(`${label} must be a lowercase 40-character SHA`); - } - return value; -} - -function compileManagedImagePath(pattern: string): RegExp { - if ( - !SAFE_PATH_PATTERN.test(pattern) || - pattern.startsWith("/") || - pattern.includes("//") || - pattern.split("/").some((segment) => segment === "" || segment === "." || segment === "..") - ) { - throw new Error(`managed-image PR path '${pattern}' is invalid`); - } - const stars = [...pattern.matchAll(/\*/gu)].map((match) => match.index); - if (stars.length === 0) { - return new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}$`, "u"); - } - if (pattern.endsWith("/**") && stars.length === 2) { - const prefix = pattern.slice(0, -3).replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); - return new RegExp(`^${prefix}/.+$`, "u"); - } - if (stars.length === 1) { - const escaped = pattern.replace(/[.+?^${}()|[\]\\]/gu, "\\$&").replaceAll("*", "[^/]*"); - return new RegExp(`^${escaped}$`, "u"); - } - throw new Error(`managed-image PR path '${pattern}' uses an unsupported glob`); -} - -/** Read the managed-image workflow path filter from the trusted workflow source. */ -export function parseManagedImagePullRequestPaths(source: string): string[] { - const workflow = record(YAML.parse(source), "managed-image workflow"); - const triggers = record(workflow.on, "managed-image workflow on block"); - const pullRequest = record(triggers.pull_request, "managed-image pull_request trigger"); - if (!Array.isArray(pullRequest.paths) || pullRequest.paths.length === 0) { - throw new Error("managed-image pull_request trigger must declare paths"); - } - const paths = pullRequest.paths.map((value) => { - if (typeof value !== "string" || value.length === 0 || value.trim() !== value) { - throw new Error("managed-image PR paths must be non-empty strings"); - } - compileManagedImagePath(value); - return value; - }); - if (new Set(paths).size !== paths.length) { - throw new Error("managed-image PR paths must be unique"); - } - if (!paths.includes(WORKFLOW_PATH)) { - throw new Error(`managed-image PR paths must include ${WORKFLOW_PATH}`); - } - return paths; -} - -/** Determine whether changed PR files require exact managed-image publication. */ -export function managedImagePublicationRequired( - changedFiles: readonly string[], - patterns: readonly string[], -): boolean { - if (changedFiles.length > MAX_CHANGED_FILES * 2) { - throw new Error(`PR changed-path count exceeds ${MAX_CHANGED_FILES * 2}`); - } - const matchers = patterns.map(compileManagedImagePath); - for (const file of changedFiles) { - if ( - file.length === 0 || - file.length > 4_096 || - /[\0\r\n]/u.test(file) || - file.startsWith("/") || - file.includes("//") || - file.split("/").some((segment) => segment === "" || segment === "." || segment === "..") - ) { - throw new Error("PR changed-file path is invalid"); - } - if (matchers.some((matcher) => matcher.test(file))) return true; - } - return false; -} - -/** Select the unique successful managed-image workflow run for one PR commit. */ -export function selectManagedImagePublicationRun( - payload: unknown, - expected: { readonly headSha: string; readonly prNumber: number; readonly workflowId: number }, -): ManagedImagePublicationRun { - if (!SHA_PATTERN.test(expected.headSha)) throw new Error("candidate SHA is invalid"); - positiveInteger(expected.prNumber, "PR number"); - positiveInteger(expected.workflowId, "managed-image workflow id"); - const response = record(payload, "managed-image workflow runs"); - if (response.total_count !== 1 || !Array.isArray(response.workflow_runs)) { - throw new Error("exact managed-image workflow run is missing or ambiguous"); - } - if (response.workflow_runs.length !== 1) { - throw new Error("exact managed-image workflow run listing is incomplete"); - } - const run = record(response.workflow_runs[0], "managed-image workflow run"); - const id = positiveInteger(run.id, "managed-image workflow run id"); - const attempt = positiveInteger(run.run_attempt, "managed-image workflow run attempt"); - if (run.workflow_id !== expected.workflowId) { - throw new Error("managed-image workflow run does not match the trusted workflow"); - } - exactString(run.name, WORKFLOW_NAME, "managed-image workflow run name"); - exactString(run.path, WORKFLOW_PATH, "managed-image workflow run path"); - exactString(run.event, "pull_request", "managed-image workflow run event"); - exactString(run.head_sha, expected.headSha, "managed-image workflow run commit"); - exactString( - record(run.repository, "managed-image workflow repository").full_name, - REPOSITORY, - "managed-image workflow repository", - ); - exactString( - record(run.head_repository, "managed-image workflow source repository").full_name, - REPOSITORY, - "managed-image workflow source repository", - ); - if ( - !Array.isArray(run.pull_requests) || - run.pull_requests.length !== 1 || - record(run.pull_requests[0], "managed-image workflow pull request").number !== expected.prNumber - ) { - throw new Error("managed-image workflow run does not match the PR number"); - } - if (run.status !== "completed" || run.conclusion !== "success") { - throw new Error( - `managed-image workflow for candidate ${expected.headSha} must complete successfully before live E2E`, - ); - } - return { id, attempt, headSha: expected.headSha }; -} - -/** Assemble one all-agent catalog and reject mixed publication authority. */ -export function assembleManagedImageCatalog( +function assembleManagedImageCatalog( values: readonly unknown[], candidateSha: string, ): ManagedImageContractCatalog { @@ -226,8 +79,7 @@ export function assembleManagedImageCatalog( ); } -/** Write one validated exact-candidate catalog from local contract paths. */ -export function writeManagedImageCatalog( +function writeManagedImageCatalog( contractPaths: readonly string[], candidateSha: string, outputPath: string, @@ -244,28 +96,27 @@ export function writeManagedImageCatalog( }); } -function validateWorkflow(payload: unknown): number { - const workflow = record(payload, "managed-image workflow"); - const id = positiveInteger(workflow.id, "managed-image workflow id"); - exactString(workflow.name, WORKFLOW_NAME, "managed-image workflow name"); - exactString(workflow.path, WORKFLOW_PATH, "managed-image workflow path"); - exactString(workflow.state, "active", "managed-image workflow state"); - return id; +function sha(value: unknown, label: string): string { + if (typeof value !== "string" || !SHA_PATTERN.test(value)) { + throw new Error(`${label} must be a lowercase 40-character SHA`); + } + return value; } async function readCommitTree( + repository: string, revision: string, label: string, request: (path: string) => Promise, ): Promise> { const commit = record( - await request(`/repos/${REPOSITORY}/git/commits/${revision}`), + await request(`/repos/${repository}/git/commits/${revision}`), `${label} commit`, ); exactString(commit.sha, revision, `${label} commit SHA`); const treeSha = sha(record(commit.tree, `${label} commit tree`).sha, `${label} tree SHA`); const payload = record( - await request(`/repos/${REPOSITORY}/git/trees/${treeSha}?recursive=1`), + await request(`/repos/${repository}/git/trees/${treeSha}?recursive=1`), `${label} tree`, ); exactString(payload.sha, treeSha, `${label} tree SHA`); @@ -277,35 +128,40 @@ async function readCommitTree( } const entries = new Map(); - const paths = new Set(); for (const value of payload.tree) { const entry = record(value, `${label} tree entry`); if (typeof entry.path !== "string" || entry.path.length === 0) { throw new Error(`${label} tree entry path is invalid`); } - if (paths.has(entry.path)) throw new Error(`${label} commit tree contains duplicate paths`); - paths.add(entry.path); - const validModes = - typeof entry.type === "string" ? TREE_ENTRY_MODES.get(entry.type) : undefined; - if (!validModes) { + if (typeof entry.type !== "string" || !TREE_ENTRY_TYPES.has(entry.type)) { throw new Error(`${label} tree entry type is invalid`); } - if (typeof entry.mode !== "string" || !validModes.has(entry.mode)) { + if (typeof entry.mode !== "string" || !/^[0-7]{6}$/u.test(entry.mode)) { throw new Error(`${label} tree entry mode is invalid`); } const entrySha = sha(entry.sha, `${label} tree entry SHA`); if (entry.type === "tree") continue; + if (entries.has(entry.path)) throw new Error(`${label} commit tree contains duplicate paths`); entries.set(entry.path, `${entry.mode}:${entry.type}:${entrySha}`); } return entries; } async function readChangedFiles( - input: { readonly baseSha: string; readonly candidateSha: string }, + input: { + readonly baseSha: string; + readonly candidateRepository: string; + readonly candidateSha: string; + }, request: (path: string) => Promise, ): Promise { - const baseTree = await readCommitTree(input.baseSha, "PR base", request); - const candidateTree = await readCommitTree(input.candidateSha, "PR candidate", request); + const baseTree = await readCommitTree(REPOSITORY, input.baseSha, "PR base", request); + const candidateTree = await readCommitTree( + input.candidateRepository, + input.candidateSha, + "PR candidate", + request, + ); const changedFiles: string[] = []; for (const changedPath of new Set([...baseTree.keys(), ...candidateTree.keys()])) { if (baseTree.get(changedPath) === candidateTree.get(changedPath)) continue; @@ -316,7 +172,11 @@ async function readChangedFiles( function validatePr( payload: unknown, - expected: { readonly baseSha: string; readonly candidateSha: string; readonly prNumber: number }, + expected: { + readonly baseSha: string; + readonly candidateRepository: string; + readonly candidateSha: string; + }, ): void { const pull = record(payload, "pull request"); exactString(pull.state, "open", "pull request state"); @@ -338,81 +198,41 @@ function validatePr( exactString( record(record(pull.head, "pull request source").repo, "pull request source repository") .full_name, - REPOSITORY, + expected.candidateRepository, "pull request source repository", ); } -/** Resolve and download the exact all-agent catalog before candidate code executes. */ -export async function resolvePrManagedImageCatalog( +/** Select the managed-image or local-Dockerfile source for a validated PR. */ +export async function resolvePrManagedImageSource( input: { readonly baseSha: string; readonly candidateRepository: string; readonly candidateSha: string; - readonly outputPath: string; readonly prNumber: number; readonly token: string; readonly workflowSource: string; }, - request: (path: string) => Promise = (apiPath) => githubRequest(apiPath, input.token), -): Promise<"not-required" | "written"> { - if (input.candidateRepository !== REPOSITORY) return "not-required"; + request: (apiPath: string) => Promise = (apiPath) => + githubRequest(apiPath, input.token, { + additionalRepository: input.candidateRepository, + }), +): Promise { if (!SHA_PATTERN.test(input.baseSha) || !SHA_PATTERN.test(input.candidateSha)) { throw new Error("PR base and candidate SHAs are required"); } + if ( + !REPOSITORY_PATTERN.test(input.candidateRepository) || + input.candidateRepository.split("/").some((segment) => segment === "." || segment === "..") + ) { + throw new Error("candidate repository is invalid"); + } positiveInteger(input.prNumber, "PR number"); if (!input.token) throw new Error("GITHUB_TOKEN is required"); validatePr(await request(`/repos/${REPOSITORY}/pulls/${input.prNumber}`), input); const changedFiles = await readChangedFiles(input, request); - const patterns = parseManagedImagePullRequestPaths(input.workflowSource); - if (!managedImagePublicationRequired(changedFiles, patterns)) return "not-required"; - - const workflowId = validateWorkflow( - await request(`/repos/${REPOSITORY}/actions/workflows/${WORKFLOW_FILE}`), - ); - const runs = await request( - `/repos/${REPOSITORY}/actions/workflows/${WORKFLOW_FILE}/runs?event=pull_request&head_sha=${input.candidateSha}&per_page=100`, - ); - const run = selectManagedImagePublicationRun(runs, { - headSha: input.candidateSha, - prNumber: input.prNumber, - workflowId, - }); - - const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-managed-catalog-")); - try { - const contracts: ManagedImageContractV1[] = []; - for (const agent of SHIPPED_MANAGED_IMAGE_AGENTS) { - const name = `managed-pr-contract-${run.id}-${run.attempt}-${agent}`; - const metadata = await request( - `/repos/${REPOSITORY}/actions/runs/${run.id}/artifacts?name=${encodeURIComponent(name)}&per_page=100`, - ); - const identity = bindNamedExactArtifact( - metadata, - { - headSha: run.headSha, - runAttempt: run.attempt, - runId: run.id, - }, - name, - ); - const archive = await downloadBoundArtifact(identity, input.token); - const contractPath = materializeContractArchive(archive, path.join(tempDirectory, agent)); - contracts.push( - JSON.parse(fs.readFileSync(contractPath, "utf8")) as unknown as ManagedImageContractV1, - ); - } - const catalog = assembleManagedImageCatalog(contracts, input.candidateSha); - fs.mkdirSync(path.dirname(path.resolve(input.outputPath)), { mode: 0o700, recursive: true }); - fs.writeFileSync(input.outputPath, `${JSON.stringify(catalog)}\n`, { - encoding: "utf8", - flag: "wx", - mode: 0o600, - }); - return "written"; - } finally { - fs.rmSync(tempDirectory, { force: true, recursive: true }); - } + const patterns = parseBaseImagePushPaths(input.workflowSource); + return baseImageInputsChanged(changedFiles, patterns) ? "local-dockerfile" : "managed-image"; } function requiredInteger(value: string | undefined, label: string): number { @@ -429,19 +249,16 @@ export async function main(argv = process.argv.slice(2), env = process.env): Pro console.log("pr-managed-image-catalog outcome=assembled"); return; } - if (argv.length !== 1) throw new Error("expected one managed-image catalog output path"); - const candidateSha = env.CANDIDATE_SHA ?? ""; - if (!candidateSha) return; - const result = await resolvePrManagedImageCatalog({ + if (argv.length !== 1 || argv[0] !== "select-source") throw new Error("expected select-source"); + const source = await resolvePrManagedImageSource({ baseSha: env.BASE_SHA ?? "", candidateRepository: env.CANDIDATE_REPOSITORY ?? "", - candidateSha, - outputPath: argv[0], + candidateSha: env.CANDIDATE_SHA ?? "", prNumber: requiredInteger(env.PR_NUMBER, "PR_NUMBER"), token: env.GITHUB_TOKEN ?? "", - workflowSource: fs.readFileSync(WORKFLOW_PATH, "utf8"), + workflowSource: fs.readFileSync(BASE_IMAGE_WORKFLOW_PATH, "utf8"), }); - console.log(`pr-managed-image-catalog outcome=${result}`); + process.stdout.write(`${source}\n`); } if (path.resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) {