> ## Documentation Index
> Fetch the complete documentation index at: https://docs.trunk.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Set up Trunk Dynamic CI

You are helping a user add Trunk Dynamic CI to a repository that runs GitHub Actions. Dynamic CI decides, push by push, which CI jobs a pull request needs, and skips the rest. Aim to do the whole setup from this one prompt and finish with an open pull request. The user confirms access and answers a few questions. You do the rest.

The `app.trunk.io` links in this file open the user's own Trunk organization once they are signed in, so give them to the user and do not fetch them yourself. If the user's prompt names their organization, put its slug first in the path: `app.trunk.io/<org>/dynamic-ci`.

The docs links in this file already end in `.md`, so open them as they are. The full index is at [docs.trunk.io/llms.txt](https://docs.trunk.io/llms.txt).

## Before you start

* **Reply first.** Your first message is the step 1 questions. Before it, read only `.github/workflows/` and the files those workflows call, so you can fill in your best guesses. Do not open docs or edit anything yet.
* **Open docs only when a step needs them.** Do not read ahead.
* **Know where you run.**
  * With the repository and a terminal (Claude Code, Cursor, Codex): follow every step.
  * In a chat app without the repository: ask the user to paste their pull request workflows, then return the edited files and the pull request description for them to apply.
* **This file covers GitHub Actions.** For a Buildkite pipeline, follow [Buildkite](https://docs.trunk.io/dynamic-ci/getting-started/buildkite.md) instead.
* **What makes this safe to merge.** A repository starts in **Learning** mode, where Trunk records a verdict for every job and skips nothing. The action also fails open: with no token, no access or no answer from Trunk, every job runs. So the pull request changes nothing about what runs until the user turns on enforcement.

## 1. Ask what they want

Ask these in one message. Fill in your best guess from the workflows, so the user can reply "ok" or change a value.

1. **Which workflows?** List the workflows you would manage (step 2) and the ones you would leave alone, with one reason each.
2. **Access.** Dynamic CI is in private beta. Ask the user to confirm each item. Do not wait for them to finish; open the pull request either way and list what is missing in it.
   * Dynamic CI is turned on for their Trunk organization: [Dynamic CI](https://app.trunk.io/dynamic-ci) opens for them. If not, they ask Trunk on [Slack](https://slack.trunk.io).
   * Trunk CI is set up for the repository, so Trunk has the CI history it decides from. See [Getting started](https://docs.trunk.io/dynamic-ci/getting-started.md).
   * A Trunk API key is stored as the Actions secret `TRUNK_API_TOKEN` (step 3).
3. **Required checks.** Which checks does branch protection require on the default branch? Read them yourself if you can (`gh api repos/{owner}/{repo}/branches/{branch}/protection`, and `gh api repos/{owner}/{repo}/rulesets`). Ask only if you cannot.
4. **Merge queue.** Do they merge through Trunk Merge Queue, GitHub's merge queue, or neither?

## 2. Choose the workflows and jobs

### Workflows

Manage a workflow when all of these are true:

* It runs on `pull_request`.
* It does the work a pull request is checked by: tests, builds, lint, type checks, static analysis.
* At least one of its jobs is worth skipping. The filter job costs one small runner for a few seconds, so a workflow of trivial jobs (a labeler, a title check) is not worth it.

Leave these alone: release, deploy and publish workflows, scheduled workflows, `workflow_dispatch`-only workflows, and workflows that run only on `pull_request_target`.

A workflow that also runs on `push` or `merge_group` is fine. The filter job runs on pull requests, and on Trunk Merge Queue branches when the user has that queue (step 4). On every other event each job runs as it does today.

### Jobs

In each workflow you manage, gate the jobs that test, build or check the change. Do not gate:

* **A job other jobs read from.** If another job uses its `outputs` or downloads its artifacts (a build that tests consume, a planner that builds a matrix), skipping it breaks the jobs that still run.
* **A job that reports for other jobs.** A fan-in or "all checks passed" job must always run. It still needs an edit when it needs a gated job (step 4).
* **A job with side effects.** Deploys, previews, publishing, comments, labels, notifications.
* **A job that runs on failure.** One whose `if:` uses `always()` or `failure()`.

When you are unsure about a job, leave it ungated and say so in the pull request. An ungated job runs exactly as before.

## 3. Store the API key

The user creates a key at [API Keys](https://app.trunk.io/settings/developer/api-tokens). When creating it, tick **Generate Dynamic CI plans**: a new key starts with no permissions, and without this one every plan request fails, so every job runs. See [Authentication](https://docs.trunk.io/api/authentication.md).

* Check whether the secret exists: `gh secret list`.
* If it does not, the user runs `gh secret set TRUNK_API_TOKEN` in their own terminal, or adds it under the repository's **Settings → Secrets and variables → Actions**. Use an organization secret when several repositories will use it.
* Never ask for the key in chat. If one is pasted, do not use it, and tell the user to revoke it.

## 4. Edit each workflow

Make only the edits below. Do not rename jobs, change job keys, change triggers or reformat the file.

### Add the filter job

Add one job per workflow, before the jobs it gates:

```yaml theme={"system"}
dynamic-ci:
  name: Dynamic CI
  runs-on: ubuntu-latest
  timeout-minutes: 5
  if: github.event_name == 'pull_request'
  permissions:
    contents: read
    pull-requests: read
  outputs:
    unit-tests: ${{ steps.dynamic-ci.outputs.unit-tests }}
    lint: ${{ steps.dynamic-ci.outputs.lint }}
  steps:
    - uses: actions/checkout@v7
      with:
        clean: false
    - id: dynamic-ci
      uses: trunk-io/dynamic-ci@v1
      with:
        token: ${{ secrets.TRUNK_API_TOKEN }}
```

* **`outputs:` lists every gated job, by its job key.** The key is what the job is written as under `jobs:`, not its `name:`. The action sets its outputs at run time, so GitHub passes on only the ones listed here.
* **Match the repository.** Use the smallest runner label the repository already uses, and the `actions/checkout` reference its other jobs use. If the repository pins actions to commit SHAs, pin `trunk-io/dynamic-ci` to the SHA of its latest [release](https://github.com/trunk-io/dynamic-ci/releases) with a version comment.
* **If a job is already named `dynamic-ci`,** pick another key and use it everywhere below.
* **Set `if:` from the merge queue answer in step 1.**
  * Trunk Merge Queue: use the condition below, so the queue's runs reach Trunk too. There, every job runs by default. Trunk skips a job in the queue only after the user changes that job's merge-queue setting, so do not tell the user their queue runs will start skipping. Do not add a trigger: if the workflow does not already run on `trunk-merge/**` branches, the extra clause changes nothing.
  * GitHub's merge queue, another queue or none: keep the pull request condition. Every job runs in the queue.

```yaml theme={"system"}
if: >-
  github.event_name == 'pull_request' ||
  startsWith(github.ref, 'refs/heads/trunk-merge/')
```

See the [action reference](https://docs.trunk.io/dynamic-ci/dynamic-ci-action-reference.md) for every input.

### Gate each job

```yaml theme={"system"}
unit-tests:
  needs: [dynamic-ci]
  if: >-
    !cancelled() &&
    needs.dynamic-ci.outputs.unit-tests != 'false'
```

1. **Add `dynamic-ci` to `needs:`,** keeping the jobs already there.
2. **Start the condition with `!cancelled()`.** Without it, GitHub skips the job whenever the filter job was skipped or failed, and nothing is tested.
3. **Compare with `!= 'false'`, never `== 'true'`.** An empty output means no verdict, and the job must run.
4. **Read the job's own output.** `unit-tests` reads `outputs.unit-tests`.
5. **Keep the job's existing condition.** Wrap it in parentheses and join it with `&&`.
6. **Keep the job's other needs meaningful.** `!cancelled()` replaces GitHub's default rule that every needed job succeeded. For each job that was already in `needs:`, add `&& needs.<job>.result == 'success'`.

A job that calls a reusable workflow (`uses: ./.github/workflows/x.yaml`) is gated the same way, on the calling job, in the calling workflow. Do not add a filter job inside the called workflow.

Do not test `github.event_name` or the branch in a gated job's condition. The filter job's `if:` decides when Trunk is asked, and Trunk tells a merge-queue run from a pull request by its branch. See [Merge queues](https://docs.trunk.io/dynamic-ci/merge-queue.md).

### Fix the jobs that report for gated jobs

A job that reports one result for other jobs (a fan-in, "all checks passed" or "CI success" job) often fails unless every job it needs succeeded. Once Trunk skips one of those jobs, that job fails and blocks the pull request.

For every such job that needs a gated job:

* Make it pass when a gated job's result is `skipped`, and still fail on `failure` and `cancelled`. For a script that tests each result, accept `success` or `skipped` for the gated jobs and for any job that needs one, and for no others.
* Make sure it runs when a needed job was skipped: its `if:` must be `always()` or `!cancelled()`.
* Leave its name and its place in branch protection unchanged.

If you cannot tell what the job accepts (it calls an action or a script you cannot read), leave the jobs it needs ungated and say so in the pull request.

## 5. Matrix jobs

Gate a matrix job like any other job, then make the two changes below. They let Trunk skip single variations once the user chooses how to group them in the Trunk app (step 8). Until then the outputs are empty, and each `||` fallback keeps the matrix exactly as it is today.

### Add a job that reports for the matrix

A skipped variation never reports a status. If branch protection requires a variation's check, such as `Test (macos-14)`, a pull request that skips it waits forever.

Add one job that runs after the matrix and passes when it passed or was skipped. Never gate this job.

```yaml theme={"system"}
test-pass:
  needs: [test]
  if: ${{ !cancelled() }}
  runs-on: ubuntu-latest
  steps:
    - run: '[[ "${{ needs.test.result }}" =~ ^(success|skipped)$ ]]'
```

If the workflow already has a job like this, do not add another. Check that it passes when a needed job's result is `skipped`, and fix it if it does not.

### Read the variations to run

Choose by how the matrix is written. Export the extra output from the filter job's `outputs:` beside the job's own.

**Axes** (`os: [...]`, `node: [...]`): read `<job>-exclude`.

```yaml theme={"system"}
strategy:
  matrix:
    os: [ubuntu-latest, macos-14]
    node: [18, 20]
    exclude: ${{ fromJSON(needs.dynamic-ci.outputs.test-exclude || '[]') }}
```

GitHub takes one `exclude` value. If the matrix already has `exclude` entries, move them into the fallback as JSON, with each value's type unchanged: `|| '[{"os":"macos-14","node":18}]'`.

**A fixed list of rows** (`include:` with no axes): `exclude` cannot remove an `include` row, so rewrite the rows as a JSON literal and read `<job>-matrix` as the whole matrix.

```yaml theme={"system"}
strategy:
  matrix: >-
    ${{ fromJSON(
      needs.dynamic-ci.outputs.unit-tests-matrix ||
      '{"include":[
        {"suite":"packages","shard":1},
        {"suite":"apps","shard":2}
      ]}'
    ) }}
```

Keep every row, the order of its fields and the type of each value, so no job name changes: a YAML number stays a JSON number, and a quoted string stays a string. Write a single quote inside a value twice (`''`). Move a comment on a row to a line above `matrix:`.

**Rows built by an earlier job** (`include: ${{ fromJSON(needs.plan.outputs.rows) }}`): pass the rows to the action, and read `<job>-include`.

```yaml theme={"system"}
dynamic-ci:
  needs: [plan]
  outputs:
    tests: ${{ steps.dynamic-ci.outputs.tests }}
    tests-include: ${{ steps.dynamic-ci.outputs.tests-include }}
  steps:
    - id: dynamic-ci
      uses: trunk-io/dynamic-ci@v1
      with:
        token: ${{ secrets.TRUNK_API_TOKEN }}
        matrices: >-
          {"tests": ${{ needs.plan.outputs.rows || '[]' }}}

tests:
  needs: [plan, dynamic-ci]
  strategy:
    matrix:
      include: ${{ fromJSON(needs.dynamic-ci.outputs.tests-include || needs.plan.outputs.rows) }}
```

Pass the planner's output unchanged. The planner job stays ungated. Every gated job in the workflow now waits for the planner, because the filter job needs it, so tell the user when the planner is slow.

**Leave these as one unit.** Gate the job, add the reporting job, and list it in the pull request as a follow-up:

* An axis written as an expression (`shard: ${{ fromJSON(...) }}`).
* Axes beside an `include:` expression.
* A whole `matrix:` built by an earlier job (`matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}`).
* An `exclude:` that is already an expression.

See [Matrix jobs on GitHub Actions](https://docs.trunk.io/dynamic-ci/getting-started/github-actions.md#matrix-jobs) for each shape in full.

## 6. Check your work

Check every edited workflow before you commit:

1. Every gated job lists `dynamic-ci` in `needs:`.
2. Every output a job reads is exported from the filter job's `outputs:` under the same name.
3. Every gated job reads its own job key, not another job's.
4. Every condition starts with `!cancelled()` and compares with `!= 'false'`.
5. No gated job is read by an ungated job for outputs or artifacts, and every job that reports for a gated job passes when that job is skipped.
6. Every matrix job has a reporting job, and reads the output that fits its shape: `-exclude` at `exclude:`, `-matrix` at `matrix:`, `-include` at `include:`.
7. Every job name is the same as before your edits.
8. The file is valid. Run `actionlint` if it is installed.

## 7. Open the pull request

Create a branch, commit and open a pull request titled "Add Trunk Dynamic CI". In the description, give:

* The workflows and jobs now managed, and the jobs left alone with the reason for each.
* The matrix jobs, and which are wired by variation and which run as one unit.
* What the user still has to do (step 8).
* Which events the filter job runs on, and what that means for the user's merge queue.
* That nothing is skipped until the repository is set to **Enforced**.

Then watch the pull request's own CI run:

* Every job should run, because this pull request changes the workflow files.
* The **Dynamic CI** job should pass. Its log holds a verdict for each job, or a notice saying why every job runs.
* If the notice says Dynamic CI is not enabled for the organization, or the token is missing, tell the user. Nothing in the workflow needs to change.
* If a matrix job fails with an invalid matrix, the fallback JSON is wrong. Fix it and push again.

## 8. Report

Tell the user what you set up, with the pull request link, and what is left for them:

1. **Confirm the access items** from step 1 that are still open.
2. **Change required checks.** For each matrix job, require its reporting job (for example `test-pass`) in place of the per-variation checks. Do this before turning on enforcement. Never change branch protection yourself.
3. **Look at the verdicts.** After the merge, each pull request's verdicts appear in [Dynamic CI](https://app.trunk.io/dynamic-ci), and [Issues](https://app.trunk.io/dynamic-ci/issues) lists any job whose gate is wired wrongly.
4. **Group matrix jobs** under [Configuration → Jobs](https://app.trunk.io/dynamic-ci/configuration/jobs) → **Group by**. See [Matrix jobs](https://docs.trunk.io/dynamic-ci/configuration/matrices.md) for which keys to pick.
5. **Turn on enforcement** under [Configuration → Mode](https://app.trunk.io/dynamic-ci/configuration/mode) when the verdicts look right, for a few engineers or a label first. See [Learning and Enforced modes](https://docs.trunk.io/dynamic-ci/configuration/mode.md).

Suggest at most two next steps that fit the repository, such as [path filters](https://docs.trunk.io/dynamic-ci/configuration/path-filters.md) for a repository that uses `dorny/paths-filter`, or [Force Run](https://docs.trunk.io/dynamic-ci/force-run.md) for a job someone wants on one pull request.

## If the repository already has Dynamic CI

If a workflow already uses `trunk-io/dynamic-ci`, do not add a second filter job to it. Run the step 6 checks on what is there, fix what fails, and add the jobs and matrix wiring that are missing.

## If the repository filters by path

Keep `dorny/paths-filter` jobs, `paths:` triggers and the conditions that read them. Join the Dynamic CI condition to them with `&&`, so a job runs only when both agree.

## Help

* [How Dynamic CI decides](https://docs.trunk.io/dynamic-ci/configuration/signals.md)
* [Job schedules](https://docs.trunk.io/dynamic-ci/configuration/jobs.md): set a job to Always Run or Always Skip
* [FAQ](https://docs.trunk.io/dynamic-ci/faq.md): outages, new jobs and pull requests from forks
* [Trunk on Slack](https://slack.trunk.io)
