diff --git a/.github/actions/artifacts/action.yml b/.github/actions/artifacts/action.yml index ad939f7..529ed78 100644 --- a/.github/actions/artifacts/action.yml +++ b/.github/actions/artifacts/action.yml @@ -10,6 +10,15 @@ outputs: is_latest: description: 'true if the pushed tag is the highest version/* tag (release flow only)' value: ${{ steps.handler.outputs.is_latest }} + version: + description: 'The published snapshot version, e.g. 0.0.0-- (PR snapshot only)' + value: ${{ steps.handler.outputs.version }} + packages: + description: 'JSON array of the published package names, [] when nothing was published (PR snapshot only)' + value: ${{ steps.handler.outputs.packages }} + integrities: + description: 'JSON object mapping each published package name to its npm integrity, {} when nothing was published (PR snapshot only)' + value: ${{ steps.handler.outputs.integrities }} runs: using: 'composite' steps: diff --git a/.github/actions/backend-e2e-checkout-commit/action.yml b/.github/actions/backend-e2e-checkout-commit/action.yml new file mode 100644 index 0000000..6452b99 --- /dev/null +++ b/.github/actions/backend-e2e-checkout-commit/action.yml @@ -0,0 +1,18 @@ +name: 'Backend E2E: check out a commit' +description: 'Moves an existing clone to one commit, and fails unless it ends up there' +inputs: + dir: + description: 'The clone, relative to the workspace' + required: true + sha: + description: 'The full commit SHA to check out' + required: true +runs: + using: 'composite' + steps: + - name: Check out the commit + shell: bash + env: + DIR: ${{ inputs.dir }} + SHA: ${{ inputs.sha }} + run: '"$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/checkout-commit.sh" "${DIR}" "${SHA}"' diff --git a/.github/actions/backend-e2e-pin/action.yml b/.github/actions/backend-e2e-pin/action.yml new file mode 100644 index 0000000..3c6e649 --- /dev/null +++ b/.github/actions/backend-e2e-pin/action.yml @@ -0,0 +1,42 @@ +name: 'Backend E2E: pin snapshot packages' +description: 'Pins the npm snapshot versions a frontend PR published into the npm projects of a backend or cplace-e2e checkout' +inputs: + version: + description: 'The published snapshot version, e.g. 0.0.0--' + required: true + packages: + description: 'JSON array of the published package names' + required: true + dirs: + description: 'Newline-separated globs of npm project dirs, relative to the workspace; a dir without package.json is skipped' + required: true + integrities: + description: 'JSON object mapping each published package name to the npm integrity its snapshot job published; a listed package whose installed integrity differs fails the pin' + required: false + default: '{}' +runs: + using: 'composite' + steps: + - name: Pin snapshot packages + shell: bash + env: + VERSION: ${{ inputs.version }} + PACKAGES: ${{ inputs.packages }} + DIRS: ${{ inputs.dirs }} + INTEGRITIES: ${{ inputs.integrities }} + run: | + set -euo pipefail + mapfile -t patterns <<<"${DIRS}" + pins="$("$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/pin-snapshots.sh" "${VERSION}" "${patterns[@]}")" + echo "${pins}" + { + echo '### Pinned snapshot packages' + echo + if [[ -n "${pins}" ]]; then + echo '```' + echo "${pins}" + echo '```' + else + echo "None of \`${DIRS//$'\n'/ }\` consumes a published package." + fi + } >>"$GITHUB_STEP_SUMMARY" diff --git a/.github/actions/backend-e2e-report/action.yml b/.github/actions/backend-e2e-report/action.yml new file mode 100644 index 0000000..40b165b --- /dev/null +++ b/.github/actions/backend-e2e-report/action.yml @@ -0,0 +1,90 @@ +name: 'Backend E2E: build the report' +description: 'Classifies a backend E2E run and writes the PR comment body from the published test results' +inputs: + results_json: + description: 'The json_file of EnricoMi/publish-unit-test-result-action' + required: true + body_file: + description: 'Where to write the comment body' + required: true + results_dir: + description: 'The dir the backend-e2e-results-* artifacts were downloaded to, one subdir per node that uploaded results' + required: true + nodes: + description: 'The number of e2e nodes' + required: true + advisory: + description: 'true when failures are reported as warnings only' + required: true + build_result: + description: 'The build job result' + required: true + e2e_result: + description: 'The e2e matrix result' + required: true + backend_repo: + description: 'The backend repository' + required: true + backend_branch: + description: 'The backend branch' + required: true + backend_sha: + description: 'The backend commit' + required: true + e2e_branch: + description: 'The cplace-e2e branch' + required: true + e2e_sha: + description: 'The cplace-e2e commit' + required: true + snapshot_version: + description: 'The published snapshot version' + required: false + default: '' + backend_packages: + description: 'JSON array of the packages pinned in the backend' + required: true + e2e_packages: + description: 'JSON array of the packages pinned in cplace-e2e' + required: true +outputs: + outcome: + description: 'cancelled, build-failure, test-failure, infrastructure-failure or passed' + value: ${{ steps.report.outputs.outcome }} + message: + description: 'One sentence explaining the outcome' + value: ${{ steps.report.outputs.message }} + tests: + description: 'The number of test results' + value: ${{ steps.report.outputs.tests }} + failed: + description: 'The number of failed and errored tests' + value: ${{ steps.report.outputs.failed }} +runs: + using: 'composite' + steps: + - id: report + shell: bash + env: + RESULTS_JSON: ${{ inputs.results_json }} + BODY_FILE: ${{ inputs.body_file }} + RESULTS_DIR: ${{ inputs.results_dir }} + NODES: ${{ inputs.nodes }} + ADVISORY: ${{ inputs.advisory }} + BUILD_RESULT: ${{ inputs.build_result }} + E2E_RESULT: ${{ inputs.e2e_result }} + BACKEND_REPO: ${{ inputs.backend_repo }} + BACKEND_BRANCH: ${{ inputs.backend_branch }} + BACKEND_SHA: ${{ inputs.backend_sha }} + E2E_BRANCH: ${{ inputs.e2e_branch }} + E2E_SHA: ${{ inputs.e2e_sha }} + SNAPSHOT_VERSION: ${{ inputs.snapshot_version }} + BACKEND_PACKAGES: ${{ inputs.backend_packages }} + E2E_PACKAGES: ${{ inputs.e2e_packages }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + shopt -s nullglob + reported=("${RESULTS_DIR}"/backend-e2e-results-*/) + export NODES_REPORTED="${#reported[@]}" + "$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/build-report.sh" "${RESULTS_JSON}" "${BODY_FILE}" diff --git a/.github/actions/backend-e2e-resolve/action.yml b/.github/actions/backend-e2e-resolve/action.yml new file mode 100644 index 0000000..9ae6747 --- /dev/null +++ b/.github/actions/backend-e2e-resolve/action.yml @@ -0,0 +1,250 @@ +name: 'Backend E2E: resolve backend' +description: 'Resolves the backend repository, the backend and cplace-e2e commits a frontend PR is tested against, whether the run is worth it, and its spec filter' +inputs: + fe_repo: + description: 'The frontend repository name, e.g. cplace-fe' + required: true + base_ref: + description: 'The PR base branch' + required: true + head_ref: + description: 'The PR head branch; used in the backend and cplace-e2e when they have a branch of that name' + required: true + pr_body: + description: 'The PR description; its backend-branch: and cplace-e2e-branch: lines choose the branches explicitly' + required: false + default: '' + in_repo_specs: + description: 'true when the FE repo has an e2e-tests/ folder' + required: false + default: 'false' + snapshot_version: + description: 'The published snapshot version, shown in the summary' + required: false + default: '' + packages: + description: 'JSON array of the published package names' + required: false + default: '[]' + e2e_specs: + description: 'Comma-separated cplace-e2e spec globs every run includes' + required: true + spec_map: + description: 'JSON object mapping a package name to the comma-separated spec globs added when it is consumed' + required: false + default: '{}' + nodes: + description: 'Number of parallel E2E nodes' + required: true + app_id: + description: 'ID of a GitHub App that can read the backend repository and cplace-e2e' + required: true + app_key: + description: 'Private key of that GitHub App' + required: true + npm_token: + description: 'A token for the cplace npm registry, to look up the FE base versions' + required: true + github_token: + description: 'A token that can list the PR files (pull-requests: read)' + required: true +outputs: + node_indexes: + description: 'JSON array [0..nodes-1] for the node matrix' + value: ${{ steps.nodes.outputs.node_indexes }} + backend_repo: + description: 'The backend repository, e.g. cplace' + value: ${{ steps.repo.outputs.backend_repo }} + repo_dir: + description: 'The checkout directory of the backend under GITHUB_WORKSPACE (main for cplace)' + value: ${{ steps.repo.outputs.repo_dir }} + backend_branch: + description: 'The backend branch to build' + value: ${{ steps.branches.outputs.backend_branch }} + backend_sha: + description: 'The backend commit to build' + value: ${{ steps.branches.outputs.backend_sha }} + e2e_branch: + description: 'The cplace-e2e branch to test with' + value: ${{ steps.branches.outputs.e2e_branch }} + e2e_sha: + description: 'The cplace-e2e commit to test with' + value: ${{ steps.branches.outputs.e2e_sha }} + backend_packages: + description: 'JSON array of the published packages the backend consumes' + value: ${{ steps.consumers.outputs.backend_packages }} + e2e_packages: + description: 'JSON array of the published packages cplace-e2e consumes' + value: ${{ steps.consumers.outputs.e2e_packages }} + run: + description: 'true when the backend or cplace-e2e consumes a published package, or the PR changed e2e-tests/' + value: ${{ steps.consumers.outputs.run }} + specs: + description: 'The comma-separated spec filter of the run' + value: ${{ steps.specs.outputs.specs }} + in_repo_specs: + description: 'true when the FE repo has an e2e-tests/ folder' + value: ${{ steps.specs.outputs.in_repo_specs }} +runs: + using: 'composite' + steps: + # First, so an invalid NODES fails before any branch resolution. + - id: nodes + shell: bash + env: + NODES: ${{ inputs.nodes }} + run: | + set -euo pipefail + node_indexes="$("$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/node-indexes.sh" "${NODES}")" + echo "node_indexes=${node_indexes}" >>"$GITHUB_OUTPUT" + + - id: repo + shell: bash + env: + FE_REPO: ${{ inputs.fe_repo }} + run: '"$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/resolve-backend.sh" repo' + + # The PR body is untrusted: it only ever reaches a script through env. + - id: directives + shell: bash + env: + PR_BODY: ${{ inputs.pr_body }} + run: '"$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/pr-directives.sh" >>"$GITHUB_OUTPUT"' + + - id: token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ inputs.app_id }} + private-key: ${{ inputs.app_key }} + owner: ${{ github.repository_owner }} + repositories: ${{ steps.repo.outputs.backend_repo }},cplace-e2e + + - id: branches + shell: bash + env: + BACKEND_REPO: ${{ steps.repo.outputs.backend_repo }} + BASE_REF: ${{ inputs.base_ref }} + HEAD_REF: ${{ inputs.head_ref }} + BACKEND_BRANCH_OVERRIDE: ${{ steps.directives.outputs.BACKEND_BRANCH_OVERRIDE }} + E2E_BRANCH_OVERRIDE: ${{ steps.directives.outputs.E2E_BRANCH_OVERRIDE }} + GH_TOKEN: ${{ steps.token.outputs.token }} + run: '"$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/resolve-backend.sh" branches' + + # Blob-less sparse checkouts: only the files that tell whether, and how, a + # published package is consumed. + - name: Fetch the backend and cplace-e2e manifests + shell: bash + env: + BACKEND_REPO: ${{ steps.repo.outputs.backend_repo }} + BACKEND_SHA: ${{ steps.branches.outputs.backend_sha }} + E2E_SHA: ${{ steps.branches.outputs.e2e_sha }} + GH_TOKEN: ${{ steps.token.outputs.token }} + run: '"$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/fetch-manifests.sh" "${RUNNER_TEMP}/backend-e2e"' + + # A failure to list the files fails the job, so a run never skips silently. + - id: changed + shell: bash + env: + GH_TOKEN: ${{ inputs.github_token }} + REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + set -euo pipefail + files="$(gh api --paginate "repos/${REPOSITORY}/pulls/${PR_NUMBER}/files" --jq '.[].filename')" + if grep -q '^e2e-tests/' <<<"${files}"; then + echo "specs_changed=true" >>"$GITHUB_OUTPUT" + else + echo "specs_changed=false" >>"$GITHUB_OUTPUT" + fi + + - id: consumers + shell: bash + env: + PACKAGES: ${{ inputs.packages }} + SPECS_CHANGED: ${{ steps.changed.outputs.specs_changed }} + run: >- + "$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/resolve-consumers.sh" + "${RUNNER_TEMP}/backend-e2e/backend" "${RUNNER_TEMP}/backend-e2e/cplace-e2e" + + - id: specs + shell: bash + env: + E2E_SPECS: ${{ inputs.e2e_specs }} + SPEC_MAP: ${{ inputs.spec_map }} + BACKEND_PACKAGES: ${{ steps.consumers.outputs.backend_packages }} + E2E_PACKAGES: ${{ steps.consumers.outputs.e2e_packages }} + IN_REPO_SPECS: ${{ inputs.in_repo_specs }} + FE_REPO: ${{ inputs.fe_repo }} + run: | + set -euo pipefail + CONSUMED="$(jq -cn --argjson backend "${BACKEND_PACKAGES}" --argjson e2e "${E2E_PACKAGES}" '$backend + $e2e | unique')" + export CONSUMED + "$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/resolve-specs.sh" + echo "in_repo_specs=${IN_REPO_SPECS}" >>"$GITHUB_OUTPUT" + + - name: npm registry auth + shell: bash + env: + NPM_TOKEN: ${{ inputs.npm_token }} + run: | + set -euo pipefail + umask 077 + { + echo "registry=https://cplace.jfrog.io/artifactory/api/npm/cplace-npm/" + echo "//cplace.jfrog.io/artifactory/api/npm/cplace-npm/:_authToken=${NPM_TOKEN}" + } >>"${HOME}/.npmrc" + chmod 600 "${HOME}/.npmrc" + + - name: Summary + shell: bash + env: + FE_REPO: ${{ inputs.fe_repo }} + BACKEND_REPO: ${{ steps.repo.outputs.backend_repo }} + BACKEND_BRANCH: ${{ steps.branches.outputs.backend_branch }} + BACKEND_SHA: ${{ steps.branches.outputs.backend_sha }} + E2E_BRANCH: ${{ steps.branches.outputs.e2e_branch }} + E2E_SHA: ${{ steps.branches.outputs.e2e_sha }} + BACKEND_BRANCH_OVERRIDE: ${{ steps.directives.outputs.BACKEND_BRANCH_OVERRIDE }} + E2E_BRANCH_OVERRIDE: ${{ steps.directives.outputs.E2E_BRANCH_OVERRIDE }} + SNAPSHOT_VERSION: ${{ inputs.snapshot_version }} + PACKAGES: ${{ inputs.packages }} + BACKEND_PACKAGES: ${{ steps.consumers.outputs.backend_packages }} + E2E_PACKAGES: ${{ steps.consumers.outputs.e2e_packages }} + RUN: ${{ steps.consumers.outputs.run }} + SPECS_CHANGED: ${{ steps.changed.outputs.specs_changed }} + IN_REPO_SPECS: ${{ inputs.in_repo_specs }} + SPECS: ${{ steps.specs.outputs.specs }} + run: | + { + echo '### Backend E2E' + echo + if [[ "${RUN}" != 'true' ]]; then + echo "Skipped: no package consumed by \`${BACKEND_REPO}\` or \`cplace-e2e\` was published, and \`e2e-tests/\` did not change." + echo + fi + echo '| | |' + echo '|---|---|' + echo "| FE repo | \`${FE_REPO}\` |" + echo "| Backend | \`${BACKEND_REPO}\` @ \`${BACKEND_BRANCH}\` \`${BACKEND_SHA}\`${BACKEND_BRANCH_OVERRIDE:+ (PR body)} |" + echo "| cplace-e2e | \`${E2E_BRANCH}\` \`${E2E_SHA}\`${E2E_BRANCH_OVERRIDE:+ (PR body)} |" + echo "| Snapshot version | \`${SNAPSHOT_VERSION:-none}\` |" + echo "| Published packages | \`${PACKAGES:-[]}\` |" + echo "| Consumed by the backend | \`${BACKEND_PACKAGES}\` |" + echo "| Consumed by cplace-e2e | \`${E2E_PACKAGES}\` |" + if [[ "${IN_REPO_SPECS}" == 'true' ]]; then + echo "| In-repo specs | \`e2e-tests/\` → \`cypress/e2e/${FE_REPO}/\`$([[ "${SPECS_CHANGED}" == true ]] && echo ', changed by this PR') |" + else + echo '| In-repo specs | none |' + fi + echo "| Spec filter | \`${SPECS}\` |" + echo + } >>"$GITHUB_STEP_SUMMARY" + + # Report only: drift never blocks the run. + - name: FE version drift + continue-on-error: true + shell: bash + env: + PACKAGES: ${{ inputs.packages }} + FE_BASE: ${{ steps.branches.outputs.base_branch }} + run: '"$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/report-drift.sh" "${RUNNER_TEMP}/backend-e2e/backend"' diff --git a/.github/workflows/fe-backend-e2e.yml b/.github/workflows/fe-backend-e2e.yml new file mode 100644 index 0000000..6469834 --- /dev/null +++ b/.github/workflows/fe-backend-e2e.yml @@ -0,0 +1,564 @@ +name: Frontend Backend E2E Workflow + +# Runs cplace-e2e Cypress specs against the backend a frontend PR ships into, +# built once with the npm snapshot versions the PR published pinned into its +# */assets. Callers pass the outputs of fe-pr-snapshot.yml. +# +# The backend steps reuse the cplace-gh-workflows composite actions, pinned to a +# release/2.0 commit (see the README to bump it); the refs inside those actions +# stay at @release/2.0. The build is shared with the test nodes as one +# artifact, so the nodes run no gradle. + +on: + workflow_call: + inputs: + GHA_REF: + description: 'The PR head branch' + type: string + required: true + GHA_BASE: + description: 'The PR base branch' + type: string + required: true + SNAPSHOT_VERSION: + description: 'The snapshot version fe-pr-snapshot.yml published' + type: string + required: true + SNAPSHOT_PACKAGES: + description: 'JSON array of the package names fe-pr-snapshot.yml published' + type: string + required: true + SNAPSHOT_INTEGRITIES: + description: >- + JSON object mapping each published package name to its npm integrity + (fe-pr-snapshot.yml's integrities output). A pinned package whose + installed integrity differs fails the run; an unlisted one is pinned + unchecked. + type: string + default: '{}' + E2E_SPECS: + description: 'Comma-separated cplace-e2e spec globs every run includes' + type: string + required: true + SPEC_MAP: + description: >- + JSON object {"@scope/pkg": "glob,glob"}: spec globs added to E2E_SPECS + when the backend or cplace-e2e consumes the published package. + type: string + default: '{}' + NODES: + description: 'Number of parallel test nodes' + type: string + default: '2' + ADVISORY: + description: >- + Report test and infrastructure failures as warnings instead of failing + the run. For backends whose own E2E suite is not green yet; build + failures still fail the run. + type: boolean + default: false + secrets: + ENV_CPLACE_ARTIFACTORY_ACTOR: + required: true + ENV_CPLACE_ARTIFACTORY_TOKEN: + required: true + SVA_ACTIONS_READ_PRODUCT_ID: + required: true + SVA_ACTIONS_READ_PRODUCT_KEY: + required: true + +# build and e2e run lifecycle scripts of PR-built packages; only report writes. +permissions: + contents: read + +# One run per PR: a new push cancels the run of the previous one. +concurrency: + group: fe-backend-e2e-${{ github.repository }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + resolve: + name: Resolve backend + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + pull-requests: read + outputs: + backend_repo: ${{ steps.resolve.outputs.backend_repo }} + repo_dir: ${{ steps.resolve.outputs.repo_dir }} + backend_branch: ${{ steps.resolve.outputs.backend_branch }} + backend_sha: ${{ steps.resolve.outputs.backend_sha }} + e2e_branch: ${{ steps.resolve.outputs.e2e_branch }} + e2e_sha: ${{ steps.resolve.outputs.e2e_sha }} + backend_packages: ${{ steps.resolve.outputs.backend_packages }} + e2e_packages: ${{ steps.resolve.outputs.e2e_packages }} + run: ${{ steps.resolve.outputs.run }} + node_indexes: ${{ steps.resolve.outputs.node_indexes }} + specs: ${{ steps.resolve.outputs.specs }} + in_repo_specs: ${{ steps.resolve.outputs.in_repo_specs }} + steps: + - name: Check out the FE repo's in-repo specs + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + ref: ${{ inputs.GHA_REF }} + path: fe-repo + sparse-checkout: e2e-tests + persist-credentials: false + + - name: Resolve backend and branches + id: resolve + uses: collaborationFactory/github-actions/.github/actions/backend-e2e-resolve@feature/fe-backend-e2e # FIXME remove before merging + with: + fe_repo: ${{ github.event.repository.name }} + in_repo_specs: ${{ hashFiles('fe-repo/e2e-tests/**') != '' }} + base_ref: ${{ inputs.GHA_BASE }} + head_ref: ${{ inputs.GHA_REF }} + pr_body: ${{ github.event.pull_request.body }} + snapshot_version: ${{ inputs.SNAPSHOT_VERSION }} + packages: ${{ inputs.SNAPSHOT_PACKAGES }} + e2e_specs: ${{ inputs.E2E_SPECS }} + spec_map: ${{ inputs.SPEC_MAP }} + nodes: ${{ inputs.NODES }} + app_id: ${{ secrets.SVA_ACTIONS_READ_PRODUCT_ID }} + app_key: ${{ secrets.SVA_ACTIONS_READ_PRODUCT_KEY }} + npm_token: ${{ secrets.ENV_CPLACE_ARTIFACTORY_TOKEN }} + github_token: ${{ github.token }} + + build: + name: Build backend + needs: resolve + if: ${{ needs.resolve.outputs.run == 'true' }} + runs-on: ${{ vars.E2E_MEDIUM_RUNNER || vars.MEDIUM_RUNNER || 'ubuntu-22.04' }} + timeout-minutes: 60 + env: + CPLACE_GENERAL_ARTIFACTPARENTREPOS: ${{ vars.CPLACE_GENERAL_ARTIFACTPARENTREPOS || 'false' }} + ENV_CPLACE_ARTIFACTORY_ACTOR: ${{ secrets.ENV_CPLACE_ARTIFACTORY_ACTOR }} + ENV_CPLACE_ARTIFACTORY_TOKEN: ${{ secrets.ENV_CPLACE_ARTIFACTORY_TOKEN }} + REPO_NAME: ${{ needs.resolve.outputs.repo_dir }} + REAL_REPO_NAME: ${{ needs.resolve.outputs.backend_repo }} + DO_UPLOAD: 'false' + CREATE_INITIAL_RELEASE: 'false' + steps: + - name: Token for the backend repository + id: token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ secrets.SVA_ACTIONS_READ_PRODUCT_ID }} + private-key: ${{ secrets.SVA_ACTIONS_READ_PRODUCT_KEY }} + owner: ${{ github.repository_owner }} + repositories: ${{ needs.resolve.outputs.backend_repo }} + + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + repository: collaborationFactory/${{ needs.resolve.outputs.backend_repo }} + ref: ${{ needs.resolve.outputs.backend_sha }} + path: ${{ env.REPO_NAME }} + token: ${{ steps.token.outputs.token }} + persist-credentials: false + fetch-depth: 1 + + - name: Load environment variables + uses: collaborationFactory/cplace-gh-workflows/.github/actions/load-env-variables@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + secrets: ${{ toJson(secrets) }} + vars: ${{ toJson(vars) }} + + - name: Prepare build environment + uses: collaborationFactory/cplace-gh-workflows/.github/actions/prepare-build-environment@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + + - name: Update git config for cloning parent repos + uses: collaborationFactory/cplace-gh-workflows/.github/actions/prepare-git-environment@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + app_id: ${{ secrets.SVA_ACTIONS_READ_PRODUCT_ID }} + app_key: ${{ secrets.SVA_ACTIONS_READ_PRODUCT_KEY }} + github_actor: ${{ github.actor }} + + - name: Fetch tags + uses: collaborationFactory/cplace-gh-workflows/.github/actions/fetch-tags@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + + - name: Prepare parent repos + if: ${{ env.CB_INCLUDE_PARENT_REPOS == 'true' }} + uses: collaborationFactory/cplace-gh-workflows/.github/actions/prepare-parent-repos@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + + - name: npm registry auth + shell: bash + run: | + set -euo pipefail + umask 077 + { + echo "registry=https://cplace.jfrog.io/artifactory/api/npm/cplace-npm/" + echo "//cplace.jfrog.io/artifactory/api/npm/cplace-npm/:_authToken=${ENV_CPLACE_ARTIFACTORY_TOKEN}" + } >>"${HOME}/.npmrc" + chmod 600 "${HOME}/.npmrc" + + - name: Rewrite npm registry URLs in package-lock.json + if: ${{ env.CB_ENABLE_REWRITE_NPM_REGISTRY_URLS == 'true' || ( env.CB_ENABLE_REWRITE_NPM_REGISTRY_URLS != 'false' && vars.CB_ENABLE_REWRITE_NPM_REGISTRY_URLS == 'true' ) }} + uses: collaborationFactory/cplace-gh-workflows/.github/actions/rewrite-package-lock-json-files@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + + # A run for changed e2e-tests/ only builds the backend's own pins. + - name: Pin the PR's snapshot packages + if: ${{ needs.resolve.outputs.backend_packages != '[]' }} + uses: collaborationFactory/github-actions/.github/actions/backend-e2e-pin@feature/fe-backend-e2e # FIXME remove before merging + with: + version: ${{ inputs.SNAPSHOT_VERSION }} + packages: ${{ needs.resolve.outputs.backend_packages }} + integrities: ${{ inputs.SNAPSHOT_INTEGRITIES }} + dirs: ${{ env.REPO_NAME }}/*/assets + + - name: Generate version_env file + uses: collaborationFactory/cplace-gh-workflows/.github/actions/patch-release-generate-version-env-file@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + create-initial-release: 'false' + trace-log: 'false' + build-current-version: ${{ env.CB_BUILD_CURRENT_VERSION }} + + - name: Build parent repos + if: ${{ env.CB_INCLUDE_PARENT_REPOS == 'true' }} + uses: collaborationFactory/cplace-gh-workflows/.github/actions/build-parent-repos@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + + - name: Build distribution + uses: collaborationFactory/cplace-gh-workflows/.github/actions/build-distribution@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + + - name: Build distribution file + working-directory: ${{ env.REPO_NAME }} + shell: bash + run: | + set -euo pipefail + _settings_file="settings.gradle" + if [ -f "settings-dist.gradle" ]; then + _settings_file="settings-dist.gradle" + fi + ./gradlew distZip -x copyResources -x gzAssets -PnoIncludes=true -c "${_settings_file}" --stacktrace + + # Same temporary workaround as cplace-gh-workflows reuseable-e2e-cypress.yml: + # the TestSetupHandler cannot start with the analytics plugin present. + - name: Remove cplace-analytics-plugin + shell: bash + run: | + set -euo pipefail + rc=0 + zip -d "${REPO_NAME}/build/distributions/software.zip" "software/cf.cplace.analytics/*" "software/WEB-INF/lib/cf.cplace.analytics*.jar" || rc=$? + # 12 is zip's "nothing to do": the distribution has no analytics plugin. + if ((rc != 0 && rc != 12)); then + echo "::error::Removing the analytics plugin from software.zip failed with exit code ${rc}" + exit "${rc}" + fi + + # A tarball, not upload-artifact's multi-path mode: that strips the paths' + # common prefix, which is `main/` for cplace and nothing for other backends. + - name: Bundle the build for the test nodes + shell: bash + run: | + set -euo pipefail + if [[ ! -d main/docker/e2e ]]; then + echo "::error::main/docker/e2e is missing; a backend other than cplace needs CB_INCLUDE_PARENT_REPOS=true so cplace is cloned into main/" + exit 1 + fi + # All of main/docker, not only e2e/: its compose file extends + # ../elasticsearch/elasticsearch-base.yml. + paths=( + "${REPO_NAME}/build/distributions/software.zip" + "${REPO_NAME}/.github/.build-env" + main/docker + ) + # Optional: the docker scripts only bind-mount it as cplace properties. + if [[ -d main/e2eConfigurations/config1 ]]; then + paths+=(main/e2eConfigurations/config1) + fi + tar -czf backend-e2e-bundle.tgz "${paths[@]}" + + - name: Upload the bundle + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: backend-e2e-bundle + path: backend-e2e-bundle.tgz + retention-days: 1 + if-no-files-found: error + + - name: Upload npm-logs + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: backend-e2e-npm-logs-build + path: ~/.npm/_logs + retention-days: 5 + if-no-files-found: ignore + + e2e: + name: E2E node ${{ matrix.node_index }} + needs: [resolve, build] + if: ${{ needs.resolve.outputs.run == 'true' }} + runs-on: ${{ vars.E2E_MEDIUM_RUNNER || vars.MEDIUM_RUNNER || 'ubuntu-22.04' }} + timeout-minutes: 60 + continue-on-error: ${{ inputs.ADVISORY }} + strategy: + fail-fast: false + matrix: + node_index: ${{ fromJSON(needs.resolve.outputs.node_indexes) }} + env: + ENV_CPLACE_ARTIFACTORY_ACTOR: ${{ secrets.ENV_CPLACE_ARTIFACTORY_ACTOR }} + ENV_CPLACE_ARTIFACTORY_TOKEN: ${{ secrets.ENV_CPLACE_ARTIFACTORY_TOKEN }} + REPO_NAME: ${{ needs.resolve.outputs.repo_dir }} + steps: + - name: Prepare e2e environment + uses: collaborationFactory/cplace-gh-workflows/.github/actions/prepare-e2e-environment@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + + - name: Download the bundle + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: backend-e2e-bundle + + - name: Unpack the bundle + shell: bash + run: tar -xzf backend-e2e-bundle.tgz && rm backend-e2e-bundle.tgz + + - name: Load environment variables + uses: collaborationFactory/cplace-gh-workflows/.github/actions/load-env-variables@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + secrets: ${{ toJson(secrets) }} + vars: ${{ toJson(vars) }} + + - name: Token for cplace-e2e + id: token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ secrets.SVA_ACTIONS_READ_PRODUCT_ID }} + private-key: ${{ secrets.SVA_ACTIONS_READ_PRODUCT_KEY }} + owner: ${{ github.repository_owner }} + repositories: cplace-e2e + + - name: Update git config + uses: collaborationFactory/cplace-gh-workflows/.github/actions/prepare-git-environment@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + github_actor: ${{ github.actor }} + github_token: ${{ steps.token.outputs.token }} + + - name: Clone cplace-e2e + uses: collaborationFactory/cplace-gh-workflows/.github/actions/clone-e2e-repo@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + repo_name: ${{ env.REPO_NAME }} + e2e_branch: ${{ needs.resolve.outputs.e2e_branch }} + + - name: Check out the resolved cplace-e2e commit + uses: collaborationFactory/github-actions/.github/actions/backend-e2e-checkout-commit@feature/fe-backend-e2e # FIXME remove before merging + with: + dir: ${{ env.REPO_NAME }}/${{ env.CB_E2E_REPO_NAME }} + sha: ${{ needs.resolve.outputs.e2e_sha }} + + - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version-file: ${{ env.REPO_NAME }}/${{ env.CB_E2E_REPO_NAME }}/package.json + + - name: npm registry auth + shell: bash + run: | + set -euo pipefail + umask 077 + { + echo "registry=https://cplace.jfrog.io/artifactory/api/npm/cplace-npm/" + echo "//cplace.jfrog.io/artifactory/api/npm/cplace-npm/:_authToken=${ENV_CPLACE_ARTIFACTORY_TOKEN}" + } >>"${HOME}/.npmrc" + chmod 600 "${HOME}/.npmrc" + + # After setup-node and the registry auth, which npm needs. + - name: Pin the PR's snapshot packages in cplace-e2e + if: ${{ needs.resolve.outputs.e2e_packages != '[]' }} + uses: collaborationFactory/github-actions/.github/actions/backend-e2e-pin@feature/fe-backend-e2e # FIXME remove before merging + with: + version: ${{ inputs.SNAPSHOT_VERSION }} + packages: ${{ needs.resolve.outputs.e2e_packages }} + integrities: ${{ inputs.SNAPSHOT_INTEGRITIES }} + dirs: ${{ env.REPO_NAME }}/${{ env.CB_E2E_REPO_NAME }} + + - name: Check out the FE repo's in-repo specs + if: ${{ needs.resolve.outputs.in_repo_specs == 'true' }} + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + ref: ${{ inputs.GHA_REF }} + path: fe-repo + sparse-checkout: e2e-tests + persist-credentials: false + + # The FE repo's e2e-tests/ run inside cplace-e2e, under cypress/e2e//; + # resolve already added that folder to the spec filter. + - name: Add the in-repo specs + if: ${{ needs.resolve.outputs.in_repo_specs == 'true' }} + shell: bash + env: + FE_REPO: ${{ github.event.repository.name }} + run: | + set -euo pipefail + target="${REPO_NAME}/${CB_E2E_REPO_NAME}/cypress/e2e/${FE_REPO}" + mkdir -p "${target}" + cp -R fe-repo/e2e-tests/. "${target}/" + + - name: Calculate node specs + id: calc-specs + uses: collaborationFactory/cplace-gh-workflows/.github/actions/calculate-e2e-specs-for-node@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + working_directory: ${{ env.REPO_NAME }}/${{ env.CB_E2E_REPO_NAME }} + node_index: ${{ matrix.node_index }} + nodes_total: ${{ inputs.NODES }} + e2e_specs: ${{ needs.resolve.outputs.specs }} + + # Uploads a results artifact for a node without specs, so report does not + # count it as a node that crashed. + - name: Mark a node without specs + if: ${{ steps.calc-specs.outputs.has_specs != 'true' }} + shell: bash + run: mkdir -p /tmp/test-results && touch /tmp/test-results/no-specs + + - name: Create and run cplace docker image + if: ${{ steps.calc-specs.outputs.has_specs == 'true' }} + uses: collaborationFactory/cplace-gh-workflows/.github/actions/create-and-run-cplace-docker@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + repo_name: ${{ env.REPO_NAME }} + java_version: '21' + cplace_port: ${{ env.CB_E2E_CPLACE_PORT }} + cplace_base_url: ${{ env.CB_E2E_CPLACE_BASE_URL }} + docker_env_variables: ${{ env.CB_E2E_DOCKER_ENV_VARIABLES }} + + - name: Wait for cplace startup + if: ${{ steps.calc-specs.outputs.has_specs == 'true' }} + uses: collaborationFactory/cplace-gh-workflows/.github/actions/wait-for-cplace-startup@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + repo_name: ${{ env.REPO_NAME }} + cplace_url: ${{ env.CB_E2E_CPLACE_BASE_URL }} + workflow_e2e_wait_timeout: ${{ env.CB_E2E_WORKFLOW_WAIT_TIMEOUT }} + + - name: Run E2E cypress test suite + if: ${{ steps.calc-specs.outputs.has_specs == 'true' }} + uses: collaborationFactory/cplace-gh-workflows/.github/actions/run-e2e-test-suite-with-cypress@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + repo_name: ${{ env.REPO_NAME }} + base_url: ${{ env.CB_E2E_CPLACE_BASE_URL }} + workflow_e2e_specs: ${{ needs.resolve.outputs.specs }} + workflow_e2e_browser: ${{ env.CB_E2E_WORKFLOW_BROWSER }} + node_index: ${{ matrix.node_index }} + nodes_total: ${{ inputs.NODES }} + specs_to_run: ${{ steps.calc-specs.outputs.specs }} + + - name: Copy e2e cypress results + if: ${{ always() && steps.calc-specs.outputs.has_specs == 'true' }} + uses: collaborationFactory/cplace-gh-workflows/.github/actions/copy-e2e-cypress-results@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + repo_name: ${{ env.REPO_NAME }} + + - name: Copy cplace logs + if: ${{ always() && steps.calc-specs.outputs.has_specs == 'true' }} + uses: collaborationFactory/cplace-gh-workflows/.github/actions/copy-cplace-logs@f621b75326b963a5c4ffda6ff66b8ceba86259f6 # release/2.0 + with: + repo_name: ${{ env.REPO_NAME }} + + - name: Upload test results + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: backend-e2e-results-${{ matrix.node_index }} + path: /tmp/test-results + retention-days: 5 + include-hidden-files: true + if-no-files-found: ignore + + - name: Upload cplace logs + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: backend-e2e-cplace-logs-${{ matrix.node_index }} + path: /tmp/cplace-logs + retention-days: 5 + if-no-files-found: ignore + + report: + name: Report + needs: [resolve, build, e2e] + if: ${{ always() && needs.resolve.outputs.run == 'true' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + checks: write + pull-requests: write + steps: + # One subdir per node that uploaded results; the report counts them. + - name: Download test results + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: backend-e2e-results-* + path: test-results + + - name: Publish test results + uses: EnricoMi/publish-unit-test-result-action/linux@c950f6fb443cb5af20a377fd0dfaa78838901040 # v2.23.0 + with: + large_files: true + check_name: 'Test Results Backend E2E' + files: test-results/*/junit/**/*.xml + json_file: backend-e2e-results.json + json_test_case_results: true + fail_on: ${{ inputs.ADVISORY && 'nothing' || 'test failures' }} + + - name: Build the report + id: report + if: ${{ always() }} + uses: collaborationFactory/github-actions/.github/actions/backend-e2e-report@feature/fe-backend-e2e # FIXME remove before merging + with: + results_json: backend-e2e-results.json + body_file: backend-e2e-comment.md + results_dir: test-results + nodes: ${{ inputs.NODES }} + advisory: ${{ inputs.ADVISORY }} + build_result: ${{ needs.build.result }} + e2e_result: ${{ needs.e2e.result }} + backend_repo: ${{ needs.resolve.outputs.backend_repo }} + backend_branch: ${{ needs.resolve.outputs.backend_branch }} + backend_sha: ${{ needs.resolve.outputs.backend_sha }} + e2e_branch: ${{ needs.resolve.outputs.e2e_branch }} + e2e_sha: ${{ needs.resolve.outputs.e2e_sha }} + snapshot_version: ${{ inputs.SNAPSHOT_VERSION }} + backend_packages: ${{ needs.resolve.outputs.backend_packages }} + e2e_packages: ${{ needs.resolve.outputs.e2e_packages }} + + # One comment per run; earlier ones from this workflow are minimized as outdated. + - name: Comment on the PR + if: ${{ always() && steps.report.outcome == 'success' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const fs = require('fs'); + const MARKER = ''; + const body = fs.readFileSync('backend-e2e-comment.md', 'utf8'); + + const issue = { owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number }; + const { data: created } = await github.rest.issues.createComment({ ...issue, body }); + + const comments = await github.paginate(github.rest.issues.listComments, { ...issue, per_page: 100 }); + const outdated = comments.filter( + (comment) => comment.id !== created.id && comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(MARKER), + ); + for (const comment of outdated) { + await github.graphql('mutation($id: ID!) { minimizeComment(input: {subjectId: $id, classifier: OUTDATED}) { clientMutationId } }', { + id: comment.node_id, + }); + } + + # needs.e2e.result is not relied on: in advisory mode continue-on-error may + # report a failed node as 'success'. The outcome counts results and nodes. + - name: Fail unless the run passed + if: ${{ always() && !inputs.ADVISORY && steps.report.outputs.outcome != 'passed' }} + shell: bash + env: + OUTCOME: ${{ steps.report.outputs.outcome }} + MESSAGE: ${{ steps.report.outputs.message }} + run: | + echo "::error::Backend E2E ${OUTCOME:-report failed}: ${MESSAGE:-the report could not be built, see its step}" + exit 1 + + - name: Warn about the outcome (advisory) + if: ${{ always() && inputs.ADVISORY && steps.report.outputs.outcome != 'passed' }} + shell: bash + env: + OUTCOME: ${{ steps.report.outputs.outcome }} + MESSAGE: ${{ steps.report.outputs.message }} + run: | + echo "::warning::Advisory mode, backend E2E ${OUTCOME:-report failed}: ${MESSAGE:-the report could not be built, see its step} Failures that also fail on the backend's own nightly are not caused by this PR." diff --git a/.github/workflows/fe-pr-snapshot.yml b/.github/workflows/fe-pr-snapshot.yml index f839237..68831c9 100644 --- a/.github/workflows/fe-pr-snapshot.yml +++ b/.github/workflows/fe-pr-snapshot.yml @@ -6,6 +6,20 @@ on: GHA_BASE: type: string required: true + REQUIRE_SNAPSHOT_LABEL: + description: 'Publish only when the PR carries the snapshot label' + type: boolean + default: true + outputs: + version: + description: 'The published snapshot version, empty when the job was skipped or the tip is a branch-off commit' + value: ${{ jobs.publish-pr-snapshot.outputs.version }} + packages: + description: 'JSON array of the published package names; [] when no project was publishable, empty when the job was skipped or the tip is a branch-off commit' + value: ${{ jobs.publish-pr-snapshot.outputs.packages }} + integrities: + description: 'JSON object mapping each published package name to its npm integrity; {} when nothing was published, empty when the job was skipped or the tip is a branch-off commit' + value: ${{ jobs.publish-pr-snapshot.outputs.integrities }} secrets: JFROG_BASE64_TOKEN: required: true @@ -18,8 +32,13 @@ on: jobs: publish-pr-snapshot: - if: contains(github.event.pull_request.labels.*.name, 'snapshot') + if: ${{ !inputs.REQUIRE_SNAPSHOT_LABEL || contains(github.event.pull_request.labels.*.name, 'snapshot') }} runs-on: ubuntu-latest + timeout-minutes: 60 + outputs: + version: ${{ steps.artifacts.outputs.version }} + packages: ${{ steps.artifacts.outputs.packages }} + integrities: ${{ steps.artifacts.outputs.integrities }} env: NODE_OPTIONS: --max-old-space-size=4096 steps: @@ -45,12 +64,12 @@ jobs: if git fetch origin "$BASE_BRANCH:$BASE_BRANCH" 2>/dev/null; then echo "✅ Base branch fetched successfully" - echo "VALIDATED_BASE=$BASE_BRANCH" >> $GITHUB_ENV + echo "VALIDATED_BASE=$BASE_BRANCH" >> "$GITHUB_ENV" else echo "❌ Base branch '$BASE_BRANCH' not found, using default" DEFAULT_BRANCH=$(git remote show origin | grep 'HEAD branch' | cut -d' ' -f5) git fetch origin "$DEFAULT_BRANCH:$DEFAULT_BRANCH" - echo "VALIDATED_BASE=$DEFAULT_BRANCH" >> $GITHUB_ENV + echo "VALIDATED_BASE=$DEFAULT_BRANCH" >> "$GITHUB_ENV" fi - name: Use .npmrc @@ -63,7 +82,8 @@ jobs: run: npm ci - name: Build and Push to Jfrog NPM Registry - uses: collaborationFactory/github-actions/.github/actions/artifacts@master + id: artifacts + uses: collaborationFactory/github-actions/.github/actions/artifacts@feature/fe-backend-e2e # FIXME remove before merging env: JFROG_BASE64_TOKEN: ${{ secrets.JFROG_BASE64_TOKEN }} JFROG_URL: ${{ secrets.JFROG_URL }} diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 5be329c..15c6927 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -55,7 +55,10 @@ jobs: sudo apt-get install -y bats shellcheck - name: shellcheck - run: shellcheck tools/scripts/lockfile/*.sh tools/scripts/lockfile/test-helper.bash + run: >- + shellcheck + tools/scripts/lockfile/*.sh tools/scripts/lockfile/test-helper.bash + tools/scripts/backend-e2e/*.sh tools/scripts/backend-e2e/test-helper.bash - name: bats - run: bats tools/scripts/lockfile/ + run: bats tools/scripts/lockfile/ tools/scripts/backend-e2e/ diff --git a/README.md b/README.md index 671c78d..86d6a5b 100644 --- a/README.md +++ b/README.md @@ -155,3 +155,35 @@ publish distinct snapshot versions; the `snapshot` dist-tag ends up on the run t Created with `GITHUB_TOKEN`, like the tag. The generated notes start at the previous tag of the same release line, and "Latest" is set only for the highest `version/*` tag. + +## Backend E2E for FE PRs + +`.github/workflows/fe-backend-e2e.yml` builds the backend a frontend PR ships into, with the PR's npm snapshots pinned, +and runs `cplace-e2e` specs against it. Callers pass the outputs of `fe-pr-snapshot.yml` (`version`, `packages`, +`integrities`). + +### Choosing the backend and cplace-e2e branch + +By default the run uses a backend or `cplace-e2e` branch named like the PR head, and otherwise the counterpart of the +PR base. A line of its own in the PR description chooses a branch explicitly: + +```text +backend-branch: feature/PFM-ISSUE-12345-my-change +cplace-e2e-branch: feature/PFM-ISSUE-12345-my-specs +``` + +A named branch that does not exist fails the run. Editing the description does not start a run: push, or re-run the +workflow. Each branch is resolved to a commit once, and every job of the run uses that commit. + +### cplace-gh-workflows pin + +The backend steps use the `cplace-gh-workflows` composite actions at a `release/2.0` commit, not at the branch. To +bump it, replace the SHA on every `collaborationFactory/cplace-gh-workflows/.github/actions/*@ # release/2.0` +line of `fe-backend-e2e.yml` with the output of: + +```bash +gh api repos/collaborationFactory/cplace-gh-workflows/commits/release/2.0 --jq .sha +``` + +The actions call each other at `@release/2.0`, so those nested refs stay mutable: a breaking change there can still +show up as a `backend-e2e` failure in FE PRs. diff --git a/specs/2026-11-19_fe-pr-e2e-reusable-workflow/design.md b/specs/2026-11-19_fe-pr-e2e-reusable-workflow/design.md new file mode 100644 index 0000000..53c7538 --- /dev/null +++ b/specs/2026-11-19_fe-pr-e2e-reusable-workflow/design.md @@ -0,0 +1,270 @@ +# Real-Backend E2E on Frontend PRs - Design Approach + +## Overview + +A new reusable workflow in `github-actions`, called from the `pull_request.yaml` of cplace-fe and cplace-paw-fe, that builds the matching backend with the PR's npm snapshot versions pinned in, boots it in docker, runs Cypress specs from `cplace-e2e` (and optionally from the FE repo) against it, and fails the PR on any failing test. It is a required check on every PR. + +## Problem Statement + +Frontend PR checks only run Cypress against Storybook with mocked data. Whether a change works inside a real cplace is discovered later — by someone writing specs in a separate `cplace-e2e` PR, or after merge. The cause: the backend consumes the frontend as exact-pinned npm packages (`/assets/package.json` + lock), while the only "run E2E on a PR" tooling (`/run-e2e-tests` orchestrator) can only swap backend git branches in `parent-repos.json`. FE repos are not entries there, so a FE PR run silently tests the base (`matched=false`). No pipeline step overrides `@cplace-*` npm versions. See [Research](./research.md). + +### Requirements +- Run on every cplace-fe and cplace-paw-fe PR as a required check (gated through `pr-checks`). +- Resolve the backend repo by naming pattern (`cplace-fe` → `cplace`, `-fe` → ``). +- Pin exactly the packages the PR published as snapshots into the backend (and into cloned `cplace-e2e`) before building. +- Build and boot the backend in docker (cplace + Elasticsearch) and run Cypress against it. +- Support spec sources: `cplace-e2e` (matching branch), an in-repo folder, an explicit spec filter, and the full suite. +- Report results on the PR and fail the job on any failing test. + +### Constraints +- FE CI lives in `github-actions@master` (nx/npm, TS scripts); the backend E2E engine lives in `cplace-gh-workflows@release/2.0` (gradle, bash, env files). Merges to either are live for all consumers immediately. +- Snapshot publishing today is label-gated, runs in a separate workflow, is affected-only, and exposes no outputs; republish briefly unpublishes the version. +- No consumable prebuilt E2E image exists; the FB pull-image mode is single-container without Elasticsearch. +- The docker contract must be kept: container `main`, port 8083, token `hIF9Z97RZiYm`, compose project `cplace-e2e`. +- Must not rely on the X.Y.999 feature-branch version rewrite (broke IAP#536 with `notarget`). +- Every action SHA-pinned. + +## Design Decisions Summary + +1. **Standalone reusable workflow in github-actions**: a new workflow called like `code-quality`, running as an ordinary synchronous job in the FE PR pipeline. + - Composes backend building blocks (build stages, docker compose, readiness wait, spec calculation, cypress-repeat, JUnit publish) from `cplace-gh-workflows@release/2.0` cross-repo rather than reimplementing them. + - New logic is limited to orchestration: resolve repos/branches, apply snapshot pins, copy in-repo specs, report. +2. **Snapshot publishing moves into the PR pipeline, unconditionally, with outputs**: `fe-pr-snapshot.yml` is called as a job inside `pull_request.yaml` on every PR, without the `snapshot` label gate. + - The artifacts action / `fe-pr-snapshot.yml` expose `version` and the published `packages` list as outputs. + - The backend-e2e job `needs:` the snapshot job — ordered, race-free handoff. +3. **Backend built from source, once per run, shared across nodes**: prebuilt image + FE overlay is a follow-up, not part of this design. + - Snapshot pins applied with the nightly upmerge recipe (`npm i @ --save-exact --legacy-peer-deps` in each `*/assets`, lock regenerated), only for packages the PR published. + - Inserted after parent repos are prepared and before parent/distribution build; the X.Y.999 rewrite is not used. + - The built distribution is reused by all test nodes instead of each node rebuilding `distZip`. +4. **Branch resolution: same-named branch, else mapped base**: applied independently to the backend repo and to `cplace-e2e`. + - Mapping: FE `main`/`master` → `master`; `release/X.Y` → `release/X.Y`; `release/X.Y-beta` → `release/X.Y` if present, else `master`. + - Follows PFM-ISSUE-34932 rules (exact `refs/heads/` match, retry with backoff, derived-missing → warning + fallback); the resolved branches are shown in the report. +5. **Single runtime consumer backend per FE repo**: cplace-fe PRs build only `cplace`; cplace-paw-fe PRs build `cplace-paw`. + - cplace-fe changes are not tested through paw-level builds. +6. **cplace-e2e as test harness, with SDK pins bumped**: `cplace-e2e` is cloned as the runner (config, support, reporters). + - Packages the PR published that `cplace-e2e` pins (`cf-e2e-testing-sdk`, `*-e2e` packages, paw-fe SDKs) are bumped in the clone with the same recipe before Cypress install. +7. **In-repo specs via an `e2e-tests/` folder**: if the FE repo has `e2e-tests/`, the new workflow copies it into the cloned `cplace-e2e` under `cypress/e2e//` before spec calculation and includes it in the spec filter. + - Specs are written against `cplace-e2e` support and its Cypress version. + - The backend's `move_own_e2e_tests.sh` is not used or changed. +8. **Small default scope, wider on demand**: the caller passes a per-product default spec filter and a small node count; only the main `e2e` suite runs (no feature-toggle, no Jira suite). + - Inputs allow a wider filter, more nodes, or the full suite. + - `timeout-minutes` on every job; concurrency group per workflow + PR number with cancel-in-progress. +9. **Skip with success when nothing relevant is published**: if the PR published no package consumed by the backend or `cplace-e2e`, the job succeeds with a summary saying so. +10. **Reporting via JUnit check and marker comment**: JUnit results published as a check; a PR comment upserted with a marker, older comments minimized; the job fails on any failed test. + Amended 2026-11-23 (plan Phase 11): advisory mode (`ADVISORY: true`) suspends "the job fails on any failed test" until the exit criteria of the Phase 10 RCA are met. The check and the comment still report every failure, and a backend build failure still fails the job. + +This means: +- Every cplace-fe and cplace-paw-fe PR gets real-backend verification as a normal blocking job, with no separate PR in another repo required. +- Paired backend + frontend + spec changes can be verified together by using the same branch name across repos. +- New specs can live in the FE PR itself (`e2e-tests/`) or in a paired `cplace-e2e` branch. +- Changes to the E2E SDK packages are verified against real specs before merge, not first in the nightly upmerge. +- Docs/Storybook-only PRs pay no E2E cost. + +Major trade-offs we're accepting: +1. Build time floor: ~30 min backend build on every relevant PR run, in exchange for a proven path that is not blocked on a missing image pipeline and an unproven overlay spike. +2. Registry volume: a JFrog snapshot publish on every PR push, in exchange for an ordered, race-free handoff with an explicit package list. +3. Coverage vs cost: the default scope misses regressions outside the product's default folder, in exchange for bounded per-PR cost and feedback time; the full suite remains available on demand. +4. Cross-ecosystem coupling: the FE workflow depends on `cplace-gh-workflows@release/2.0` internals and FE repos need backend secrets/App access, in exchange for not duplicating the backend E2E engine. +5. Authoring friction: in-repo specs cannot be linted/type-checked in the FE repo (they depend on `cplace-e2e` support and Cypress 13), and the folder convention may shift when the owning-repos design settles. +6. Branch fragility: a stale same-named feature backend branch can fail a FE PR for backend reasons, in exchange for paired-change testing. + +What we're NOT doing (out of scope): +- Prebuilt-image mode with FE overlay (needs a compose-compatible nightly E2E image and an overlay feasibility spike) — follow-up. +- Changes to the `/run-e2e-tests` orchestrator, IAP, or the backend PR E2E flow. +- Fixing or reusing the backend's `move_own_e2e_tests.sh`. +- Wiring other FE repos (project-planning, resource-management, forms-wizard), though the naming rule would allow it later. +- Paw-level testing of cplace-fe changes (bumping parent `../main` assets in a cplace-paw build). +- Automatic "affected spec" selection from the FE change set. +- Feature-toggle and Jira suites in the default run. +- Changes to the existing Storybook E2E jobs. + +Deferred to planning: +- Mechanism for sharing the built distribution across nodes (artifact vs cache) — implementation detail of decision 3. +- Exact default spec filter per product and default node count — tuning values, not shape. +- Which GitHub App/token posts the PR comment from FE repos (`SVA_ACTIONS_WRITE_PRODUCT_FE`?) and which App clones backend + `cplace-e2e` — wiring, given the read-App installation constraint. +- Whether the label-based `fe-pr-snapshot` caller is retired or kept for manual use — caller housekeeping. +- Exact composite actions/scripts reused from `cplace-gh-workflows` vs small local copies where no composite action exists — implementation detail. +- Input names and the snapshot output format — interface detail. + +Success criteria: +- A cplace-fe PR that breaks a real-backend flow covered by the default filter fails the `pr-checks` gate, and the PR comment links the failing specs. +- The report shows the resolved backend and `cplace-e2e` branches and the exact snapshot versions pinned; the built backend's `assets/package-lock.json` contains those versions. +- A docs-only PR passes the check without building the backend. +- A typical PR run finishes within the configured `timeout-minutes`, and a new push cancels the previous run for the same PR. + +## Design Decisions - Details + +### Workflow Home + +**Chosen Approach:** Standalone reusable workflow in `github-actions`, composing backend building blocks cross-repo. + +**Rationale:** Matches the established thin-caller / fat-reusable FE pattern, and it is the only option where the result is an ordinary job status that `pr-checks` can gate on with `needs:`. + +**Alternatives Considered:** +- **New FE mode in the `/run-e2e-tests` orchestrator** (`npm_overrides` input, IAP dispatch): Rejected because it is asynchronous (a required check would need a status bridge), inherits the 8-node IAP footprint, creates test-branch/test-PR churn per FE PR, and goes through the version rewrite that broke IAP#536. +- **Call backend `e2e-cypress.yml` directly with a new pin input**: Rejected because `build.yml` loads env files from the calling repo's `.github/`, which FE repos lack; making it work needs a refactor of a shared backend workflow that is live for all backend consumers. + +**Implications:** +- FE repos need `ENV_CPLACE_ARTIFACTORY_*`, an App installed on the backend repo and `cplace-e2e`, and access to Ubicloud runner vars. +- Drift in `cplace-gh-workflows@release/2.0` can break the FE workflow. + +--- + +### Snapshot Availability + +**Chosen Approach:** Unconditional snapshot job inside `pull_request.yaml`, exposing `version` and `packages` outputs. + +**Rationale:** The only option giving an ordered, race-free handoff with an explicit list of published packages, which the pin step needs to avoid `notarget`. + +**Alternatives Considered:** +- **Keep the separate label workflow and poll registry/comment**: Rejected because the label means not every PR is covered, polling races with the unpublish/republish window, and parsing comment text is fragile. +- **No publish; pack FE build locally and install tarballs**: Rejected because it deviates from registry-based pins, rewrites lock `resolved`/`integrity` to file paths inside the gradle/cplace-asc install (unverified it tolerates this), and needs the same trick for `cplace-e2e`. + +**Implications:** +- Snapshot triggers must include `opened`; every push publishes to `cplace-npm-local`. +- The artifacts action writes outputs on PR snapshots (today only on release). + +--- + +### Backend Production + +**Chosen Approach:** Build from source once per run; share the distribution across nodes; apply snapshot pins with the upmerge bump recipe. + +**Rationale:** The only path not blocked on a missing image pipeline and an unproven overlay spike; all pieces are proven in the backend E2E engine. + +**Alternatives Considered:** +- **Both modes now, prebuilt default** (the research-phase decision): Set aside because no compose-compatible prebuilt E2E image exists and overlay feasibility is unknown; it remains the follow-up for faster runs. +- **Build from source with a reserved `backend_mode` input**: Rejected as a dead input until prebuilt mode exists. + +**Implications:** +- Only packages in the snapshot job's `packages` output are bumped. +- The per-node `distZip` rebuild seen in the backend engine must be avoided. + +--- + +### Branch Resolution + +**Chosen Approach:** Same-named branch if it exists, else mapped base — independently for the backend repo and `cplace-e2e`. + +**Rationale:** Enables paired BE+FE and FE+spec changes in one PR, with a base fallback for the common case. + +**Alternatives Considered:** +- **Always mapped base**: Rejected because paired changes and new specs in `cplace-e2e` could not be verified until one side merges. + +**Implications:** +- FE repos have no gradle project, so `cplace-e2e` branch resolution is done by the new workflow, not `determine_e2e_branch.sh`. +- The resolved branches appear in the report so a backend-caused failure is recognisable. + +--- + +### Test Scope and Cost + +**Chosen Approach:** Small default (per-product filter from the caller, ~2 nodes, main suite only), wider via inputs; timeouts and per-PR cancel-in-progress concurrency. + +**Rationale:** The only way a required check on every PR stays affordable; the full suite stays reachable. + +**Alternatives Considered:** +- **Full `e2e` suite, IAP-sized**: Rejected because ~45–60 min and ~4 vCPU-h per push would slow every merge. +- **Explicit filter only, else skip**: Rejected because the check would pass by default without testing anything. + +**Implications:** +- The concurrency group must include the PR number (a `workflow+ref` group silently cancelled dispatches in PFM-ISSUE-34615). + +--- + +### Nothing Published + +**Chosen Approach:** Skip the run and succeed with a summary when no package consumed by the backend or `cplace-e2e` was published. + +**Rationale:** Avoids a full run that only re-verifies the base. + +**Alternatives Considered:** +- **Run against base pins anyway**: Rejected as cost without signal. + +**Implications:** +- Correctness relies on nx affected detection in the snapshot job. + +--- + +### cplace-e2e SDK Pins + +**Chosen Approach:** Bump published packages that `cplace-e2e` pins in the cloned `cplace-e2e` before Cypress install. + +**Rationale:** SDK regressions show on the FE PR instead of in the nightly upmerge. + +**Alternatives Considered:** +- **Keep base pins**: Rejected because SDK changes would be tested with the old SDK. + +--- + +### In-Repo Specs + +**Chosen Approach:** `e2e-tests/` folder in the FE repo, copied by the new workflow into `cplace-e2e/cypress/e2e//` before spec calculation. + +**Rationale:** Uses the folder name that both the backend hook default and the `cplace-e2e` owning-repos research already use, without touching the backend's shared script. + +**Alternatives Considered:** +- **Fix and reuse `move_own_e2e_tests.sh`**: Rejected because it changes a shared backend script (ordering + `mv` nesting) live for all backend consumers and deepens the cross-repo coupling. +- **Defer in-repo specs**: Rejected because the research phase requires in-repo specs to be supported. + +**Implications:** +- In-repo specs depend on `cplace-e2e` support paths and Cypress 13; they are validated only during the E2E run. + +--- + +## Overall Architecture + +The FE PR pipeline gains two jobs: an unconditional snapshot publish that outputs the version and published packages, and a backend-e2e job that depends on it and feeds `pr-checks`. The backend-e2e reusable workflow resolves the backend repo and branches, builds the backend once with the snapshot pins applied, then runs a small matrix of nodes that each boot the docker compose stack from the shared build, run their share of the selected specs in the cloned `cplace-e2e` harness, and publish results. + +``` +FE repo pull_request.yaml + install-deps ─┬─ build / code-quality / storybook e2e (unchanged) + ├─ snapshot (unconditional) ── outputs: version, packages + └─ backend-e2e (needs snapshot) ──► pr-checks + +backend-e2e (github-actions reusable) + resolve ─► build backend once (pins applied) ─► N nodes: clone cplace-e2e, + bump SDK pins, copy e2e-tests/, compose up, wait, cypress-repeat ─► report +``` + +### Key Components +1. **Snapshot job**: publishes affected FE packages for every PR and outputs `version` + `packages`. +2. **Resolve step**: maps FE repo → backend repo, resolves backend and `cplace-e2e` branches, decides skip vs run, builds the spec filter. +3. **Backend build with pin step**: clones backend + parents, bumps published packages in `*/assets`, builds the distribution once. +4. **Test nodes**: harness setup (clone, SDK bump, in-repo spec copy), docker compose boot, readiness wait, Cypress run. +5. **Reporter**: JUnit check, marker PR comment, job status. + +### Data Flow +PR push → snapshot job publishes to JFrog `cplace-npm-local` and outputs the package list → backend build installs those exact versions via the backend registry config → distribution shared to nodes → nodes run specs against `localhost:8083/intern/tricia/` → JUnit/mochawesome results aggregated into check + comment. + +### Integration Points +- `github-actions`: `fe-pr-snapshot.yml` and the artifacts action (new outputs), new reusable workflow. +- FE callers: `cplace-fe/.github/workflows/pull_request.yaml`, `cplace-paw-fe` `fe-pr.yml` (new jobs, `pr-checks` needs). +- `cplace-gh-workflows@release/2.0`: build stages, `setup_npmrc.sh`, docker compose scripts, `wait_for_cplace_startup.sh`, `calculate_e2e_specs_for_node.sh`, `run_e2e_cypress_test_suite.sh`, JUnit publish. +- Backend repos `cplace` / `cplace-paw`: `*/assets/package.json` + lock, `docker/e2e` compose setup. +- `cplace-e2e`: runner, support, reporters, SDK pins. + +## Known Risks + +1. **Secrets and App access in FE repos**: paw-fe may lack artifactory/App secrets; the FE read App is not installed on `cplace-e2e` (non-installed repo in `repositories:` fails the mint with 422). - Mitigation: verify and provision before rollout; plan the token per purpose. +2. **Registry visibility**: unverified whether the backend's virtual `cplace-npm` serves fresh `cplace-npm-local` PR snapshots immediately. - Mitigation: verify early in planning; retry install if needed. +3. **gradle/cplace-asc install semantics**: unverified whether assets install uses `npm ci` (honours lock) or `npm install`. - Mitigation: verify in a first trial run that the built assets contain the pinned versions. +4. **Upstream drift**: changes in `cplace-gh-workflows@release/2.0` can break the FE workflow. - Mitigation: pin to a ref/SHA where possible; stage changes with branch-pinned test consumers. +5. **Runner availability**: Ubicloud runner vars may not be available to FE repos. - Mitigation: confirm org-level vars; fall back to a defined runner label. +6. **Default scope tuning**: a too-wide default makes runs slow; a too-narrow one gives false confidence. - Mitigation: start narrow, measure, adjust inputs. + +## Next Steps + +1. Review this design document +2. Refine if needed based on feedback +3. Proceed to implementation planning: `/spec-driven-development:create_plan specs/2026-11-19_fe-pr-e2e-reusable-workflow/design.md` + +## References + +- Original ticket: none (no PFM ticket) +- Related research: [Research](./research.md) +- `cplace-e2e/specs/2026-11-19_e2e-tests-in-owning-repos/research.md` — `e2e-tests/` convention, owning-repos direction +- `main/specs/2026-09-28_PFM-ISSUE-28989_adapt-e2e-docker-setup/` — docker compose contract +- `cplace-gh-workflows/specs/2026-09-28_PFM-ISSUE-34932_e2e-branch-remote-unreachable/` — branch resolution rules +- `cplace-fe/specs/2026-10-15_PFM-ISSUE-34281_github-app-cross-repo-clone/` — FE App token pattern +- Similar features: `cplace-gh-workflows` `upmerge_and_bump_releases.sh` (bump recipe), `integration-e2e-orchestrator.yml` (marker reporting) diff --git a/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md b/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md new file mode 100644 index 0000000..98a2eae --- /dev/null +++ b/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md @@ -0,0 +1,1351 @@ +# Real-Backend E2E on Frontend PRs Implementation Plan + +## Overview + +Add a reusable workflow `.github/workflows/fe-backend-e2e.yml` to `github-actions`. It is called from the PR pipelines of cplace-fe and +cplace-paw-fe, and does the following: + +- builds the matching backend (`cplace` or `cplace-paw`) once, with the npm snapshot versions the PR published pinned into its `*/assets`; +- boots the backend in docker on a small matrix of nodes; +- runs Cypress specs from a cloned `cplace-e2e` (plus specs from the FE repo's `e2e-tests/` folder); +- fails the PR on any failing test. + +The snapshot publishing that feeds it moves into the PR pipeline and exposes its result as outputs. See [Design](./design.md). + +## Current State Analysis + +- **No snapshot outputs.** The PR snapshot publish (`.github/workflows/fe-pr-snapshot.yml`) is label-gated at line 21. It runs in a + separate caller workflow and exposes no outputs. The artifacts step (lines 65-73) has no `id:`. `Utils.writeOutput` is called only on the + release path (`tools/scripts/artifacts/artifacts-handler.ts`, `tagAndPublishRelease`). +- **Backend E2E building blocks exist only in `cplace-gh-workflows@release/2.0`, as composite actions.** Each action resolves its scripts + from its own checkout (`$GITHUB_ACTION_PATH/../../../src/scripts`), so other repos can call them. They need the following: + - `env.REPO_NAME` naming a checkout directory under `$GITHUB_WORKSPACE`. + - `load-env-variables` to read `${REPO_NAME}/.github/.build-env`. Once we check out the backend repo ourselves, that is the backend's + own env file. + - `CB_*` variables from that file. The `CB_E2E_*` values, `CB_INCLUDE_PARENT_REPOS` and `CB_E2E_REPO_NAME=cplace-e2e` all come from + there. +- **Per-node layout expected by `create_and_run_cplace_docker.sh` (release/2.0):** `$REPO_NAME/build/distributions/software.zip`, + `$GITHUB_WORKSPACE/main/docker/e2e/` (compose path when `docker-compose.yml` exists), and + `$GITHUB_WORKSPACE/main/e2eConfigurations/config1/properties/`. The backend engine rebuilds `distZip` on every node + (`reuseable-e2e-cypress.yml`, "Build distribution file"). +- **`clone-e2e-repo` fails when given an explicit `e2e_branch` that does not exist.** Without one, it derives the branch from + `./gradlew properties`. +- **`prepare-git-environment` takes either a pre-minted `github_token`, or `app_id`/`app_key`.** With the App, it reads + `parent-repos.json` and `REAL_REPO_NAME`. +- **Both FE `pr-checks` aggregators fail on any `needs` result other than `success`, including `skipped`** + (`cplace-fe: .github/workflows/pull_request.yaml:118-134`, `cplace-paw-fe: .github/workflows/fe-pr.yml:49-65`). +- **Secrets.** cplace-paw-fe passes no App secrets and no `ENV_CPLACE_ARTIFACTORY_*`. cplace-fe has `ENV_CPLACE_ARTIFACTORY_*` (used by + the devkit test template) but not the product read App. +- **github-actions self-CI** (`.github/workflows/pr-checks.yml`) runs shellcheck and bats on `tools/scripts/lockfile/` only. It does not + run jest, and it forbids adding npm devDependencies. +- **Neither FE repo has an `e2e-tests/` folder.** + +## Desired End State + +- Every PR in cplace-fe and cplace-paw-fe runs a `snapshot` job, which publishes affected packages and outputs `version` and + `packages`. It also runs a `backend-e2e` job that needs the snapshot job and is part of `pr-checks`. +- `backend-e2e` either skips with success, or does the following: + - builds the backend once, with the published packages it consumes pinned; + - runs the default spec filter on N nodes against the docker stack; + - publishes a "Test Results Backend E2E" check; + - posts a marker comment with the resolved branches, the pins and the failing specs; + - fails when any test fails. +- The label-based snapshot callers in both FE repos are deleted. + +Verify end to end with a cplace-fe PR that changes a published app: + +- the check runs; +- the job summary lists the backend branch, the `cplace-e2e` branch and the pinned versions; +- the build log shows those versions in `cf.cplace.platform/assets/package-lock.json`; +- the comment appears. + +Also verify that a PR touching only docs finishes `backend-e2e` green without a build job. + +### Key Discoveries: + +- `artifacts-handler.ts` `handle()` builds and publishes in its final `else` branch (`initProjects(); await this.buildAndPublishProjects();`). + A failed publish ends the process with `process.exit(1)`, so every `isPublishable` project that is still there afterwards was + published. +- `NxProject` exposes the public fields `name`, `scope` and `isPublishable` (`tools/scripts/artifacts/nx-project.ts:39-50`). +- Test pattern for outputs: `jest.spyOn(Utils, 'writeOutput').mockReturnValue()` with + `expect(output).toHaveBeenCalledWith('tag', …)`, in `tools/scripts/artifacts/artifacts-handler-release-flow.test.ts`. +- Bats pattern: `tools/scripts/lockfile/*.bats` with `tools/scripts/lockfile/test-helper.bash`. They run in the `scripts` job of + `.github/workflows/pr-checks.yml`. +- release/2.0 per-node order: clone `cplace-e2e` → `calculate-e2e-specs-for-node` (`has_specs`, `specs` outputs) → docker → wait → run. + We keep this order and insert the SDK bump and the spec copy after the clone. +- `run-e2e-test-suite-with-cypress` takes `specs_to_run`. Results land in `/test-results/junit`, and `copy-e2e-cypress-results` + copies them to `/tmp/test-results`. +- JUnit publish action: `EnricoMi/publish-unit-test-result-action/linux@c950f6fb443cb5af20a377fd0dfaa78838901040 # v2.23.0`. +- App token action: `actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0` (`cplace-fe: + .github/workflows/devkit-test-template.yaml:91`). +- The `cplace-e2e` support has the global commands `cy.loginAsAdminViaTestSetupHandler()` and `cy.waitForCplacePageToLoad()`. The SDK + constant `CF_PLATFORM_LIB_FOOTER` is published (`cplace-e2e: cypress/e2e/cplace/specs/commonFunctionalities/footer/footer-dialog.spec.ts`). + +## What We're NOT Doing + +- Prebuilt-image mode or FE overlay. +- Changes to `cplace-gh-workflows`, the `/run-e2e-tests` orchestrator, IAP or backend repos. +- Reusing or fixing `move_own_e2e_tests.sh`. +- Wiring the project-planning, resource-management or forms-wizard FE repos. +- Paw-level testing of cplace-fe changes. +- Affected-spec selection. +- Feature-toggle and Jira suites. +- Changes to the Storybook E2E jobs. +- A separate `FULL_SUITE` input. The full suite is `E2E_SPECS: 'cypress/e2e/**/*.spec.ts'`. +- Sharing the build through the Ubicloud/GitHub cache (`persist-build-workspace`). The build is shared as an artifact instead, so no + Ubicloud secrets are needed. +- Adding jest to github-actions self-CI. Phase 1 jest tests run locally. + +## Implementation Approach + +The planning-time choices below settle the "Deferred to planning" list in design.md. + +- **Sharing the build across nodes: artifact.** + - The build job runs `distZip` once, strips analytics, and uploads one artifact, `backend-e2e-bundle`. It contains + `/build/distributions/software.zip`, `/.github/.build-env`, `main/docker/e2e/` and + `main/e2eConfigurations/config1/`. + - Nodes download it into `$GITHUB_WORKSPACE`. The layout is then exactly what `load-env-variables` and the docker script expect, with no + gradle, no cache provider and no backend checkout. + - `REPO_NAME` is `main` for cplace, so the two trees coincide there. +- **Default scope.** + - cplace-fe: `cypress/e2e/cplace/specs/commonFunctionalities/**/*.spec.ts,cypress/e2e/cplace/specs/collaborativeExperience/**/*.spec.ts,cypress/e2e/cplace/specs/ai/**/*.spec.ts` + with `NODES: '3'`. + - cplace-paw-fe: `cypress/e2e/cplace-paw/**/*.spec.ts` with `NODES: '2'`. + - These are starting values. Phase 2 measures them, and Phase 6 sets the final ones. +- **Tokens.** + - **Product read App** (`SVA_ACTIONS_READ_PRODUCT_ID`/`_KEY`), provisioned as secrets to both FE repos. It is minted per job with + `create-github-app-token` and handed to `prepare-git-environment` as `github_token`. + - **The build job** also uses `prepare-git-environment` with `app_id`/`app_key` for parent repos. There, `REAL_REPO_NAME` is set to the + backend repo name, so no token is requested for the FE repo. + - **PR comment and checks:** the caller's `GITHUB_TOKEN` (`pull-requests: write`, `checks: write`), as `fe-pr-snapshot.yml` already does. +- **Label callers:** deleted in both FE repos. In `fe-pr-snapshot.yml` the gate becomes the input `REQUIRE_SNAPSHOT_LABEL` (default `true`), + so other FE repos keep today's behavior. +- **Reuse vs local code.** + - All backend steps reuse `cplace-gh-workflows/.github/actions/*@release/2.0`, pinned to the branch like every backend consumer. Their + inner `uses:` are `@release/2.0` anyway. + Amended 2026-11-23 (Phase 9 §3): the top-level refs are pinned to a release/2.0 commit SHA; only the nested refs stay mutable. + - New logic lives in bash under `tools/scripts/backend-e2e/`, with bats tests run by `pr-checks.yml`. It covers repo mapping, branch + resolution, consumed-package detection and pin application. + - Two composite actions wrap the scripts: `backend-e2e-resolve` and `backend-e2e-pin`. Copying the in-repo specs is a short inline step. +- **Interface.** + - Workflow inputs: `GHA_REF`, `GHA_BASE`, `SNAPSHOT_VERSION`, `SNAPSHOT_PACKAGES` (JSON array of `@scope/name`), `E2E_SPECS`, + `NODES` (default `'2'`). + Amended 2026-11-23 (Phase 9): `SNAPSHOT_INTEGRITIES` (JSON object, default `'{}'`) and `SPEC_MAP` (JSON object, default `'{}'`). + Amended 2026-11-23 (Phase 11): `ADVISORY` (boolean, default `false`). When it is `true`, the e2e nodes get `continue-on-error`, the + JUnit check uses `fail_on: nothing`, and the final fail step is skipped; a backend build failure still fails the run, and the report + still shows the outcome. The trial caller runs with `ADVISORY: true` and `NODES: '2'` (two nodes keep the run under the 60-minute job + timeout). The Phase 6 rollout callers start with `ADVISORY: true` and switch to `false` once Phase 10's exit criteria are met. + - Secrets: `ENV_CPLACE_ARTIFACTORY_ACTOR`, `ENV_CPLACE_ARTIFACTORY_TOKEN`, `SVA_ACTIONS_READ_PRODUCT_ID`, `SVA_ACTIONS_READ_PRODUCT_KEY`. + - Snapshot outputs: `version` (string) and `packages` (JSON array, `[]` when nothing was published). +- **Staging.** + - Work happens on github-actions branch `feature/fe-backend-e2e`. During Phases 2-5, the internal `collaborationFactory/github-actions/...` + refs touched by this plan point at that branch. Each such line carries `# FIXME remove before merging` (EDIT-GEN-06). Phase 6 resets + them to `@master`. + - A draft PR in cplace-fe (branch `feature/fe-backend-e2e-trial`) calls the workflows `@feature/fe-backend-e2e` and serves as the trial + consumer. +- **Rules applied** (from `cplace-best-practices`, read via the `repos/` copy because the repos7 symlinks are broken): + - `details/backend/shell-scripts.md`: `#!/usr/bin/env bash`, `set -euo pipefail`, `shell: bash`, a `case` for choices, tokens only via + env, bats tests (SH-07). + - `details/backend/editing-general.md`. + - `details/e2e/e2e-general.md`, `e2e-structure.md`, `e2e-selectors.md`, `e2e-stability.md` for the sample spec. + +## Phase 1: Snapshot outputs and optional label gate + +### Overview + +The artifacts action reports what a PR snapshot published. `fe-pr-snapshot.yml` exposes it, and its label gate becomes optional. This is +additive: existing callers keep identical behavior. + +### Changes Required: + +#### 1. Artifacts handler + +**File**: `tools/scripts/artifacts/artifacts-handler.ts` +**Changes**: after `buildAndPublishProjects()` in the final `else` branch of `handle()`, write both outputs for PR snapshots. + +```ts +console.log(`About to build and release projects`); +this.initProjects(); +await this.buildAndPublishProjects(); +if (this.task === TASK.PR_SNAPSHOT) { + this.writePrSnapshotOutputs(); +} +``` + +```ts +private writePrSnapshotOutputs() { + const packages = this.projects.filter((project) => project.isPublishable).map((project) => `${project.scope}/${project.name}`); + Utils.writeOutput('version', this.currentVersion.toString()); + Utils.writeOutput('packages', JSON.stringify(packages)); +} +``` + +#### 2. Jest tests + +**File**: `tools/scripts/artifacts/artifacts-handler-pr-snapshot-outputs.test.ts` (new) +**Changes**: follow `artifacts-handler-release-flow.test.ts` (env setup, `jest.spyOn(Utils, 'writeOutput')`, a mocked publish). Write the +first test, run it, and confirm it fails before the handler change. Then add the others. + +- An affected app plus a publishable lib produce `version` = `0.0.0--` and `packages` = `["@scope/app","@scope/lib"]`. +- A non-publishable lib is not listed. +- Nothing affected produces `packages` = `[]`, and `version` is still set. +- A main snapshot (no `PR_NUMBER`) writes neither output. +- PR close (`ONLY_DELETE_ARTIFACTS` with `PR_NUMBER`, `fe-pr-close.yml`) writes neither output. Added during implementation: that path + runs through the same `else` branch, so the handler guards with `!this.onlyDeleteArtifacts`. + +#### 3. Composite action outputs + +**File**: `.github/actions/artifacts/action.yml` +**Changes**: add the outputs `version` and `packages`, each with `value: ${{ steps.handler.outputs. }}` and a description "(PR +snapshot only)". + +#### 4. Reusable snapshot workflow + +**File**: `.github/workflows/fe-pr-snapshot.yml` +**Changes**: +- Add the input `REQUIRE_SNAPSHOT_LABEL` (`type: boolean`, `default: true`). +- Change the job `if:` to `${{ !inputs.REQUIRE_SNAPSHOT_LABEL || contains(github.event.pull_request.labels.*.name, 'snapshot') }}`. +- Give the artifacts step `id: artifacts`. +- Add job `outputs: version, packages` from `steps.artifacts.outputs.*`. +- Add `on.workflow_call.outputs` `version` and `packages` from `jobs.publish-pr-snapshot.outputs.*`. +- Add `timeout-minutes: 60` to the job. +- Point the artifacts step at `@feature/fe-backend-e2e # FIXME remove before merging` (staging, see Implementation Approach), since the + new outputs exist only on that branch until merge. Phase 6 resets it. + +### Success Criteria: + +#### Automated Verification: + +- [x] Jest passes: `npx jest --config=./jest.config.js tools/scripts/artifacts` + (new suite 5/5 green. `utils.test.ts`, `nx-project.test.ts` and `artifacts-handler-tag.test.ts` fail 8 tests identically on + unchanged `master` on Windows; not touched by this change) +- [x] Prettier passes: `npx prettier --check tools/scripts/artifacts .github` (all changed files pass with `--end-of-line auto`; the + remaining warnings are CRLF working copies and untouched files) +- [x] Workflow syntax valid: `npx --yes actionlint@1.7.7 .github/workflows/fe-pr-snapshot.yml` (or `docker run --rm -v "$PWD":/repo + -w /repo rhysd/actionlint:1.7.7`) (docker variant; quoting `"$GITHUB_ENV"` in the base-branch step cleared two SC2086 infos) +- [x] `pr-checks.yml` stays green on the github-actions PR (github-actions#190: lockfile and shell-script checks pass) + +#### Manual Verification: + +- [x] In the trial cplace-fe PR, a job calling `fe-pr-snapshot.yml@feature/fe-backend-e2e` with `REQUIRE_SNAPSHOT_LABEL: false` publishes + without the label. Its outputs (`version` and `packages`) are visible in a downstream `echo` job. (run 44682804442: + `version=0.0.0-feature-fe-backend-e2e-trial-3075`, `packages=["@cplace-next/cf-platform"]`) +- [x] The existing label caller still skips without the label. (cplace-fe#3075 at `81b6bf1`, label caller pointed at the feature + branch: "Frontend Pull Request Snapshot CI" concluded `skipped`) + +--- + +## Phase 2: Walking skeleton — build with pins, one node, JUnit check + +### Overview + +Run an end-to-end path through every layer of the design, on the trial cplace-fe PR, with the following limits: + +- mapped base branches only; +- no skip path; +- no SDK bump; +- no in-repo specs; +- check only, no comment. + +This proves the composites work outside a backend repo. It also settles risks 2 (registry visibility), 3 (install semantics) and 5 +(runners). + +### Changes Required: + +#### 1. Sample bats test first (test pattern) + +**File**: `tools/scripts/backend-e2e/pin-snapshots.bats`, `tools/scripts/backend-e2e/test-helper.bash` (new) +**Changes**: write one test first, modeled on `tools/scripts/lockfile/*.bats`. It stubs `npm` on `PATH` and records its argv to a file. +Run it red, then green, before writing the remaining tests. + +```bash +@test "pins only published packages that the assets dir depends on" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"0.0.0-SNAPSHOT-x","lodash":"4.17.21"}}' + + run env PACKAGES='["@cplace-next/cf-platform","@cplace-next/cf-shell"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 0 ] + assert_npm_called_in "$WORK/plugin.a/assets" \ + "i @cplace-next/cf-platform@0.0.0-feat-1-42 --save-exact --legacy-peer-deps" +} +``` + +Remaining cases: +- No matching dependency: npm is not called, exit 0, nothing is printed. +- A dependency in `devDependencies` is pinned too. +- A missing `package.json` is skipped. +- npm fails: the script exits non-zero with the directory in the message. +- Several dirs give one npm call each. +- The output prints one ` @` line per pin. + +#### 2. Shared lib and pin script + +**File**: `tools/scripts/backend-e2e/lib.sh` (new, sourced, no `set -e`) +**Changes**: `consumed_packages ` prints the published names found in that file's `dependencies` or +`devDependencies`, one per line: + +```bash +consumed_packages() { + local manifest="$1" packages="$2" + jq -r --argjson published "${packages}" \ + '[(.dependencies // {}), (.devDependencies // {})] | add | keys[] | select(. as $name | $published | index($name))' \ + "${manifest}" +} +``` + +**File**: `tools/scripts/backend-e2e/pin-snapshots.sh` (new) +**Changes**: `pin-snapshots.sh ...`, with env `PACKAGES` (a JSON array). +- Shebang `#!/usr/bin/env bash` and `set -euo pipefail`. +- For each dir that has `package.json`, collect the consumed names into an array. +- When the array is non-empty, run `(cd "$dir" && npm i "${args[@]}" --save-exact --legacy-peer-deps)`, the nightly upmerge recipe. +- On npm failure, exit 1 with `"pinning failed in ${dir}"` on stderr. + +**File**: `.github/actions/backend-e2e-pin/action.yml` (new) +**Changes**: a composite with inputs `version`, `packages` and `dirs` (newline-separated globs, expanded with `shopt -s nullglob`). It runs +`"$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/pin-snapshots.sh"`, appends its stdout to `$GITHUB_STEP_SUMMARY`, and uses +`shell: bash`. + +#### 3. Resolve script, mapped-base version + +**File**: `tools/scripts/backend-e2e/resolve-backend.sh` (new), `tools/scripts/backend-e2e/resolve-backend.bats` (new) +**Changes**: env `FE_REPO` and `BASE_REF`. It writes `backend_repo`, `repo_dir`, `backend_branch` and `e2e_branch` to `$GITHUB_OUTPUT`. +One `case` maps the repo: + +```bash +case "${FE_REPO:-}" in + cplace-fe) backend_repo=cplace; repo_dir=main ;; + *-fe) backend_repo="${FE_REPO%-fe}"; repo_dir="${backend_repo}" ;; + *) echo "No backend repo for '${FE_REPO:-}': expected cplace-fe or -fe" >&2; exit 1 ;; +esac +``` + +A second `case` maps the base: +- `main` and `master` map to `master`. +- `release/[0-9]*.[0-9]*-beta` maps to `release/X.Y`. +- `release/*` maps to itself. +- Anything else maps to `master`, with a `::warning::`. + +Phase 3 adds the existence checks. bats cases: +- cplace-fe maps to cplace/main. +- cplace-paw-fe maps to cplace-paw. +- An unknown repo fails. +- Each base mapping. + +**File**: `.github/actions/backend-e2e-resolve/action.yml` (new) +**Changes**: a composite wrapping `resolve-backend.sh`. It has outputs `backend_repo`, `repo_dir`, `backend_branch`, `e2e_branch` and `run` +(always `true` in this phase). It also writes a step summary table: FE repo, backend repo and branch, `cplace-e2e` branch, snapshot version, +packages. + +#### 4. Reusable workflow + +**File**: `.github/workflows/fe-backend-e2e.yml` (new) +**Changes**: `on: workflow_call` with the inputs and secrets from Implementation Approach. Jobs: + +- **resolve** (`ubuntu-latest`, `timeout-minutes: 10`): run the `backend-e2e-resolve` composite. Map its outputs to job outputs. +- **build** (`needs: resolve`, `if: needs.resolve.outputs.run == 'true'`, runner + `${{ vars.E2E_MEDIUM_RUNNER || vars.MEDIUM_RUNNER || 'ubuntu-22.04' }}`, `timeout-minutes: 60`). Job env: `REPO_NAME` = resolve + `repo_dir`, `REAL_REPO_NAME` = resolve `backend_repo`, `DO_UPLOAD: 'false'`, `CREATE_INITIAL_RELEASE: 'false'`, + `ENV_CPLACE_ARTIFACTORY_*` from secrets. Steps, mirroring `cplace-gh-workflows@release/2.0 .github/workflows/build.yml`: + 1. `create-github-app-token` with `app-id`/`private-key` from the product read App and `repositories: `. + 2. Check out `collaborationFactory/` at `backend_branch`, with `path: ${{ env.REPO_NAME }}`, `persist-credentials: false`, + `fetch-depth: 1` and the token. + 3. `load-env-variables@release/2.0`, with `secrets: ${{ toJson(secrets) }}` and `vars: ${{ toJson(vars) }}`. + 4. `prepare-build-environment@release/2.0`. + 5. `prepare-git-environment@release/2.0` with `app_id`/`app_key`, so parent repos come from the backend's `parent-repos.json`. + 6. `fetch-tags@release/2.0`. + 7. `prepare-parent-repos@release/2.0`, only `if: env.CB_INCLUDE_PARENT_REPOS == 'true'`. + 8. The npm auth step (below). + 9. `rewrite-package-lock-json-files@release/2.0`, under the same condition as in build.yml. + 10. `backend-e2e-pin` with `dirs: ${{ env.REPO_NAME }}/*/assets`. + 11. `patch-release-generate-version-env-file@release/2.0` with `create-initial-release: 'false'`, `trace-log: 'false'` and + `build-current-version: ${{ env.CB_BUILD_CURRENT_VERSION }}`. + 12. `build-parent-repos@release/2.0` (if) and `build-distribution@release/2.0`. + 13. The inline `distZip` and analytics strip, copied from release/2.0 `reuseable-e2e-cypress.yml`. + 14. Upload artifact `backend-e2e-bundle` with `retention-days: 1` and these paths: + - `${{ env.REPO_NAME }}/build/distributions/software.zip` + - `${{ env.REPO_NAME }}/.github/.build-env` + - `main/docker/e2e` + - `main/e2eConfigurations/config1` +- **e2e** (`needs: [resolve, build]`, matrix `node_index: ${{ fromJSON(format('[{0}]', ...)) }}`). + - The matrix is built by a tiny step in resolve that emits a `node_indexes` JSON array from `NODES`. `fail-fast: false`, same runner, + `timeout-minutes: 60`. Job env: `REPO_NAME` and `ENV_CPLACE_ARTIFACTORY_*`. + - Steps: + 1. `prepare-e2e-environment@release/2.0`. + 2. Download `backend-e2e-bundle` to `$GITHUB_WORKSPACE`. + 3. `load-env-variables@release/2.0`. + 4. `create-github-app-token` (`repositories: cplace-e2e`). + 5. `prepare-git-environment@release/2.0` with `github_actor: ${{ github.actor }}` and `github_token` = the minted token. + 6. `clone-e2e-repo@release/2.0` with `e2e_branch` = resolve `e2e_branch`. + 7. `actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0` with + `node-version-file: ${{ env.REPO_NAME }}/${{ env.CB_E2E_REPO_NAME }}/package.json`. + 8. The npm auth step. + 9. `calculate-e2e-specs-for-node@release/2.0` with `e2e_specs: inputs.E2E_SPECS`. + 10. `create-and-run-cplace-docker@release/2.0`, `wait-for-cplace-startup@release/2.0` and `run-e2e-test-suite-with-cypress@release/2.0`, + with the same inputs and `has_specs` guards as release/2.0 `reuseable-e2e-cypress.yml`. + 11. `copy-e2e-cypress-results` and `copy-cplace-logs` (`always()`). + 12. Upload `backend-e2e-results-${{ matrix.node_index }}` (`/tmp/test-results`) and `backend-e2e-cplace-logs-${{ matrix.node_index }}`, + with `retention-days: 5`. +- **report** (`needs: [resolve, e2e]`, `if: always() && needs.resolve.outputs.run == 'true'`, `ubuntu-latest`, `timeout-minutes: 15`): + 1. Download the artifacts with `pattern: backend-e2e-results-*` and `merge-multiple: true`. + 2. Run the EnricoMi action with `check_name: 'Test Results Backend E2E'`, `files: test-results/junit/**/*.xml` and + `json_file: backend-e2e-results.json`. + 3. A final step fails the job unless `needs.e2e.result == 'success'`. + +Changed during implementation: +- The bundle is one `backend-e2e-bundle.tgz` built with `tar`, uploaded as the `backend-e2e-bundle` artifact and unpacked on + the nodes. `upload-artifact` with several paths strips their common prefix, which is `main/` for cplace and nothing for + other backends, so the layout would differ per backend. +- The bundle holds all of `main/docker` (~375 KB), not only `main/docker/e2e`: the e2e compose file `extends` + `../elasticsearch/elasticsearch-base.yml`, and trial run 44774066471 failed on the node without it. +- `main/e2eConfigurations/config1` is bundled only when it exists. It is not in the cplace repository; the docker scripts + only bind-mount it as cplace properties. +- After the bundle upload, an `always()` step uploads `~/.npm/_logs` as `backend-e2e-npm-logs-build`, so a failed pin + step's `npm i` can be diagnosed from its debug log. + +npm auth step (inline, `shell: bash`). The token stays in env, the file is `chmod 600`, and the token never appears in argv: + +```bash +umask 077 +{ + echo "registry=https://cplace.jfrog.io/artifactory/api/npm/cplace-npm/" + echo "//cplace.jfrog.io/artifactory/api/npm/cplace-npm/:_authToken=${ENV_CPLACE_ARTIFACTORY_TOKEN}" +} >> "${HOME}/.npmrc" +``` + +Top-level `permissions:` is `contents: read`, because `build` and `e2e` run lifecycle scripts of PR-built packages; only `report` adds +`checks: write` and `pull-requests: write`, which callers already grant. Every external action is SHA-pinned in +the `owner/repo@ # vX.Y.Z` form. + +#### 5. Self-CI for the new scripts + +**File**: `.github/workflows/pr-checks.yml` +**Changes**: the `shellcheck` step also checks `tools/scripts/backend-e2e/*.sh tools/scripts/backend-e2e/test-helper.bash`. The `bats` step +runs `bats tools/scripts/lockfile/ tools/scripts/backend-e2e/`. + +#### 6. Trial consumer + +**File**: `cplace-fe: .github/workflows/pull_request.yaml` (only on trial branch `feature/fe-backend-e2e-trial`, draft PR, never merged) +**Changes**: +- Add a `snapshot` job calling `fe-pr-snapshot.yml@feature/fe-backend-e2e` with `REQUIRE_SNAPSHOT_LABEL: false` and the JFrog and npmrc + secrets. +- Add a `backend-e2e` job (`needs: snapshot`) calling `fe-backend-e2e.yml@feature/fe-backend-e2e`. Pass the snapshot outputs, the cplace + default filter and `NODES: '1'`. +- Make a trivial change in `apps/cf-platform` so a package consumed by `cf.cplace.platform` is published. + +### Success Criteria: + +#### Automated Verification: + +- [x] bats passes locally: `bats tools/scripts/lockfile/ tools/scripts/backend-e2e/` + (93/93 in `bats/bats:1.11.1` with jq and git added, on an LF copy of the tree; the first pin test ran red before + `pin-snapshots.sh` existed) +- [x] shellcheck passes: `shellcheck tools/scripts/backend-e2e/*.sh tools/scripts/backend-e2e/test-helper.bash` +- [x] Workflow syntax valid: `actionlint .github/workflows/fe-backend-e2e.yml .github/workflows/pr-checks.yml` (docker + `rhysd/actionlint:1.7.7`; also the trial `cplace-fe: .github/workflows/pull_request.yaml`) +- [x] `pr-checks.yml` on the github-actions PR runs the new bats files and is green (github-actions#190, 93/93 bats) +- [x] On the trial PR, `backend-e2e / report` publishes the "Test Results Backend E2E" check with at least one executed spec + (run 44777680475, after the secrets were provisioned: "9 fail, 542 pass in 33m 19s". The 9 failures are in 6 specs that fail + on all three Cypress attempts; not yet triaged against cplace master) + +#### Manual Verification: + +- [x] The build log shows the pinned `@cplace-next/cf-platform@0.0.0--` in `cf.cplace.platform/assets/package-lock.json` after the + pin step, and the build succeeds with it (risks 2 and 3). (run 44774066471: pin step logged + `main/cf.cplace.platform/assets @cplace-next/cf-platform@0.0.0-feature-fe-backend-e2e-trial-3075`; build green) +- [x] The bundle download plus compose boot reaches `applicationStatus.txt` 200 on the node without gradle running there. (run + 44777680475: docker step 67s, "Wait for cplace startup" green after 10s) +- [x] The runner labels resolve for an FE repo (risk 5). Note the wall-clock of build and node. (build job 3m37s, of which + `build-distribution` ~4 min in the earlier run; node job 59m29s, nearly all Cypress) +- [ ] Spec counts and the node time for the cplace default filter are recorded in the PR description, to set the Phase 6 `NODES` values. + (measured, not yet in the PR description: 99 specs, 602 tests, 38m34s for the first Cypress pass on one node, plus ~10 min of + retries for the 6 failing specs; the node job ended 31s before its 60-min timeout. `NODES: '3'` gives ~13 min per node) + +--- + +## Phase 3: Branch resolution, skip path, SDK bump, cost controls + +### Overview + +Complete the decisions on the resolve side and the harness side: +- same-named branches; +- skip with success when nothing consumed was published; +- `cplace-e2e` SDK pins; +- concurrency and timeouts. + +### Changes Required: + +#### 1. Branch existence and same-named resolution + +**File**: `tools/scripts/backend-e2e/lib.sh`, `tools/scripts/backend-e2e/resolve-backend.sh`, `tools/scripts/backend-e2e/resolve-backend.bats` +**Changes**: +- `lib.sh` gains `remote_branch_exists `. It runs + `git ls-remote --heads "https://github.com/collaborationFactory/${repo}.git" "refs/heads/${branch}"` with a credential helper that + reads `GH_TOKEN` from env, so the token never appears in argv. It retries 3 times with backoff 5/10/20s and compares the output for an + exact `refs/heads/${branch}` line, never `--exit-code` (PFM-ISSUE-34932). + - A network failure after the retries exits 2 and fails the job. + - "Not found" returns 1. +- `resolve-backend.sh` reads `HEAD_REF` as well, and applies the following to the backend repo and to `cplace-e2e` independently: + - Use `HEAD_REF` if it exists in the target. + - Otherwise use the mapped base. + - A mapped `release/X.Y` that is missing in the target falls back to `master` with a `::warning::`. +- bats cases stub `git`: + - same-named branch present; + - absent, falling back to the base; + - `-beta` with and without `release/X.Y`; + - an unreachable remote fails; + - prefix-only matches such as `refs/heads/feature/x-2` for `feature/x` are not treated as a match. + +#### 2. Consumed-package detection and skip + +**File**: `tools/scripts/backend-e2e/resolve-consumers.sh` (new), `tools/scripts/backend-e2e/resolve-consumers.bats` (new) +**Changes**: env `PACKAGES`, args ` `. It uses `consumed_packages` on every `/*/assets/package.json` +and on `/package.json`, and writes `backend_packages`, `e2e_packages` and `run` (`true` iff either list is non-empty) to `$GITHUB_OUTPUT`. +An empty or missing `PACKAGES` (for example after a branch-off early return) counts as `[]`. bats cases: +- consumed only by the backend; +- consumed only by `cplace-e2e`; +- consumed by neither, giving `run=false`; +- `[]`. + +**File**: `.github/actions/backend-e2e-resolve/action.yml` +**Changes**: +- Before calling the scripts, mint a token for `,cplace-e2e`. The script already knows `backend_repo`, so split it: the + composite runs `resolve-backend.sh` for the repo, then mints, then resolves the branches. +- Make blob-less sparse clones (`git clone --depth 1 --filter=blob:none --no-checkout`, then `git sparse-checkout set --no-cone '/*/assets/package.json'` + for the backend and `'/package.json'` for `cplace-e2e`). Credentials come from `GH_TOKEN` via the same helper. +- Run `resolve-consumers.sh`. +- When `run=false`, the summary states "Skipped: no package consumed by `` or `cplace-e2e` was published". + +**File**: `.github/workflows/fe-backend-e2e.yml` +**Changes**: the e2e matrix and the report are gated on `run == 'true'`, as build already is, so a skip leaves only `resolve` green. + +#### 3. SDK bump in cloned cplace-e2e + +**File**: `.github/workflows/fe-backend-e2e.yml` +**Changes**: in the e2e job, after `clone-e2e-repo`, run `backend-e2e-pin` with `dirs: ${{ env.REPO_NAME }}/${{ env.CB_E2E_REPO_NAME }}` +when `needs.resolve.outputs.e2e_packages != '[]'`. + +#### 4. Cost controls + +**File**: `.github/workflows/fe-backend-e2e.yml` +**Changes**: add workflow-level `concurrency: { group: fe-backend-e2e-${{ github.repository }}-${{ github.event.pull_request.number }}, +cancel-in-progress: true }`. Confirm that every job has `timeout-minutes`. + +Changed during implementation: +- `resolve-backend.sh` takes a step argument: `repo` writes `backend_repo` and `repo_dir`, `branches` (env `BACKEND_REPO`, `BASE_REF`, + `HEAD_REF`, `GH_TOKEN`) writes `backend_branch` and `e2e_branch`. That is the split §2 asks for, since the token is minted between the two. +- `lib.sh` also gains `git_with_token`, used by `remote_branch_exists` and by the sparse clones. `RETRY_DELAYS` overrides the 5/10/20s + backoff, so bats runs without sleeping. +- The resolve composite takes `head_ref`, `app_id` and `app_key` (composites cannot read `secrets`), and outputs `backend_packages` and + `e2e_packages`; the summary lists both. +- `resolve-consumers.sh` warns when the backend checkout has no `*/assets/package.json`, since that skips the run. +- The `cplace-e2e` pin step sits after `setup-node` and the npm auth step, not directly after the clone, because `npm i` needs both. + +### Success Criteria: + +#### Automated Verification: + +- [x] bats passes: `bats tools/scripts/backend-e2e/` (115/115 with `tools/scripts/lockfile/`, in `bats/bats:1.11.1` with jq and git, on + an LF copy of the tree) +- [x] shellcheck passes: `shellcheck tools/scripts/backend-e2e/*.sh tools/scripts/backend-e2e/test-helper.bash` (docker + `koalaman/shellcheck:stable`; also the inline sparse-clone step of `backend-e2e-resolve`) +- [x] `actionlint .github/workflows/fe-backend-e2e.yml` (docker `rhysd/actionlint:1.7.7`) +- [x] github-actions `pr-checks.yml` green (github-actions#190: lockfile and shell-script checks pass with the new bats files) + +#### Manual Verification: + +- [ ] On the trial PR, a push touching only a Markdown file ends with `backend-e2e` = `success`. Only `resolve` ran, its summary says + "Skipped". The caller's `needs.backend-e2e.result` is `success`, not `skipped`. +- [ ] With a same-named `cplace-e2e` branch pushed, the summary shows it. Without one, it shows the mapped base. +- [ ] A trivial change to `libs/cf-e2e-testing-sdk` pins it in the cloned `cplace-e2e` (node log), and the specs still run. +- [ ] Two quick pushes: the first run's `backend-e2e` is cancelled. + +--- + +## Phase 4: In-repo specs (`e2e-tests/`) + +### Overview + +Copy the FE repo's `e2e-tests/` into the cloned `cplace-e2e` and include it in the spec filter. Prove it with a sample spec in cplace-fe. + +### Changes Required: + +#### 1. Copy and filter + +**File**: `.github/workflows/fe-backend-e2e.yml` +**Changes**: +- In the e2e job, sparse-check out the FE PR head (`actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3`, + `ref: ${{ inputs.GHA_REF }}`, `path: fe-repo`, `sparse-checkout: e2e-tests`, `persist-credentials: false`). +- After the SDK bump, run this inline step: + +```bash +target="${REPO_NAME}/${CB_E2E_REPO_NAME}/cypress/e2e/${FE_REPO}" +if [ -d fe-repo/e2e-tests ]; then + mkdir -p "${target}" + cp -R fe-repo/e2e-tests/. "${target}/" + echo "specs=${E2E_SPECS},cypress/e2e/${FE_REPO}/**/*.spec.ts" >> "$GITHUB_OUTPUT" +else + echo "specs=${E2E_SPECS}" >> "$GITHUB_OUTPUT" +fi +``` + +- `calculate-e2e-specs-for-node` then uses this step's `specs` output. +- `FE_REPO` is `${{ github.event.repository.name }}`. +- The resolve step also checks `e2e-tests/` existence the same way, sparse-checking out the FE head, and lists it in the summary. + +#### 2. Sample in-repo spec + +**File**: `cplace-fe: e2e-tests/platform/startPage.spec.ts` (new) +**Changes**: a minimal spec following `cplace-e2e`'s support. It uses only global commands and a published SDK constant, with no relative +support imports, so it works from `cypress/e2e/cplace-fe/`. + +```ts +/* + * Copyright 2026, collaboration Factory GmbH. All rights reserved. + */ + +// Test document: + +import { CF_PLATFORM_LIB_FOOTER } from '@cplace-next/cf-e2e-testing-sdk'; + +describe('cplace-fe in-repo specs run against the PR backend', () => { + before(() => { + cy.loginAsAdminViaTestSetupHandler(); + cy.waitForCplacePageToLoad(); + }); + + it('TC01: renders the platform footer after login', () => { + cy.getByQaName(CF_PLATFORM_LIB_FOOTER).should('be.visible'); + }); +}); +``` + +**File**: `cplace-fe: e2e-tests/README.md` (new) +**Changes**: three short sections: +- what runs here: real-backend specs executed inside `cplace-e2e` on every PR; +- the constraints: `cplace-e2e` support and its Cypress major, not linted or type-checked in this repo, `*.spec.ts` only; +- how to run locally: copy into a `cplace-e2e` checkout under `cypress/e2e/cplace-fe/`. + +**File**: `cplace-fe: .eslintrc.json`, `cplace-fe: tsconfig.base.json`, and `nx.json` if needed +**Changes**: make sure the `e2e-tests/` folder is not picked up by root lint, tsc or prettier. Add it to the ignore patterns (`.eslintignore` +or `ignorePatterns`, plus `.prettierignore`) only if a check actually picks it up. + +Changed during implementation: +- The resolve job checks out `e2e-tests` before the resolve composite and passes + `in_repo_specs: ${{ hashFiles('fe-repo/e2e-tests/**') != '' }}`, a new composite input that adds an "In-repo specs" row to the summary. +- `run-e2e-test-suite-with-cypress` gets the same `specs` output as `calculate-e2e-specs-for-node` for `workflow_e2e_specs`. +- No ignore change in cplace-fe: `e2e-tests/` belongs to no Nx project, the root `.eslintrc.json` ignores `**/*`, and no tsconfig + includes it. Prettier formats it, and the new files pass. + +### Success Criteria: + +#### Automated Verification: + +- [x] `actionlint .github/workflows/fe-backend-e2e.yml` (docker `rhysd/actionlint:1.7.7`, with `pr-checks.yml`) +- [x] cplace-fe checks stay green with the new folder: `nx format:check` and `nx affected lint` (no `node_modules` in the local + cplace-fe checkout: prettier 3.8.1 with the repo's options and `prettier-plugin-organize-imports` passes on `e2e-tests/`; lint + cannot reach the folder, see above) +- [ ] On the trial PR, the "Test Results Backend E2E" check lists `TC01: renders the platform footer after login` as passed + +#### Manual Verification: + +- [ ] Temporarily break the sample assertion and confirm that the check and `backend-e2e` fail. Then revert. +- [ ] A PR without `e2e-tests/`, such as cplace-paw-fe in Phase 6, runs only the default filter. + +--- + +## Phase 5: Reporting — marker comment + +### Overview + +Post one PR comment per run with the outcome, resolved branches, pins and failing specs, and minimize earlier comments from this workflow. + +### Changes Required: + +#### 1. Comment step + +**File**: `.github/workflows/fe-backend-e2e.yml` +**Changes**: +- In `report`, add `actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0`. It reads `backend-e2e-results.json` from the + EnricoMi step (`json_test_case_results: true`) and the resolve outputs, passed through env. +- It creates a comment beginning with `` that contains: + - ✅/❌, passed/failed/skipped counts; + - the backend repo and branch, and the `cplace-e2e` branch; + - snapshot version, and the pinned backend and e2e packages; + - up to 20 failing test names with their spec files; + - links to the run and to the check. +- It pages through the issue comments (`github.paginate`). Every older comment whose body starts with the marker and whose author is + `github-actions[bot]` is minimized through the GraphQL `minimizeComment(input: {subjectId, classifier: OUTDATED})`. +- The skip path posts no comment. The resolve summary is enough there, and docs-only PRs stay quiet. +- The step runs `if: always()` before the final status step. + +Changed during implementation: +- The new comment is created first and the older marker comments are minimized afterwards, so the PR always shows one. +- The spec file of a failing test is the JUnit `test_file`, else the result file name with the `cplace-e2e-results-` prefix and + `.xml` stripped (`cplace-e2e` writes one `cplace-e2e-results-[suiteFilename].xml` per spec). Only the first failing attempt of a test + is listed. + +### Success Criteria: + +#### Automated Verification: + +- [x] `actionlint .github/workflows/fe-backend-e2e.yml` (docker `rhysd/actionlint:1.7.7`; the script ran locally against stubbed + `github`/`context` and a sample results file: one comment, the older bot comment minimized, a foreign comment left alone) +- [ ] On the trial PR, a run produces exactly one non-minimized comment starting with `` + +#### Manual Verification: + +- [ ] After a second run, the first comment is minimized as outdated. +- [ ] With the sample spec broken, the comment names `TC01` and `startPage.spec.ts` and shows ❌. +- [ ] The comment shows the same branches and versions as the job summary and the build log. + +--- + +## Phase 6: Rollout to cplace-fe and cplace-paw-fe + +### Overview + +Settle final defaults, document, reset staging refs, provision secrets, wire both FE repos as required checks, and delete the label +callers. github-actions merges first. The FE PRs follow. + +### Changes Required: + +#### 1. github-actions finalization + +**File**: `.github/workflows/fe-pr-snapshot.yml`, `.github/workflows/fe-backend-e2e.yml` +**Changes**: reset every `@feature/fe-backend-e2e` ref to `@master` and remove the `# FIXME remove before merging` markers. + +**File**: `README.md` +**Changes**: add a section `## FE Backend E2E (fe-backend-e2e.yml)` covering: +- what it does, with the job graph from design.md; +- inputs, outputs and the required secrets (product read App, `ENV_CPLACE_ARTIFACTORY_*`); +- the branch-resolution and skip rules; +- the `e2e-tests/` convention; +- tool requirements for the scripts (bash ≥ 4.4, jq, git; SH-08); +- the full-suite example `E2E_SPECS: 'cypress/e2e/**/*.spec.ts'`. + +Add `REQUIRE_SNAPSHOT_LABEL` to the snapshot description. + +**File**: `.github/workflow-templates/fe/fe-pr.yml` +**Changes**: add the `snapshot` and `backend-e2e` jobs and the `pr-checks` need. Add `pull-requests: write` and `checks: write` to the +template's permissions if they are missing. + +#### 2. Secrets (operational, before the FE PRs merge) + +- [ ] `SVA_ACTIONS_READ_PRODUCT_ID` and `SVA_ACTIONS_READ_PRODUCT_KEY` are available to cplace-fe and cplace-paw-fe (org secret visibility + or repo secrets). The App is installed on `cplace`, `cplace-paw` and `cplace-e2e`. +- [ ] `ENV_CPLACE_ARTIFACTORY_ACTOR` and `ENV_CPLACE_ARTIFACTORY_TOKEN` are available to cplace-paw-fe. +- [ ] `JFROG_*` and `DOT_NPMRC` are already present in both repos. The snapshot callers use them. + +#### 3. cplace-fe wiring + +**File**: `cplace-fe: .github/workflows/pull_request.yaml` +**Changes**: + +```yaml +snapshot: + uses: collaborationFactory/github-actions/.github/workflows/fe-pr-snapshot.yml@master + with: + GHA_BASE: ${{ github.event.pull_request.base.ref }} + REQUIRE_SNAPSHOT_LABEL: false + secrets: + JFROG_BASE64_TOKEN: ${{ secrets.JFROG_BASE64_TOKEN }} + JFROG_URL: ${{ secrets.JFROG_URL }} + JFROG_USER: ${{ secrets.JFROG_USER }} + DOT_NPMRC: ${{ secrets.DOT_NPMRC }} + +backend-e2e: + needs: snapshot + uses: collaborationFactory/github-actions/.github/workflows/fe-backend-e2e.yml@master + with: + GHA_REF: ${{ github.event.pull_request.head.ref }} + GHA_BASE: ${{ github.event.pull_request.base.ref }} + SNAPSHOT_VERSION: ${{ needs.snapshot.outputs.version }} + SNAPSHOT_PACKAGES: ${{ needs.snapshot.outputs.packages }} + E2E_SPECS: 'cypress/e2e/cplace/specs/commonFunctionalities/**/*.spec.ts,cypress/e2e/cplace/specs/collaborativeExperience/**/*.spec.ts,cypress/e2e/cplace/specs/ai/**/*.spec.ts' + NODES: '3' + secrets: + ENV_CPLACE_ARTIFACTORY_ACTOR: ${{ secrets.ENV_CPLACE_ARTIFACTORY_ACTOR }} + ENV_CPLACE_ARTIFACTORY_TOKEN: ${{ secrets.ENV_CPLACE_ARTIFACTORY_TOKEN }} + SVA_ACTIONS_READ_PRODUCT_ID: ${{ secrets.SVA_ACTIONS_READ_PRODUCT_ID }} + SVA_ACTIONS_READ_PRODUCT_KEY: ${{ secrets.SVA_ACTIONS_READ_PRODUCT_KEY }} +``` + +- `pr-checks.needs` becomes `[build, code-quality, e2e, backend-e2e]`. +- Replace `NODES` and the filter with the values measured in Phase 2 if they differ. Keep the Phase 4 sample spec and its README. + +**File**: `cplace-fe: .github/workflows/pull_request_snapshot.yaml` +**Changes**: delete. + +#### 4. cplace-paw-fe wiring + +**File**: `cplace-paw-fe: .github/workflows/fe-pr.yml` +**Changes**: +- The same two jobs, with `E2E_SPECS: 'cypress/e2e/cplace-paw/**/*.spec.ts'` and `NODES: '2'`. +- Add `pr-checks` needs. +- Permissions: add `pull-requests: write` and `checks: write` if they are not already granted. `actions: read` stays. + +**File**: `cplace-paw-fe: .github/workflows/fe-pr-snapshot.yml` +**Changes**: delete. + +### Success Criteria: + +#### Automated Verification: + +- [ ] `grep -rn "feature/fe-backend-e2e\|FIXME remove before merging" .github` in github-actions returns nothing +- [ ] `actionlint` passes on all changed workflows in github-actions, cplace-fe and cplace-paw-fe +- [ ] github-actions `pr-checks.yml` green, bats and shellcheck included +- [ ] On the cplace-fe rollout PR, `PR Checks` lists `backend-e2e: success` +- [ ] On the cplace-paw-fe rollout PR, `PR Checks` lists `backend-e2e: success` (run or skip) + +#### Manual Verification: + +- [ ] A cplace-fe PR that breaks a flow covered by the default filter fails `pr-checks`, and the comment links the failing specs (design + success criterion 1). +- [ ] A cplace-paw-fe PR changing `cf-landing-page` pins `@cplace-paw-fe/cf-landing-page` in the `cplace-paw` build and runs the paw specs. +- [ ] A docs-only PR in either repo passes without a build job. +- [ ] A typical run stays within the timeouts. Wall-clock is noted in the README section. +- [ ] Labeling a PR `snapshot` no longer triggers a second publish. + +--- + +## Phase 7: Move inline workflow shell into tested scripts + +### Overview + +Two pieces of logic still live as inline shell in YAML, where the `pr-checks.yml` shellcheck and bats steps never reach them: the `NODES` +validation in `fe-backend-e2e.yml` and the glob expansion with its no-match error in `backend-e2e-pin`. Move both into +`tools/scripts/backend-e2e/` and cover them with bats. This phase lands on `feature/fe-backend-e2e` before Phase 6 merges github-actions; +it changes where the logic lives, not how the workflow behaves. + +### Changes Required: + +#### 1. Glob expansion in `pin-snapshots.sh` + +**File**: `tools/scripts/backend-e2e/pin-snapshots.sh` +**Changes**: +- Usage becomes `PACKAGES='[...]' pin-snapshots.sh ...`. Update the header comment and the usage message. +- Before the pin loop, expand every argument with `shopt -s nullglob`, skipping blank arguments. The expansion is unquoted on purpose and + keeps its `# shellcheck disable=SC2206` with the reason. +- When the expansion yields no directory, print `No directory matches: ` to stderr and exit 1. +- A literal path expands to itself, so existing callers and the existing bats cases are unaffected. + +**File**: `tools/scripts/backend-e2e/pin-snapshots.bats` +**Changes**: add cases: +- a glob such as `"$WORK/*/assets"` matching two dirs pins in both (two npm calls); +- a glob that matches nothing exits 1, names the glob on stderr, and calls npm zero times; +- a blank argument next to a matching glob is ignored. + +#### 2. Pin action delegates to the script + +**File**: `.github/actions/backend-e2e-pin/action.yml` +**Changes**: remove the `dirs` array loop, the `nullglob` and the no-match check. Read the `DIRS` input lines with +`mapfile -t patterns <<<"${DIRS}"` and call `pin-snapshots.sh "${VERSION}" "${patterns[@]}"`. Keep the step-summary block unchanged. The +`dirs` input description stays as is. + +#### 3. Node index script + +**File**: `tools/scripts/backend-e2e/node-indexes.sh` (new) +**Changes**: `node-indexes.sh `. It rejects `''`, any non-digit and a leading `0` with +`NODES must be a positive integer, got ''` on stderr and exit 1, and otherwise prints `jq -cn --argjson n "" '[range($n)]'`. +Same header and `set -euo pipefail` conventions as the sibling scripts. + +**File**: `tools/scripts/backend-e2e/node-indexes.bats` (new) +**Changes**: `''`, `abc`, `0`, `05`, `-1` fail with exit 1 and the message; `1` prints `[0]`; `3` prints `[0,1,2]`. + +#### 4. Wire node indexes through the resolve action + +**File**: `.github/actions/backend-e2e-resolve/action.yml` +**Changes**: add input `nodes` (required, `Number of parallel E2E nodes`) and output `node_indexes` (`JSON array [0..nodes-1] for the node +matrix`). Add a step `id: nodes` that passes `NODES: ${{ inputs.nodes }}` through env and writes +`node_indexes=$("$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/node-indexes.sh" "${NODES}")` to `$GITHUB_OUTPUT`. It runs first, +so an invalid `NODES` fails the job before branch resolution. + +**File**: `.github/workflows/fe-backend-e2e.yml` +**Changes**: pass `nodes: ${{ inputs.NODES }}` to the resolve action, delete the inline "Node matrix" step, and point the job output at +`${{ steps.resolve.outputs.node_indexes }}`. No extra checkout is needed, since the composite action already ships the scripts. + +### Success Criteria: + +#### Automated Verification: + +- [x] `shellcheck tools/scripts/backend-e2e/*.sh tools/scripts/backend-e2e/test-helper.bash` (docker `koalaman/shellcheck:stable`) +- [x] `bats tools/scripts/backend-e2e/` passes, including the new glob and node-index cases (99/99 with `tools/scripts/lockfile/`, in + `bats/bats:1.11.1` with jq and git, on an LF copy of the tree) +- [x] `actionlint .github/workflows/fe-backend-e2e.yml` (docker `rhysd/actionlint:1.7.7`, with `pr-checks.yml`) +- [x] `grep -n 'nullglob\|\[!0-9\]' .github/actions/backend-e2e-pin/action.yml .github/workflows/fe-backend-e2e.yml` returns nothing +- [x] Review findings [2.4] marked resolved in review.md. Ticking this item means editing review.md's `- [ ] Resolved` line for [2.4] to + `- [x] Resolved — `. + +#### Manual Verification: + +- [ ] On the trial PR, a run with the default `NODES` produces the same node matrix and the same pin summary as before. +- [ ] Temporarily set `NODES: '0'` on the trial caller and confirm that `resolve` fails with the positive-integer error. Then revert. + +--- + +## Phase 8: Move the manifest fetch into a tested script + +### Overview + +The "Fetch the backend and cplace-e2e manifests" step in `backend-e2e-resolve` is the last inline shell with a function and branching of +its own, so the `pr-checks.yml` shellcheck and bats steps never reach it. Move it into `tools/scripts/backend-e2e/` and cover it with bats, +following Phase 7. It changes where the logic lives, not how the workflow behaves. + +### Changes Required: + +#### 1. Manifest fetch script + +**File**: `tools/scripts/backend-e2e/fetch-manifests.sh` (new) +**Changes**: `fetch-manifests.sh `. It reads `BACKEND_REPO`, `BACKEND_BRANCH`, `E2E_BRANCH` and `GH_TOKEN` from env, and +exits 1 with ` is not set` on stderr when one is empty. It sources `lib.sh` and keeps the current `manifests +` function as is: a `git_with_token clone --quiet --depth 1 --filter=blob:none --no-checkout --branch ` of +`https://github.com/collaborationFactory/.git`, then `sparse-checkout set --no-cone ` and `checkout --quiet`. It fetches +`/backend` with `/*/assets/package.json` and `/cplace-e2e` with `/package.json`. Same header and +`set -euo pipefail` conventions as the sibling scripts, so a failing git call fails the script. + +#### 2. git stub covers clone and checkout + +**File**: `tools/scripts/backend-e2e/test-helper.bash` +**Changes**: the `git` stub keeps its `ls-remote` behaviour. For any other subcommand it logs argv to `GIT_LOG` and exits 0, or exits 128 +with a `fatal:` line on stderr when `${REMOTES}/.unreachable` exists for the cloned repo. Update the stub's header comment. + +**File**: `tools/scripts/backend-e2e/fetch-manifests.bats` (new) +**Changes**: cases: +- the backend and cplace-e2e clones use the right URL, `--branch` and sparse pattern, and their target dirs are under ``; +- `GH_TOKEN`'s value appears nowhere in `GIT_LOG`; +- each missing env var exits 1 and names it; +- an unreachable repo makes the script exit non-zero. + +#### 3. Resolve action delegates to the script + +**File**: `.github/actions/backend-e2e-resolve/action.yml` +**Changes**: the "Fetch the backend and cplace-e2e manifests" step keeps its env and runs +`'"$GITHUB_ACTION_PATH/../../../tools/scripts/backend-e2e/fetch-manifests.sh" "${RUNNER_TEMP}/backend-e2e"'`. The inline `manifests()` +function, the `source` of `lib.sh` and its `shellcheck source=/dev/null` directive go. Keep the comment above the step. + +### Success Criteria: + +#### Automated Verification: + +- [x] `shellcheck tools/scripts/backend-e2e/*.sh tools/scripts/backend-e2e/test-helper.bash` (docker `koalaman/shellcheck:stable`) +- [x] `bats tools/scripts/lockfile/ tools/scripts/backend-e2e/` passes, including the new fetch-manifests cases (121/121 in + `bats/bats:1.11.1` with jq and git, on an LF copy of the tree; 6 new cases, including a usage check for a missing ``) +- [x] `actionlint .github/workflows/fe-backend-e2e.yml .github/workflows/pr-checks.yml` (docker `rhysd/actionlint:1.7.7`) +- [x] `grep -n 'manifests()\|sparse-checkout' .github/actions/backend-e2e-resolve/action.yml` returns nothing +- [x] Review findings [5.3] marked resolved in review.md. Ticking this item means editing review.md's `- [ ] Resolved` line for [5.3] to + `- [x] Resolved — `. + +#### Manual Verification: + +- [ ] On the trial PR, `resolve` produces the same `backend_packages`, `e2e_packages` and `run` outputs as before. + +--- + +## Phase 9: Review hardening + +### Overview + +Apply the decisions from the 2026-11-23 review of the branch: + +- the run verifies that it installs the exact snapshot its snapshot job published; +- the backend and `cplace-e2e` are pinned to commits, not branch tips; +- upmerge and backport PRs resolve to the base line; +- a PR can choose the backend and `cplace-e2e` branch explicitly; +- PRs that only change `e2e-tests/` run; +- spec selection follows the consumed packages through a caller-provided map; +- FE version drift between the backend's pins and the FE base is reported; +- the report says whether a failure is a build, infrastructure or test failure. + +Like Phases 7 and 8, this phase lands on `feature/fe-backend-e2e` before Phase 6 merges github-actions. §3 amends the Implementation +Approach line "pinned to the branch like every backend consumer". The nested `@release/2.0` refs inside the `cplace-gh-workflows` +composites stay mutable; this phase cannot change them, and the README says so. + +**Research**: See [Additional Research: Review hardening (Phase 9)](./research.md#additional-research-review-hardening-phase-9) + +### Changes Required: + +#### 1. Snapshot integrity (review item 1) + +**File**: `tools/scripts/artifacts/nx-project.ts`, `tools/scripts/artifacts/artifacts-handler.ts`, `.github/actions/artifacts/action.yml`, +`.github/workflows/fe-pr-snapshot.yml`, `tools/scripts/artifacts/artifacts-handler-pr-snapshot-outputs.test.ts` +**Changes**: +- `publish()` runs `npm publish --json`, keeps logging its stdout, and stores the `integrity` from the JSON in a public field + `publishedIntegrity`. +- `writePrSnapshotOutputs()` also writes `integrities`, a JSON object mapping each published `@scope/name` to its integrity. The artifacts + action and `fe-pr-snapshot.yml` expose it as an output (`{}` when nothing was published). +- jest: `integrities` lists exactly the published packages with their integrity; non-publishable projects are left out. + +**File**: `tools/scripts/backend-e2e/pin-snapshots.sh`, `tools/scripts/backend-e2e/pin-snapshots.bats`, +`.github/actions/backend-e2e-pin/action.yml`, `.github/workflows/fe-backend-e2e.yml` +**Changes**: +- New workflow input `SNAPSHOT_INTEGRITIES` (JSON object, default `'{}'`), passed to the pin action as `integrities` and to the script as + env `INTEGRITIES`. +- After each `npm i`, the script reads `.packages["node_modules/"].integrity` from that dir's `package-lock.json`. A value that differs + from the expected one fails with `::error::@ changed since this run's snapshot job (republished by a newer push); re-run on + the latest push`. +- A package without an expected integrity (an older caller) is pinned with a `::warning::` and not checked. +- bats: a match passes; a mismatch exits 1 and names the package; a missing entry warns; an empty `INTEGRITIES` warns once per package. + +#### 2. Branch and commit resolution (review items 3, 4, 9) + +**File**: `tools/scripts/backend-e2e/lib.sh`, `tools/scripts/backend-e2e/resolve-backend.sh`, `tools/scripts/backend-e2e/resolve-backend.bats` +**Changes**: +- `remote_branch_exists` becomes `remote_branch_sha `: it prints the commit of the exact `refs/heads/` line, with the + same retries and exit codes (0 found, 1 not found, 2 unreachable). +- `resolve_branch` picks, in this order: + 1. An explicit branch from env `BACKEND_BRANCH_OVERRIDE` / `E2E_BRANCH_OVERRIDE`, validated with `git check-ref-format --branch`. A missing + explicit branch fails with `::error::` (explicit missing is an error, PFM-ISSUE-34932). + 2. `HEAD_REF`, only when it is not `main`, `master` or `release/*`. An upmerge or backport head is never used as the backend line. + 3. The mapped base, with the existing release-to-master fallback. +- New outputs `backend_sha` and `e2e_sha`. +- bats: an upmerge head (`release/26.1` into `release/26.2`) resolves to `release/26.2`; a `main` head is ignored; an existing override wins + over a same-named branch; a missing override fails; an invalid override name fails; both SHAs are written. + +**File**: `tools/scripts/backend-e2e/pr-directives.sh` (new), `tools/scripts/backend-e2e/pr-directives.bats` (new) +**Changes**: reads env `PR_BODY` (passed through env, never interpolated into a script). It prints `BACKEND_BRANCH_OVERRIDE=` and +`E2E_BRANCH_OVERRIDE=` from lines matching `^backend-branch:[[:space:]]*(\S+)` and `^cplace-e2e-branch:[[:space:]]*(\S+)`; the +last match wins and the rest of the body is ignored. bats: no directive; both directives; a CRLF body; a directive inside other text is +ignored. Editing the PR body does not trigger a run; the README says to push or re-run. + +**File**: `.github/actions/backend-e2e-resolve/action.yml`, `tools/scripts/backend-e2e/fetch-manifests.sh`, +`tools/scripts/backend-e2e/fetch-manifests.bats`, `.github/workflows/fe-backend-e2e.yml` +**Changes**: +- The resolve action gets input `pr_body` (`github.event.pull_request.body`) and runs `pr-directives.sh` before the `branches` step. It + outputs `backend_sha` and `e2e_sha`. The summary shows ` @ ` and "(PR body)" when an override was used. +- `fetch-manifests.sh` takes `BACKEND_SHA` and `E2E_SHA` and fetches those commits (`git fetch --depth 1 origin `) instead of the + branch tips. +- build: `actions/checkout` uses `ref: ${{ needs.resolve.outputs.backend_sha }}`. +- e2e: after `clone-e2e-repo`, `tools/scripts/backend-e2e/checkout-commit.sh ` (new, with bats) runs + `git fetch --depth 1 origin ` and `git checkout --detach `, then fails unless `git rev-parse HEAD` equals ``. + +#### 3. SHA-pin the cplace-gh-workflows actions (review item 5) + +**File**: `.github/workflows/fe-backend-e2e.yml`, the `README.md` section from Phase 6 +**Changes**: +- Every `collaborationFactory/cplace-gh-workflows/.github/actions/*@release/2.0` becomes `@ # release/2.0`, at the release/2.0 commit + current when this phase is implemented (`f621b75326b963a5c4ffda6ff66b8ceba86259f6` on 2026-11-23). +- The README documents how to bump that SHA, and that the actions' nested `uses:` stay at `@release/2.0`. + +#### 4. FE version drift report (review item 6) + +**File**: `tools/scripts/backend-e2e/report-drift.sh` (new), `tools/scripts/backend-e2e/report-drift.bats` (new), +`tools/scripts/backend-e2e/fetch-manifests.sh`, `.github/actions/backend-e2e-resolve/action.yml`, `.github/workflows/fe-backend-e2e.yml` +**Changes**: +- `fetch-manifests.sh` also checks out `/.github/.frontend-upmerge-env` from the backend. +- `report-drift.sh `, with env `PACKAGES` and `FE_BASE`: + - For every dependency in `*/assets/package.json` that matches `FE_PACKAGE_PREFIXES` and is not in `PACKAGES`, it looks up the latest FE + base version with `npm view @ version --json`. The spec is the `snapshot` dist-tag for `main`/`master` and `X.Y` for + `release/X.Y`, the mapping of `version_spec_for` in `upmerge_and_bump_releases.sh`. + - It writes a Markdown table (package, backend pin, FE base latest, `behind`/`current`) to the step summary and outputs `drift`, the + number of packages behind. + - Report only: a failed `npm view` gives a `::warning::` naming the package, and the script exits 0. Without a prefixes file it writes one + notice and no table. +- The resolve action gets input `npm_token` (`ENV_CPLACE_ARTIFACTORY_TOKEN`) and writes a `chmod 600` `.npmrc` like the build job's auth + step. +- bats: current and behind; the release spec; an npm failure warns and exits 0; no prefixes file; a published package is excluded. + +#### 5. Run when `e2e-tests/` changed (review item 7) + +**File**: `tools/scripts/backend-e2e/resolve-consumers.sh`, `tools/scripts/backend-e2e/resolve-consumers.bats`, +`.github/actions/backend-e2e-resolve/action.yml`, `.github/workflows/fe-backend-e2e.yml` +**Changes**: +- The resolve action lists the PR's changed files with `gh api --paginate repos//pulls//files --jq '.[].filename'` and + `GITHUB_TOKEN`; the resolve job gets `permissions: pull-requests: read`. A failure to list the files fails the job, so the run never + skips silently. +- `resolve-consumers.sh` reads env `SPECS_CHANGED`; `true` (any path under `e2e-tests/`) sets `run=true` even when nothing consumed was + published. +- The build job's pin step runs only `if: needs.resolve.outputs.backend_packages != '[]'`, so a specs-only run builds the base pins and the + pin script never sees an empty version. +- bats: changed specs with nothing published give `run=true` with empty package arrays. + +#### 6. Package-to-spec map (review item 10) + +**File**: `tools/scripts/backend-e2e/resolve-specs.sh` (new), `tools/scripts/backend-e2e/resolve-specs.bats` (new), +`.github/actions/backend-e2e-resolve/action.yml`, `.github/workflows/fe-backend-e2e.yml`, `cplace-fe: .github/workflows/pull_request.yaml` +(trial branch only) +**Changes**: +- New workflow input `SPEC_MAP` (JSON object `{"@scope/pkg": "glob,glob"}`, default `'{}'`). +- `resolve-specs.sh` (env `E2E_SPECS`, `SPEC_MAP`, `CONSUMED` = backend and e2e packages) outputs `specs`: `E2E_SPECS` followed by the mapped + globs of the consumed packages, comma-joined, duplicates removed in order. Invalid JSON fails. +- Every use of `inputs.E2E_SPECS` in the workflow switches to `needs.resolve.outputs.specs`. Phase 4's copy step appends its `e2e-tests` + glob to that value. The summary lists the final filter. +- The trial caller passes a sample map. Phase 6 sets the real map per FE repo. +- bats: no map; a mapped package adds its globs; an unconsumed package is ignored; duplicate globs collapse; invalid JSON fails. + +#### 7. Classify the outcome (review item 14) + +**File**: `tools/scripts/backend-e2e/classify-outcome.sh` (new), `tools/scripts/backend-e2e/classify-outcome.bats` (new), +`.github/workflows/fe-backend-e2e.yml` +**Changes**: +- `report` gets `needs: [resolve, build, e2e]`. +- The script (env `BUILD_RESULT`, `E2E_RESULT`, `TESTS`, `FAILED`) writes `outcome` and a summary heading, one of: + - `build-failure`: build is not `success`. The text says the backend build failed, there is no test result, and names the backend branch + and SHA. + - `infrastructure-failure`: e2e is not `success` and `TESTS` is 0 (docker, startup or harness). + - `test-failure`: `FAILED` is above 0. + - `cancelled`. + - `passed`. +- The advisory warning and the final fail step use the category text. Phase 5's comment shows the same `outcome`. +- bats: one case per category; a build failure wins over a skipped e2e. + +### Success Criteria: + +#### Automated Verification: + +- [x] `bats tools/scripts/lockfile/ tools/scripts/backend-e2e/` passes, including the new and extended files +- [x] `shellcheck tools/scripts/backend-e2e/*.sh tools/scripts/backend-e2e/test-helper.bash` +- [x] `npx jest --config=./jest.config.js tools/scripts/artifacts/artifacts-handler-pr-snapshot-outputs.test.ts` +- [x] `actionlint .github/workflows/fe-backend-e2e.yml .github/workflows/fe-pr-snapshot.yml .github/workflows/pr-checks.yml` +- [x] `grep -n 'cplace-gh-workflows/.*@release/2.0' .github/workflows/fe-backend-e2e.yml` returns nothing +- [x] `grep -n 'inputs.E2E_SPECS' .github/workflows/fe-backend-e2e.yml` matches only the resolve step's input + +#### Manual Verification: + +The trial-PR checks of this phase are listed under [After the Last Push](#after-the-last-push). + +#### Implementation notes (2026-11-23) + +- The lockfile bats suite fails on a Windows checkout with `core.autocrlf=true` (CRLF in `test-helper.bash`); it passes from an LF export + and in CI. +- The e2e and report jobs do not check out github-actions, so the new scripts run through two composite actions next to + `backend-e2e-pin`: `backend-e2e-checkout-commit` (§2) and `backend-e2e-report` (§7, extended in Phase 11 §1). +- `resolve-backend.sh` now fails when the mapped base branch itself is missing, instead of passing a branch that does not exist to the + build. It also outputs `base_branch`, which `report-drift.sh` uses as `FE_BASE`. +- `report-drift.sh` reads `dependencies` only, like `discover_matching_deps` in `upmerge_and_bump_releases.sh`. +- §6's "Phase 4's copy step appends its `e2e-tests` glob" was implemented directly as Phase 11 §3: `resolve-specs.sh` adds the glob. +- §3: the README had no backend E2E section yet, so this phase adds "Backend E2E for FE PRs" with the PR-body directives and the SHA + bump; Phase 6 extends it. +- A node without specs uploads a `no-specs` marker, so Phase 11 §2's node count does not take it for a crashed node. + +--- + +## Phase 10: RCA of the advisory-mode failures + +### Overview + +Find the root cause of every spec that fails in the trial runs, so that `ADVISORY` is switched off on evidence. The output is a research +note, not code. + +### Changes Required: + +#### 1. RCA note + +**File**: `specs/2026-11-19_fe-pr-e2e-reusable-workflow/rca-advisory-failures.md` (new) +**Changes**: +- Collect the failing tests of trial run 44777680475 and the later trial runs from their `backend-e2e-results-*` artifacts. +- For each failing spec, compare it with the backend's own nightly E2E on the same branch (the same spec on the nearest nightly runs) and + classify it: + - fails on the nightly too (pre-existing); + - specific to this setup: a harness difference such as `config1`, the analytics strip, the node count, ordering under + `testIsolation: false`, or the SDK pins; + - caused by the PR; + - flaky: passes on a retry, or differs between runs. +- Give each a root cause with evidence (log lines, screenshots, run links) and an owner or action. +- End with the exit criteria for `ADVISORY: false`, for example no unexplained failure over N consecutive runs plus a quarantine list for + pre-existing failures, and the follow-up tasks. + +### Success Criteria: + +#### Manual Verification: + +- [ ] Every failing spec of the analysed runs has a category, evidence and an action. +- [ ] The note states measurable exit criteria for advisory mode and links the follow-ups. + +--- + +## Phase 11: Report script, crashed-node detection, advisory decisions + +### Overview + +Move the `report` job's comment logic into a tested script, detect nodes that crash before producing results, keep the in-repo specs +decision in one place, and record the advisory-mode and node-count decisions taken during the trial. This phase runs after Phase 9: it +extends `classify-outcome.sh` (Phase 9 §7) and `resolve-specs.sh` (Phase 9 §6). Like Phases 7–9, it lands on `feature/fe-backend-e2e` +before Phase 6 merges github-actions. + +### Changes Required: + +#### 1. Report builder script (review items [6.1], [6.3], [6.5]) + +**File**: `tools/scripts/backend-e2e/build-report.sh` (new), `tools/scripts/backend-e2e/build-report.bats` (new), +`tools/scripts/backend-e2e/fixtures/` (results JSON fixtures) +**Changes**: +- Input: path to the EnricoMi results JSON, env `OUTCOME` (from `classify-outcome.sh`), `ADVISORY`, and the output path for the comment + body. +- With jq it produces the Markdown body that the inline github-script builds today: the heading with verdict and `(advisory)`, the counts, + and the failure list (`states.failure` and `states.error`, the first message only, and the spec filename fallback when no spec is set), + capped at 20 items with an "and N more" line. +- Each failure's spec and test name is written inside a code span. Backticks, CR and LF are removed, and the result is truncated to 200 + characters with `…`. PR-controlled test titles therefore cannot inject links, Markdown or `@mentions`. +- It writes `tests` and `failed` (`tests_fail + tests_error`) to `$GITHUB_OUTPUT`. A missing or unreadable JSON fails with `::error::` + instead of falling back to zeros. +- bats, with fixtures: all passed; failures from both `failure` and `error`; the spec fallback; more than 20 failures; a title with + backticks, a newline, `@someone` and `[x](y)` comes out inside one code span; an over-long title is truncated; missing JSON fails. + +**File**: `.github/workflows/fe-backend-e2e.yml` +**Changes**: +- `report` runs `build-report.sh`. The github-script step only reads the body file and upserts the marker comment. +- The jq "advisory warning" step and its `2>/dev/null || echo "0 0"` fallback are deleted. `classify-outcome.sh` receives `TESTS` and + `FAILED` from `build-report.sh`'s outputs, and the advisory warning uses the outcome text. + +#### 2. Crashed-node detection (review item [6.2]) + +**File**: `tools/scripts/backend-e2e/classify-outcome.sh`, `tools/scripts/backend-e2e/classify-outcome.bats`, +`.github/workflows/fe-backend-e2e.yml` +**Changes**: +- `report` counts the downloaded `backend-e2e-results-*` artifacts and passes `NODES` (the length of `needs.resolve.outputs.node_indexes`) + and `NODES_REPORTED` to the classifier. +- `NODES_REPORTED < NODES` gives `infrastructure-failure`, with text naming how many nodes produced no results, even when the other nodes + passed. A test failure still wins when `FAILED > 0`, and both facts are shown. +- This applies in advisory mode too, so `continue-on-error` cannot hide a crashed node. +- bats: 2 of 2 reported and passing gives `passed`; 1 of 2 reported and passing gives `infrastructure-failure`; 1 of 2 reported with + failures gives `test-failure` with the missing-node line. + +#### 3. One in-repo specs decision (review item [6.4]) + +**File**: `.github/workflows/fe-backend-e2e.yml`, `tools/scripts/backend-e2e/resolve-specs.sh`, +`tools/scripts/backend-e2e/resolve-specs.bats`, `.github/actions/backend-e2e-resolve/action.yml` +**Changes**: +- The `resolve` job exposes `in_repo_specs` (the existing `hashFiles('fe-repo/e2e-tests/**') != ''`) as a job output. +- In `e2e`, the "Check out the FE repo's in-repo specs" and "Add the in-repo specs" steps run only + `if: needs.resolve.outputs.in_repo_specs == 'true'`. The copy step only copies; its `[[ -d fe-repo/e2e-tests ]]` branch is removed. +- `resolve-specs.sh` reads env `IN_REPO_SPECS` and `FE_REPO`. When `IN_REPO_SPECS` is `true`, it appends + `cypress/e2e//**/*.spec.ts` to `specs`. This amends Phase 9 §6, where the copy step appended the glob. +- bats: `IN_REPO_SPECS=true` appends the glob once; `false` leaves the filter unchanged. + +#### 4. Sample spec header (review item [6.8]) + +**File**: `cplace-fe: e2e-tests/platform/startPage.spec.ts`, `cplace-fe: e2e-tests/README.md` (trial branch) +**Changes**: +- Remove the `// Test document: ` line. +- The README says to add `// Test document: ` under the copyright header when a cplace test document exists for the spec, following + the `cplace-e2e` convention. + +#### 5. Record advisory mode and the trial node count (review items [6.7], [6.9], [6.10]) + +**File**: `specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md`, `specs/2026-11-19_fe-pr-e2e-reusable-workflow/design.md` +**Changes**: +- plan.md Implementation Approach, Interface: add `ADVISORY` (boolean, default `false`) to the workflow inputs with an + "Amended 2026-11-23 (Phase 11)" line. When it is `true`, the e2e nodes get `continue-on-error`, the JUnit check uses `fail_on: nothing`, + and the final fail step is skipped. The report still shows the outcome. +- The same amendment records that the trial caller runs with `ADVISORY: true` and `NODES: '2'` (two nodes keep the run under the + 60-minute job timeout), and that the Phase 6 rollout callers start with `ADVISORY: true` and switch to `false` when Phase 10's exit + criteria are met. +- design.md decision 10: add an amendment line saying advisory mode suspends "the job fails on any failed test" until Phase 10's exit + criteria are met. + +### Success Criteria: + +#### Automated Verification: + +- [x] `bats tools/scripts/lockfile/ tools/scripts/backend-e2e/` passes, including `build-report.bats` and the extended + `classify-outcome.bats` and `resolve-specs.bats` +- [x] `shellcheck tools/scripts/backend-e2e/*.sh tools/scripts/backend-e2e/test-helper.bash` +- [x] `actionlint .github/workflows/fe-backend-e2e.yml` +- [x] `grep -n 'jq -r .\.stats' .github/workflows/fe-backend-e2e.yml` returns nothing +- [x] `grep -n 'fe-repo/e2e-tests ]]' .github/workflows/fe-backend-e2e.yml` returns nothing +- [x] `grep -n 'placeholder' ../cplace-fe/e2e-tests/platform/startPage.spec.ts` returns nothing +- [x] Review findings [6.1], [6.2], [6.3], [6.4], [6.5], [6.7], [6.8], [6.9], [6.10] marked resolved in review.md. Ticking this item means + editing each finding's `- [ ] Resolved` line in review.md to `- [x] Resolved — `. + +#### Manual Verification: + +The trial-PR checks of this phase are listed under [After the Last Push](#after-the-last-push). + +#### Implementation notes (2026-11-23) + +- §1 and §2 as written form a cycle: `build-report.sh` takes `OUTCOME` from `classify-outcome.sh`, which takes `TESTS` and `FAILED` from + `build-report.sh`. `build-report.sh` counts once and then runs `classify-outcome.sh` with those counts; both scripts keep their + documented env and outputs, and the `backend-e2e-report` action runs only `build-report.sh`. +- §2 counts the `backend-e2e-results-*` subdirs that `download-artifact` writes without `merge-multiple`, and passes `inputs.NODES` + (validated by `node-indexes.sh`) as `NODES`. The JUnit glob became `test-results/*/junit/**/*.xml`. +- The comment adds an `****: ` line and the resolved commits; table values go through the same code-span cleaning as + test names, since a branch from the PR body may contain a backtick. + +--- + +## Testing Strategy + +### Unit Tests: + +- **jest** (`tools/scripts/artifacts/artifacts-handler-pr-snapshot-outputs.test.ts`): output names and values for PR snapshots; empty list; + non-publishable libs excluded; no outputs for main snapshots. +- **bats** (`tools/scripts/backend-e2e/*.bats`, with `npm` and `git` stubbed on `PATH`): + - **Repo mapping:** every `case` arm, plus the unknown-repo error. + - **Base mapping:** `main`, `master`, `release/X.Y`, `release/X.Y-beta` with and without a target, an unknown base. + - **Branch existence:** exact match only, retries, unreachable fails, missing falls back with a warning. + - **Consumed detection:** `dependencies` and `devDependencies`, missing manifest, empty or blank `PACKAGES`. + - **Pinning:** only consumed packages, one npm call per dir, npm failure propagates, summary lines. + - **Glob expansion:** multi-dir match, no match fails, blank patterns ignored. + - **Node indexes:** empty, non-digit, zero, leading zero and negative rejected; `1` and `3` produce the expected arrays. + +### Integration Tests: + +On the trial cplace-fe PR: +- the skeleton run; +- the skip run; +- same-named vs base branches; +- the SDK bump; +- the in-repo sample spec, passing and failing; +- comment upsert and minimize; +- concurrency cancel. + +### Manual Testing Steps: + +1. Push a cf-platform change to the trial PR. Check the summary, the lock contents in the build log, the check and the comment. +2. Push a README-only change. `backend-e2e` should be green with only `resolve` run. +3. Push a same-named `cplace-e2e` branch and re-run. The summary should show it. +4. Break `TC01`. The check, the comment and `pr-checks` should fail. Revert. +5. Push twice quickly. The first `backend-e2e` should be cancelled. + +## After the Last Push + +These checks need pushes to the trial PR (cplace-fe `feature/fe-backend-e2e-trial`). Record each outcome in the trial PR's description. + +- Phase 9: the resolve summary shows the backend and `cplace-e2e` ` @ `, the drift table and the final spec filter, and the + snapshot job's outputs include `integrities`. +- Phase 9: two quick pushes; a run that pins after the next push republished the snapshot fails with the integrity error instead of + testing mixed content. +- Phase 9: a `backend-branch: ` line in the PR body plus a re-run uses that branch; a missing branch fails `resolve`. +- Phase 9: a push that changes only `e2e-tests/` runs build and e2e without pins. +- Phase 9: a deliberately broken backend branch, chosen through the override, makes `report` show `build-failure`; a broken assertion + shows `test-failure`. +- Phase 11: the marker comment matches the earlier format, and a failing test with Markdown in its title shows as plain code. +- Phase 11: cancelling one e2e node mid-run makes `report` show `infrastructure-failure` naming the missing node, with `ADVISORY: true` + set. +- Phase 11: a push without `e2e-tests/` changes in a repo that has no `e2e-tests/` skips both in-repo steps in `e2e`. + +## Performance Considerations + +- One gradle build per run (~30 min measured in IAP on `ubicloud-standard-4`). Nodes skip gradle entirely, because the bundle replaces the + per-node `distZip`. +- Default nodes: cplace-fe 3, cplace-paw-fe 2. Phase 2 measures this, and the final values are set in Phase 6. +- Every PR push publishes snapshots to `cplace-npm-local` (accepted in the design). `fe-cleanup-snapshots.yml` and `fe-pr-close.yml` stay + responsible for cleanup. +- Per-PR `cancel-in-progress` keeps at most one run per PR. + +## Migration Notes + +- Additive for other `fe-pr-snapshot.yml` callers: `REQUIRE_SNAPSHOT_LABEL` defaults to `true`, and the new outputs are ignored. +- Merge order: + 1. github-actions (`master`). + 2. The secrets provisioned. + 3. The cplace-fe and cplace-paw-fe rollout PRs. + 4. Branch protection: `PR Checks` is already the required check, so no ruleset change is needed. +- Rollback: remove `backend-e2e` from `pr-checks.needs` in the FE repos. The workflow can stay in github-actions unused. +- Upstream drift (risk 4): the workflow pins `cplace-gh-workflows` actions to a release/2.0 commit SHA (Phase 9 §3). The actions' own + nested `uses:` stay at `@release/2.0`, so a breaking change there can still show up as a `backend-e2e` failure in FE PRs. The README + section names that dependency and how to bump the SHA. + +## References + +- Research: [Research Document](./research.md) +- Design: [Design Document](./design.md) +- Original ticket: none +- Backend per-node flow: `cplace-gh-workflows@release/2.0: .github/workflows/reuseable-e2e-cypress.yml` +- Backend build stages: `cplace-gh-workflows@release/2.0: .github/workflows/build.yml` +- Bump recipe: `cplace-gh-workflows@release/2.0: src/scripts/upmerge_and_bump_releases.sh` (`bump_plugin`) +- Output test pattern: `tools/scripts/artifacts/artifacts-handler-release-flow.test.ts` +- Bats pattern: `tools/scripts/lockfile/check-lockfile.bats`, `tools/scripts/lockfile/test-helper.bash` +- App token and cross-repo checkout: `cplace-fe: .github/workflows/devkit-test-template.yaml:88-136` +- Branch resolution rules: `cplace-gh-workflows/specs/2026-09-28_PFM-ISSUE-34932_e2e-branch-remote-unreachable/` diff --git a/specs/2026-11-19_fe-pr-e2e-reusable-workflow/research.md b/specs/2026-11-19_fe-pr-e2e-reusable-workflow/research.md new file mode 100644 index 0000000..0b853e7 --- /dev/null +++ b/specs/2026-11-19_fe-pr-e2e-reusable-workflow/research.md @@ -0,0 +1,232 @@ +--- +date: 2026-11-19T19:18:05+01:00 +git_commit: 3e8a45b364d0e9f6aae577fe230a0f85be09791c +branch: master +topic: "Reusable workflow to run real-backend Cypress E2E on frontend PRs (cplace-fe, cplace-paw-fe) using the PR's npm snapshots" +tags: [research, ci, github-actions, e2e, cypress, docker, npm-snapshot, cplace-gh-workflows, cplace-integration-all-products, cplace-e2e] +status: complete +last_updated: 2026-11-19 +--- + +# Research: Reusable workflow to run real-backend Cypress E2E on frontend PRs + +**Date**: 2026-11-19T19:18:05+01:00 +**Git Commit**: 3e8a45b364d0e9f6aae577fe230a0f85be09791c (github-actions) +**Branch**: master + +Repos inspected (all under `C:\Users\SenthanalSirpiManoha\cplace-dev\repos7\`): `github-actions`, `cplace-gh-workflows` (local `master`; consumers pin `@release/2.0`, read via `git show origin/release/2.0:`), `cplace-integration-all-products` (IAP), `cplace-e2e`, `main` (= backend repo `cplace`), `cplace-paw`, `cplace-fe`, `cplace-paw-fe`, `cplace-project-planning-fe`, `cplace-staging-builds`, `cplace-resource-management`, `cplace-forms-wizard`. + +Ref legend: **RB** = `cplace-gh-workflows@origin/release/2.0`; **FB** = `cplace-gh-workflows@origin/feature/PFM-ISSUE-33733-Automate-Integration-E2E-Tests-on-PRs`; **IAP** = `cplace-integration-all-products@master`. + +## Research Question + +Today, verifying a frontend change against a real cplace means writing Cypress specs in `cplace-e2e` in a separate PR that is not part of the frontend PR pipeline. Goal: a reusable GitHub workflow in `github-actions` (called from FE `pull_request.yaml` like `code-quality`) that + +1. finds the backend repo for the FE repo by naming pattern (`cplace-fe` → `cplace`, `cplace-paw-fe` → `cplace-paw`), +2. updates the relevant `@cplace-*` npm dependencies in the backend repo to the PR's snapshot versions (e.g. the `published-artifacts` comment on cplace-fe#3058), +3. builds/deploys the backend in docker and serves a cplace instance, +4. runs Cypress specs from `cplace-e2e` or from a folder in the FE repo against it, +5. collects results and fails the PR on any failing test. + +Prior art to analyze: the `/run-e2e-tests` solution used on cplace-integration-all-products#536. + +### User decisions captured during research + +| Topic | Decision | +|---|---| +| Relation to existing `/run-e2e-tests` orchestrator | Research both (standalone in github-actions vs. extending orchestrator); decide in design | +| Backend production | Both, per input: default prebuilt image + FE overlay; build from source when matching backend branch exists | +| Trigger | Every PR, required check | +| Spec source | cplace-e2e (matching branch), in-repo folder, explicit spec filter, full suite — all supported | +| Research location | `github-actions/specs/` (no PFM ticket) | + +## Summary + +- **No existing mechanism tests a frontend PR against a real backend.** FE PR E2E (`github-actions/.github/workflows/fe-e2e.yml`) is Storybook + mocks only. The `/run-e2e-tests` orchestrator only swaps *git branches* in `parent-repos.json`; FE repos are not entries there, so a FE PR run is `matched=false` and silently tests the base. No step in cplace-gh-workflows or IAP overrides `@cplace-*` npm versions. +- **Every building block except the npm override exists**, mostly in RB: backend build (`build.yml`), docker compose with cplace + Elasticsearch (`main/docker/e2e`, `create_and_run_cplace_docker*.sh`), readiness wait, cplace-e2e clone with branch resolution, spec glob sharding, `cypress-repeat` runner, JUnit publish, report comment + marker pattern, GitHub App tokens. +- **The npm override has a proven recipe**: nightly `frontend-upmerge` `bump_plugin` runs `npm i @ --save-exact --legacy-peer-deps` in each `/assets` (updates package.json + lock). Insert this between clone and build with the PR snapshot version. +- **Snapshot version is deterministic** (`0.0.0--`), but **publishing is opt-in via the `snapshot` label, runs in a separate workflow, only publishes affected projects, and exposes no outputs**. "Every PR, required check" therefore needs a change to how/when snapshots are published. +- **Prebuilt-image mode exists only on FB (PR #306) and is incompatible with current master images** (they require external Elasticsearch). No prebuilt E2E image is consumed by any test run today; images from `cplace-staging-builds` are product images. +- **FE in-repo `apps/*-e2e` specs cannot target a real backend** (all Storybook, `*.cy.ts`, mocks). "Specs in the FE repo" needs a new folder convention executed inside the cplace-e2e harness. +- **Cost**: one IAP E2E run ≈ 30 min build + 8 nodes × 22–32 min ≈ 4.5 vCPU-h, ~66 min wall-clock. Running on every FE PR requires a much smaller default footprint (fewer nodes, build once, targeted specs). + +## Detailed Findings + +### 1. Current frontend PR pipeline (github-actions) + +- Consumers call `collaborationFactory/github-actions/.github/workflows/.yml@master`; inputs UPPER_CASE strings, secrets passed explicitly. +- cplace-fe `pull_request.yaml`: `install-deps` → `build`, `code-quality`, `e2e` → `pr-checks` (jq aggregator; a new job must be added to `needs:` to gate merges). Identical shape in cplace-paw-fe (`fe-pr.yml`) and cplace-project-planning-fe (`fe-pr.yml`). No repo sets `concurrency` (template `workflow-templates/fe/fe-pr.yml:13-16` does). +- Caching: `actions/cache` on `**/node_modules`, key `${{ runner.os }}-modules-${{ hashFiles('**/package-lock.json') }}` (`fe-install-deps.yml:25-30`). Downstream jobs restore it. +- `GHA_REF` = `pull_request.head.ref` (branch name, not SHA); `GHA_BASE` = base ref. `run-many` (`tools/scripts/run-many/run-many.ts`) computes nx affected and round-robin shards. +- `fe-e2e.yml`: `cypress/browsers:24.22.1` container, 4 shards, `nx run-many --targets=e2e -c ci`; every e2e project uses `@nx/cypress:cypress` with a Storybook `devServerTarget` (e.g. `cplace-fe/apps/cf-frontend-sdk-e2e/project.json:20-38`, baseUrl `localhost:4409`). **No real backend.** +- Secrets in use: `DOT_NPMRC`, `JFROG_*`, `SONAR_CLOUD_TOKEN`, `PERCY_TOKEN`, `GIT_USER*`, `SVA_ACTIONS_READ_PRODUCT_FE_CLIENT_ID/_KEY` (read App), `SVA_ACTIONS_WRITE_PRODUCT_FE_*`, `ENV_CPLACE_ARTIFACTORY_ACTOR/TOKEN` (cplace-fe devkit only). Unverified whether paw-fe/pp-fe have the App/artifactory secrets. +- Closest cross-repo precedent: `cplace-fe/.github/workflows/devkit-test-template.yaml:88-115` — mints `actions/create-github-app-token@v3.3.0` (client-id, `repositories:`, `permission-contents: read`), checks out `collaborationFactory/cplace`. + +### 2. PR snapshot publishing + +- Caller: `cplace-fe/.github/workflows/pull_request_snapshot.yaml` (paw/pp: `fe-pr-snapshot.yml`) → `github-actions/.github/workflows/fe-pr-snapshot.yml@master`. Triggers `pull_request: [labeled, synchronize, reopened]` (not `opened`); job gated by `contains(labels, 'snapshot')` (`fe-pr-snapshot.yml:21`). Runs in parallel to `pull_request.yaml`, own checkout + `npm ci` + build. +- Version: `github-actions/tools/scripts/artifacts/utils.ts:315-319` + ```ts + return `-${branch.substring(0, 50).replace(/[^0-9A-Za-z-.@]/g, '-')}-${prNumber}`; + ``` + → `0.0.0--`, `currentBranch = GITHUB_HEAD_REF` on PR events (`utils.ts:284-299`). Dist-tag `latest-pr-snapshot` (`nx-project.ts:~357`). Main snapshots: `0.0.0-SNAPSHOT--`, tag `snapshot` (`utils.ts:311-312`). +- Packages: affected only (`artifacts-handler.ts:31,187-204`); `*-e2e` apps dropped unless they have `src/public_api.ts`; `api-*` dropped; libs only if `"publishable": true` (`nx-project.ts:52-63`). Scope = root package.json name: `@cplace-next` (cplace-fe), `@cplace-paw-fe`, `@cplace-project-planning-fe`. +- Re-publish: unpublish same version then publish (`artifacts-handler.ts:164-168`) → brief window where the version does not exist; consumers must poll. +- Comment: `githubCommentsForPR.txt` → github-script upserts a comment with marker `` (`fe-pr-snapshot.yml:75-89`), one `@scope/name@version` per line; default text "No snapshots of projects have been published (probably no project is affected)". +- **Downstream knowledge**: version recomputable from `github.head_ref` + `github.event.number`; package list **not** exposed as output. Options: parse comment, re-run affected query, add `$GITHUB_OUTPUT` in `artifacts-handler.ts` + `outputs:` on `fe-pr-snapshot.yml` (cleanest), or `npm view` against JFrog. +- **Ordering**: separate workflow → no `needs:`. Options: call `fe-pr-snapshot.yml` as a job inside `pull_request.yaml`; `workflow_run` trigger; or poll registry/comment. + +### 3. Backend consumption of FE packages + +| FE repo (default) | npm scope | Backend repo | Pinning file(s) | +|---|---|---|---| +| cplace-fe (`main`) | `@cplace-next` | cplace (`main/`) | `cf.cplace.platform/assets/package.json:20-22` (`cf-frontend-customization`, `cf-platform`, `cf-shell`) | +| cplace-paw-fe (`master`) | `@cplace-paw-fe` | cplace-paw | `cf.cplace.landingPage`, `cf.cplace.lowCodeWidgets`, `cf.cplace.training.extended`, `cf.cplace.userpilot` `/assets/package.json` | +| cplace-project-planning-fe (`master`) | `@cplace-project-planning-fe` | cplace-project-planning (not checked out) | `cf.cplace.gantt/assets/package.json` | +| cplace-resource-management-fe | `@cplace-resource-management-fe` | cplace-resource-management | `cf.cplace.resourceManagement/assets/package.json` | +| cplace-forms-wizard-fe | `@cplace-forms-wizard-fe` | cplace-forms-wizard | `cf.cplace.formsWizard/assets/package.json` | + +- Naming pattern `-fe` → `` holds except `cplace-fe` → `cplace` (local dir `main`). Each FE package is consumed at runtime by exactly one backend repo. `@cplace-next/*` also appears in other FE repos' root package.json (build-time FE→FE), not in their backends. +- Pins are exact; `package-lock.json` next to each with `resolved` + `integrity` (`main/cf.cplace.platform/assets/package-lock.json:173-177`); `.npmrc` `save-exact=true`. Editing package.json alone is insufficient — regenerate lock. +- Registry auth in CI: `cplace-gh-workflows/src/scripts/setup_npmrc.sh:9-29` (`cplace-npm` virtual repo, `ENV_CPLACE_ARTIFACTORY_*`). Note FE snapshots are published to `cplace-npm-local` (`github-actions/tools/scripts/artifacts/configuration.ts`); the backend reads via the virtual `cplace-npm` (to verify it aggregates local). +- Install happens inside gradle/cplace-asc (`build_distribution.sh:42`, `-PgeneratePackageJson=true`; `build_cplace_asc.sh:19-36`). Whether it uses `npm ci` or `npm install` is unverified (no plugin source locally); assume lock is honoured. +- **Bump recipe** (RB `src/scripts/upmerge_and_bump_releases.sh`): `discover_matching_deps` (`:173-185`, jq on `.dependencies` matching `^(FE_PACKAGE_PREFIXES)/`), `bump_plugin` (`:224-251`, `npm i pkg@spec --save-exact --legacy-peer-deps` in `/assets`), loop `*/assets/package.json` (`:287-320`), allowlist `^([^/]+/assets/)?(package|package-lock)\.json$` (`:93-96`). Prefixes in `/.github/.frontend-upmerge-env` (`FE_PACKAGE_PREFIXES=@cplace-next` in main, `@cplace-paw-fe` in cplace-paw; resource-management/forms-wizard have none). `version_spec_for` (`:158-171`) maps `master|main` → `snapshot`, `release/X.Y` → `X.Y`. +- Alternative tooling: `cplace-fe/libs/cf-devkit/src/lib/commands/integrate/` (`integrate.service.ts:271-281`, `utils/package-installer.ts:168`) — dev-oriented, opens PRs; `--skipPullRequest` exists. +- **Only bump packages the PR actually published** (affected-only publishing); blanket bump → `notarget`. +- Parent repos: `cplace-paw/parent-repos.json` = `main@master` only; resource-management/forms-wizard list more. Parents are cloned (`cplace-cli repos --clone --depth 1`) and their assets built (`buildParentReposResources`). Hence a cplace-fe override when building cplace-paw would mean bumping `../main/cf.cplace.platform/assets`. +- Branch mapping: FE `main`/`master` → BE `master`; `release/X.Y` → `release/X.Y`; `release/X.Y-beta` (cplace-fe only) → no BE counterpart. + +### 4. Existing `/run-e2e-tests` solution (cplace-gh-workflows RB + IAP) + +Flow: PR comment → consumer `slash-commands.yml` (IAP: gated by `vars.CB_SLASH_COMMANDS_ENABLED`, OWNER/MEMBER/COLLABORATOR, `:19-27`) → RB `slash-command-router.yml:95-105` → `run-e2e-tests-command.yml` (parses ```` ```yaml ```` params via `parse_slash_command_parameters.sh`; mints `SVA_CONTAINER_BUILD_BOT` token; `command_run_integration_e2e_dispatch.sh:93-111` dispatches with retry) → IAP `integration-e2e-orchestrator.yml` (concurrency `integration-e2e--`) → RB `integration-e2e-orchestrator.yml`: + +1. validate inputs (`:82-111`); 2. derive test branch `e2e//pr-` (`functions.sh:276-282`); 3. cancel previous runs; 4. sparse-checkout source `parent-repos.json` (`:132-150`); 5. reset test branch to `integration_branch || base_branch` (`integration_e2e_prepare_branch.sh`); 6. `merge_parent_repos.sh` — source entries replace target, source's own entry (matched by url basename) gets PR head branch, outputs `source_matched`; 7. commit + force-push; 8. dispatch `commit.yml`, `e2e-cypress.yml`, `e2e-cypress-feature-toggle.yml` (`integration_e2e_dispatch_workflows.sh:79-93`, run IDs parsed from `gh workflow run` output); 9. upsert draft test PR authored by `SVA_CONTAINER_BUILD_BOT` with marker ``; 10. status comment via `SVA_ACTIONS_PR_WRITER`. `cleanup` action on PR close. + +Reporting: trailing `report` job in each IAP run (`if startsWith(ref_name,'e2e/')`, serialized per branch) → `integration-e2e-reporter.yml` → `integration_e2e_report.sh` reads marker, renders run table, minimizes older comments (`minimizeComment`). + +**FE support: none.** FE repos aren't IAP `parent-repos.json` entries → `matched=false` warning (`integration_e2e_report.sh:214-216`); no npm input. + +PR #536 evidence: three triggers; test PR #551 (`e2e/cplace-integration-all-products/pr-536`); 2026-11-10 runs all failed in `build` (~12–24 min) before Cypress: `npm error notarget No matching version found for @cplace-assets/cplace@27.1.999` — the `X.Y.999` feature-branch version rewrite (`rewrite_versions_for_customer_and_feature_branches.sh`) is not propagated to inter-repo npm deps. **Lesson: a FE PR flow must own npm pinning and must not rely on the 999 rewrite.** + +### 5. E2E engine (RB) + +- `e2e-cypress.yml`: `build` (→ `build.yml`, `do_upload: true`, `:52-59`) → `setup-matrix` (`CB_E2E_NUMBER_OF_NODES`, IAP = 8) → `e2e-cypress` matrix (`fail-fast: false`) → `collect-and-publish-e2e-test-results` (merged HTML to gh-pages) → Slack (cron only) → `delete_build_cache`. +- `build.yml:62-186`: load env (`.github/.build-env` + `.github/.-env`, `<>` placeholders) → JDK 21 + `setup_npmrc.sh` → `prepare-parent-repos` → optional `rewrite-package-lock-json-files` → optional 999 rewrite → `build-parent-repos` → `build-distribution` → persist workspace (Ubicloud/GH cache). **Insertion point for npm override: after `prepare-parent-repos`, before `build-parent-repos`/`build-distribution`.** +- `reuseable-e2e-cypress.yml` per node (`:68-232`): runner `vars.E2E_MEDIUM_RUNNER || vars.MEDIUM_RUNNER || inputs.runner`; Chrome pinned 157.0.8103.78; attach cache; `prepare-git-environment` (read App + `cplace-e2e`); `clone-e2e-repo`; `calculate_e2e_specs_for_node.sh` (`:116-123`); per-node `./gradlew distZip -x copyResources -x gzAssets` (`:125-134`); strip `cf.cplace.analytics` (`:136-140`); `create_and_run_cplace_docker.sh` (`:142-150`); `wait_for_cplace_startup.sh` (`:152-158`); optional self-provided tests (`:166-170`); Cypress (`:172-182`); upload `test_results-N`, `cplace-logs-e2e-N`, JUnit check "Test Results E2E" via `EnricoMi/publish-unit-test-result-action` (`:196-232`). No `timeout-minutes` anywhere. +- Docker (`create_and_run_cplace_docker.sh:32-44`): if `../main/docker/e2e/docker-compose.yml` exists → `create_and_run_cplace_docker_compose.sh` (cplace container `main` + single-node ES `${CB_E2E_ES_VERSION:-8.19.x}`, health-gated); else `docker build` + `docker run -d --name main -p 8083:8083 -e E2ETOKEN=hIF9Z97RZiYm …`. Image: `azul/zulu-openjdk-alpine:21`, unpacks `software.zip`, embedded HSQLDB, fixed license env, `ACTIVATED_PLUGINS`, context `/intern/tricia/`; `startup.sh` aborts without `ES_HTTP_ADDRESSES`. Image is local only, never pushed. +- Contract to keep (from `main/specs/2026-09-28_PFM-ISSUE-28989_adapt-e2e-docker-setup/design.md`): container name `main`, host port = container port 8083, token `hIF9Z97RZiYm`, logs `/app/data/log`, properties at `/app/properties` from `main/e2eConfigurations/config1/properties`; logs via `docker compose -p cplace-e2e logs`. +- Readiness: poll `/intern/tricia/applicationStatus.txt` → 200, then `administrationDashboard/listPlugins?testSetupHandlerE2EToken=…` → JSON; 5 s interval, `CB_E2E_WORKFLOW_WAIT_TIMEOUT=300`. +- Cypress (`run_e2e_cypress_test_suite.sh:37-41` RB): `npm install --legacy-peer-deps; npx cypress-repeat run -n 3 --rerun-failed-only --spec "" --browser chrome` (master: `-n 2`). The `BASE_URL` input is passed but unused; `cypress.config.ts` baseUrl `localhost:8083` applies. +- Runtime measured (IAP run 44547870980, release/26.2, success): build ~30 min on `ubicloud-standard-4`; 8 nodes × 22–32 min on `ubicloud-standard-8` (each node rebuilds distZip + image + boots ES/cplace); ~66 min wall-clock, ≈4.5 vCPU-h. Runners: Ubicloud managed. +- **Pull-image mode (FB only, PR #306)**: `docker_image` input skips `build` and per-node distZip; `docker/login-action` to `cplace.jfrog.io` (`ENV_[TEST_]CPLACE_ARTIFACTORY_DOCKER_*`); `pull_docker_image()`; `derive_e2e_branch_from_image.sh` maps `/e2e//` → `release/X.Y`. Image format `cplace.jfrog.io/cplace-product-registry/e2e//:`, produced by `cplace-staging-builds` (`/container-build`). Predates compose/ES → runs single container; incompatible with current master images. Related open PRs #274 (PFM-ISSUE-33733 "Automate Integration E2E tests on PRs") and #206 (`/e2e-run`) touch the same scripts. +- Required secrets for E2E path: `ENV_CPLACE_ARTIFACTORY_ACTOR/TOKEN`, `SVA_ACTIONS_READ_PRODUCT_ID/KEY`, (pull mode) `ENV_CPLACE_ARTIFACTORY_DOCKER_*`, `UBICLOUD_*`, plus suite secrets referenced in env files (Jira, SharePoint, Userpilot). + +### 6. cplace-e2e + +- Single root `cypress.config.ts`: `baseUrl: 'http://localhost:8083/'` (`:61`), `specPattern: 'cypress/**/*.spec.ts'` (`:62`), `testIsolation: false`, multi-reporter junit (`test-results/junit/…`) + mochawesome (`:65-84`), flaky-attempt handling in `after:spec` (`:35-50`). No `retries` (runner provides). Cypress `^13` (cplace-fe uses 15.8.0). Node 24.22.1. +- Layout: `cypress/e2e//specs/**` (cplace 137, project-planning 486, resource-management 86, board 31, paw 18 …), `cypress/e2e_toggle/` (cplace 353, paw 17, pp 10), `cypress/e2e_jira/cplace-jira` (63). Support in `cypress/support/` (TestSetupHandler login `setup.ts:6-10,46-48`, `config.ts:8-13` derives URLs from `Cypress.config('baseUrl')` + `/intern/tricia/`). +- Selection is path-glob only; no tags (`@cypress/grep` absent). Spec filter contract (`calculate_e2e_specs_for_node.sh:27-73,97-103`): comma-separated globs, leading `*` added, `find -wholename`, round-robin by `i % NODES_TOTAL`; empty or `**` = all `*.spec.ts`. IAP defaults: `cypress/e2e/**/*.spec.ts` (`.e2e-cypress-env:25`), `cypress/e2e_toggle/**/*.spec.ts` (`.e2e-cypress-feature-toggle-env:29`), jira subset. +- Own CI: lint + `tsc` only (`continuous-integration.yml`); nightly `frontend-upmerge.yml` bumps FE pins. +- Branches: `master`, `release/NN.M`; features `improvement/`, `fix/`, `feature/`, `e2e/`. Branch resolution (`determine_e2e_branch.sh:10-37`): explicit input (missing → **fail**) else `release/` else `master` (warning). Uses `./gradlew properties` → needs a gradle project; FE repos have none. "Matching branch with fallback" requires an own `git ls-remote --heads` pre-check (exact `refs/heads/` match; retry; see PFM-ISSUE-34932 rules). +- FE package dependence: exact pins of `@cplace-next/cf-e2e-testing-sdk` (imported by 199 files / 75 specs; registers commands in `cypress/support/e2e.ts:13`), `cf-ai-companion-e2e`, `cf-ai-usage-e2e`, `cf-cleanup-page-e2e`, `cf-comments-widget-e2e`, `cf-data-model-types-e2e` (18 specs), `cf-system-groups-e2e` (exports full test bodies, `allRegisteredUsers.spec.ts:23-26`), plus paw-fe/pp-fe/rm-fe/workflow-fe SDKs. **A FE PR that changes these packages needs them bumped in the cloned cplace-e2e too**; otherwise base pins suffice. +- Self-provided tests hook: `CB_E2E_RUN_SELF_PROVIDED_TESTS` / `CB_E2E_SELF_PROVIDED_TESTS_PATH=e2e-tests` → `move_own_e2e_tests.sh:116-118` (`mv cplace-e2e/cypress/e2e`). Broken for reuse: specs are calculated (`:116`) before the move (`:166`), and `mv` nests to `cypress/e2e/e2e-tests/`. Disabled everywhere. + +### 7. FE in-repo E2E + +- cplace-fe: 23 `apps/*-e2e` projects, all Storybook (ports 4400/4402/4409/4415/4432), `*.cy.ts`, `getE2EConfig()` from `@cplace-next/cf-e2e-testing-sdk/config`; only `/intern/tricia` URL is a mock (`apps/cf-ai-companion-1-e2e/src/integration/ai-sidebar.advanced-search.cy.ts:39`). Published via `@nx/js:tsc` on `src/public_api.ts` as `@cplace-next/`. +- cplace-paw-fe: `cf-landing-page-lib-e2e` (4401), `cf-training-extended-lib-e2e` (4400) — Storybook only. +- **Implication**: "specs in the FE repo" needs a new folder (e.g. `e2e-tests/` with `*.spec.ts` targeting `localhost:8083/intern/tricia` and TestSetupHandler) copied into `cplace-e2e/cypress/e2e//` *before* spec calculation, run with cplace-e2e's support/reporters. + +### 8. Affected-spec mapping (feasibility) + +Possible only partially: nx-affected published `*-e2e`/SDK packages → grep cplace-e2e imports (+ transitive `cypress/support/**`); SDK change hits ≥75 specs. No ownership metadata linking FE apps to cplace-e2e product folders. Recommendation from analysis: ship explicit filter + full suite; "affected" later as a suggestion helper. + +## Code References + +- `github-actions/.github/workflows/fe-pr-snapshot.yml:21,65-89` — label gate, artifacts action, PR comment upsert +- `github-actions/tools/scripts/artifacts/utils.ts:311-319` — snapshot version strings +- `github-actions/tools/scripts/artifacts/artifacts-handler.ts:31,99-107,148-204,317-319` — PR snapshot flow, affected projects, outputs (release only) +- `github-actions/tools/scripts/artifacts/nx-project.ts:52-63,111-140,~357` — publishable rules, publish, dist-tags +- `github-actions/.github/workflows/fe-e2e.yml:19-87` — current Storybook E2E +- `github-actions/.github/actions/use-npmrc/action.yml:15,31` — npmrc handling +- `cplace-fe/.github/workflows/pull_request.yaml:109-134` — e2e job + pr-checks aggregator +- `cplace-fe/.github/workflows/devkit-test-template.yaml:88-115` — App token + cross-repo checkout precedent +- `main/cf.cplace.platform/assets/package.json:20-22` — `@cplace-next` pins in backend +- `cplace-paw/cf.cplace.*/assets/package.json:5-6` — `@cplace-paw-fe` pins +- RB `src/scripts/upmerge_and_bump_releases.sh:93-96,158-185,224-251,287-320` — npm bump recipe +- RB `src/scripts/setup_npmrc.sh:9-29` — backend registry auth +- RB `.github/workflows/build.yml:62-186` — backend build stages +- RB `.github/workflows/e2e-cypress.yml:52-108` — build + matrix +- RB `.github/workflows/reuseable-e2e-cypress.yml:68-232` — per-node E2E +- RB `src/scripts/create_and_run_cplace_docker.sh:32-87`, `create_and_run_cplace_docker_compose.sh` — docker/compose +- RB `src/scripts/wait_for_cplace_startup.sh:18-29` — readiness +- RB `src/scripts/calculate_e2e_specs_for_node.sh:27-103` — spec filter + sharding +- RB `src/scripts/run_e2e_cypress_test_suite.sh:37-41` — cypress-repeat +- RB `src/scripts/determine_e2e_branch.sh:10-37` — e2e branch resolution +- RB `src/scripts/move_own_e2e_tests.sh:116-118` — self-provided tests hook +- RB `.github/workflows/integration-e2e-orchestrator.yml:72-318` — orchestrator +- RB `src/scripts/merge_parent_repos.sh:26-78` — parent-repos merge / `source_matched` +- RB `src/scripts/integration_e2e_report.sh:13,214-216,276` — report + matched warning +- RB `src/scripts/parse_slash_command_parameters.sh:19-58` — slash params +- FB `.github/workflows/e2e-cypress.yml:46-90`, `reuseable-e2e-cypress.yml:175-181`, `create_and_run_cplace_docker.sh:12-29` — pull-image mode +- `main/docker/e2e/{Dockerfile,docker-compose.yml,startup.sh,README.md}` — E2E image +- `cplace-e2e/cypress.config.ts:7-84` — Cypress config +- `cplace-e2e/package.json:36` and `.npmrc` — FE SDK pins +- IAP `.github/workflows/{slash-commands,integration-e2e-orchestrator,e2e-cypress,e2e-cypress-feature-toggle,commit}.yml`, `.github/.build-env:128-141`, `.github/.e2e-cypress-env:25` + +## Architecture Insights + +- **Thin caller / fat reusable split** everywhere: consumer repos hold tiny `workflow_dispatch`/`pull_request` wrappers; logic lives in `github-actions@master` (FE) or `cplace-gh-workflows@release/2.0` (BE). A merge to those refs is live for all consumers immediately; staging uses branch-pinned test consumers (`replace_workflow_action_branch.sh`, `pin_consumer_workflows_to_branch.sh`). +- **Two CI ecosystems**: FE (github-actions; nx, npm, JFrog `cplace-npm-local`, `ubuntu-latest`, TS scripts) vs BE (cplace-gh-workflows; gradle, cplace-cli, dotenv config in `.github/.*-env` with `<>`, bash scripts with BATS/shellcheck rules, Ubicloud runners). The new workflow bridges both — placing it in github-actions means calling or duplicating BE composite actions from cplace-gh-workflows. +- **Override-by-pin, not by branch**: BE composition is git-branch driven (`parent-repos.json`); FE integration is version-pin driven (`assets/package.json` + lock). The FE PR workflow is a new "pin override" axis that neither orchestrator nor staging-builds (`dependency_overrides` = repo→branch) supports. +- **Marker-comment state**: both snapshot publishing (``) and integration E2E (``) persist cross-run state in PR comments/bodies. +- **GitHub App per purpose**: read-product (clone), container-build-bot (cross-repo dispatch, PR author), pr-writer (comments). FE side has its own `sva-actions-read-product-fe` App (not installed on `cplace-e2e`; a non-installed repo in `repositories:` fails the mint with 422). +- **Every action SHA-pinned** (Sonar flags unpinned third-party actions). + +## Historical Context (from specs/) + +- `cplace-e2e/specs/2026-11-19_e2e-tests-in-owning-repos/research.md` — closest prior work: move specs into owning repos (pilot cplace-paw + cplace-paw-fe), cplace-e2e as foundation. Explicitly names FE PR snapshot injection into a container build as the core open gap (Open Q5); lists candidate options (snapshot label, assets override before build, staging-builds npm override, Storybook-only FE). Notes no package boundary between foundation and specs (login/TSH/page objects live only in `cplace-e2e/cypress/support`). +- `main/specs/2026-09-28_PFM-ISSUE-28989_adapt-e2e-docker-setup/` — compose + ES topology, image/workflow contract, `DOCKER_ENV` handling, staging procedure, runner facts (`ubicloud-standard-4`, Compose v2.38.2); out of scope: moving docker setup out of main; deliberately does not anticipate pull mode. +- `cplace-gh-workflows/specs/2026-09-28_PFM-ISSUE-34932_e2e-branch-remote-unreachable/` — authoritative branch-resolution rules (exact ref match, retry with backoff, explicit missing → error, derived missing → warning + master, don't use `ls-remote --exit-code`); token propagation race. +- `cplace-fe/specs/2026-10-15_PFM-ISSUE-34281_github-app-cross-repo-clone/` — FE read App design, mint step config, `required-repos` gating pattern in a reusable template, SHA pinning. +- `cplace-gh-workflows/specs/2026-07-02_jfrog-snapshot-version-duplication/` — backend `RAW_VERSION` parsing pitfalls; irrelevant to npm snapshots but warns against parsing multi-line gradle output. +- `cplace-integration-all-products/specs/2026-09-02_PFM-ISSUE-34615_remove-e2e-cypress-concurrency/` — `concurrency` group `workflow+ref` silently cancelled dispatches. +- FB `specs/2026-06-25_e2e-prebuilt-image-mode/design.md` — pull-image mode design (image format, branch derivation). + +## Related Research + +- `cplace-e2e/specs/2026-11-19_e2e-tests-in-owning-repos/research.md` +- `main/specs/2026-09-28_PFM-ISSUE-28989_adapt-e2e-docker-setup/` +- `github-actions/specs/2026-10-12_PFM-ISSUE-34283_consolidate-fe-release-workflow/` +- `github-actions/specs/2026-10-26_PFM-ISSUE-34282_github-token-scoped-permissions/` + +## Open Questions + +1. **Snapshot availability for "every PR, required check"**: make snapshot publishing unconditional (drop label gate) and run it as a job inside `pull_request.yaml` so E2E can `needs:` it? Or `workflow_run`/poll? Expose `version` + `packages` outputs from `fe-pr-snapshot.yml`/`artifacts` action? +2. **PRs that publish nothing** (no affected app consumed by backend, e.g. docs/storybook-only): skip E2E (pass) or run against base pins? +3. **Home of the workflow**: standalone in github-actions (calling BE composite actions cross-repo via `uses: collaborationFactory/cplace-gh-workflows/.github/actions/...@release/2.0`) vs. new FE mode in the cplace-gh-workflows orchestrator (`npm_overrides` input + IAP test branch). Secrets (`ENV_CPLACE_ARTIFACTORY_*`, read App installed on backend + cplace-e2e, Ubicloud) must be available to FE repos for the standalone option. +4. **Prebuilt-image mode**: no consumable prebuilt E2E image today; FB pull mode is single-container and lacks ES. Options: (a) reconcile pull mode with compose and have staging-builds publish `e2e//cplace:head` nightly; then overlay FE assets into the running image (requires knowing where plugin assets live inside `software.zip` and whether the overlay needs `cplace-asc` compile — unverified); (b) build-from-source only, but build once and share `software.zip` across nodes. +5. **Overlay feasibility**: can FE bundles be swapped inside an already-built `software.zip`/image without re-running gradle/cplace-asc (are `node_modules/@cplace-next/*` copied verbatim into the plugin's static resources)? Needs a spike. +6. **Backend branch selection**: same-named backend branch (paired BE+FE change) else mapped base (`main|master` → `master`, `release/X.Y` → same, `-beta` → ?). Is a feature-branch backend acceptable given the X.Y.999 rewrite breakage seen on IAP#536? +7. **cplace-e2e pins**: bump `@cplace-next/*-e2e` and `cf-e2e-testing-sdk` in the cloned cplace-e2e when the PR published them? Cypress major mismatch (13 vs 15) for any in-repo specs. +8. **In-repo spec folder convention**: name/location (`e2e-tests/`?), copy target in cplace-e2e, fix of `move_own_e2e_tests.sh` ordering and `mv` nesting — or a separate copy step in the new workflow. +9. **Default spec scope and cost budget** for every PR: node count, toggle suite on/off, Jira excluded, `timeout-minutes`, `concurrency` per PR with cancel-in-progress, runner labels available to FE repos (Ubicloud vars). +10. **Multi-backend reach**: cplace-fe packages are built into cplace only; do cplace-fe PRs ever need paw-level specs (cplace-paw build pulls `../main` assets — would need bumping parent assets)? +11. **Reporting**: JUnit check + PR comment (reuse marker/minimize pattern) — which App posts comments from FE repos (`SVA_ACTIONS_WRITE_PRODUCT_FE`)? +12. **Unverified items**: whether cplace-gradle-plugin uses `npm ci` vs `npm install` for assets; whether JFrog virtual `cplace-npm` serves `cplace-npm-local` PR snapshots immediately; master vs release/2.0 script drift; `integration-e2e-reporter` internals. + +## Additional Research: Review hardening (Phase 9) + +*Added: 2026-11-23* + +- The PR snapshot version is `0.0.0--` for every push of a PR, and each publish deletes the version first + (`tools/scripts/artifacts/artifacts-handler.ts`, `deleteArtifact` before `publish`). A run that is still installing can therefore get a + newer push's content under the same version; the integrity check in Phase 9 §1 catches that. +- `nx-project.ts` `publish()` runs a plain `npm publish`. `npm publish --json` prints the pack summary, including `integrity`, which the + handler can collect. +- `cplace-gh-workflows@release/2.0` `clone-e2e-repo` clones with `git clone --depth 1 --branch "$E2E_REF"` (`src/scripts/clone_e2e_repo.sh`), + so it accepts a branch, not a SHA; pinning `cplace-e2e` to a commit needs a fetch and checkout after the clone. +- Composites in `cplace-gh-workflows@release/2.0` call each other at `@release/2.0` (for example `load-env-variables` → `load-dotenv-file`, + `prepare-build-environment` → `build-cplace-cli`), so pinning the top-level refs to a SHA leaves the nested refs mutable. +- The backend's FE package prefixes live in `/.github/.frontend-upmerge-env` (`FE_PACKAGE_PREFIXES`), and + `upmerge_and_bump_releases.sh` `version_spec_for` maps `master|main` → `snapshot` and `release/X.Y` → `X.Y` (see § 3 above). diff --git a/specs/2026-11-19_fe-pr-e2e-reusable-workflow/review.md b/specs/2026-11-19_fe-pr-e2e-reusable-workflow/review.md new file mode 100644 index 0000000..3f174f7 --- /dev/null +++ b/specs/2026-11-19_fe-pr-e2e-reusable-workflow/review.md @@ -0,0 +1,653 @@ +# Code Review: Real-Backend E2E on Frontend PRs + +## Iteration 1 — 2026-11-20 + +*Reviewed two repositories against `plan.md`. github-actions: `origin/master...HEAD` (4 files); cplace-fe: `origin/main...HEAD` (2 files). cplace-paw-fe was skipped because it is on `master` (its work is in Phase 6). Agents: plan-conformance, correctness, craft, test and security in github-actions; plan-conformance, correctness, craft and security in cplace-fe. best-practices did not run in either repo: github-actions has no rule index, and cplace-fe's rule symlinks are broken. 7 findings kept, 0 dropped in verification, 1 merged.* + +Merged: +- github-actions / craft — "Hardcoded FIXME ref in the action reference" — into [1.1] + +### [1.1] 🙏 Secrets-bearing reusable workflow pinned to a mutable feature branch + +- [x] Resolved — No code change: the branch ref is intentional staging per plan.md Implementation Approach; Phase 6 resets it to `@master` and its automated criterion (grep for `feature/fe-backend-e2e` / `FIXME remove before merging` in `.github`) is the merge gate. + +**Agent(s):** security, craft + +**Repo:** github-actions + +**File(s):** +- [fe-pr-snapshot.yml:82](/.github/workflows/fe-pr-snapshot.yml#L82) + +**Reference(s):** +- [fe-pr-snapshot.yml:16](/.github/workflow-templates/fe/fe-pr-snapshot.yml#L16) + +The artifacts step receives `JFROG_BASE64_TOKEN`, `JFROG_URL` and `JFROG_USER`, and it now loads its action from `@feature/fe-backend-e2e`. A branch ref is mutable, so anyone who can push to that branch controls the code that gets the publish credentials. The template consumers call `fe-pr-snapshot.yml@master`. If this merges unchanged, all of them would run branch code, and deleting the branch would break them. The plan stages the ref on purpose and resets it in Phase 6. Treat it as a merge blocker, for example with a CI check that rejects `FIXME remove before merging` or a non-`master` ref. + +### [1.2] 🙏 Branch-off tip commit on a PR returns early and emits no `version` or `packages` outputs + +- [x] Resolved — Reworded the `version` and `packages` output descriptions in fe-pr-snapshot.yml to state they are empty when the job is skipped or the tip is a branch-off commit; consumers guard empty values (Phase 3 `resolve-consumers.sh` treats empty `PACKAGES` as `[]`), since a code-side `[]` could not cover the skipped-job case anyway. + +**Agent(s):** correctness + +**Repo:** github-actions + +**File(s):** +- [artifacts-handler.ts:142](/tools/scripts/artifacts/artifacts-handler.ts#L142) +- [fe-pr-snapshot.yml:35](/.github/workflows/fe-pr-snapshot.yml#L35) + +**Reference(s):** +- [artifacts-handler.ts:117](/tools/scripts/artifacts/artifacts-handler.ts#L117) + +On a branch-off tip commit, `handle()` returns before `initProjects`, so `writePrSnapshotOutputs` never runs. The workflow's `version` and `packages` outputs are then empty strings, not `[]`, which contradicts the output description ("[] when nothing was published"). A skipped job (label required and missing) also yields empty outputs. Either write `packages=[]` on that path, or reword the output description and have consumers guard against empty values. The plan's Phase 3 `resolve-consumers.sh` already treats an empty `PACKAGES` as `[]` (plan.md:474). + +### [1.3] 💡 Unrelated hardening mixed into the snapshot workflow change + +- [x] Resolved — No code change: `timeout-minutes: 60` is required by plan.md Phase 1 §4 and the `"$GITHUB_ENV"` quoting is the recorded actionlint fix; both stay and get a line in the PR description. + +**Agent(s):** craft + +**Repo:** github-actions + +**File(s):** +- [fe-pr-snapshot.yml:34](/.github/workflows/fe-pr-snapshot.yml#L34) +- [fe-pr-snapshot.yml:63](/.github/workflows/fe-pr-snapshot.yml#L63) + +**Reference(s):** +- [fe-e2e.yml:22](/.github/workflows/fe-e2e.yml#L22) + +`timeout-minutes: 60` and the `"$GITHUB_ENV"` quoting have nothing to do with the new outputs or the label toggle, and they widen the diff. Note that plan.md Phase 1 §4 does ask for `timeout-minutes: 60`, and the Phase 1 verification notes record the quoting as the actionlint fix. Mentioning both in the PR description would be enough. + +### [1.4] 💡 Comment on `writePrSnapshotOutputs` assumes the failure path + +- [x] Resolved — Declined: the comment already states the invariant (a failed publish exits the process); tracking published packages separately adds state for a failure mode the handler does not have. + +**Agent(s):** craft + +**Repo:** github-actions + +**File(s):** +- [artifacts-handler.ts:149](/tools/scripts/artifacts/artifacts-handler.ts#L149) + +The `packages` output is correct only as long as a failed publish exits the process. If the handler ever tolerates a failed publish, the output will list packages that were never published, and nothing will flag it. Consider having `buildAndPublishProjects` record what it actually published, or keep this invariant next to the exit logic. + +### [1.5] 💡 PR-snapshot output guard sits inline in `handle()` + +- [x] Resolved — Moved the `PR_SNAPSHOT && !onlyDeleteArtifacts` guard into `writePrSnapshotOutputs` as an early return; `handle()` now calls it unconditionally after publishing. Artifacts PR-snapshot tests still pass. + +**Agent(s):** craft + +**Repo:** github-actions + +**File(s):** +- [artifacts-handler.ts:154](/tools/scripts/artifacts/artifacts-handler.ts#L154) + +**Reference(s):** +- [artifacts-handler.ts:327](/tools/scripts/artifacts/artifacts-handler.ts#L327) + +The helper usage matches the release flow, which writes its outputs inside its own method. The `TASK.PR_SNAPSHOT && !this.onlyDeleteArtifacts` guard, however, sits inline in `handle()`. Moving it into `writePrSnapshotOutputs` would keep `handle()` free of the special case. + +### [1.6] 💡 Trial workflow forwards JFrog and npm secrets to a branch-pinned reusable workflow + +- [x] Resolved — No code change: the trial PR is a never-merged draft and must track the moving `feature/fe-backend-e2e` branch across Phases 2-5, so a SHA pin would need re-pinning on every push; the branch is deleted after Phase 6. + +**Agent(s):** security + +**Repo:** cplace-fe + +**File(s):** +- [pull_request.yaml:120](../cplace-fe/.github/workflows/pull_request.yaml#L120) +- [pull_request.yaml:125](../cplace-fe/.github/workflows/pull_request.yaml#L125) + +The `snapshot` job sends `JFROG_BASE64_TOKEN` and `DOT_NPMRC` to `fe-pr-snapshot.yml@feature/fe-backend-e2e`, which is a mutable, unreviewed ref. The trial PR is never merged, so the exposure is limited to the trial. Still, consider pinning to a commit SHA for the trial, and protecting or deleting the branch afterwards. + +### [1.7] ℹ️ Trial consumer has no `backend-e2e` job yet (Phase 2 item 6 not done) + +- [x] Resolved — Acknowledged: Phase 2 is in progress; the `backend-e2e` trial job lands with Phase 2 item 6. + +**Agent(s):** plan-conformance + +**Repo:** cplace-fe + +**File(s):** +- [pull_request.yaml](../cplace-fe/.github/workflows/pull_request.yaml) + +**Reference(s):** +- [plan.md:412](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md#L412) + +The trial branch has only the Phase 1 pieces (`snapshot` and the `snapshot-outputs` echo job) plus Phase 2's trivial `cf-platform` change. The `backend-e2e` caller is not there yet. None of Phase 2's criteria are checked off, so this is work in progress, not a gap. It is recorded so nobody reads the trial branch as covering Phase 2. + +## Iteration 2 — 2026-11-20 + +*Reviewed two repositories against `plan.md`. github-actions: `origin/master...HEAD` (14 files); cplace-fe: `origin/main...HEAD` (3 files). cplace-paw-fe was skipped because its work is in Phase 6, which has not started. The untracked `dist/` in github-actions was not reviewed. Agents: plan-conformance, correctness, craft, best-practices, test and security in github-actions; plan-conformance, correctness, craft and security in cplace-fe. best-practices used the sibling `cplace-best-practices` backend index, because github-actions has no rule index of its own. In cplace-fe it did not run: the only change outside workflows is a deliberate trial FIXME comment. plan-conformance returned nothing in either repo, and craft and security returned nothing in cplace-fe. 7 findings kept, 0 dropped in verification, 0 merged.* + +### [2.1] 💡 Resolve action's `run` output is hard-coded to `true` + +- [x] Resolved — Declined: plan.md Phase 2 §3 requires the constant `true` and Phase 3 replaces the step with the `resolve-consumers.sh` skip condition; a placeholder comment would only describe plan history. + +**Agent(s):** craft + +**Repo:** github-actions + +**File(s):** +- [action.yml:44](/.github/actions/backend-e2e-resolve/action.yml#L44) +- [fe-backend-e2e.yml:85](/.github/workflows/fe-backend-e2e.yml#L85) + +The `run` step always writes `run=true`, so the output and the `if:` gates on `build`, `e2e` and `report` can never be false. plan.md Phase 2 §3 asks for exactly this ("always `true` in this phase"), and Phase 3 wires the real skip condition. A one-line comment saying it is a placeholder until Phase 3 would stop it reading as a bug. + +### [2.2] 💡 npm registry auth step is copied verbatim into two jobs + +- [x] Resolved — Declined: a composite action for a 9-line step used twice in one file would add another `@feature/fe-backend-e2e` FIXME ref for Phase 6 to rewrite; both copies stay side by side in fe-backend-e2e.yml. + +**Agent(s):** craft + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:138](/.github/workflows/fe-backend-e2e.yml#L138) +- [fe-backend-e2e.yml:284](/.github/workflows/fe-backend-e2e.yml#L284) + +**Reference(s):** +- [action.yml:1](/.github/actions/backend-e2e-pin/action.yml#L1) + +The `build` and `e2e` jobs contain the same 9-line `.npmrc` setup, including the registry URL and the token format, so changing either means editing two places. This PR already puts small shared steps in `backend-e2e-*` composite actions, and the auth step could become one more. + +### [2.3] 💡 Backend E2E can go green without pinning anything from the PR + +- [x] Resolved — The pin action now fails with `::error::` when no directory matches its globs (layout drift); an empty pin list stays a summary line because Phase 4 reuses the action on the cplace-e2e checkout, where consuming nothing is legitimate, and Phase 3's `resolve-consumers.sh` skips runs with no consumer. + +**Agent(s):** correctness + +**Repo:** github-actions + +**File(s):** +- [action.yml:32](/.github/actions/backend-e2e-pin/action.yml#L32) +- [pin-snapshots.sh:31](/tools/scripts/backend-e2e/pin-snapshots.sh#L31) +- [fe-backend-e2e.yml:154](/.github/workflows/fe-backend-e2e.yml#L154) + +The pin step succeeds when nothing is pinned: no matching dir, empty or `[]` packages, or no assets dir that consumes a published package. The build and every node then run against the backend's stock versions, and the check reports green with only a warning or summary line as signal. Phase 3's `resolve-consumers.sh` skip covers the "nothing consumed" case at resolve time. A glob that matches nothing, or a layout drift after resolve, would still pass silently. Consider failing the pin step when the resolve step expected pins but none were applied. + +### [2.4] 💡 Inline shell for NODES validation and pin-dir globbing has no test + +- [x] Resolved — Plan Phase 7: the glob expansion and its no-match failure moved into `pin-snapshots.sh` and the NODES check into the new `node-indexes.sh` (called first by `backend-e2e-resolve`), both covered by bats in `pr-checks.yml`. + +**Agent(s):** test + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:78](/.github/workflows/fe-backend-e2e.yml#L78) +- [action.yml:32](/.github/actions/backend-e2e-pin/action.yml#L32) + +**Reference(s):** +- [pr-checks.yml:58](/.github/workflows/pr-checks.yml#L58) + +bats and shellcheck only cover `tools/scripts/backend-e2e/*`. The `NODES` validation (the `0*` arm is easy to get subtly wrong) and the glob and no-match branch of the pin action are inline workflow shell, so they are never exercised. Moving them into scripts under `tools/scripts/backend-e2e/` would let the existing bats setup test them. + +### [2.5] 💡 Blanket `|| true` on the analytics `zip -d` hides a missing or corrupt archive + +- [x] Resolved — Replaced `|| true` with an exit-code check that tolerates only zip's "nothing to do" (12) and fails with an `::error::` naming the exit code otherwise. + +**Agent(s):** best-practices + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:190](/.github/workflows/fe-backend-e2e.yml#L190) + +**Reference(s):** +- [shell-scripts.md:16](../cplace-best-practices/details/backend/shell-scripts.md#L16) + +This breaks [SH-01] (never blanket-suppress a step whose success matters). `zip -d` exits non-zero both when nothing matches, which is benign, and when the archive is missing or corrupt. If analytics stays in the zip, the TestSetupHandler fails later on the nodes, far from the cause. Tolerate only zip's "nothing to do" exit code (12), or warn on stderr with context. + +### [2.6] ❓ PR snapshot packages are installed with the Artifactory token in scope + +- [x] Resolved — No code change: callers trigger on `pull_request` (not `pull_request_target`), so fork PRs get no secrets and cannot publish a snapshot; a same-repo PR author already controls the calling workflow and its secrets, so a lifecycle script adds no exposure. + +**Agent(s):** security + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:291](/.github/workflows/fe-backend-e2e.yml#L291) +- [fe-backend-e2e.yml:154](/.github/workflows/fe-backend-e2e.yml#L154) +- [pin-snapshots.sh:39](/tools/scripts/backend-e2e/pin-snapshots.sh#L39) + +`~/.npmrc` holds the Artifactory token before `npm i ` runs without `--ignore-scripts`. A lifecycle script in a PR-built package could therefore read that token and any git credentials on the runner. This is acceptable if only same-repo PRs reach the workflow with secrets: can you confirm that fork PRs cannot? Otherwise, consider `--ignore-scripts` on the pin, or writing the token only after the pin. + +### [2.7] 💡 Trial `snapshot` job can double-publish alongside the label caller + +- [x] Resolved — No code change: the `snapshot` label stays off the trial PR, and Phase 6 deletes the label caller. + +**Agent(s):** correctness + +**Repo:** cplace-fe + +**File(s):** +- [pull_request.yaml:119](../cplace-fe/.github/workflows/pull_request.yaml#L119) +- [pull_request_snapshot.yaml:16](../cplace-fe/.github/workflows/pull_request_snapshot.yaml#L16) + +Both workflows call `fe-pr-snapshot.yml@feature/fe-backend-e2e` on `synchronize` and `reopened`. The label caller keeps the default `REQUIRE_SNAPSHOT_LABEL: true`, so it skips unless the PR carries the `snapshot` label, and Phase 1 verified that it does. If the label is ever added to the trial PR, the two runs would publish the same version concurrently and could fail the `snapshot` job, which would skip `backend-e2e`. Keep the label off the trial PR. Phase 6 deletes the label caller anyway. + +## Iteration 3 — 2026-11-20 + +*Reviewed two repositories against `plan.md`. github-actions: `origin/master...HEAD` (14 files); cplace-fe: `origin/main...HEAD` (3 files). cplace-paw-fe was skipped because it is on `master` and its work is in Phase 6, which has not started. The run went ahead on committed code only, at the user's request. The github-actions working tree holds uncommitted Phase 7 work and the iteration-2 fixes for [2.3] and [2.5], and the untracked `dist/`; none of these were reviewed. Agents: plan-conformance, correctness, craft, best-practices, test and security in github-actions; plan-conformance, correctness, craft and security in cplace-fe. best-practices used the sibling `cplace-best-practices` backend index, because github-actions has no rule index of its own. In cplace-fe it did not run, as in iteration 2: the only change outside workflows is a deliberate trial FIXME comment. test and security returned nothing in github-actions, and every cplace-fe agent returned nothing. 6 findings kept, 0 dropped in verification, 3 merged.* + +Merged: +- github-actions / plan-conformance — "[2.5] fix is not on the branch: analytics `zip -d` still ends in `|| true`" — into [3.2] +- github-actions / best-practices — "Blanket `|| true` on the analytics `zip -d` is still in the diff (SH-01)" — into [3.2] +- github-actions / plan-conformance — "[2.3] fix is not on the branch: no-match in the pin action still warns and exits 0" — into [3.3] + +### [3.1] 🚨 Phase 7 is checked off, but none of its changes are committed + +- [x] Resolved — No code change: the Phase 7 working-tree changes (`node-indexes.sh`/`.bats`, glob expansion in `pin-snapshots.sh`, the resolve action's NODES call) are now committed on `feature/fe-backend-e2e`. + +**Agent(s):** plan-conformance + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:78](/.github/workflows/fe-backend-e2e.yml#L78) +- [action.yml:24](/.github/actions/backend-e2e-pin/action.yml#L24) +- `tools/scripts/backend-e2e/node-indexes.sh` + +**Reference(s):** +- [plan.md:832](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md#L832) + +Every Phase 7 Automated Verification item is `- [x]`. On the branch, though, the inline NODES `case` and the "Node matrix" step are still in fe-backend-e2e.yml, the pin action still expands globs with `nullglob`, and `node-indexes.sh` and `node-indexes.bats` do not exist. The ticked grep criterion therefore fails against HEAD. The changes exist only in the working tree, so committing them should resolve this, together with the [2.4] tick that describes them. + +### [3.2] 🙏 Blanket `|| true` on the analytics `zip -d` is still on the branch + +- [x] Resolved — No code change: the [2.5] exit-code check (tolerate only zip's 12, else `::error::` and exit) was correct but uncommitted; it is now committed. The earlier tick did not hold because it was written against the working tree, not HEAD. + +**Regression of** [2.5] + +**Agent(s):** correctness, plan-conformance, best-practices + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:190](/.github/workflows/fe-backend-e2e.yml#L190) + +**Reference(s):** +- [shell-scripts.md:16](../cplace-best-practices/details/backend/shell-scripts.md#L16) +- [review.md:188](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/review.md#L188) + +The tick note on [2.5] says `|| true` was replaced by a check that tolerates only exit code 12, but HEAD still has the blanket suppression ([SH-01]). A missing or corrupt `software.zip` stays green and fails later on the test nodes. The exit-code check exists only in the uncommitted working tree. + +### [3.3] 🙏 Pin step still warns and exits 0 when no directory matches + +- [x] Resolved — No code change: the [2.3] fix (no-match fails in `pin-snapshots.sh` with `exit 1`, covered by bats) was uncommitted and is now committed. The earlier tick did not hold because it was written against the working tree, not HEAD. + +**Regression of** [2.3] + +**Agent(s):** correctness, plan-conformance + +**Repo:** github-actions + +**File(s):** +- [action.yml:32](/.github/actions/backend-e2e-pin/action.yml#L32) + +**Reference(s):** +- [review.md:156](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/review.md#L156) + +The tick note on [2.3] says a no-match glob now fails with `::error::`, but the committed action emits `::warning::` and `exit 0`. If the backend layout drifts so `${REPO_NAME}/*/assets` matches nothing, the build and every node run against stock versions, and the check goes green without testing the PR's snapshot. Phase 7 §1 moves this check into `pin-snapshots.sh` as `exit 1`. That change is uncommitted too. + +### [3.4] 🙏 npm's stdout is captured as the pin list and written into the step summary + +- [x] Resolved — `pin-snapshots.sh` sends `npm i` stdout to stderr; the bats `npm` stub now prints a progress line to stdout and the per-pin output test runs with `--separate-stderr`, so the two-line assertion fails without the redirect (bats not runnable locally on Windows; verified by the `pr-checks.yml` bats job). + +**Agent(s):** correctness + +**Repo:** github-actions + +**File(s):** +- [pin-snapshots.sh:39](/tools/scripts/backend-e2e/pin-snapshots.sh#L39) +- [action.yml:36](/.github/actions/backend-e2e-pin/action.yml#L36) + +**Reference(s):** +- [pin-snapshots.bats:90](/tools/scripts/backend-e2e/pin-snapshots.bats#L90) + +`npm i` prints progress and audit notices to stdout, which is not redirected, and the action captures the script's whole stdout as `pins`. The "Pinned snapshot packages" summary therefore mixes npm output with the ` @` lines. The bats case asserts exactly two output lines, but its `npm` stub prints nothing, so it cannot catch this. Redirect npm's stdout to stderr (`>&2`) in the script. + +### [3.5] 💡 Bundle step hardcodes `main/docker/e2e`, which exists only for cplace or with parent repos + +- [x] Resolved — The bundle step now fails up front with an `::error::` when `main/docker/e2e` is missing, naming `CB_INCLUDE_PARENT_REPOS=true` as the fix; the path stays required because the test nodes cannot run without the docker scripts. + +**Agent(s):** correctness + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:201](/.github/workflows/fe-backend-e2e.yml#L201) + +For a non-cplace backend (`repo_dir` = `cplace-paw`), `main/` exists only when a parent-repo step clones cplace there, and that step runs only when `CB_INCLUDE_PARENT_REPOS == 'true'`. `tar -czf` fails on a missing path. `config1` is guarded by `-d`, but this path is not. Check this before the cplace-paw-fe rollout in Phase 6. + +### [3.6] 💡 `tools/scripts/backend-e2e/` has no README, unlike the sibling script directory + +- [x] Resolved — Declined: each script's header comment already states its usage, env and output contract, so a README would duplicate them; add one if the directory grows beyond its current handful of scripts. + +**Agent(s):** craft + +**Repo:** github-actions + +**File(s):** +- [lib.sh:1](/tools/scripts/backend-e2e/lib.sh#L1) + +**Reference(s):** +- [README.md:204](/tools/scripts/lockfile/README.md#L204) + +The directory adds scripts, a sourced lib, bats tests and a helper, wired into two composite actions and a workflow. Its env and argument contracts (`PACKAGES`, `FE_REPO`, `BASE_REF`) are spread across header comments. `tools/scripts/lockfile/` documents its files, invariants and usage in a short README, and a few lines here would follow the same convention. + +## Iteration 4 — 2026-11-20 + +*Reviewed two repositories against `plan.md`. github-actions: `origin/master...HEAD` (16 files); cplace-fe: `origin/main...HEAD` (3 files). cplace-paw-fe was skipped because it is on `master` and its work is in Phase 6, which has not started. The untracked `dist/` in github-actions was not reviewed. Agents: plan-conformance, correctness, craft, best-practices, test and security in github-actions; plan-conformance, correctness, craft and security in cplace-fe. best-practices found no rule index covering github-actions' paths (workflows, composite actions, bash/bats, the artifacts handler) and filed nothing. plan-conformance, best-practices and test returned nothing in github-actions, and every cplace-fe agent returned nothing. 5 findings kept, 0 dropped in verification, 0 merged.* + +### [4.1] 💡 Fixed artifact names collide if the workflow is called twice in one run + +- [x] Resolved — Declined: each caller invokes the workflow once per run by design; add a caller-supplied artifact-name suffix input when a caller needs a second invocation. + +**Agent(s):** correctness + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:212](/.github/workflows/fe-backend-e2e.yml#L212) +- [fe-backend-e2e.yml:221](/.github/workflows/fe-backend-e2e.yml#L221) +- [fe-backend-e2e.yml:350](/.github/workflows/fe-backend-e2e.yml#L350) + +`backend-e2e-bundle`, `backend-e2e-npm-logs-build` and `backend-e2e-results-` contain nothing that tells one invocation from another. Artifacts are scoped to the whole caller run, so a caller that invokes the workflow twice (another spec set or backend) gets a 409 on the second upload, and the report's `backend-e2e-results-*` pattern would merge both invocations' results. Today's callers invoke it once, so this matters only if that changes; a caller-supplied suffix in the names would cover it. + +### [4.2] 💡 No `permissions:` block, so jobs that install PR-built packages inherit the caller's token scope + +- [x] Resolved — Added top-level `permissions: contents: read` to fe-backend-e2e.yml and job-level `contents: read`, `checks: write`, `pull-requests: write` on `report`, superseding plan.md's "omit top-level permissions" note; all scopes stay within what callers grant. + +**Agent(s):** security + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:11](/.github/workflows/fe-backend-e2e.yml#L11) +- [fe-backend-e2e.yml:365](/.github/workflows/fe-backend-e2e.yml#L365) + +`build` and `e2e` run `npm i` on PR-published snapshot packages, whose lifecycle scripts then run with whatever `GITHUB_TOKEN` scope the caller grants. Only `report` needs `checks: write` and `pull-requests: write`. plan.md omits top-level `permissions:` on purpose; a top-level `contents: read` with the write scopes on `report` alone would cap the exposure regardless of the caller. + +### [4.3] 💡 Backend `.github/.build-env` is shipped inside a downloadable artifact + +- [x] Resolved — No code change: `.build-env` is the backend's committed file and `load-env-variables` never writes to it; secrets are interpolated only into `$GITHUB_ENV`, so the bundled copy holds the same non-secret `CB_*` settings and placeholders as the repo. + +**Agent(s):** security + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:200](/.github/workflows/fe-backend-e2e.yml#L200) + +`load-env-variables` receives `toJson(secrets)`, and the env file is tarred into `backend-e2e-bundle.tgz`, which anyone with repo read access can download during its 1-day retention. If the cplace-gh-workflows env handling ever writes resolved secret values into `.build-env`, the bundle exposes them. Confirm it holds only non-secret `CB_*` settings, or regenerate it on the nodes instead of shipping it. + +### [4.4] 💡 Required `GHA_REF` input is not read anywhere yet + +- [x] Resolved — No code change: plan.md fixes the input contract up front and Phase 4 §1 consumes `GHA_REF` for the `e2e-tests/` sparse checkout; declaring it now keeps callers from changing between phases. + +**Agent(s):** craft + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:14](/.github/workflows/fe-backend-e2e.yml#L14) + +**Reference(s):** +- [fe-e2e.yml:32](/.github/workflows/fe-e2e.yml#L32) + +`GHA_REF` is `required: true` but only declared; nothing in the workflow consumes it, unlike sibling fe-* workflows that check out `ref: ${{ inputs.GHA_REF }}`. plan.md Phase 4 §1 uses it for the `e2e-tests/` sparse checkout, so it becomes live then; until that lands, every caller passes a dead value. + +### [4.5] 💡 `lib.sh` is a sourced library with one function and one caller + +- [x] Resolved — No code change: Phase 3 is committed plan work that adds `resolve-consumers.sh` as a second `consumed_packages` caller and `remote_branch_exists` to `lib.sh`, so the split stays. + +**Agent(s):** craft + +**Repo:** github-actions + +**File(s):** +- [lib.sh:11](/tools/scripts/backend-e2e/lib.sh#L11) + +**Reference(s):** +- [pin-snapshots.sh:47](/tools/scripts/backend-e2e/pin-snapshots.sh#L47) +- [plan.md:486](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md#L486) + +`consumed_packages` lives in its own sourced file but `pin-snapshots.sh` is its only caller. plan.md Phase 3 adds `resolve-consumers.sh` as a second caller, which justifies the split once Phase 3 lands; keep it if that phase is committed work. + +## Iteration 5 — 2026-11-20 + +*Reviewed `origin/master...HEAD` (18 files) in github-actions against `plan.md`. cplace-fe and cplace-paw-fe were skipped: the review covers this repository only. The uncommitted `plan.md` edit and the untracked `dist/` were not part of the diff. Agents: plan-conformance, correctness, craft, best-practices, test, security. best-practices used the sibling `cplace-best-practices` backend index (`shell-scripts.md`, `editing-general.md`) and returned nothing; correctness and security returned nothing. 4 findings kept, 2 dropped in verification, 0 merged.* + +Dropped: +- test — "Retry-then-succeed path of remote_branch_exists is untested" — external did not confirm +- craft — "`https://github.com/collaborationFactory/` is hard-coded in the shell, while the workflow uses `github.repository_owner`" — external did not confirm + +### [5.1] 💡 Empty-PACKAGES normalisation is copied into two scripts + +- [x] Resolved — Moved the blank-to-`[]` guard into `consumed_packages` in `lib.sh` and dropped it from `pin-snapshots.sh` and `resolve-consumers.sh`; the existing blank-PACKAGES bats cases in both suites cover it. + +**Agent(s):** craft + +**File(s):** +- [pin-snapshots.sh:25](/tools/scripts/backend-e2e/pin-snapshots.sh#L25) +- [resolve-consumers.sh:42](/tools/scripts/backend-e2e/resolve-consumers.sh#L42) + +**Reference(s):** +- [lib.sh:11](/tools/scripts/backend-e2e/lib.sh#L11) + +Both scripts open with the same two lines that turn an empty or blank `PACKAGES` into `[]`, and both header comments restate the rule. `lib.sh` already holds `consumed_packages`, which both call right afterwards. A `normalize_packages` helper there would keep the rule, and its blank-list test, in one place. + +### [5.2] 💡 `resolve_branch` returns its result through a variable that its caller declares + +- [x] Resolved — `resolve_branch` now prints the branch and its callers capture it with `$(...)`; its `::warning::` and `remote_branch_exists`'s `::error::` moved to stderr so the capture cannot swallow them, and an unreachable remote still exits 2. + +**Agent(s):** craft + +**File(s):** +- [resolve-backend.sh:58](/tools/scripts/backend-e2e/resolve-backend.sh#L58) +- [resolve-backend.sh:91](/tools/scripts/backend-e2e/resolve-backend.sh#L91) + +`resolve_branch` writes to `branch`, which exists only because `resolve_branches` declares it as a local. That relies on bash dynamic scope, so the function breaks if it is called from anywhere else. The rest of the directory either returns a status code or prints a value for the caller to capture. Printing the branch and capturing it with `backend_branch="$(resolve_branch …)"` would remove the shared variable. The `::warning::` line would then have to go to stderr. + +### [5.3] 💡 Manifest-fetch shell is inline in the resolve action, while the other logic moved into tested scripts + +- [x] Resolved — Phase 8 moved the step into `tools/scripts/backend-e2e/fetch-manifests.sh`, covered by `fetch-manifests.bats` through the extended git stub, and the action now only calls the script. + +**Agent(s):** craft + +**File(s):** +- [action.yml:104](/.github/actions/backend-e2e-resolve/action.yml#L104) + +**Reference(s):** +- [resolve-backend.sh:1](/tools/scripts/backend-e2e/resolve-backend.sh#L1) + +The sparse-clone step is the only one in the action whose YAML holds a function with its own branching plus a sourced lib. `pr-checks.yml` lints and tests only `tools/scripts/backend-e2e/*`, so neither shellcheck nor bats covers this step. Phase 7 already moved inline shell into tested scripts. Moving this step into something like `fetch-manifests.sh` would follow the same convention and let the existing git stub test it. + +### [5.4] ❓ Build job uploads an npm-logs artifact that no phase or design decision asks for + +- [x] Resolved — Intended: it keeps the debug log of the pin step's `npm i`; plan.md Phase 2 "Changed during implementation" now lists the `backend-e2e-npm-logs-build` upload. + +**Agent(s):** plan-conformance + +**File(s):** +- [fe-backend-e2e.yml:233](/.github/workflows/fe-backend-e2e.yml#L233) + +**Reference(s):** +- [plan.md:359](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md#L359) + +The `build` job ends with an `always()` upload of `~/.npm/_logs` as `backend-e2e-npm-logs-build`. The plan's build steps stop at the bundle upload (step 14), and the Phase 2 "Changed during implementation" notes do not mention this upload. It looks like a sensible debugging aid for the pin step's `npm i`. If it is intended, add a line to those notes so the plan lists everything the workflow uploads. + +## Iteration 6 — 2026-11-23 + +*Reviewed three repositories against `plan.md`. github-actions: `origin/master...HEAD` (20 files); cplace-fe: `origin/main...HEAD` (5 files); cplace-paw-fe: `origin/master...HEAD` (2 files). The uncommitted `plan.md`/`research.md` edits (Phases 9–10) and the untracked `dist/` in github-actions were not part of the diff. Agents: plan-conformance, correctness, craft, test, security in github-actions (no rule index there, so no best-practices); plan-conformance, correctness, craft, best-practices, test, security in cplace-fe (correctness, best-practices, test and security returned nothing); plan-conformance, correctness, craft, best-practices, security in cplace-paw-fe (correctness, craft, best-practices and security returned nothing). Several github-actions findings cited diff line numbers; they were re-anchored to the file lines of their verified quotes. 11 findings kept, 1 dropped in verification, 0 merged.* + +Dropped: +- cplace-paw-fe / plan-conformance — "cplace-paw-fe gets a second trial consumer that the plan does not describe" — quote not in diff + +### [6.1] 💡 PR comment embeds spec and test names from PR-controlled results as unescaped markdown + +- [x] Resolved — Phase 11 §1: `build-report.sh` writes every spec and test name inside a code span, without backticks or line breaks and cut to 200 characters (bats-tested with a Markdown title). + +**Agent(s):** security + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:520](/.github/workflows/fe-backend-e2e.yml#L520) + +`failure.name` is written into the comment outside a code span. Test titles come from specs the PR can add through `e2e-tests/`, so a same-repo author can inject markdown, links or `@mentions` into a comment posted as github-actions[bot]. Impact is low (fork PRs get no secrets). Wrapping the name in a code span or escaping it, and truncating its length, would close it. + +### [6.2] 💡 Advisory mode reports a green result when one node crashes before Cypress runs + +- [x] Resolved — Phase 11 §2: `report` counts the nodes that uploaded results and `classify-outcome.sh` reports `infrastructure-failure` for a missing node, in advisory mode too; a node without specs uploads a marker so it is not counted as missing. + +**Agent(s):** correctness + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:491](/.github/workflows/fe-backend-e2e.yml#L491) +- [fe-backend-e2e.yml:554](/.github/workflows/fe-backend-e2e.yml#L554) + +With `continue-on-error: ${{ inputs.ADVISORY }}` on `e2e`, a node that dies before producing JUnit output still leaves `needs.e2e.result` at `success`. If another node produced results, the comment shows ✅ with "N passed, 0 failed" and the advisory warning stays silent, hiding the untested share. Comparing the number of `backend-e2e-results-*` artifacts with `NODES`, and warning or marking the run not-ok when they differ, would surface it. + +### [6.3] 💡 Report-comment logic is inline workflow JS with no test + +- [x] Resolved — Phase 11 §1: the comment body is built by the bats-tested `build-report.sh` (via the `backend-e2e-report` action); the github-script step only posts it and minimizes older comments. + +**Agent(s):** test + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:491](/.github/workflows/fe-backend-e2e.yml#L491) +- [fe-backend-e2e.yml:496](/.github/workflows/fe-backend-e2e.yml#L496) + +The comment's verdict, the failure extraction (`states.failure`/`error`, `slice(0, 1)`, the `specOf` filename fallback) and the 20-item cap branch on the EnricoMi JSON shape and are never exercised. Earlier iterations moved comparable inline logic into bats-tested scripts ([2.4], [5.3]). Moving the comment builder to a script under `tools/scripts/backend-e2e/` with a results-JSON fixture would cover it; otherwise accept the gap in the PR. + +### [6.4] 💡 In-repo specs checkout is duplicated in `resolve` and `e2e` + +- [x] Resolved — Phase 11 §3: `resolve` outputs `in_repo_specs`, both in-repo steps in `e2e` run only when it is true, and `resolve-specs.sh` adds the in-repo glob once. + +**Agent(s):** craft + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:78](/.github/workflows/fe-backend-e2e.yml#L78) +- [fe-backend-e2e.yml:336](/.github/workflows/fe-backend-e2e.yml#L336) + +Both jobs run the same sparse checkout and decide "has `e2e-tests/`" separately: `resolve` with `hashFiles(...) != ''`, `e2e` with `[[ -d fe-repo/e2e-tests ]]`. The two can drift. Exposing `in_repo_specs` as a `resolve` job output and checking out in `e2e` only when it is `true` removes one copy and one decision. + +### [6.5] 💡 Advisory warning step re-parses the results JSON the comment script already parses + +- [x] Resolved — Phase 11 §1: the results JSON is parsed once in `build-report.sh`; the jq advisory step and its `|| echo "0 0"` fallback are gone, and a missing JSON fails instead of reporting zeros. + +**Agent(s):** craft + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:488](/.github/workflows/fe-backend-e2e.yml#L488) +- [fe-backend-e2e.yml:554](/.github/workflows/fe-backend-e2e.yml#L554) + +`report` computes the tests and failed counts twice, in JavaScript for the comment and in jq for the advisory warning, so `tests_fail + tests_error` lives in two languages. The github-script step could emit `core.warning` itself when `ADVISORY` is set, dropping the jq step and its `2>/dev/null || echo "0 0"` fallback. + +### [6.6] ❓ Backend distribution is uploaded as an artifact under the FE repo's access control + +- [x] Resolved — No code change: cplace-fe, cplace-paw-fe, cplace, cplace-paw and cplace-e2e are all `internal` repositories, so the FE repos' read audience is the same as the backends'. + +**Agent(s):** security + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:243](/.github/workflows/fe-backend-e2e.yml#L243) + +The bundle holds the full backend `software.zip`, `main/docker` and the e2e configuration, and anyone with read access to the FE repo can download it for its 1-day retention. Backend source access is otherwise granted through a GitHub App token. Is the FE repos' audience no wider than the backend repos'? If it is wider, the bundle needs another transfer path or a restricted audience. + +### [6.7] ❓ `ADVISORY` input stops failed tests from failing the run, but no phase adds it + +- [x] Resolved — Phase 11 §5: plan.md Implementation Approach, Interface records `ADVISORY` and its effects; design.md decision 10 carries the matching amendment. + +**Agent(s):** plan-conformance + +**Repo:** github-actions + +**File(s):** +- [fe-backend-e2e.yml:38](/.github/workflows/fe-backend-e2e.yml#L38) +- [fe-backend-e2e.yml:263](/.github/workflows/fe-backend-e2e.yml#L263) +- [fe-backend-e2e.yml:458](/.github/workflows/fe-backend-e2e.yml#L458) +- [fe-backend-e2e.yml:541](/.github/workflows/fe-backend-e2e.yml#L541) + +**Reference(s):** +- [design.md:53](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/design.md#L53) +- [plan.md:131](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md#L131) + +With `ADVISORY` set, the nodes get `continue-on-error`, the check uses `fail_on: nothing`, and the final fail step is skipped. Design decision 10 says the job fails on any failed test, and the plan's input list has no `ADVISORY`. Phases 9 and 10 refer to advisory mode, so it was likely agreed informally. If so, record it as a plan update and a design amendment so the deviation from decision 10 is written down. + +### [6.8] 💡 Placeholder "Test document" comment left in the sample spec + +- [x] Resolved — Phase 11 §4: the placeholder line is removed, and `e2e-tests/README.md` says when to add a `// Test document: ` line. + +**Agent(s):** craft + +**Repo:** cplace-fe + +**File(s):** +- [startPage.spec.ts:5](../cplace-fe/e2e-tests/platform/startPage.spec.ts#L5) + +The header carries a literal `` that points at nothing, in the spec meant to be the template for future in-repo specs. Fill in the real test document link or drop the line. If the `cplace-e2e` convention requires the line, the README should say so. + +### [6.9] ❓ Trial caller passes `ADVISORY: true`, which no plan phase introduces + +- [x] Resolved — Phase 11 §5: plan.md records that the trial caller runs with `ADVISORY: true` and the rollout callers start in advisory mode until Phase 10's exit criteria are met. + +**Agent(s):** plan-conformance + +**Repo:** cplace-fe + +**File(s):** +- [pull_request.yaml:141](../cplace-fe/.github/workflows/pull_request.yaml#L141) + +**Reference(s):** +- [plan.md:131](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md#L131) +- [design.md:5](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/design.md#L5) + +The trial `backend-e2e` job runs in advisory mode, so failing tests do not fail it. Phase 2 §6's trial-caller instructions do not mention it, and the design says the check fails on any failing test. This is the caller-side counterpart of [6.7]: when recording the input, also say whether the Phase 6 rollout callers set it. + +### [6.10] ❓ Trial caller uses `NODES: '2'` where Phase 2 §6 specifies `'1'` + +- [x] Resolved — Phase 11 §5: plan.md records the trial caller's `NODES: '2'`, which keeps the run under the 60-minute job timeout. + +**Agent(s):** plan-conformance + +**Repo:** cplace-fe + +**File(s):** +- [pull_request.yaml:140](../cplace-fe/.github/workflows/pull_request.yaml#L140) + +**Reference(s):** +- [plan.md:428](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md#L428) + +The plan's trial runs on one node, and the Phase 2 measurement notes suggest `'3'`. The branch uses 2, recorded only in the commit "Split the trial backend E2E over two nodes", probably to stay clear of the 60-minute timeout. If intended, add a line to Phase 2's implementation notes. + +### [6.11] ℹ️ Phase 6 §4 pieces for cplace-paw-fe are not in this diff + +- [x] Resolved — Acknowledged: Phase 6 has not started; the cplace-paw-fe `pr-checks` needs and the label caller's removal land with Phase 6 §4, and the `snapshot` label stays off the trial PR meanwhile. + +**Agent(s):** plan-conformance + +**Repo:** cplace-paw-fe + +**File(s):** +- [fe-pr.yml:81](../cplace-paw-fe/.github/workflows/fe-pr.yml#L81) +- [fe-pr-snapshot.yml](../cplace-paw-fe/.github/workflows/fe-pr-snapshot.yml) + +**Reference(s):** +- [plan.md:780](/specs/2026-11-19_fe-pr-e2e-reusable-workflow/plan.md#L780) + +`pr-checks` still needs only `[build, code-quality, e2e]`, and the label-based `fe-pr-snapshot.yml` caller still exists. No Phase 6 criterion is ticked, so this is not a false check-off; it is recorded so nobody reads this trial branch as the Phase 6 §4 rollout. While both callers coexist, labeling the PR `snapshot` would publish the same version twice, as noted for cplace-fe in [2.7]. diff --git a/tools/scripts/artifacts/artifacts-handler-pr-snapshot-outputs.test.ts b/tools/scripts/artifacts/artifacts-handler-pr-snapshot-outputs.test.ts new file mode 100644 index 0000000..f69d100 --- /dev/null +++ b/tools/scripts/artifacts/artifacts-handler-pr-snapshot-outputs.test.ts @@ -0,0 +1,163 @@ +import { expect } from '@jest/globals'; +import * as child_process from 'child_process'; +import { ArtifactsHandler } from './artifacts-handler'; +import { NxProject, NxProjectKind } from './nx-project'; +import { Utils } from './utils'; + +process.env.JFROG_BASE64_TOKEN = 'jfrog_base64_token'; +process.env.JFROG_URL = 'jfrog_url'; +process.env.JFROG_USER = 'jfrog_user'; + +const SCOPE = '@cplace-next'; +const BRANCH = 'feature/PFM-1-some-work'; + +afterEach(() => { + jest.restoreAllMocks(); + process.env.BASE = ''; + process.env.TAG = ''; + process.env.ONLY_BUMP_VERSION = 'false'; + process.env.ONLY_DELETE_ARTIFACTS = 'false'; + process.env.PR_NUMBER = ''; +}); + +test('a PR snapshot outputs its version and every published package', async () => { + process.env.PR_NUMBER = '42'; + mockHandlerDependencies([ + project('cf-platform', NxProjectKind.Application), + project('cf-frontend-sdk', NxProjectKind.Library, true), + ]); + const output = jest.spyOn(Utils, 'writeOutput').mockReturnValue(); + + await new ArtifactsHandler().handle(); + + expect(output).toHaveBeenCalledWith( + 'version', + '0.0.0-feature-PFM-1-some-work-42' + ); + expect(output).toHaveBeenCalledWith( + 'packages', + '["@cplace-next/cf-platform","@cplace-next/cf-frontend-sdk"]' + ); +}); + +test('a non-publishable lib is not listed in the packages output', async () => { + process.env.PR_NUMBER = '42'; + mockHandlerDependencies([ + project('cf-platform', NxProjectKind.Application), + project('cf-internal-utils', NxProjectKind.Library, false), + ]); + const output = jest.spyOn(Utils, 'writeOutput').mockReturnValue(); + + await new ArtifactsHandler().handle(); + + expect(output).toHaveBeenCalledWith( + 'packages', + '["@cplace-next/cf-platform"]' + ); +}); + +test('a PR snapshot with nothing affected outputs an empty packages list and still a version', async () => { + process.env.PR_NUMBER = '42'; + mockHandlerDependencies([]); + const output = jest.spyOn(Utils, 'writeOutput').mockReturnValue(); + + await new ArtifactsHandler().handle(); + + expect(output).toHaveBeenCalledWith( + 'version', + '0.0.0-feature-PFM-1-some-work-42' + ); + expect(output).toHaveBeenCalledWith('packages', '[]'); +}); + +test('integrities maps every published package to its integrity', async () => { + process.env.PR_NUMBER = '42'; + mockHandlerDependencies([ + project('cf-platform', NxProjectKind.Application, true, 'sha512-platform'), + project('cf-frontend-sdk', NxProjectKind.Library, true, 'sha512-sdk'), + project('cf-internal-utils', NxProjectKind.Library, false, 'sha512-x'), + ]); + const output = jest.spyOn(Utils, 'writeOutput').mockReturnValue(); + + await new ArtifactsHandler().handle(); + + expect(output).toHaveBeenCalledWith( + 'integrities', + '{"@cplace-next/cf-platform":"sha512-platform","@cplace-next/cf-frontend-sdk":"sha512-sdk"}' + ); +}); + +test('integrities is an empty object when nothing was published', async () => { + process.env.PR_NUMBER = '42'; + mockHandlerDependencies([]); + const output = jest.spyOn(Utils, 'writeOutput').mockReturnValue(); + + await new ArtifactsHandler().handle(); + + expect(output).toHaveBeenCalledWith('integrities', '{}'); +}); + +test.each([ + ['a plain summary', '{"name":"x","integrity":"sha512-a"}', 'sha512-a'], + [ + 'script output before the summary', + '> prepublish\nbuilding\n{\n "integrity": "sha512-b"\n}', + 'sha512-b', + ], + ['a summary keyed by package', '{"@s/x":{"integrity":"sha512-c"}}', 'sha512-c'], + ['no JSON', 'npm notice published', ''], + ['a summary without integrity', '{"name":"x"}', ''], +])('integrityOf reads %s', (_case, summary, expected) => { + expect(NxProject.integrityOf(summary)).toBe(expected); +}); + +test('a main snapshot writes neither output', async () => { + mockHandlerDependencies([project('cf-platform', NxProjectKind.Application)]); + const output = jest.spyOn(Utils, 'writeOutput').mockReturnValue(); + + await new ArtifactsHandler().handle(); + + expect(output).not.toHaveBeenCalled(); +}); + +test('deleting a PR snapshot on PR close writes neither output', async () => { + process.env.PR_NUMBER = '42'; + process.env.ONLY_DELETE_ARTIFACTS = 'true'; + mockHandlerDependencies([project('cf-platform', NxProjectKind.Application)]); + const output = jest.spyOn(Utils, 'writeOutput').mockReturnValue(); + + await new ArtifactsHandler().handle(); + + expect(output).not.toHaveBeenCalled(); +}); + +function project( + name: string, + kind: NxProjectKind, + publishable = true, + integrity = '' +): NxProject { + const nxProject = new NxProject(name, kind); + nxProject.scope = SCOPE; + nxProject.isPublishable = publishable; + nxProject.publishedIntegrity = integrity; + return nxProject; +} + +function mockHandlerDependencies(affected: NxProject[]) { + jest.spyOn(child_process, 'execSync').mockReturnValue(Buffer.from('')); + jest + .spyOn(Utils, 'getCurrentBranchNameFromGithubEnv') + .mockReturnValue(BRANCH); + jest.spyOn(Utils, 'parseScopeFromPackageJson').mockReturnValue(SCOPE); + jest.spyOn(Utils, 'isBranchOffCommit').mockReturnValue(false); + jest.spyOn(Utils, 'initGithubActionsFile').mockReturnValue(); + // applications and libraries are queried separately: return the whole list once + jest + .spyOn(Utils, 'getAffectedNxProjects') + .mockReturnValueOnce(affected) + .mockReturnValueOnce([]); + jest + .spyOn(ArtifactsHandler.prototype as any, 'buildAndPublishProjects') + .mockResolvedValue(undefined); +} diff --git a/tools/scripts/artifacts/artifacts-handler.ts b/tools/scripts/artifacts/artifacts-handler.ts index 33e62c3..981d903 100644 --- a/tools/scripts/artifacts/artifacts-handler.ts +++ b/tools/scripts/artifacts/artifacts-handler.ts @@ -138,10 +138,34 @@ export class ArtifactsHandler { console.log(`About to build and release projects`); this.initProjects(); await this.buildAndPublishProjects(); + this.writePrSnapshotOutputs(); } return Promise.resolve(); } + // a failed publish exits the process, so every publishable project left here was published + private writePrSnapshotOutputs() { + // fe-pr-close deletes the PR snapshot through the same path: nothing was published there + if (this.task !== TASK.PR_SNAPSHOT || this.onlyDeleteArtifacts) { + return; + } + const published = this.projects.filter((project) => project.isPublishable); + const packages = published.map( + (project) => `${project.scope}/${project.name}` + ); + const integrities = Object.fromEntries( + published + .filter((project) => project.publishedIntegrity !== '') + .map((project) => [ + `${project.scope}/${project.name}`, + project.publishedIntegrity, + ]) + ); + Utils.writeOutput('version', this.currentVersion.toString()); + Utils.writeOutput('packages', JSON.stringify(packages)); + Utils.writeOutput('integrities', JSON.stringify(integrities)); + } + private async buildAndPublishProjects() { console.log(`Number of projects being processed: ${this.projects.length}`); console.log(`Projects being processed: ${JSON.stringify(this.projects)}`); diff --git a/tools/scripts/artifacts/nx-project.ts b/tools/scripts/artifacts/nx-project.ts index 99968f7..5187120 100644 --- a/tools/scripts/artifacts/nx-project.ts +++ b/tools/scripts/artifacts/nx-project.ts @@ -40,6 +40,8 @@ export class NxProject { public hasPackageJson = false; // release flow: publish under release-X.Y-pending, promote() moves release-X.Y later public stageRelease = false; + // set by publish(): the sha512 integrity npm reported for the published tarball + public publishedIntegrity = ''; private _pathToProject = ''; constructor( @@ -111,11 +113,11 @@ export class NxProject { public async publish() { if (this.isPublishable) { try { - console.log( - execSync(`npm publish`, { - cwd: `${this.getPathToProjectInDist()}`, - }).toString() - ); + const summary = execSync(`npm publish --json`, { + cwd: `${this.getPathToProjectInDist()}`, + }).toString(); + console.log(summary); + this.publishedIntegrity = NxProject.integrityOf(summary); Utils.writePublishedProjectToGithubCommentsFile( `${this.getMarkdownLink()}` ); @@ -128,6 +130,26 @@ export class NxProject { } } + /** + * The `integrity` of an `npm publish --json` summary, or '' when the + * summary has none. Output that lifecycle scripts print before the JSON is + * skipped. + */ + public static integrityOf(summary: string): string { + const start = summary.search(/^\{/m); + if (start < 0) return ''; + try { + const parsed = JSON.parse(summary.slice(start)); + if (typeof parsed?.integrity === 'string') return parsed.integrity; + const nested = Object.values(parsed ?? {}).find( + (value: any) => typeof value?.integrity === 'string' + ) as { integrity: string } | undefined; + return nested?.integrity ?? ''; + } catch { + return ''; + } + } + public build() { console.log( execSync( diff --git a/tools/scripts/backend-e2e/build-report.bats b/tools/scripts/backend-e2e/build-report.bats new file mode 100755 index 0000000..6eedcea --- /dev/null +++ b/tools/scripts/backend-e2e/build-report.bats @@ -0,0 +1,106 @@ +#!/usr/bin/env bats +# +# Behavioral tests for build-report.sh, with EnricoMi results JSON fixtures +# under fixtures/. +# +# Run with: bats tools/scripts/backend-e2e/ + +setup() { + load 'test-helper' + export GITHUB_OUTPUT="${BATS_TEST_TMPDIR}/github_output" GITHUB_STEP_SUMMARY="${BATS_TEST_TMPDIR}/summary" + : >"${GITHUB_OUTPUT}" + BODY="${BATS_TEST_TMPDIR}/body.md" + export BUILD_RESULT=success E2E_RESULT=success NODES=2 NODES_REPORTED=2 ADVISORY=false \ + BACKEND_REPO=cplace BACKEND_BRANCH=master BACKEND_SHA=abc123 E2E_BRANCH=master E2E_SHA=def456 \ + SNAPSHOT_VERSION=0.0.0-feat-1-42 BACKEND_PACKAGES='["@cplace-next/cf-platform"]' E2E_PACKAGES='[]' \ + RUN_URL=https://github.com/collaborationFactory/cplace-fe/actions/runs/7 +} + +output_of() { + sed -n "s/^$1=//p" "${GITHUB_OUTPUT}" +} + +report() { + run "$SCRIPTS/build-report.sh" "${SCRIPTS}/fixtures/$1" "${BODY}" +} + +@test "all passed: marker, verdict, counts, table and links, no failure list" { + report results-passed.json + + [ "$status" -eq 0 ] + [ "$(output_of tests)" = 12 ] + [ "$(output_of failed)" = 0 ] + [ "$(output_of outcome)" = passed ] + [ "$(sed -n 1p "${BODY}")" = '' ] + grep -qxF '### ✅ Backend E2E' "${BODY}" + grep -qxF '12 passed, 0 failed, 0 skipped' "${BODY}" + grep -qxF '| Backend | `cplace` @ `master` `abc123` |' "${BODY}" + grep -qxF '| Pinned in the backend | `["@cplace-next/cf-platform"]` |' "${BODY}" + grep -qxF '[Workflow run](https://github.com/collaborationFactory/cplace-fe/actions/runs/7) · [Test Results Backend E2E](https://github.com/collaborationFactory/cplace-fe/runs/1)' "${BODY}" + ! grep -q 'Failing tests' "${BODY}" +} + +@test "failures from failure and error are listed once each, with the spec fallback" { + report results-failed.json + + [ "$status" -eq 0 ] + [ "$(output_of tests)" = 12 ] + [ "$(output_of failed)" = 3 ] + [ "$(output_of outcome)" = test-failure ] + grep -qxF '### ❌ Backend E2E' "${BODY}" + grep -qxF -- '- `cypress/e2e/cplace-fe/platform/startPage.spec.ts`: `TC01: renders the platform footer after login`' "${BODY}" + grep -qxF -- '- `menu.spec.ts`: `TC02: opens the menu`' "${BODY}" + grep -qxF -- '- `cypress/e2e/cplace/specs/footer.spec.ts`: `TC03: from the result`' "${BODY}" + [ "$(grep -c '^- `' "${BODY}")" -eq 3 ] +} + +@test "advisory mode marks the heading" { + ADVISORY=true report results-failed.json + + [ "$status" -eq 0 ] + grep -qxF '### ❌ Backend E2E (advisory)' "${BODY}" +} + +@test "more than 20 failures are capped with an and-more line" { + report results-many-failures.json + + [ "$status" -eq 0 ] + grep -qxF '**Failing tests** (first 20 of 25):' "${BODY}" + [ "$(grep -c '^- `cypress' "${BODY}")" -eq 20 ] + grep -qxF -- '- and 5 more' "${BODY}" +} + +@test "a Markdown title comes out as one plain code span, truncated" { + report results-markdown-title.json + + [ "$status" -eq 0 ] + local line + line="$(grep '^- `cypress' "${BODY}")" + [ "$(grep -c 'someone' "${BODY}")" -eq 1 ] + [[ "${line}" == '- `cypress/e2e/evil.spec.ts`: `Evil titlewith @someone and [x](y) aaa'* ]] + [[ "${line}" == *'…`' ]] + [ "$(tr -cd '`' <<<"${line}" | wc -c)" -eq 4 ] +} + +@test "a missing node shows up in the outcome even when the others passed" { + NODES_REPORTED=1 report results-passed.json + + [ "$status" -eq 0 ] + [ "$(output_of outcome)" = infrastructure-failure ] + grep -qF '**infrastructure-failure**: 1 of 2 E2E nodes produced no results' "${BODY}" +} + +@test "a missing results JSON fails instead of reporting zeros" { + run "$SCRIPTS/build-report.sh" "${BATS_TEST_TMPDIR}/nope.json" "${BODY}" + + [ "$status" -eq 1 ] + [[ "$output" == *'::error::No readable test results JSON'* ]] + [ ! -s "${GITHUB_OUTPUT}" ] +} + +@test "wrong arguments fail with the usage" { + run "$SCRIPTS/build-report.sh" x + + [ "$status" -eq 2 ] + [[ "$output" == *'Usage:'* ]] +} diff --git a/tools/scripts/backend-e2e/build-report.sh b/tools/scripts/backend-e2e/build-report.sh new file mode 100755 index 0000000..ccc1609 --- /dev/null +++ b/tools/scripts/backend-e2e/build-report.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# +# Builds the backend E2E PR comment from the results JSON of +# EnricoMi/publish-unit-test-result-action, and classifies the run with +# classify-outcome.sh. +# +# Usage: build-report.sh +# +# Env: +# ADVISORY true when failures are reported as warnings only +# BUILD_RESULT, E2E_RESULT, NODES, NODES_REPORTED +# passed on to classify-outcome.sh +# BACKEND_REPO, BACKEND_BRANCH, BACKEND_SHA, E2E_BRANCH, E2E_SHA, +# SNAPSHOT_VERSION, BACKEND_PACKAGES, E2E_PACKAGES +# shown in the comment's table +# RUN_URL the workflow run, linked from the comment +# GITHUB_OUTPUT receives tests, failed, outcome and message +# +# Test names and spec paths come from the PR's own specs, so every value is +# written inside a code span, without backticks or line breaks and cut to 200 +# characters: a title cannot add links, Markdown or @mentions to the comment. + +set -euo pipefail + +readonly MARKER='' +readonly MAX_FAILURES=20 + +main() { + if (($# != 2)); then + echo "Usage: $(basename "$0") " >&2 + exit 2 + fi + if [[ -z "${GITHUB_OUTPUT:-}" ]]; then + echo "GITHUB_OUTPUT is not set" >&2 + exit 1 + fi + local results="$1" body="$2" + if ! jq -e 'type == "object"' "${results}" >/dev/null 2>&1; then + echo "::error::No readable test results JSON at ${results}" >&2 + exit 1 + fi + + local tests failed + read -r tests failed < <(jq -r '.stats // {} | "\(.tests // 0) \((.tests_fail // 0) + (.tests_error // 0))"' "${results}") + + local classified outcome message + classified="$(mktemp)" + GITHUB_OUTPUT="${classified}" TESTS="${tests}" FAILED="${failed}" \ + "$(dirname "${BASH_SOURCE[0]}")/classify-outcome.sh" + outcome="$(sed -n 's/^outcome=//p' "${classified}")" + message="$(sed -n 's/^message=//p' "${classified}")" + + jq -r \ + --arg marker "${MARKER}" \ + --argjson max "${MAX_FAILURES}" \ + --arg outcome "${outcome}" \ + --arg message "${message}" \ + --arg advisory "${ADVISORY:-false}" \ + --arg backend_repo "${BACKEND_REPO:-}" \ + --arg backend_branch "${BACKEND_BRANCH:-}" \ + --arg backend_sha "${BACKEND_SHA:-}" \ + --arg e2e_branch "${E2E_BRANCH:-}" \ + --arg e2e_sha "${E2E_SHA:-}" \ + --arg snapshot_version "${SNAPSHOT_VERSION:-}" \ + --arg backend_packages "${BACKEND_PACKAGES:-}" \ + --arg e2e_packages "${E2E_PACKAGES:-}" \ + --arg run_url "${RUN_URL:-}" ' + def code: tostring | gsub("[`\r\n]"; "") | (if length > 200 then .[0:200] + "…" else . end) | "`\(.)`"; + def spec_of: .test_file // ((.result_file // "") | split("/") | last | sub("^cplace-e2e-results-"; "") | sub("\\.xml$"; "")); + (.stats // {}) as $stats + | [ (.cases // [])[] as $case + | (($case.states.failure // []) + ($case.states.error // []))[0:1][] + | {spec: spec_of, name: ($case.test_name // .test_name // "")} ] as $failures + | [ $marker, + "### \(if $outcome == "passed" then "✅" else "❌" end) Backend E2E\(if $advisory == "true" then " (advisory)" else "" end)", + "", + "\($stats.tests_succ // 0) passed, \(($stats.tests_fail // 0) + ($stats.tests_error // 0)) failed, \($stats.tests_skip // 0) skipped", + "", + "**\($outcome)**: \($message)", + "", + "| | |", + "|---|---|", + "| Backend | \($backend_repo | code) @ \($backend_branch | code) \($backend_sha | code) |", + "| cplace-e2e | \($e2e_branch | code) \($e2e_sha | code) |", + "| Snapshot version | \(if $snapshot_version == "" then "none" else $snapshot_version end | code) |", + "| Pinned in the backend | \($backend_packages | code) |", + "| Pinned in cplace-e2e | \($e2e_packages | code) |" ] + + (if ($failures | length) > 0 then + [ "", + "**Failing tests**\(if ($failures | length) > $max then " (first \($max) of \($failures | length))" else "" end):", + "" ] + + [ $failures[0:$max][] | "- \(.spec | code): \(.name | code)" ] + + (if ($failures | length) > $max then [ "- and \(($failures | length) - $max) more" ] else [] end) + else [] end) + + [ "", + "[Workflow run](\($run_url))\(if .check_url then " · [Test Results Backend E2E](\(.check_url))" else "" end)" ] + | join("\n")' "${results}" >"${body}" + + { + echo "tests=${tests}" + echo "failed=${failed}" + cat "${classified}" + } >>"${GITHUB_OUTPUT}" + rm -f "${classified}" +} + +main "$@" diff --git a/tools/scripts/backend-e2e/checkout-commit.bats b/tools/scripts/backend-e2e/checkout-commit.bats new file mode 100755 index 0000000..f11f1fd --- /dev/null +++ b/tools/scripts/backend-e2e/checkout-commit.bats @@ -0,0 +1,51 @@ +#!/usr/bin/env bats +# +# Behavioral tests for checkout-commit.sh. +# +# Run with: bats tools/scripts/backend-e2e/ + +setup() { + load 'test-helper' + stub_git + SHA=3333333333333333333333333333333333333333 +} + +@test "fetches and checks out the commit" { + run env STUB_HEAD="${SHA}" "$SCRIPTS/checkout-commit.sh" e2e "${SHA}" + + [ "$status" -eq 0 ] + grep -qxF -- "-C e2e fetch --quiet --depth 1 origin ${SHA}" "${GIT_LOG}" + grep -qxF -- "-C e2e checkout --quiet --detach ${SHA}" "${GIT_LOG}" + [[ "$output" == *"e2e is at ${SHA}"* ]] +} + +@test "a HEAD other than the commit fails" { + run env STUB_HEAD=4444444444444444444444444444444444444444 "$SCRIPTS/checkout-commit.sh" e2e "${SHA}" + + [ "$status" -eq 1 ] + [[ "$output" == *"::error::e2e is at 4444444444444444444444444444444444444444 after checking out ${SHA}"* ]] +} + +@test "a value that is not a full SHA fails before any git call" { + local value + for value in '' main 3333333 "--upload-pack=x${SHA}"; do + run "$SCRIPTS/checkout-commit.sh" e2e "${value}" + + [ "$status" -eq 1 ] + done + [ "$(git_call_count)" -eq 0 ] +} + +@test "a failing fetch fails the script before the checkout" { + run env STUB_FAIL=fetch STUB_HEAD="${SHA}" "$SCRIPTS/checkout-commit.sh" e2e "${SHA}" + + [ "$status" -ne 0 ] + ! grep -q checkout "${GIT_LOG}" +} + +@test "wrong arguments fail with the usage" { + run "$SCRIPTS/checkout-commit.sh" e2e + + [ "$status" -eq 2 ] + [[ "$output" == *'Usage:'* ]] +} diff --git a/tools/scripts/backend-e2e/checkout-commit.sh b/tools/scripts/backend-e2e/checkout-commit.sh new file mode 100755 index 0000000..7f9da70 --- /dev/null +++ b/tools/scripts/backend-e2e/checkout-commit.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# +# Moves an existing clone to one commit, so a test node runs exactly the +# cplace-e2e commit the resolve job chose, even when its branch moved since. +# clone-e2e-repo clones a branch tip and accepts no commit. +# +# Usage: checkout-commit.sh +# +# Uses the git credentials the job configured for the clone. + +set -euo pipefail + +main() { + if (($# != 2)); then + echo "Usage: $(basename "$0") " >&2 + exit 2 + fi + local dir="$1" sha="$2" head + if [[ ! "${sha}" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::'${sha}' is not a full commit SHA" >&2 + exit 1 + fi + + git -C "${dir}" fetch --quiet --depth 1 origin "${sha}" + git -C "${dir}" checkout --quiet --detach "${sha}" + head="$(git -C "${dir}" rev-parse HEAD)" + if [[ "${head}" != "${sha}" ]]; then + echo "::error::${dir} is at ${head} after checking out ${sha}" >&2 + exit 1 + fi + echo "${dir} is at ${sha}" +} + +main "$@" diff --git a/tools/scripts/backend-e2e/classify-outcome.bats b/tools/scripts/backend-e2e/classify-outcome.bats new file mode 100755 index 0000000..a09ecdc --- /dev/null +++ b/tools/scripts/backend-e2e/classify-outcome.bats @@ -0,0 +1,92 @@ +#!/usr/bin/env bats +# +# Behavioral tests for classify-outcome.sh. +# +# Run with: bats tools/scripts/backend-e2e/ + +setup() { + load 'test-helper' + export GITHUB_OUTPUT="${BATS_TEST_TMPDIR}/github_output" GITHUB_STEP_SUMMARY="${BATS_TEST_TMPDIR}/summary" + : >"${GITHUB_OUTPUT}" + : >"${GITHUB_STEP_SUMMARY}" +} + +output_of() { + sed -n "s/^$1=//p" "${GITHUB_OUTPUT}" +} + +# classify [ ] +classify() { + run env BUILD_RESULT="$1" E2E_RESULT="$2" TESTS="$3" FAILED="$4" NODES="${5:-2}" NODES_REPORTED="${6:-2}" \ + BACKEND_REPO=cplace BACKEND_BRANCH=master BACKEND_SHA=abc123 "$SCRIPTS/classify-outcome.sh" +} + +@test "every node passing is passed" { + classify success success 12 0 + + [ "$status" -eq 0 ] + [ "$(output_of outcome)" = passed ] + grep -qxF '### Backend E2E: passed' "${GITHUB_STEP_SUMMARY}" +} + +@test "failed tests are a test failure" { + classify success failure 12 3 + + [ "$(output_of outcome)" = test-failure ] + [[ "$(output_of message)" == "3 of 12 backend E2E tests failed"* ]] +} + +@test "a failed build is a build failure naming the backend commit" { + classify failure skipped 0 0 + + [ "$(output_of outcome)" = build-failure ] + [[ "$(output_of message)" == *'`cplace` @ `master` `abc123`'* ]] + [[ "$(output_of message)" == *'no test ran'* ]] +} + +@test "a build failure wins over a skipped e2e with no results" { + classify failure skipped 0 0 2 0 + + [ "$(output_of outcome)" = build-failure ] +} + +@test "failed nodes without results are an infrastructure failure" { + classify success failure 0 0 + + [ "$(output_of outcome)" = infrastructure-failure ] + [[ "$(output_of message)" == *'(E2E nodes: `failure`)'* ]] +} + +@test "a cancelled run is cancelled" { + classify success cancelled 4 1 + + [ "$(output_of outcome)" = cancelled ] +} + +@test "two of two nodes reported and passing is passed" { + classify success success 12 0 2 2 + + [ "$(output_of outcome)" = passed ] +} + +@test "one of two nodes reported and passing is an infrastructure failure" { + classify success success 6 0 2 1 + + [ "$(output_of outcome)" = infrastructure-failure ] + [[ "$(output_of message)" == '1 of 2 E2E nodes produced no results'* ]] +} + +@test "one of two nodes reported with failures is a test failure that names the missing node" { + classify success success 6 2 2 1 + + [ "$(output_of outcome)" = test-failure ] + [[ "$(output_of message)" == '2 of 6 backend E2E tests failed'*'1 of 2 E2E nodes produced no results'* ]] +} + +@test "a count that is not a number fails" { + classify success success '' 0 + + [ "$status" -eq 1 ] + [[ "$output" == *'TESTS is not a non-negative integer'* ]] + [ ! -s "${GITHUB_OUTPUT}" ] +} diff --git a/tools/scripts/backend-e2e/classify-outcome.sh b/tools/scripts/backend-e2e/classify-outcome.sh new file mode 100755 index 0000000..923a128 --- /dev/null +++ b/tools/scripts/backend-e2e/classify-outcome.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# +# Says what kind of result a backend E2E run had, so a reader knows whether to +# look at the backend build, the test infrastructure or the tests. +# +# Usage: classify-outcome.sh +# +# Env: +# BUILD_RESULT the build job's result (success, failure, cancelled, skipped) +# E2E_RESULT the e2e matrix's result +# TESTS the number of test results +# FAILED the number of failed and errored tests +# NODES the number of e2e nodes +# NODES_REPORTED the number of nodes that uploaded results +# BACKEND_REPO, BACKEND_BRANCH, BACKEND_SHA +# the backend that was built, named on a build failure +# GITHUB_OUTPUT receives outcome and message +# GITHUB_STEP_SUMMARY receives a heading with the message +# +# outcome is one of cancelled, build-failure, test-failure, +# infrastructure-failure and passed, checked in that order. Missing nodes are +# named in the message of a test failure too. + +set -euo pipefail + +# non_negative : fails unless the env var is a non-negative integer +non_negative() { + if [[ ! "${!1:-}" =~ ^[0-9]+$ ]]; then + echo "$1 is not a non-negative integer: '${!1:-}'" >&2 + exit 1 + fi +} + +main() { + local var + for var in GITHUB_OUTPUT GITHUB_STEP_SUMMARY; do + if [[ -z "${!var:-}" ]]; then + echo "${var} is not set" >&2 + exit 1 + fi + done + for var in TESTS FAILED NODES NODES_REPORTED; do + non_negative "${var}" + done + + local missing=$((NODES - NODES_REPORTED)) missing_text='' + if ((missing > 0)); then + missing_text="${missing} of ${NODES} E2E nodes produced no results (crashed or timed out); see their logs." + fi + + local outcome message + if [[ "${BUILD_RESULT:-}" == cancelled || "${E2E_RESULT:-}" == cancelled ]]; then + outcome=cancelled + message='The run was cancelled, usually by a newer push.' + elif [[ "${BUILD_RESULT:-}" != success ]]; then + outcome=build-failure + message="The backend build failed (\`${BACKEND_REPO:-}\` @ \`${BACKEND_BRANCH:-}\` \`${BACKEND_SHA:-}\`), so no test ran. Check the build job's log." + elif ((FAILED > 0)); then + outcome=test-failure + message="${FAILED} of ${TESTS} backend E2E tests failed; see 'Test Results Backend E2E'.${missing_text:+ ${missing_text}}" + elif ((missing > 0)); then + outcome=infrastructure-failure + message="${missing_text}" + elif ((TESTS == 0)); then + outcome=infrastructure-failure + message="No backend E2E test results were produced (E2E nodes: \`${E2E_RESULT:-}\`): docker, cplace startup or the Cypress harness broke before any test ran. Check the E2E node logs." + else + outcome=passed + message="All ${TESTS} backend E2E tests passed." + fi + + { + echo "outcome=${outcome}" + echo "message=${message}" + } >>"${GITHUB_OUTPUT}" + { + echo "### Backend E2E: ${outcome}" + echo + echo "${message}" + } >>"${GITHUB_STEP_SUMMARY}" +} + +main "$@" diff --git a/tools/scripts/backend-e2e/fetch-manifests.bats b/tools/scripts/backend-e2e/fetch-manifests.bats new file mode 100755 index 0000000..3cf31ce --- /dev/null +++ b/tools/scripts/backend-e2e/fetch-manifests.bats @@ -0,0 +1,84 @@ +#!/usr/bin/env bats +# +# Behavioral tests for fetch-manifests.sh. +# +# Run with: bats tools/scripts/backend-e2e/ + +setup() { + load 'test-helper' + stub_git + DEST="${BATS_TEST_TMPDIR}/dest" + BACKEND_SHA=1111111111111111111111111111111111111111 + E2E_SHA=2222222222222222222222222222222222222222 + export BACKEND_REPO=cplace BACKEND_SHA E2E_SHA GH_TOKEN=ghs_secret_token +} + +# assert_git_called +assert_git_called() { + if ! grep -qF -- "$1" "${GIT_LOG}"; then + echo "expected git call containing: $1" >&2 + echo "recorded git calls:" >&2 + cat "${GIT_LOG}" >&2 + return 1 + fi +} + +@test "checks out the backend's manifests and upmerge env at the backend commit" { + run "$SCRIPTS/fetch-manifests.sh" "${DEST}" + + [ "$status" -eq 0 ] + assert_git_called "-C ${DEST}/backend remote add origin https://github.com/collaborationFactory/cplace.git" + assert_git_called "-C ${DEST}/backend sparse-checkout set --no-cone /*/assets/package.json /.github/.frontend-upmerge-env" + assert_git_called "-C ${DEST}/backend fetch --quiet --depth 1 --filter=blob:none origin ${BACKEND_SHA}" + assert_git_called "-C ${DEST}/backend checkout --quiet --detach ${BACKEND_SHA}" +} + +@test "checks out cplace-e2e's root manifest at the e2e commit" { + run "$SCRIPTS/fetch-manifests.sh" "${DEST}" + + [ "$status" -eq 0 ] + assert_git_called "-C ${DEST}/cplace-e2e sparse-checkout set --no-cone /package.json" + assert_git_called "-C ${DEST}/cplace-e2e fetch --quiet --depth 1 --filter=blob:none origin ${E2E_SHA}" + assert_git_called "-C ${DEST}/cplace-e2e checkout --quiet --detach ${E2E_SHA}" +} + +@test "no branch tip is fetched" { + run "$SCRIPTS/fetch-manifests.sh" "${DEST}" + + [ "$status" -eq 0 ] + ! grep -q -- '--branch' "${GIT_LOG}" +} + +@test "the token never appears in git's argv" { + run "$SCRIPTS/fetch-manifests.sh" "${DEST}" + + [ "$status" -eq 0 ] + ! grep -q ghs_secret_token "${GIT_LOG}" +} + +@test "each missing env var fails and is named" { + local var + for var in BACKEND_REPO BACKEND_SHA E2E_SHA GH_TOKEN; do + run env -u "${var}" "$SCRIPTS/fetch-manifests.sh" "${DEST}" + + [ "$status" -eq 1 ] + [[ "$output" == *"${var} is not set"* ]] + done + [ "$(git_call_count)" -eq 0 ] +} + +@test "an unreachable repo fails the script" { + remote_unreachable cplace-e2e + + run "$SCRIPTS/fetch-manifests.sh" "${DEST}" + + [ "$status" -ne 0 ] + [[ "$output" == *"fatal: unable to access 'https://github.com/collaborationFactory/cplace-e2e.git'"* ]] +} + +@test "a missing dest-root fails with the usage" { + run "$SCRIPTS/fetch-manifests.sh" + + [ "$status" -eq 2 ] + [[ "$output" == *'Usage:'* ]] +} diff --git a/tools/scripts/backend-e2e/fetch-manifests.sh b/tools/scripts/backend-e2e/fetch-manifests.sh new file mode 100755 index 0000000..edd6858 --- /dev/null +++ b/tools/scripts/backend-e2e/fetch-manifests.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# +# Fetches the files that tell whether, and how, a frontend PR's published +# packages are consumed: every */assets/package.json and the +# .github/.frontend-upmerge-env of the backend, and the package.json of +# cplace-e2e. Fetches only those files, at the commits resolve-backend.sh chose. +# +# Usage: fetch-manifests.sh +# +# Env: +# BACKEND_REPO the backend repository, e.g. cplace +# BACKEND_SHA the backend commit to read +# E2E_SHA the cplace-e2e commit to read +# GH_TOKEN a token that can read BACKEND_REPO and cplace-e2e +# +# Checks out into /backend and /cplace-e2e. + +set -euo pipefail + +# shellcheck source=tools/scripts/backend-e2e/lib.sh +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +# manifests ...: a blob-less sparse checkout of the +# s from collaborationFactory/ at commit into . +manifests() { + local repo="$1" sha="$2" dir="$3" + shift 3 + git init --quiet "${dir}" + git -C "${dir}" remote add origin "https://github.com/collaborationFactory/${repo}.git" + git -C "${dir}" sparse-checkout set --no-cone "$@" + git_with_token -C "${dir}" fetch --quiet --depth 1 --filter=blob:none origin "${sha}" + git_with_token -C "${dir}" checkout --quiet --detach "${sha}" +} + +main() { + if (($# != 1)); then + echo "Usage: $(basename "$0") " >&2 + exit 2 + fi + local var + for var in BACKEND_REPO BACKEND_SHA E2E_SHA GH_TOKEN; do + if [[ -z "${!var:-}" ]]; then + echo "${var} is not set" >&2 + exit 1 + fi + done + + local dest="$1" + manifests "${BACKEND_REPO}" "${BACKEND_SHA}" "${dest}/backend" '/*/assets/package.json' '/.github/.frontend-upmerge-env' + manifests cplace-e2e "${E2E_SHA}" "${dest}/cplace-e2e" '/package.json' +} + +main "$@" diff --git a/tools/scripts/backend-e2e/fixtures/results-failed.json b/tools/scripts/backend-e2e/fixtures/results-failed.json new file mode 100644 index 0000000..634f9a1 --- /dev/null +++ b/tools/scripts/backend-e2e/fixtures/results-failed.json @@ -0,0 +1,28 @@ +{ + "title": "2 fail, 1 errors, 9 pass", + "check_url": "https://github.com/collaborationFactory/cplace-fe/runs/2", + "stats": { "files": 3, "tests": 12, "tests_succ": 9, "tests_skip": 0, "tests_fail": 2, "tests_error": 1 }, + "cases": [ + { + "test_name": "TC01: renders the platform footer after login", + "states": { + "failure": [ + { "test_file": "cypress/e2e/cplace-fe/platform/startPage.spec.ts", "test_name": "TC01", "message": "first" }, + { "test_file": "cypress/e2e/cplace-fe/platform/startPage.spec.ts", "test_name": "TC01", "message": "retry" } + ] + } + }, + { + "test_name": "TC02: opens the menu", + "states": { + "error": [{ "result_file": "test-results/backend-e2e-results-1/junit/cplace-e2e-results-menu.spec.ts.xml", "message": "boom" }] + } + }, + { + "states": { + "failure": [{ "test_file": "cypress/e2e/cplace/specs/footer.spec.ts", "test_name": "TC03: from the result" }] + } + }, + { "test_name": "TC04: passes", "states": { "success": [{ "test_file": "cypress/e2e/cplace/specs/ok.spec.ts" }] } } + ] +} diff --git a/tools/scripts/backend-e2e/fixtures/results-many-failures.json b/tools/scripts/backend-e2e/fixtures/results-many-failures.json new file mode 100644 index 0000000..59e4ffc --- /dev/null +++ b/tools/scripts/backend-e2e/fixtures/results-many-failures.json @@ -0,0 +1,261 @@ +{ + "stats": { + "tests": 25, + "tests_succ": 0, + "tests_skip": 0, + "tests_fail": 25, + "tests_error": 0 + }, + "cases": [ + { + "test_name": "TC0", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC1", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC2", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC3", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC4", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC5", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC6", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC7", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC8", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC9", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC10", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC11", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC12", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC13", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC14", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC15", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC16", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC17", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC18", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC19", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC20", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC21", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC22", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC23", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + }, + { + "test_name": "TC24", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/many.spec.ts" + } + ] + } + } + ] +} diff --git a/tools/scripts/backend-e2e/fixtures/results-markdown-title.json b/tools/scripts/backend-e2e/fixtures/results-markdown-title.json new file mode 100644 index 0000000..985b02f --- /dev/null +++ b/tools/scripts/backend-e2e/fixtures/results-markdown-title.json @@ -0,0 +1,21 @@ +{ + "stats": { + "tests": 1, + "tests_succ": 0, + "tests_skip": 0, + "tests_fail": 1, + "tests_error": 0 + }, + "cases": [ + { + "test_name": "Evil `title`\nwith @someone and [x](y) aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "states": { + "failure": [ + { + "test_file": "cypress/e2e/evil`.spec.ts" + } + ] + } + } + ] +} diff --git a/tools/scripts/backend-e2e/fixtures/results-passed.json b/tools/scripts/backend-e2e/fixtures/results-passed.json new file mode 100644 index 0000000..4aef5e1 --- /dev/null +++ b/tools/scripts/backend-e2e/fixtures/results-passed.json @@ -0,0 +1,6 @@ +{ + "title": "12 tests pass", + "check_url": "https://github.com/collaborationFactory/cplace-fe/runs/1", + "stats": { "files": 2, "tests": 12, "tests_succ": 12, "tests_skip": 0, "tests_fail": 0, "tests_error": 0 }, + "cases": [] +} diff --git a/tools/scripts/backend-e2e/lib.sh b/tools/scripts/backend-e2e/lib.sh new file mode 100755 index 0000000..944de70 --- /dev/null +++ b/tools/scripts/backend-e2e/lib.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# +# Shared helpers for the backend E2E scripts (.github/workflows/fe-backend-e2e.yml). +# +# This file is sourced, never executed, so it sets no shell options of its own. + +# consumed_packages +# +# Prints the names from the JSON array that +# lists in `dependencies` or `devDependencies`, one per line, sorted. A blank +# counts as `[]`, as fe-pr-snapshot.yml leaves its `packages` +# output empty when it publishes nothing. +consumed_packages() { + local manifest="$1" packages="$2" + [[ -n "${packages// /}" ]] || packages='[]' + jq -r --argjson published "${packages}" \ + '[(.dependencies // {}), (.devDependencies // {})] | add | keys[] | select(. as $name | $published | index($name))' \ + "${manifest}" +} + +# git_with_token ... +# +# Runs git with a credential helper that answers with GH_TOKEN from the +# environment, so the token never appears in argv. The -c settings reach the +# child processes git starts, such as the lazy blob fetch of a partial clone. +git_with_token() { + # Single quotes on purpose: the helper's shell expands GH_TOKEN, not this one. + # shellcheck disable=SC2016 + git -c credential.helper= \ + -c 'credential.helper=!f() { echo username=x-access-token; echo "password=${GH_TOKEN:-}"; }; f' \ + "$@" +} + +# remote_branch_sha +# +# Prints the commit of exactly refs/heads/ in collaborationFactory/ +# and returns 0. Returns 1 when the branch does not exist, and 2 when the remote +# stays unreachable after the retries. Compares the listed refs itself instead +# of trusting `ls-remote --exit-code`, whose pattern also matches refs that +# merely end in (PFM-ISSUE-34932). +# RETRY_DELAYS holds the seconds to wait before each retry (default "5 10 20"). +remote_branch_sha() { + local repo="$1" branch="$2" heads delay sha ref + local -a delays + read -r -a delays <<<"${RETRY_DELAYS-5 10 20}" + for delay in "${delays[@]}" ''; do + if heads="$(git_with_token ls-remote --heads "https://github.com/collaborationFactory/${repo}.git" "refs/heads/${branch}")"; then + while IFS=$'\t' read -r sha ref; do + if [[ "${ref}" == "refs/heads/${branch}" ]]; then + echo "${sha}" + return 0 + fi + done <<<"${heads}" + return 1 + fi + if [[ -n "${delay}" ]]; then + echo "Listing the branches of ${repo} failed, retrying in ${delay}s" >&2 + sleep "${delay}" + fi + done + echo "::error::Cannot reach collaborationFactory/${repo} to look up branch '${branch}'" >&2 + return 2 +} diff --git a/tools/scripts/backend-e2e/node-indexes.bats b/tools/scripts/backend-e2e/node-indexes.bats new file mode 100755 index 0000000..93b5cca --- /dev/null +++ b/tools/scripts/backend-e2e/node-indexes.bats @@ -0,0 +1,33 @@ +#!/usr/bin/env bats +# +# Behavioral tests for node-indexes.sh. +# +# Run with: bats tools/scripts/backend-e2e/ + +setup() { + load 'test-helper' +} + +@test "anything but a positive integer fails with the value in the message" { + local value + for value in '' abc 0 05 -1; do + run "$SCRIPTS/node-indexes.sh" "$value" + + [ "$status" -eq 1 ] + [ "$output" = "NODES must be a positive integer, got '$value'" ] + done +} + +@test "1 gives a single node" { + run "$SCRIPTS/node-indexes.sh" 1 + + [ "$status" -eq 0 ] + [ "$output" = '[0]' ] +} + +@test "3 gives three nodes" { + run "$SCRIPTS/node-indexes.sh" 3 + + [ "$status" -eq 0 ] + [ "$output" = '[0,1,2]' ] +} diff --git a/tools/scripts/backend-e2e/node-indexes.sh b/tools/scripts/backend-e2e/node-indexes.sh new file mode 100755 index 0000000..41a1abf --- /dev/null +++ b/tools/scripts/backend-e2e/node-indexes.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# +# Prints the node matrix of the backend E2E job: the JSON array [0..n-1]. +# +# Usage: node-indexes.sh +# +# Fails unless is a positive integer without a leading zero. + +set -euo pipefail + +main() { + local nodes="${1:-}" + case "${nodes}" in + '' | *[!0-9]* | 0*) echo "NODES must be a positive integer, got '${nodes}'" >&2; exit 1 ;; + esac + jq -cn --argjson n "${nodes}" '[range($n)]' +} + +main "$@" diff --git a/tools/scripts/backend-e2e/pin-snapshots.bats b/tools/scripts/backend-e2e/pin-snapshots.bats new file mode 100755 index 0000000..1c5213a --- /dev/null +++ b/tools/scripts/backend-e2e/pin-snapshots.bats @@ -0,0 +1,208 @@ +#!/usr/bin/env bats +# +# Behavioral tests for pin-snapshots.sh. npm is stubbed on PATH. +# +# Run with: bats tools/scripts/backend-e2e/ + +bats_require_minimum_version 1.5.0 + +setup() { + load 'test-helper' + stub_npm +} + +@test "pins only published packages that the assets dir depends on" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"0.0.0-SNAPSHOT-x","lodash":"4.17.21"}}' + + run env PACKAGES='["@cplace-next/cf-platform","@cplace-next/cf-shell"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 0 ] + assert_npm_called_in "$WORK/plugin.a/assets" \ + "i @cplace-next/cf-platform@0.0.0-feat-1-42 --save-exact --legacy-peer-deps" +} + +@test "a dir that consumes no published package is left alone, silently" { + make_assets_dir plugin.a '{"dependencies":{"lodash":"4.17.21"}}' + + run env PACKAGES='["@cplace-next/cf-platform"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 0 ] + [ "$(npm_call_count)" -eq 0 ] + [ -z "$output" ] +} + +@test "a published package in devDependencies is pinned too" { + make_assets_dir plugin.a '{"devDependencies":{"@cplace-next/cf-e2e-testing-sdk":"26.4.1"}}' + + run env PACKAGES='["@cplace-next/cf-e2e-testing-sdk"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 0 ] + assert_npm_called_in "$WORK/plugin.a/assets" \ + "i @cplace-next/cf-e2e-testing-sdk@0.0.0-feat-1-42 --save-exact --legacy-peer-deps" +} + +@test "a dir without package.json is skipped" { + mkdir -p "$WORK/plugin.empty/assets" + + run env PACKAGES='["@cplace-next/cf-platform"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.empty/assets" + + [ "$status" -eq 0 ] + [ "$(npm_call_count)" -eq 0 ] +} + +@test "an npm failure fails the script and names the dir" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0"}}' + + run env NPM_EXIT=1 PACKAGES='["@cplace-next/cf-platform"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -ne 0 ] + [[ "$output" == *"pinning failed in $WORK/plugin.a/assets"* ]] +} + +@test "several dirs get one npm call each" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0"}}' + make_assets_dir plugin.b '{"dependencies":{"@cplace-next/cf-shell":"1.0.0"}}' + + run env PACKAGES='["@cplace-next/cf-platform","@cplace-next/cf-shell"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" "$WORK/plugin.b/assets" + + [ "$status" -eq 0 ] + [ "$(npm_call_count)" -eq 2 ] + assert_npm_called_in "$WORK/plugin.a/assets" \ + "i @cplace-next/cf-platform@0.0.0-feat-1-42 --save-exact --legacy-peer-deps" + assert_npm_called_in "$WORK/plugin.b/assets" \ + "i @cplace-next/cf-shell@0.0.0-feat-1-42 --save-exact --legacy-peer-deps" +} + +@test "prints one ' @' line per pin, and nothing else on stdout" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0","@cplace-next/cf-shell":"1.0.0"}}' + + run --separate-stderr env PACKAGES='["@cplace-next/cf-platform","@cplace-next/cf-shell"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 0 ] + [ "$(npm_call_count)" -eq 1 ] + assert_npm_called_in "$WORK/plugin.a/assets" \ + "i @cplace-next/cf-platform@0.0.0-feat-1-42 @cplace-next/cf-shell@0.0.0-feat-1-42 --save-exact --legacy-peer-deps" + [ "${#lines[@]}" -eq 2 ] + [ "${lines[0]}" = "$WORK/plugin.a/assets @cplace-next/cf-platform@0.0.0-feat-1-42" ] + [ "${lines[1]}" = "$WORK/plugin.a/assets @cplace-next/cf-shell@0.0.0-feat-1-42" ] +} + +@test "an empty PACKAGES pins nothing" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0"}}' + + run env PACKAGES='' "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 0 ] + [ "$(npm_call_count)" -eq 0 ] +} + +@test "a glob matching two dirs pins in both" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0"}}' + make_assets_dir plugin.b '{"dependencies":{"@cplace-next/cf-platform":"1.0.0"}}' + + run env PACKAGES='["@cplace-next/cf-platform"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/*/assets" + + [ "$status" -eq 0 ] + [ "$(npm_call_count)" -eq 2 ] + assert_npm_called_in "$WORK/plugin.a/assets" \ + "i @cplace-next/cf-platform@0.0.0-feat-1-42 --save-exact --legacy-peer-deps" + assert_npm_called_in "$WORK/plugin.b/assets" \ + "i @cplace-next/cf-platform@0.0.0-feat-1-42 --save-exact --legacy-peer-deps" +} + +@test "a glob matching nothing fails, names the glob and calls no npm" { + mkdir -p "$WORK" + + run env PACKAGES='["@cplace-next/cf-platform"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/*/assets" + + [ "$status" -eq 1 ] + [[ "$output" == *"No directory matches: $WORK/*/assets"* ]] + [ "$(npm_call_count)" -eq 0 ] +} + +@test "a blank glob next to a matching one is ignored" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0"}}' + + run env PACKAGES='["@cplace-next/cf-platform"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 '' "$WORK/*/assets" ' ' + + [ "$status" -eq 0 ] + [ "$(npm_call_count)" -eq 1 ] + assert_npm_called_in "$WORK/plugin.a/assets" \ + "i @cplace-next/cf-platform@0.0.0-feat-1-42 --save-exact --legacy-peer-deps" +} + +# lock_has : the package-lock.json npm leaves behind +lock_has() { + jq -n --arg key "node_modules/$2" --arg integrity "$3" '{packages: {($key): {integrity: $integrity}}}' >"$1/package-lock.json" +} + +@test "an installed integrity that matches the published one passes" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0"}}' + lock_has "$WORK/plugin.a/assets" @cplace-next/cf-platform sha512-published + + run env PACKAGES='["@cplace-next/cf-platform"]' INTEGRITIES='{"@cplace-next/cf-platform":"sha512-published"}' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 0 ] + [[ "$output" != *'::warning::'* ]] +} + +@test "an installed integrity that differs fails and names the package" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0"}}' + lock_has "$WORK/plugin.a/assets" @cplace-next/cf-platform sha512-newer-push + + run env PACKAGES='["@cplace-next/cf-platform"]' INTEGRITIES='{"@cplace-next/cf-platform":"sha512-published"}' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 1 ] + [[ "$output" == *"::error::@cplace-next/cf-platform@0.0.0-feat-1-42 changed since this run's snapshot job"* ]] +} + +@test "a package without a published integrity is pinned with a warning" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0","@cplace-next/cf-shell":"1.0.0"}}' + lock_has "$WORK/plugin.a/assets" @cplace-next/cf-platform sha512-published + + run env PACKAGES='["@cplace-next/cf-platform","@cplace-next/cf-shell"]' INTEGRITIES='{"@cplace-next/cf-platform":"sha512-published"}' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 0 ] + [[ "$output" == *'::warning::No published integrity for @cplace-next/cf-shell@0.0.0-feat-1-42'* ]] + [[ "$output" != *'No published integrity for @cplace-next/cf-platform'* ]] +} + +@test "an empty INTEGRITIES warns once per package" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0","@cplace-next/cf-shell":"1.0.0"}}' + + run env PACKAGES='["@cplace-next/cf-platform","@cplace-next/cf-shell"]' INTEGRITIES='' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 0 ] + [ "$(grep -c '::warning::No published integrity' <<<"$output")" -eq 2 ] +} + +@test "an INTEGRITIES that is not a JSON object fails before any npm call" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0"}}' + + run env PACKAGES='["@cplace-next/cf-platform"]' INTEGRITIES='["x"]' \ + "$SCRIPTS/pin-snapshots.sh" 0.0.0-feat-1-42 "$WORK/plugin.a/assets" + + [ "$status" -eq 1 ] + [ "$(npm_call_count)" -eq 0 ] +} + +@test "a missing version is a usage error" { + run "$SCRIPTS/pin-snapshots.sh" '' "$WORK" + + [ "$status" -eq 2 ] + [[ "$output" == *'Usage:'* ]] +} diff --git a/tools/scripts/backend-e2e/pin-snapshots.sh b/tools/scripts/backend-e2e/pin-snapshots.sh new file mode 100755 index 0000000..e188359 --- /dev/null +++ b/tools/scripts/backend-e2e/pin-snapshots.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash +# +# Pins the snapshot versions a frontend PR published into the npm projects that +# consume them, with the same npm call the nightly upmerge uses to bump plugins. +# +# Usage: PACKAGES='["@scope/name", ...]' INTEGRITIES='{"@scope/name": "sha512-..."}' \ +# pin-snapshots.sh ... +# +# Each glob is expanded to npm project dirs; a blank glob is ignored, and the +# script fails when no glob matches a dir. A literal path expands to itself. +# A dir without package.json is skipped. Prints one " @" +# line per pin, and nothing when no dir consumes a published package. +# +# Every PR push republishes the same snapshot version. After each install, the +# integrity recorded in the dir's package-lock.json must equal the one this +# run's snapshot job published (INTEGRITIES), so a run never tests a newer +# push's content. A package INTEGRITIES does not list is pinned unchecked, with +# a warning. + +set -euo pipefail + +# shellcheck source=tools/scripts/backend-e2e/lib.sh +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +# verify_integrity +verify_integrity() { + local dir="$1" name="$2" version="$3" integrities="$4" expected actual + expected="$(jq -r --arg name "${name}" '.[$name] // empty' <<<"${integrities}")" + if [[ -z "${expected}" ]]; then + echo "::warning::No published integrity for ${name}@${version}, so it is pinned unchecked" + return 0 + fi + actual="$(jq -r --arg key "node_modules/${name}" '.packages[$key].integrity // empty' "${dir}/package-lock.json" 2>/dev/null || true)" + if [[ "${actual}" != "${expected}" ]]; then + echo "::error::${name}@${version} changed since this run's snapshot job (republished by a newer push); re-run on the latest push" + return 1 + fi +} + +main() { + if (($# < 2)) || [[ -z "$1" ]]; then + echo "Usage: PACKAGES='[\"@scope/name\"]' $(basename "$0") ..." >&2 + exit 2 + fi + local version="$1" + shift + local packages="${PACKAGES:-}" + local integrities="${INTEGRITIES:-}" + [[ -n "${integrities// /}" ]] || integrities='{}' + if ! jq -e 'type == "object"' <<<"${integrities}" >/dev/null 2>&1; then + echo "INTEGRITIES is not a JSON object: ${integrities}" >&2 + exit 1 + fi + + local pattern + local -a dirs=() + shopt -s nullglob + for pattern in "$@"; do + [[ -n "${pattern// /}" ]] || continue + # Unquoted on purpose: the pattern is a glob to expand. + # shellcheck disable=SC2206 + dirs+=(${pattern}) + done + shopt -u nullglob + if ((${#dirs[@]} == 0)); then + echo "No directory matches: $*" >&2 + exit 1 + fi + + local dir consumed name + for dir in "${dirs[@]}"; do + [[ -f "${dir}/package.json" ]] || continue + + consumed="$(consumed_packages "${dir}/package.json" "${packages}")" + [[ -n "${consumed}" ]] || continue + + local -a names=() specs=() + mapfile -t names <<<"${consumed}" + for name in "${names[@]}"; do + specs+=("${name}@${version}") + done + + if ! (cd "${dir}" && npm i "${specs[@]}" --save-exact --legacy-peer-deps >&2); then + echo "pinning failed in ${dir}" >&2 + exit 1 + fi + + for name in "${names[@]}"; do + verify_integrity "${dir}" "${name}" "${version}" "${integrities}" >&2 + done + for name in "${names[@]}"; do + echo "${dir} ${name}@${version}" + done + done +} + +main "$@" diff --git a/tools/scripts/backend-e2e/pr-directives.bats b/tools/scripts/backend-e2e/pr-directives.bats new file mode 100755 index 0000000..2e5208a --- /dev/null +++ b/tools/scripts/backend-e2e/pr-directives.bats @@ -0,0 +1,68 @@ +#!/usr/bin/env bats +# +# Behavioral tests for pr-directives.sh. +# +# Run with: bats tools/scripts/backend-e2e/ + +setup() { + load 'test-helper' +} + +directives() { + run env PR_BODY="$1" "$SCRIPTS/pr-directives.sh" +} + +@test "a body without directives prints empty overrides" { + directives $'Fixes the footer.\n\nNo special setup.' + + [ "$status" -eq 0 ] + [ "${lines[0]}" = 'BACKEND_BRANCH_OVERRIDE=' ] + [ "${lines[1]}" = 'E2E_BRANCH_OVERRIDE=' ] +} + +@test "an unset body prints empty overrides" { + run env -u PR_BODY "$SCRIPTS/pr-directives.sh" + + [ "$status" -eq 0 ] + [ "${lines[0]}" = 'BACKEND_BRANCH_OVERRIDE=' ] +} + +@test "both directives are read" { + directives $'Pairs with a backend change.\n\nbackend-branch: feature/PFM-1-x\ncplace-e2e-branch:feature/PFM-1-specs\n' + + [ "$status" -eq 0 ] + [ "${lines[0]}" = 'BACKEND_BRANCH_OVERRIDE=feature/PFM-1-x' ] + [ "${lines[1]}" = 'E2E_BRANCH_OVERRIDE=feature/PFM-1-specs' ] +} + +@test "a CRLF body yields the bare branch" { + directives $'Intro\r\nbackend-branch: feature/x\r\ncplace-e2e-branch: feature/y\r\n' + + [ "$status" -eq 0 ] + [ "${lines[0]}" = 'BACKEND_BRANCH_OVERRIDE=feature/x' ] + [ "${lines[1]}" = 'E2E_BRANCH_OVERRIDE=feature/y' ] +} + +@test "a directive inside other text is ignored" { + directives $'Do not set backend-branch: feature/x here.\n> backend-branch: feature/quoted\n cplace-e2e-branch: feature/indented' + + [ "$status" -eq 0 ] + [ "${lines[0]}" = 'BACKEND_BRANCH_OVERRIDE=' ] + [ "${lines[1]}" = 'E2E_BRANCH_OVERRIDE=' ] +} + +@test "the last directive wins" { + directives $'backend-branch: feature/old\nbackend-branch: feature/new' + + [ "$status" -eq 0 ] + [ "${lines[0]}" = 'BACKEND_BRANCH_OVERRIDE=feature/new' ] +} + +@test "the body is never executed" { + directives $'backend-branch: $(touch '"${BATS_TEST_TMPDIR}"$'/pwned)\n`touch '"${BATS_TEST_TMPDIR}"$'/pwned2`' + + [ "$status" -eq 0 ] + [ "${lines[0]}" = 'BACKEND_BRANCH_OVERRIDE=$(touch' ] + [ ! -e "${BATS_TEST_TMPDIR}/pwned" ] + [ ! -e "${BATS_TEST_TMPDIR}/pwned2" ] +} diff --git a/tools/scripts/backend-e2e/pr-directives.sh b/tools/scripts/backend-e2e/pr-directives.sh new file mode 100755 index 0000000..ad64fb3 --- /dev/null +++ b/tools/scripts/backend-e2e/pr-directives.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# +# Reads the backend E2E directives from a frontend PR's description, so a PR can +# name the backend and cplace-e2e branch it is tested against. +# +# Usage: PR_BODY="" pr-directives.sh +# +# A directive is a line of its own: +# backend-branch: +# cplace-e2e-branch: +# +# Prints BACKEND_BRANCH_OVERRIDE= and E2E_BRANCH_OVERRIDE=, empty +# when the body has no such line. The last matching line wins; everything else +# in the body is ignored. The value is not validated here: resolve-backend.sh +# checks that it is a branch that exists. +# +# The body is untrusted input. It arrives through the environment, never as +# part of a script. + +set -euo pipefail + +main() { + local backend='' e2e='' line + local backend_re='^backend-branch:[[:space:]]*([^[:space:]]+)' + local e2e_re='^cplace-e2e-branch:[[:space:]]*([^[:space:]]+)' + while IFS= read -r line || [[ -n "${line}" ]]; do + line="${line%$'\r'}" + if [[ "${line}" =~ ${backend_re} ]]; then + backend="${BASH_REMATCH[1]}" + elif [[ "${line}" =~ ${e2e_re} ]]; then + e2e="${BASH_REMATCH[1]}" + fi + done <<<"${PR_BODY:-}" + + echo "BACKEND_BRANCH_OVERRIDE=${backend}" + echo "E2E_BRANCH_OVERRIDE=${e2e}" +} + +main "$@" diff --git a/tools/scripts/backend-e2e/report-drift.bats b/tools/scripts/backend-e2e/report-drift.bats new file mode 100755 index 0000000..af17cd4 --- /dev/null +++ b/tools/scripts/backend-e2e/report-drift.bats @@ -0,0 +1,102 @@ +#!/usr/bin/env bats +# +# Behavioral tests for report-drift.sh. npm is stubbed on PATH. +# +# Run with: bats tools/scripts/backend-e2e/ + +setup() { + load 'test-helper' + stub_npm + export GITHUB_OUTPUT="${BATS_TEST_TMPDIR}/github_output" GITHUB_STEP_SUMMARY="${BATS_TEST_TMPDIR}/summary" + : >"${GITHUB_OUTPUT}" + : >"${GITHUB_STEP_SUMMARY}" + mkdir -p "${WORK}/.github" + printf 'FE_PACKAGE_PREFIXES=@cplace-next' >"${WORK}/.github/.frontend-upmerge-env" + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"0.0.0-SNAPSHOT-a","@cplace-next/cf-shell":"0.0.0-SNAPSHOT-b","lodash":"4.17.21"}}' +} + +output_of() { + sed -n "s/^$1=//p" "${GITHUB_OUTPUT}" +} + +drift() { + run env PACKAGES="${PACKAGES:-[]}" FE_BASE="$1" "$SCRIPTS/report-drift.sh" "${WORK}" +} + +@test "a current and a behind pin are both reported, and only the behind one counts" { + npm_view_returns @cplace-next/cf-platform@snapshot '"0.0.0-SNAPSHOT-a"' + npm_view_returns @cplace-next/cf-shell@snapshot '"0.0.0-SNAPSHOT-c"' + + drift master + + [ "$status" -eq 0 ] + [ "$(output_of drift)" = 1 ] + grep -qF '| `@cplace-next/cf-platform` | `0.0.0-SNAPSHOT-a` | `0.0.0-SNAPSHOT-a` | current |' "${GITHUB_STEP_SUMMARY}" + grep -qF '| `@cplace-next/cf-shell` | `0.0.0-SNAPSHOT-b` | `0.0.0-SNAPSHOT-c` | behind |' "${GITHUB_STEP_SUMMARY}" + ! grep -q lodash "${GITHUB_STEP_SUMMARY}" +} + +@test "a release line looks up the highest X.Y version" { + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"26.1.3"}}' + npm_view_returns @cplace-next/cf-platform@26.1 '["26.1.1","26.1.3","26.1.4"]' + + drift release/26.1 + + [ "$status" -eq 0 ] + assert_npm_called_in "${PWD}" "view @cplace-next/cf-platform@26.1 version --json" + [ "$(output_of drift)" = 1 ] + grep -qF '| `26.1.3` | `26.1.4` | behind |' "${GITHUB_STEP_SUMMARY}" +} + +@test "an npm failure warns, names the package and exits 0" { + npm_view_returns @cplace-next/cf-platform@snapshot '"0.0.0-SNAPSHOT-a"' + + drift master + + [ "$status" -eq 0 ] + [[ "$output" == *'::warning::Could not look up the latest @cplace-next/cf-shell@snapshot'* ]] + [ "$(output_of drift)" = 0 ] + grep -qF '| `@cplace-next/cf-shell` | `0.0.0-SNAPSHOT-b` | ? | unknown |' "${GITHUB_STEP_SUMMARY}" +} + +@test "a published package is excluded" { + npm_view_returns @cplace-next/cf-shell@snapshot '"0.0.0-SNAPSHOT-b"' + + PACKAGES='["@cplace-next/cf-platform"]' drift main + + [ "$status" -eq 0 ] + ! grep -q cf-platform "${GITHUB_STEP_SUMMARY}" + ! grep -q cf-platform "${NPM_LOG}" + [ "$(output_of drift)" = 0 ] +} + +@test "no prefixes file writes one notice and no table" { + rm "${WORK}/.github/.frontend-upmerge-env" + + drift master + + [ "$status" -eq 0 ] + [[ "$output" == *'::notice::No FE_PACKAGE_PREFIXES'* ]] + [ ! -s "${GITHUB_STEP_SUMMARY}" ] + [ "$(npm_call_count)" -eq 0 ] + [ "$(output_of drift)" = 0 ] +} + +@test "a line without an FE base writes one notice and no table" { + drift feature/x + + [ "$status" -eq 0 ] + [[ "$output" == *"::notice::'feature/x' is not a backend line"* ]] + [ ! -s "${GITHUB_STEP_SUMMARY}" ] +} + +@test "the same pin in two plugins is one row" { + make_assets_dir plugin.b '{"dependencies":{"@cplace-next/cf-platform":"0.0.0-SNAPSHOT-a"}}' + npm_view_returns @cplace-next/cf-platform@snapshot '"0.0.0-SNAPSHOT-a"' + npm_view_returns @cplace-next/cf-shell@snapshot '"0.0.0-SNAPSHOT-b"' + + drift master + + [ "$status" -eq 0 ] + [ "$(grep -c 'cf-platform' "${GITHUB_STEP_SUMMARY}")" -eq 1 ] +} diff --git a/tools/scripts/backend-e2e/report-drift.sh b/tools/scripts/backend-e2e/report-drift.sh new file mode 100755 index 0000000..16a8b50 --- /dev/null +++ b/tools/scripts/backend-e2e/report-drift.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# +# Reports how far the backend's pins of the frontend packages this PR did not +# publish lag behind the frontend base. Those packages are tested at the +# backend's pins, so a backend that lags its FE base tests the PR against older +# frontend code than the PR is based on. Report only: it never fails the run. +# +# Usage: report-drift.sh +# +# Reads /*/assets/package.json and the FE_PACKAGE_PREFIXES of +# /.github/.frontend-upmerge-env, the file the nightly +# upmerge bumps the same pins from. +# +# Env: +# PACKAGES JSON array of the packages the PR published; excluded +# FE_BASE the backend line: master, main or release/X.Y +# GITHUB_OUTPUT receives drift, the number of packages behind +# GITHUB_STEP_SUMMARY receives the table +# +# The FE base's latest version is the one the nightly upmerge would bump to: +# the `snapshot` dist-tag for master/main, the highest X.Y.* for release/X.Y. + +set -euo pipefail + +# version_spec : the npm spec of the FE base's latest version, +# the mapping of version_spec_for in cplace-gh-workflows' +# upmerge_and_bump_releases.sh. Fails for any other line. +version_spec() { + case "$1" in + master | main) echo snapshot ;; + release/[0-9]*.[0-9]*) + local line="${1#release/}" + [[ "${line}" =~ ^[0-9]+\.[0-9]+$ ]] || return 1 + echo "${line}" + ;; + *) return 1 ;; + esac +} + +# latest_version : the highest version of matching +latest_version() { + npm view "$1@$2" version --json 2>/dev/null | jq -er 'if type == "array" then last else . end' +} + +main() { + if (($# != 1)); then + echo "Usage: $(basename "$0") " >&2 + exit 2 + fi + local var + for var in GITHUB_OUTPUT GITHUB_STEP_SUMMARY; do + if [[ -z "${!var:-}" ]]; then + echo "${var} is not set" >&2 + exit 1 + fi + done + local backend="$1" packages="${PACKAGES:-}" + [[ -n "${packages// /}" ]] || packages='[]' + + local env_file="${backend}/.github/.frontend-upmerge-env" prefixes='' + if [[ -f "${env_file}" ]]; then + prefixes="$(sed -n 's/^FE_PACKAGE_PREFIXES=//p' "${env_file}" | tr -d '\r"' | tail -n 1)" + fi + if [[ -z "${prefixes}" ]]; then + echo "::notice::No FE_PACKAGE_PREFIXES in ${env_file}, so no FE version drift is reported" + echo "drift=0" >>"${GITHUB_OUTPUT}" + return + fi + local spec + if ! spec="$(version_spec "${FE_BASE:-}")"; then + echo "::notice::'${FE_BASE:-}' is not a backend line with an FE base, so no FE version drift is reported" + echo "drift=0" >>"${GITHUB_OUTPUT}" + return + fi + + local -a manifests + shopt -s nullglob + manifests=("${backend}"/*/assets/package.json) + shopt -u nullglob + + local pins='' + if ((${#manifests[@]} > 0)); then + # " " for each FE dependency the PR did not publish. + pins="$(jq -r --arg re "^(${prefixes})/" --argjson published "${packages}" \ + '.dependencies // {} | to_entries[] | select((.key | test($re)) and (.key as $k | $published | index($k) | not)) | "\(.key) \(.value)"' \ + "${manifests[@]}" | sort -u)" + fi + + local drift=0 name pin latest state + local -a rows=() + while read -r name pin; do + [[ -n "${name}" ]] || continue + if ! latest="$(latest_version "${name}" "${spec}")"; then + echo "::warning::Could not look up the latest ${name}@${spec}; its drift is not reported" + rows+=("| \`${name}\` | \`${pin}\` | ? | unknown |") + continue + fi + if [[ "${pin}" == "${latest}" ]]; then + state=current + else + state=behind + drift=$((drift + 1)) + fi + rows+=("| \`${name}\` | \`${pin}\` | \`${latest}\` | ${state} |") + done <<<"${pins}" + + { + echo "### FE version drift (\`${FE_BASE}\`, npm \`${spec}\`)" + echo + if ((${#rows[@]} == 0)); then + echo 'The backend pins no FE package other than the published ones.' + else + echo "${drift} of ${#rows[@]} FE packages the PR did not publish are behind the FE base." + echo + echo '| Package | Backend pin | FE base latest | |' + echo '|---|---|---|---|' + printf '%s\n' "${rows[@]}" + fi + } >>"${GITHUB_STEP_SUMMARY}" + echo "drift=${drift}" >>"${GITHUB_OUTPUT}" +} + +main "$@" diff --git a/tools/scripts/backend-e2e/resolve-backend.bats b/tools/scripts/backend-e2e/resolve-backend.bats new file mode 100755 index 0000000..12f48d4 --- /dev/null +++ b/tools/scripts/backend-e2e/resolve-backend.bats @@ -0,0 +1,274 @@ +#!/usr/bin/env bats +# +# Behavioral tests for resolve-backend.sh. +# +# Run with: bats tools/scripts/backend-e2e/ + +setup() { + load 'test-helper' + export GITHUB_OUTPUT="${BATS_TEST_TMPDIR}/github_output" + : >"${GITHUB_OUTPUT}" + stub_git + export RETRY_DELAYS='0 0 0' GH_TOKEN=ghs_secret_token +} + +# output_of : the value resolve-backend.sh wrote for +output_of() { + sed -n "s/^$1=//p" "${GITHUB_OUTPUT}" +} + +# branches []: runs the branches step for the cplace backend. +# BACKEND_BRANCH_OVERRIDE and E2E_BRANCH_OVERRIDE pass through from the caller. +branches() { + run env BACKEND_REPO=cplace BASE_REF="$1" HEAD_REF="${2:-}" BACKEND_BRANCH_OVERRIDE="${BACKEND_BRANCH_OVERRIDE:-}" E2E_BRANCH_OVERRIDE="${E2E_BRANCH_OVERRIDE:-}" "$SCRIPTS/resolve-backend.sh" branches +} + +@test "cplace-fe maps to cplace, checked out as main" { + run env FE_REPO=cplace-fe "$SCRIPTS/resolve-backend.sh" repo + + [ "$status" -eq 0 ] + [ "$(output_of backend_repo)" = cplace ] + [ "$(output_of repo_dir)" = main ] +} + +@test "cplace-paw-fe maps to cplace-paw, checked out under its own name" { + run env FE_REPO=cplace-paw-fe "$SCRIPTS/resolve-backend.sh" repo + + [ "$status" -eq 0 ] + [ "$(output_of backend_repo)" = cplace-paw ] + [ "$(output_of repo_dir)" = cplace-paw ] +} + +@test "an unknown repo fails and names it" { + run env FE_REPO=some-tool "$SCRIPTS/resolve-backend.sh" repo + + [ "$status" -eq 1 ] + [[ "$output" == *"No backend repo for 'some-tool'"* ]] + [ ! -s "${GITHUB_OUTPUT}" ] +} + +@test "a bare -fe is not a repo name" { + run env FE_REPO=-fe "$SCRIPTS/resolve-backend.sh" repo + + [ "$status" -eq 1 ] +} + +@test "base main maps to master" { + remote_has cplace master + remote_has cplace-e2e master + + branches main + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = master ] + [ "$(output_of e2e_branch)" = master ] +} + +@test "base master maps to master" { + remote_has cplace master + remote_has cplace-e2e master + + branches master + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = master ] +} + +@test "a beta release maps to its release line" { + remote_has cplace release/26.4 + remote_has cplace-e2e release/26.4 + + branches release/26.4-beta + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = release/26.4 ] + [ "$(output_of e2e_branch)" = release/26.4 ] +} + +@test "a beta release without its release line falls back to master with a warning" { + remote_has cplace release/26.4 + remote_has cplace-e2e master + + branches release/26.4-beta + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = release/26.4 ] + [ "$(output_of e2e_branch)" = master ] + [[ "$output" == *"::warning::cplace-e2e has no branch 'release/26.4'"* ]] +} + +@test "a release branch maps to itself" { + remote_has cplace release/26.1 + remote_has cplace-e2e release/26.1 + + branches release/26.1 + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = release/26.1 ] +} + +@test "any other base maps to master with a warning" { + remote_has cplace master + remote_has cplace-e2e master + + branches feature/epic + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = master ] + [[ "$output" == *"::warning::Base branch 'feature/epic'"* ]] +} + +@test "a same-named branch is used in each repo that has it" { + remote_has cplace master + remote_has cplace-e2e master feature/x + + branches main feature/x + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = master ] + [ "$(output_of e2e_branch)" = feature/x ] +} + +@test "a same-named branch present in both repos is used for both" { + remote_has cplace feature/x + remote_has cplace-e2e feature/x + + branches release/26.1 feature/x + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = feature/x ] + [ "$(output_of e2e_branch)" = feature/x ] +} + +@test "a branch that only starts with the head ref is not a match" { + remote_has cplace master feature/x-2 + remote_has cplace-e2e master other/feature/x + + branches main feature/x + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = master ] + [ "$(output_of e2e_branch)" = master ] +} + +@test "both commits are written next to their branches" { + remote_has cplace master feature/x + remote_has cplace-e2e master + + branches main feature/x + + [ "$status" -eq 0 ] + [ "$(output_of base_branch)" = master ] + [ "$(output_of backend_sha)" = "$(sha_of cplace feature/x)" ] + [ "$(output_of e2e_sha)" = "$(sha_of cplace-e2e master)" ] +} + +@test "an upmerge head is not used as the backend line" { + remote_has cplace release/26.1 release/26.2 + remote_has cplace-e2e release/26.1 release/26.2 + + branches release/26.2 release/26.1 + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = release/26.2 ] + [ "$(output_of e2e_branch)" = release/26.2 ] +} + +@test "a main head is ignored" { + remote_has cplace master main + remote_has cplace-e2e master main + + branches main main + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = master ] +} + +@test "a missing base branch fails" { + remote_has cplace-e2e master + + branches main + + [ "$status" -eq 1 ] + [[ "$output" == *"::error::cplace has no branch 'master'"* ]] + [ ! -s "${GITHUB_OUTPUT}" ] +} + +@test "an existing override wins over a same-named branch" { + remote_has cplace master feature/x feature/backend + remote_has cplace-e2e master feature/x feature/specs + + BACKEND_BRANCH_OVERRIDE=feature/backend E2E_BRANCH_OVERRIDE=feature/specs branches main feature/x + + [ "$status" -eq 0 ] + [ "$(output_of backend_branch)" = feature/backend ] + [ "$(output_of backend_sha)" = "$(sha_of cplace feature/backend)" ] + [ "$(output_of e2e_branch)" = feature/specs ] +} + +@test "a missing override fails instead of falling back" { + remote_has cplace master + remote_has cplace-e2e master + + BACKEND_BRANCH_OVERRIDE=feature/gone branches main + + [ "$status" -eq 1 ] + [[ "$output" == *"::error::cplace has no branch 'feature/gone', which the PR body asks for"* ]] + [ ! -s "${GITHUB_OUTPUT}" ] +} + +@test "an invalid override name fails before any lookup" { + remote_has cplace master + remote_has cplace-e2e master + + local name + for name in 'feature..x' '-upload-pack=x' 'a b'; do + BACKEND_BRANCH_OVERRIDE="${name}" branches main + + [ "$status" -eq 1 ] + [[ "$output" == *"::error::'${name}' from the PR body is not a valid branch name"* ]] + done + ! grep -q ls-remote "${GIT_LOG}" +} + +@test "an unreachable remote fails after the retries and writes nothing" { + remote_unreachable cplace + + branches main feature/x + + [ "$status" -eq 2 ] + [[ "$output" == *"::error::Cannot reach collaborationFactory/cplace"* ]] + [ "$(git_call_count)" -eq 4 ] + [ ! -s "${GITHUB_OUTPUT}" ] +} + +@test "the token never appears in git's argv" { + remote_has cplace feature/x + remote_has cplace-e2e master + + branches main feature/x + + [ "$status" -eq 0 ] + ! grep -q ghs_secret_token "${GIT_LOG}" +} + +@test "branches without BACKEND_REPO fails" { + run env BASE_REF=main "$SCRIPTS/resolve-backend.sh" branches + + [ "$status" -eq 1 ] + [[ "$output" == *'BACKEND_REPO is not set'* ]] +} + +@test "an unknown step fails with the usage" { + run "$SCRIPTS/resolve-backend.sh" both + + [ "$status" -eq 2 ] + [[ "$output" == *'Usage:'* ]] +} + +@test "a missing GITHUB_OUTPUT fails" { + run env -u GITHUB_OUTPUT FE_REPO=cplace-fe "$SCRIPTS/resolve-backend.sh" repo + + [ "$status" -eq 1 ] + [[ "$output" == *'GITHUB_OUTPUT is not set'* ]] +} diff --git a/tools/scripts/backend-e2e/resolve-backend.sh b/tools/scripts/backend-e2e/resolve-backend.sh new file mode 100755 index 0000000..306df2b --- /dev/null +++ b/tools/scripts/backend-e2e/resolve-backend.sh @@ -0,0 +1,154 @@ +#!/usr/bin/env bash +# +# Resolves which backend a frontend PR is tested against, and on which branches. +# +# Usage: +# resolve-backend.sh repo writes backend_repo, repo_dir +# resolve-backend.sh branches writes base_branch, backend_branch, backend_sha, +# e2e_branch, e2e_sha +# +# The two steps are separate because the token that `branches` needs is minted +# for the repository that `repo` resolves. +# +# Env: +# FE_REPO (repo) the frontend repository name, e.g. cplace-fe +# BACKEND_REPO (branches) the backend repository, as `repo` resolved it +# BASE_REF (branches) the PR's base branch +# HEAD_REF (branches) the PR's head branch; optional +# BACKEND_BRANCH_OVERRIDE, E2E_BRANCH_OVERRIDE +# (branches) explicit branches from the PR body; optional +# GH_TOKEN (branches) a token that can read BACKEND_REPO and cplace-e2e +# GITHUB_OUTPUT receives the outputs +# +# The backend's checkout directory (repo_dir) is `main` for cplace, because the +# cplace-gh-workflows actions expect the platform there. +# +# Each branch is resolved to the commit it points to now, so every job of the +# run builds and tests the same commits. See resolve_branch for the order of +# preference. An unreachable remote fails with exit code 2. + +set -euo pipefail + +# shellcheck source=tools/scripts/backend-e2e/lib.sh +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +resolve_repo() { + local backend_repo repo_dir + case "${FE_REPO:-}" in + cplace-fe) backend_repo=cplace; repo_dir=main ;; + ?*-fe) backend_repo="${FE_REPO%-fe}"; repo_dir="${backend_repo}" ;; + *) echo "No backend repo for '${FE_REPO:-}': expected cplace-fe or -fe" >&2; exit 1 ;; + esac + + { + echo "backend_repo=${backend_repo}" + echo "repo_dir=${repo_dir}" + } >>"${GITHUB_OUTPUT}" +} + +# lookup : sets LOOKUP_SHA to the commit of in . +# Returns 1 when the branch does not exist, and exits the script when the +# remote is unreachable. +lookup() { + local rc=0 + LOOKUP_SHA="$(remote_branch_sha "$1" "$2")" || rc=$? + if ((rc == 2)); then + exit 2 + fi + return "${rc}" +} + +# valid_branch_name : a name git accepts as a branch, not an option +valid_branch_name() { + [[ "$1" != -* ]] && git check-ref-format --branch "$1" >/dev/null 2>&1 +} + +# resolve_branch : prints " ", the +# branch of to test with and its commit, in this order of preference: +# 1. , an explicit branch from the PR body; a missing or invalid +# one fails, as an explicit choice must not be silently replaced. +# 2. HEAD_REF when has it, unless it is main, master or release/*: +# an upmerge or backport head is never a backend line of its own. +# 3. ; a release line does not have falls back to master. +resolve_branch() { + local repo="$1" base="$2" override="$3" + if [[ -n "${override}" ]]; then + if ! valid_branch_name "${override}"; then + echo "::error::'${override}' from the PR body is not a valid branch name" >&2 + exit 1 + fi + if ! lookup "${repo}" "${override}"; then + echo "::error::${repo} has no branch '${override}', which the PR body asks for" >&2 + exit 1 + fi + echo "${override} ${LOOKUP_SHA}" + return + fi + + case "${HEAD_REF:-}" in + '' | main | master | release/*) ;; + *) + if lookup "${repo}" "${HEAD_REF}"; then + echo "${HEAD_REF} ${LOOKUP_SHA}" + return + fi + ;; + esac + + if lookup "${repo}" "${base}"; then + echo "${base} ${LOOKUP_SHA}" + elif [[ "${base}" == release/* ]] && lookup "${repo}" master; then + echo "::warning::${repo} has no branch '${base}', testing against master" >&2 + echo "master ${LOOKUP_SHA}" + else + echo "::error::${repo} has no branch '${base}'" >&2 + exit 1 + fi +} + +resolve_branches() { + if [[ -z "${BACKEND_REPO:-}" ]]; then + echo "BACKEND_REPO is not set" >&2 + exit 1 + fi + + local base_branch + case "${BASE_REF:-}" in + main | master) base_branch=master ;; + release/[0-9]*.[0-9]*-beta) base_branch="${BASE_REF%-beta}" ;; + release/*) base_branch="${BASE_REF}" ;; + *) + base_branch=master + echo "::warning::Base branch '${BASE_REF:-}' has no backend counterpart, testing against master" + ;; + esac + + local backend e2e backend_branch backend_sha e2e_branch e2e_sha + backend="$(resolve_branch "${BACKEND_REPO}" "${base_branch}" "${BACKEND_BRANCH_OVERRIDE:-}")" + e2e="$(resolve_branch cplace-e2e "${base_branch}" "${E2E_BRANCH_OVERRIDE:-}")" + read -r backend_branch backend_sha <<<"${backend}" + read -r e2e_branch e2e_sha <<<"${e2e}" + + { + echo "base_branch=${base_branch}" + echo "backend_branch=${backend_branch}" + echo "backend_sha=${backend_sha}" + echo "e2e_branch=${e2e_branch}" + echo "e2e_sha=${e2e_sha}" + } >>"${GITHUB_OUTPUT}" +} + +main() { + if [[ -z "${GITHUB_OUTPUT:-}" ]]; then + echo "GITHUB_OUTPUT is not set" >&2 + exit 1 + fi + + case "${1:-}" in + repo) resolve_repo ;; + branches) resolve_branches ;; + *) echo "Usage: $(basename "$0") repo|branches" >&2; exit 2 ;; + esac +} + +main "$@" diff --git a/tools/scripts/backend-e2e/resolve-consumers.bats b/tools/scripts/backend-e2e/resolve-consumers.bats new file mode 100755 index 0000000..8f4b09a --- /dev/null +++ b/tools/scripts/backend-e2e/resolve-consumers.bats @@ -0,0 +1,106 @@ +#!/usr/bin/env bats +# +# Behavioral tests for resolve-consumers.sh. +# +# Run with: bats tools/scripts/backend-e2e/ + +setup() { + load 'test-helper' + export GITHUB_OUTPUT="${BATS_TEST_TMPDIR}/github_output" + : >"${GITHUB_OUTPUT}" + mkdir -p "${WORK}/e2e" + printf '%s\n' '{"devDependencies":{"@cplace-next/cf-e2e-testing-sdk":"1.0.0","cypress":"14.0.0"}}' >"${WORK}/e2e/package.json" + make_assets_dir plugin.a '{"dependencies":{"@cplace-next/cf-platform":"1.0.0","lodash":"4.17.21"}}' + make_assets_dir plugin.b '{"dependencies":{"@cplace-next/cf-platform":"1.0.0","@cplace-next/cf-shell":"1.0.0"}}' +} + +# output_of : the value resolve-consumers.sh wrote for +output_of() { + sed -n "s/^$1=//p" "${GITHUB_OUTPUT}" +} + +consumers() { + run env PACKAGES="$1" "$SCRIPTS/resolve-consumers.sh" "${WORK}" "${WORK}/e2e" +} + +@test "a package only the backend consumes runs, listed once across plugins" { + consumers '["@cplace-next/cf-platform","@cplace-next/cf-shell","@cplace-next/other"]' + + [ "$status" -eq 0 ] + [ "$(output_of backend_packages)" = '["@cplace-next/cf-platform","@cplace-next/cf-shell"]' ] + [ "$(output_of e2e_packages)" = '[]' ] + [ "$(output_of run)" = true ] +} + +@test "a package only cplace-e2e consumes runs" { + consumers '["@cplace-next/cf-e2e-testing-sdk"]' + + [ "$status" -eq 0 ] + [ "$(output_of backend_packages)" = '[]' ] + [ "$(output_of e2e_packages)" = '["@cplace-next/cf-e2e-testing-sdk"]' ] + [ "$(output_of run)" = true ] +} + +@test "packages nobody consumes skip" { + consumers '["@cplace-next/unused"]' + + [ "$status" -eq 0 ] + [ "$(output_of backend_packages)" = '[]' ] + [ "$(output_of e2e_packages)" = '[]' ] + [ "$(output_of run)" = false ] +} + +@test "changed in-repo specs run even when nothing consumed was published" { + run env PACKAGES='[]' SPECS_CHANGED=true "$SCRIPTS/resolve-consumers.sh" "${WORK}" "${WORK}/e2e" + + [ "$status" -eq 0 ] + [ "$(output_of backend_packages)" = '[]' ] + [ "$(output_of e2e_packages)" = '[]' ] + [ "$(output_of run)" = true ] +} + +@test "unchanged in-repo specs do not run on their own" { + run env PACKAGES='["@cplace-next/unused"]' SPECS_CHANGED=false "$SCRIPTS/resolve-consumers.sh" "${WORK}" "${WORK}/e2e" + + [ "$status" -eq 0 ] + [ "$(output_of run)" = false ] +} + +@test "an empty package list skips" { + consumers '[]' + + [ "$status" -eq 0 ] + [ "$(output_of run)" = false ] +} + +@test "a blank package list counts as empty" { + consumers ' ' + + [ "$status" -eq 0 ] + [ "$(output_of backend_packages)" = '[]' ] + [ "$(output_of run)" = false ] +} + +@test "a backend without assets warns and consumes nothing" { + mkdir -p "${BATS_TEST_TMPDIR}/empty" + + run env PACKAGES='["@cplace-next/cf-platform"]' "$SCRIPTS/resolve-consumers.sh" "${BATS_TEST_TMPDIR}/empty" "${WORK}/e2e" + + [ "$status" -eq 0 ] + [[ "$output" == *"::warning::"*"has no */assets/package.json"* ]] + [ "$(output_of run)" = false ] +} + +@test "an invalid package list fails" { + consumers 'not json' + + [ "$status" -ne 0 ] + [ ! -s "${GITHUB_OUTPUT}" ] +} + +@test "wrong arguments fail with the usage" { + run "$SCRIPTS/resolve-consumers.sh" "${WORK}" + + [ "$status" -eq 2 ] + [[ "$output" == *'Usage:'* ]] +} diff --git a/tools/scripts/backend-e2e/resolve-consumers.sh b/tools/scripts/backend-e2e/resolve-consumers.sh new file mode 100755 index 0000000..625c8ea --- /dev/null +++ b/tools/scripts/backend-e2e/resolve-consumers.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# +# Decides whether a frontend PR is worth a backend E2E run: when the backend or +# cplace-e2e consumes a package the PR published, or when the PR changed its +# in-repo specs. +# +# Usage: PACKAGES='["@scope/name", ...]' SPECS_CHANGED=true|false # resolve-consumers.sh +# +# Reads /*/assets/package.json and /package.json. +# An empty or unset PACKAGES counts as `[]`. SPECS_CHANGED is true when the PR +# changed a file under e2e-tests/. +# +# Writes to GITHUB_OUTPUT: +# backend_packages JSON array of the published packages the backend consumes +# e2e_packages JSON array of the published packages cplace-e2e consumes +# run true when either array is non-empty or SPECS_CHANGED is true + +set -euo pipefail + +# shellcheck source=tools/scripts/backend-e2e/lib.sh +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +# consumed_json ...: the published packages the +# manifests consume, as one sorted JSON array without duplicates. +consumed_json() { + local packages="$1" manifest + shift + for manifest in "$@"; do + consumed_packages "${manifest}" "${packages}" || return 1 + done | jq -Rsc 'split("\n") | map(select(length > 0)) | unique' +} + +main() { + if [[ -z "${GITHUB_OUTPUT:-}" ]]; then + echo "GITHUB_OUTPUT is not set" >&2 + exit 1 + fi + if (($# != 2)); then + echo "Usage: PACKAGES='[\"@scope/name\"]' $(basename "$0") " >&2 + exit 2 + fi + local backend="$1" e2e="$2" + local packages="${PACKAGES:-}" + + local -a backend_manifests e2e_manifests=() + shopt -s nullglob + backend_manifests=("${backend}"/*/assets/package.json) + shopt -u nullglob + if ((${#backend_manifests[@]} == 0)); then + echo "::warning::${backend} has no */assets/package.json, so the backend consumes nothing" + fi + if [[ -f "${e2e}/package.json" ]]; then + e2e_manifests=("${e2e}/package.json") + fi + + local backend_packages e2e_packages run=false + backend_packages="$(consumed_json "${packages}" ${backend_manifests[@]+"${backend_manifests[@]}"})" + e2e_packages="$(consumed_json "${packages}" ${e2e_manifests[@]+"${e2e_manifests[@]}"})" + if [[ "${backend_packages}" != '[]' || "${e2e_packages}" != '[]' || "${SPECS_CHANGED:-false}" == true ]]; then + run=true + fi + + { + echo "backend_packages=${backend_packages}" + echo "e2e_packages=${e2e_packages}" + echo "run=${run}" + } >>"${GITHUB_OUTPUT}" +} + +main "$@" diff --git a/tools/scripts/backend-e2e/resolve-specs.bats b/tools/scripts/backend-e2e/resolve-specs.bats new file mode 100755 index 0000000..c416b76 --- /dev/null +++ b/tools/scripts/backend-e2e/resolve-specs.bats @@ -0,0 +1,97 @@ +#!/usr/bin/env bats +# +# Behavioral tests for resolve-specs.sh. +# +# Run with: bats tools/scripts/backend-e2e/ + +setup() { + load 'test-helper' + export GITHUB_OUTPUT="${BATS_TEST_TMPDIR}/github_output" + : >"${GITHUB_OUTPUT}" + DEFAULTS='cypress/e2e/cplace/specs/a/**/*.spec.ts,cypress/e2e/cplace/specs/b/**/*.spec.ts' +} + +specs_output() { + sed -n 's/^specs=//p' "${GITHUB_OUTPUT}" +} + +# specs [] +specs() { + run env E2E_SPECS="${DEFAULTS}" SPEC_MAP="$1" CONSUMED="$2" IN_REPO_SPECS="${3:-false}" FE_REPO=cplace-fe \ + "$SCRIPTS/resolve-specs.sh" +} + +@test "without a map the filter is the default" { + specs '' '["@cplace-next/cf-platform"]' + + [ "$status" -eq 0 ] + [ "$(specs_output)" = "${DEFAULTS}" ] +} + +@test "a consumed package adds its mapped globs after the default" { + specs '{"@cplace-next/cf-platform":"cypress/e2e/cplace/specs/footer/**/*.spec.ts, cypress/e2e/cplace/specs/menu/**/*.spec.ts"}' \ + '["@cplace-next/cf-platform"]' + + [ "$status" -eq 0 ] + [ "$(specs_output)" = "${DEFAULTS},cypress/e2e/cplace/specs/footer/**/*.spec.ts,cypress/e2e/cplace/specs/menu/**/*.spec.ts" ] +} + +@test "an unconsumed package is ignored" { + specs '{"@cplace-next/cf-shell":"cypress/e2e/cplace/specs/shell/**/*.spec.ts"}' '["@cplace-next/cf-platform"]' + + [ "$status" -eq 0 ] + [ "$(specs_output)" = "${DEFAULTS}" ] +} + +@test "duplicate globs collapse in order" { + specs '{"@cplace-next/cf-platform":"cypress/e2e/cplace/specs/b/**/*.spec.ts,cypress/e2e/x.spec.ts","@cplace-next/cf-shell":"cypress/e2e/x.spec.ts"}' \ + '["@cplace-next/cf-platform","@cplace-next/cf-shell"]' + + [ "$status" -eq 0 ] + [ "$(specs_output)" = "${DEFAULTS},cypress/e2e/x.spec.ts" ] +} + +@test "an invalid map fails" { + local map + for map in 'not json' '["a"]' '{"@cplace-next/cf-platform":["a"]}'; do + : >"${GITHUB_OUTPUT}" + specs "${map}" '[]' + + [ "$status" -eq 1 ] + [[ "$output" == *'::error::SPEC_MAP is not a JSON object'* ]] + [ ! -s "${GITHUB_OUTPUT}" ] + done +} + +@test "an invalid consumed list fails" { + specs '{}' 'nope' + + [ "$status" -eq 1 ] + [ ! -s "${GITHUB_OUTPUT}" ] +} + +@test "in-repo specs append the FE repo's glob once, last" { + specs '{"@cplace-next/cf-platform":"cypress/e2e/cplace-fe/**/*.spec.ts"}' '["@cplace-next/cf-platform"]' true + + [ "$status" -eq 0 ] + [ "$(specs_output)" = "${DEFAULTS},cypress/e2e/cplace-fe/**/*.spec.ts" ] + + : >"${GITHUB_OUTPUT}" + specs '' '[]' true + + [ "$(specs_output)" = "${DEFAULTS},cypress/e2e/cplace-fe/**/*.spec.ts" ] +} + +@test "no in-repo specs leave the filter unchanged" { + specs '' '[]' false + + [ "$status" -eq 0 ] + [ "$(specs_output)" = "${DEFAULTS}" ] +} + +@test "in-repo specs without FE_REPO fail" { + run env E2E_SPECS="${DEFAULTS}" IN_REPO_SPECS=true "$SCRIPTS/resolve-specs.sh" + + [ "$status" -eq 1 ] + [[ "$output" == *'FE_REPO is not set'* ]] +} diff --git a/tools/scripts/backend-e2e/resolve-specs.sh b/tools/scripts/backend-e2e/resolve-specs.sh new file mode 100755 index 0000000..6b8255e --- /dev/null +++ b/tools/scripts/backend-e2e/resolve-specs.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# +# Builds the cplace-e2e spec filter of a backend E2E run: the caller's default +# filter, the specs mapped to the packages the backend and cplace-e2e consume, +# and the FE repo's in-repo specs. +# +# Usage: resolve-specs.sh +# +# Env: +# E2E_SPECS comma-separated spec globs every run includes +# SPEC_MAP JSON object {"@scope/pkg": "glob,glob"}; optional, default {} +# CONSUMED JSON array of the published packages the backend or +# cplace-e2e consumes +# IN_REPO_SPECS true when the FE repo has an e2e-tests/ folder; its specs +# are copied to cypress/e2e// in cplace-e2e +# FE_REPO the frontend repository name; required with IN_REPO_SPECS +# GITHUB_OUTPUT receives specs, the comma-joined globs without duplicates, +# in that order + +set -euo pipefail + +main() { + if [[ -z "${GITHUB_OUTPUT:-}" ]]; then + echo "GITHUB_OUTPUT is not set" >&2 + exit 1 + fi + local map="${SPEC_MAP:-}" consumed="${CONSUMED:-}" + [[ -n "${map// /}" ]] || map='{}' + [[ -n "${consumed// /}" ]] || consumed='[]' + if ! jq -e 'type == "object" and all(.[]; type == "string")' <<<"${map}" >/dev/null 2>&1; then + echo "::error::SPEC_MAP is not a JSON object of comma-separated globs: ${map}" >&2 + exit 1 + fi + if ! jq -e 'type == "array"' <<<"${consumed}" >/dev/null 2>&1; then + echo "::error::CONSUMED is not a JSON array: ${consumed}" >&2 + exit 1 + fi + + local in_repo='' + if [[ "${IN_REPO_SPECS:-false}" == true ]]; then + if [[ -z "${FE_REPO:-}" ]]; then + echo "FE_REPO is not set" >&2 + exit 1 + fi + in_repo="cypress/e2e/${FE_REPO}/**/*.spec.ts" + fi + + local specs + specs="$(jq -rn --arg defaults "${E2E_SPECS:-}" --argjson map "${map}" --argjson consumed "${consumed}" --arg in_repo "${in_repo}" ' + [ ($defaults | split(",")[]), + ($map | to_entries[] | select(.key as $k | $consumed | index($k)) | .value | split(",")[]), + $in_repo ] + | map(gsub("^\\s+|\\s+$"; "") | select(length > 0)) + | reduce .[] as $glob ([]; if index([$glob]) then . else . + [$glob] end) + | join(",")')" + + echo "specs=${specs}" >>"${GITHUB_OUTPUT}" +} + +main "$@" diff --git a/tools/scripts/backend-e2e/test-helper.bash b/tools/scripts/backend-e2e/test-helper.bash new file mode 100644 index 0000000..2273a6e --- /dev/null +++ b/tools/scripts/backend-e2e/test-helper.bash @@ -0,0 +1,147 @@ +#!/usr/bin/env bash +# +# Shared bats fixtures for tools/scripts/backend-e2e/. External tools the +# scripts call (npm, git) are replaced by stubs on PATH that record their argv. +# +# shellcheck disable=SC2034 # SCRIPTS/WORK are consumed by the .bats files that load this + +SCRIPTS="${BATS_TEST_DIRNAME}" +WORK="${BATS_TEST_TMPDIR}/work" +NPM_LOG="${BATS_TEST_TMPDIR}/npm.log" + +# Puts an `npm` stub first on PATH. Each call appends "|" to NPM_LOG. +# `npm view @ ...` prints what npm_view_returns recorded for +# @, or fails with E404. Any other call prints a progress line to +# stdout like real npm, and exits with NPM_EXIT (default 0). +stub_npm() { + NPM_VIEWS="${BATS_TEST_TMPDIR}/npm-views" + mkdir -p "${BATS_TEST_TMPDIR}/bin" "${NPM_VIEWS}" + cat >"${BATS_TEST_TMPDIR}/bin/npm" <<'STUB' +#!/usr/bin/env bash +echo "${PWD}|$*" >>"${NPM_LOG}" +if [[ "$1" == view ]]; then + file="${NPM_VIEWS}/${2//\//_}" + if [[ -f "${file}" ]]; then + cat "${file}" + exit 0 + fi + echo "npm error code E404" >&2 + exit 1 +fi +echo "added 1 package, and audited 2 packages in 1s" +exit "${NPM_EXIT:-0}" +STUB + chmod +x "${BATS_TEST_TMPDIR}/bin/npm" + export PATH="${BATS_TEST_TMPDIR}/bin:${PATH}" NPM_LOG NPM_VIEWS + : >"${NPM_LOG}" +} + +# npm_view_returns @ : what the stubbed `npm view` prints +npm_view_returns() { + printf '%s\n' "$2" >"${NPM_VIEWS}/${1//\//_}" +} + +# make_assets_dir +make_assets_dir() { + mkdir -p "${WORK}/$1/assets" + printf '%s\n' "$2" >"${WORK}/$1/assets/package.json" +} + +# assert_npm_called_in +assert_npm_called_in() { + if ! grep -qxF "$1|$2" "${NPM_LOG}"; then + echo "expected npm call: $1|$2" >&2 + echo "recorded npm calls:" >&2 + cat "${NPM_LOG}" >&2 + return 1 + fi +} + +npm_call_count() { + wc -l <"${NPM_LOG}" | tr -d ' ' +} + +# Puts a `git` stub first on PATH. Each call appends its argv to GIT_LOG. +# +# It answers `git ... ls-remote --heads refs/heads/` from fixture +# files under REMOTES. It prints a head line for every listed branch that merely +# contains , which is looser than real git, so exact matching stays the +# job of the script under test. +# +# Each listed branch points to the commit `sha_of ` prints. +# +# A call whose argv holds the word STUB_FAIL exits 1. `check-ref-format` runs +# the real git. `rev-parse` prints STUB_HEAD. Any other +# subcommand, such as clone, fetch or checkout, exits 0 without touching the +# filesystem, or exits 128 with a `fatal:` line on stderr when its argv holds +# the URL of a repo marked unreachable. +stub_git() { + REMOTES="${BATS_TEST_TMPDIR}/remotes" + GIT_LOG="${BATS_TEST_TMPDIR}/git.log" + REAL_GIT="$(command -v git)" + mkdir -p "${BATS_TEST_TMPDIR}/bin" "${REMOTES}" + cat >"${BATS_TEST_TMPDIR}/bin/git" <<'STUB' +#!/usr/bin/env bash +echo "$*" >>"${GIT_LOG}" +if [[ -n "${STUB_FAIL:-}" && " $* " == *" ${STUB_FAIL} "* ]]; then + echo "fatal: ${STUB_FAIL} failed" >&2 + exit 1 +fi +if [[ "$1" == check-ref-format ]]; then + exec "${REAL_GIT}" "$@" +fi +if [[ " $* " == *" rev-parse "* ]]; then + echo "${STUB_HEAD:-}" + exit 0 +fi +if [[ " $* " != *" ls-remote "* ]]; then + for arg in "$@"; do + repo="${arg##*/}" + if [[ "${arg}" == https://*.git && -f "${REMOTES}/${repo%.git}.unreachable" ]]; then + echo "fatal: unable to access '${arg}': Could not resolve host: github.com" >&2 + exit 128 + fi + done + exit 0 +fi +url="${*: -2:1}" +pattern="${*: -1}" +pattern="${pattern#refs/heads/}" +repo="${url##*/}" +repo="${repo%.git}" +if [[ -f "${REMOTES}/${repo}.unreachable" ]]; then + echo "fatal: unable to access '${url}': Could not resolve host: github.com" >&2 + exit 128 +fi +[[ -f "${REMOTES}/${repo}" ]] || exit 0 +while read -r branch; do + if [[ "${branch}" == *"${pattern}"* ]]; then + printf '%s\trefs/heads/%s\n' "$(printf '%s/%s' "${repo}" "${branch}" | sha1sum | cut -c1-40)" "${branch}" + fi +done <"${REMOTES}/${repo}" +STUB + chmod +x "${BATS_TEST_TMPDIR}/bin/git" + export PATH="${BATS_TEST_TMPDIR}/bin:${PATH}" REMOTES GIT_LOG REAL_GIT + : >"${GIT_LOG}" +} + +# sha_of : the commit the stubbed remote lists for +sha_of() { + printf '%s/%s' "$1" "$2" | sha1sum | cut -c1-40 +} + +# remote_has ...: the stubbed remote has these branches +remote_has() { + local repo="$1" + shift + printf '%s\n' "$@" >>"${REMOTES}/${repo}" +} + +# remote_unreachable : every ls-remote or clone against fails +remote_unreachable() { + : >"${REMOTES}/$1.unreachable" +} + +git_call_count() { + wc -l <"${GIT_LOG}" | tr -d ' ' +}