Combining GitHub Actions Matrix Reports into One Pull Request Comment

A GitHub Actions matrix is useful for running the same check across several targets, but its output becomes awkward when every job finishes independently. Let each job publish its own comment and the pull request fills with updates; keep everything in the workflow logs and reviewers have to open several jobs to understand the result.

I prefer to keep report generation parallel and give one follow-up job responsibility for publishing:

  1. Run each target as an independent matrix job.
  2. Upload one report from each job as a workflow artifact.
  3. Download those artifacts in a follow-up job.
  4. Update one bot-owned pull request comment with the combined result.

The matrix retains parallel execution and isolated failures, while the pull request gets one current summary rather than a comment for every target.

One job owns the pull request comment

The workflow below generates documentation, test and screenshot reports. Each matrix job uploads a uniquely named artifact, then publish-report downloads the artifacts from the current run attempt and updates one comment.

on:
  pull_request:

permissions:
  contents: read

jobs:
  generate-reports:
    name: Generate ${{ matrix.name }} report
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        include:
          - slug: docs
            name: Documentation
            command: npm run preview:docs
          - slug: tests
            name: Test summary
            command: npm run test:report
          - slug: screenshots
            name: Screenshots
            command: npm run screenshots

    steps:
      - uses: actions/checkout@v7

      - name: Generate report
        id: generate
        continue-on-error: true
        env:
          REPORT_COMMAND: ${{ matrix.command }}
        run: |
          mkdir -p report

          set +e
          bash -o pipefail -c "$REPORT_COMMAND" > report/summary.md 2>&1
          exit_code=$?
          set -e

          {
            echo
            echo "Exit code: \`$exit_code\`"
          } >> report/summary.md

          echo "exit_code=$exit_code" >> "$GITHUB_OUTPUT"

      - name: Upload report
        if: ${{ !cancelled() }}
        uses: actions/upload-artifact@v7
        with:
          name: preview-${{ matrix.slug }}-${{ github.run_id }}-${{ github.run_attempt }}
          path: report/summary.md
          if-no-files-found: error
          retention-days: 2

      - name: Fail job when report generation failed
        if: ${{ steps.generate.outputs.exit_code != '0' }}
        env:
          EXIT_CODE: ${{ steps.generate.outputs.exit_code }}
        run: exit "$EXIT_CODE"

  publish-report:
    name: Publish combined PR report
    needs: [generate-reports]
    if: >-
      ${{
        !cancelled() &&
        github.event.pull_request.head.repo.full_name == github.repository
      }}
    runs-on: ubuntu-latest
    permissions:
      actions: read
      contents: read
      pull-requests: write

    steps:
      - name: Download reports
        continue-on-error: true
        uses: actions/download-artifact@v8
        with:
          pattern: preview-*-${{ github.run_id }}-${{ github.run_attempt }}
          path: reports

      - name: Publish PR comment
        uses: actions/github-script@v9
        with:
          github-token: ${{ github.token }}
          script: |
            const fs = require('fs');
            const path = require('path');

            const marker = '<!-- combined-preview-report -->';
            const reports = [
              { slug: 'docs', label: 'Documentation' },
              { slug: 'tests', label: 'Test summary' },
              { slug: 'screenshots', label: 'Screenshots' },
            ];

            const sections = [];

            for (const { slug, label } of reports) {
              if (!fs.existsSync('reports')) break;

              const directory = fs.readdirSync('reports').find(entry =>
                entry.startsWith(`preview-${slug}-`)
              );

              if (!directory) continue;

              const summaryPath = path.join('reports', directory, 'summary.md');
              if (!fs.existsSync(summaryPath)) continue;

              let report = fs.readFileSync(summaryPath, 'utf8');
              if (report.length > 12000) {
                report = `${report.slice(0, 12000)}\n\n_Report truncated. Download the workflow artifact for the full output._`;
              }

              sections.push(`<details>
            <summary><strong>${label}</strong></summary>

            ${report}

            </details>`);
            }

            const body = [
              marker,
              '## Combined preview report',
              '',
              sections.length
                ? sections.join('\n\n')
                : '_No reports were produced. Check the workflow logs for details._',
              '',
              `Workflow run: [${context.runId}](https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId})`,
            ].join('\n');

            const comments = await github.paginate(
              github.rest.issues.listComments,
              {
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                per_page: 100,
              }
            );

            const existing = comments.find(comment =>
              comment.user?.login === 'github-actions[bot]' &&
              typeof comment.body === 'string' &&
              comment.body.includes(marker)
            );

            if (existing) {
              await github.rest.issues.updateComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: existing.id,
                body,
              });
            } else {
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                body,
              });
            }

The example uses the current major releases documented in the official repositories for <a href="https://github.com/actions/checkout">actions/checkout</a>, <a href="https://github.com/actions/upload-artifact">actions/upload-artifact</a>, <a href="https://github.com/actions/download-artifact">actions/download-artifact</a> and <a href="https://github.com/actions/github-script">actions/github-script</a>. For a production workflow, I would pin each action to a full commit SHA, especially when the job can write to a pull request.

The example targets GitHub.com. Artifact action support differs on GitHub Enterprise Server, so check the relevant action documentation before using the same versions there.

The matrix jobs do not need write access

The workflow-level permission is contents: read. Only publish-report receives pull-requests: write, along with the read permissions it needs to collect the artifacts and create the comment.

Keeping the permission on the publishing job matters because the matrix commands execute code from the pull request. There is no reason for documentation, test or screenshot generation to inherit permission to edit the pull request when those jobs only need to produce files.

The report command is also passed through an environment variable rather than being inserted directly into the shell script. The matrix is defined in the workflow rather than supplied by a pull request author, but keeping data out of generated shell source makes the boundary easier to reason about if the matrix changes later.

Artifact names must identify the job and run attempt

Current versions of upload-artifact do not allow several jobs to mutate the same artifact. Each matrix entry therefore gets a separate name:

name: preview-${{ matrix.slug }}-${{ github.run_id }}-${{ github.run_attempt }}

The slug separates the matrix entries. github.run_id identifies the workflow run, while github.run_attempt increments when that run is re-run. Including both stops the publishing job from collecting an artifact left by an earlier attempt.

When download-artifact matches several artifacts and merge-multiple remains at its default value of false, it extracts each one into a separate named directory beneath reports. The publishing script relies on that structure to locate summary.md for each matrix entry.

A failed check should still leave a report

The generator runs with continue-on-error: true, records the command’s exit code and writes its output to report/summary.md. This allows the upload step to preserve useful failure details before the final step returns the original non-zero exit code and marks the matrix job as failed.

The upload and publishing jobs use if: ${{ !cancelled() }}. GitHub’s expression documentation recommends this instead of always() for tasks that may encounter a critical failure, because always() can leave a workflow waiting until timeout.

The example uses if-no-files-found: error because reaching the upload step without a report is a workflow defect. A warning would leave the matrix job looking healthier than it is and give the publishing job nothing useful to display.

The hidden marker identifies the comment across runs

The comment contains a marker that later runs can find:

const marker = '<!-- combined-preview-report -->';

The lookup matches both the marker and github-actions[bot] before editing. Matching only the visible heading is brittle, while matching only the marker could select a copied comment belonging to somebody else.

I covered the same update-or-create pattern in How to update a pull request comment from GitHub Actions instead of creating duplicates. The difference here is that several jobs contribute data, so the workflow needs an aggregation point before it publishes anything.

Repositories with several reporting workflows should use a different marker for each logical report. The marker identifies the report, not the workflow run, because every run needs to find and update the same comment.

Keep the comment smaller than the reports

Pull request comments are a presentation layer rather than storage for raw test output. The example places each report inside a <details> block, truncates long content, links to the workflow run and retains the complete files as short-lived artifacts.

The order is fixed by the reports array, so Documentation, Test summary and Screenshots appear consistently even when the artifact directory order changes. Repeated reports are easier to scan when sections do not move between runs.

The same pattern works for several types of matrix output:

Use caseMatrix entriesCombined comment
DocumentationSites, API docs, examplesBuild status, preview links, broken links
TestsNode versions, packages, servicesSummaries, failures, coverage
ScreenshotsBrowsers, viewports, themesChanged images and diff links
DeploymentsEnvironments, regionsURLs and smoke-test results
SecurityScanners, policies, dependency groupsFindings and artifact links
InfrastructureEnvironments, providers, modulesPlan summaries and drift checks

Fork pull requests need a separate decision

GitHub normally reduces the GITHUB_TOKEN for a pull_request workflow from a fork to read-only, so that run cannot create or update the comment. The example makes this explicit by allowing publish-report to run only when the pull request branch belongs to the same repository.

I would keep that restriction unless publishing results for external contributions is a real requirement. Moving the whole workflow to pull_request_target would run in the context of the base repository, where secrets and write permissions may be available. Checking out and executing untrusted pull request code there creates an unnecessary route to those privileges.

If fork reporting is required, keep build and test execution in the unprivileged pull_request workflow. Transfer only the minimum validated result to a separately triggered publishing workflow, and treat the artifact contents as untrusted input when rendering the comment.

When adding this pattern to an existing workflow, I would first check the permissions on every matrix job and then force one target to fail. The pull request should receive one updated comment containing the failure, while the generating job still ends in a failed state. If either part does not happen, the aggregation path is not ready to become the reviewer’s main view of the workflow.

Leave a comment

Discover more from Thomas Thornton Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading