> For the complete documentation index, see [llms.txt](https://docs.getantidote.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.getantidote.com/welcome-to-antidote/integrations/triggering-explorations-from-any-ci.md). Agents can also search and read this documentation through its [MCP server](https://docs.getantidote.com/~gitbook/mcp).

# Triggering explorations from any CI

Call the Antidote Platform API directly from CircleCI, GitLab CI, Jenkins, Buildkite or any other pipeline.

Antidote's GitHub Actions are thin wrappers around our Platform API. If your pipelines run somewhere else, CircleCI, Jenkins, GitLab CI, or Buildkite, you can make the same API calls directly with `curl`. This page walks through the complete flow, with CircleCI as the worked example.

> **Using GitHub Actions?** Use the Antidote `preview` or `environment` actions instead. On GitLab CI, Antidote's CI components do the same; see [GitLab](https://docs.getantidote.com/welcome-to-antidote/integrations/gitlab.md).

What you will set up:

* Exchange your Antidote API key for a short-lived access token.
* **Preview flow.** Register a per-PR build and have Antidote test the pull request on its preview deployment.
* **Environment flow.** Record the build you deployed to a long-lived environment and start Antidote's run on it.
* Get results posted back to your GitHub pull requests via the Antidote GitHub App, or to your GitLab merge requests.

### Endpoints

| What                   | URL                                                              |
| ---------------------- | ---------------------------------------------------------------- |
| Token endpoint         | `https://auth.duku.ai/realms/duku/protocol/openid-connect/token` |
| Platform API (GraphQL) | `https://platform.duku.ai/graphql`                               |

All Platform API operations are GraphQL: `POST` a JSON body of the form `{"query": "...", "variables": {...}}` with an `Authorization: Bearer <token>` header.

### Prerequisites

* An Antidote API key. Generate one in **Settings → API keys**. The key is shown once. Store it as a secret in your CI. In CircleCI, put it in a context as `DUKU_API_KEY`.
* **Preview flow:** your product ID (the part after /p/ in the dashboard address while the product is open).
* **Environment flow:** your product ID, and the ID and name of the environment you deploy to (see Find each environment's ID below).
* The product needs a base URL. Without one, and without a per-run `url`, `startExploration` returns `BAD_USER_INPUT`.
* `curl` and `jq` in your job image. CircleCI's `cimg/base` image includes both.
* For PR comments: the Antidote GitHub App installed on your repository (next section).

> **Tip.** You can list your products over the API with `query { subjects { id name } }`. Products are called "subjects" in the API schema.

### Install the Antidote GitHub App

On GitHub the App is listed as Antidote Bot, and its comments and checks come from the `antidote-bot` account.

When you name a GitHub pull request on `startExploration`, Antidote reads it through the Antidote GitHub App and tests what it changes. The App posts one comment on the pull request while the test runs, updates it with the result, and posts the `Duku Exploration (<product name>)` check run, so you never need to handle a GitHub token in your CI job. The check is still named Duku Exploration, so your branch protection rules keep working.

1. Open [github.com/apps/antidote-bot](https://github.com/apps/antidote-bot).
2. Click **Install** (or **Configure** if your organisation already has it) and choose the GitHub organisation that owns your repositories. If you are not an organisation owner, GitHub forwards the request to one for approval.
3. Choose **Only select repositories** and pick repositories whose pull requests should receive Antidote comments. You can also choose **All repositories**.
4. Accept the requested permissions. Pull-request comments and check runs need read and write access.
5. Link the installation to your Antidote organisation: an org admin opens **Settings → Integrations**, selects **Connect** on the **GitHub** card under **Source control & CI/CD**, then selects **Link existing install**. **Install on GitHub** completes steps 1 to 5. Until the installation is linked, Antidote posts no PR comments or check runs to its repositories.

If the App is not installed and linked, Antidote cannot read the pull request, so it does not test it. `startExploration` still succeeds, and its `warnings` say what to fix.

### Step 1: Exchange your API key for an access token

See [API Keys](https://docs.getantidote.com/welcome-to-antidote/integrations/api-keys.md) for how keys work and how to exchange one for an access token. In short: the key is a base64-encoded `clientId:clientSecret` pair; decode it, split on the first `:`, and use the standard OAuth2 client-credentials grant to get a short-lived access token.

Save the following helpers to `scripts/duku-lib.sh` in your repository. The rest of this page builds on them:

```bash
#!/usr/bin/env bash
# scripts/duku-lib.sh: helpers for calling the Antidote Platform API.
# Requires: bash, curl, jq. Expects DUKU_API_KEY in the environment.

DUKU_API_URL=${DUKU_API_URL:-https://platform.duku.ai/graphql}
DUKU_AUTH_URL=${DUKU_AUTH_URL:-https://auth.duku.ai}

# Exchange the API key for a short-lived access token.
duku_token() {
  local decoded client_id client_secret
  decoded=$(printf '%s' "$DUKU_API_KEY" | base64 -d) || {
    echo 'DUKU_API_KEY is not valid base64' >&2
    return 1
  }
  client_id=${decoded%%:*}
  client_secret=${decoded#*:}
  curl -sfS -X POST "$DUKU_AUTH_URL/realms/duku/protocol/openid-connect/token" \
    -H 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode grant_type=client_credentials \
    --data-urlencode "client_id=$client_id" \
    --data-urlencode "client_secret=$client_secret" |
    jq -r .access_token
}

# duku_gql <query> <variables-json>
# Runs a GraphQL operation. Prints the JSON response on success; prints the
# API's error messages and returns non-zero if the response contains errors.
duku_gql() {
  local query=$1 variables=${2:-'{}'} body response
  body=$(jq -n --arg q "$query" --argjson v "$variables" '{query: $q, variables: $v}')
  response=$(curl -sfS "$DUKU_API_URL" \
    -H "Authorization: Bearer $(duku_token)" \
    -H 'Content-Type: application/json' \
    -d "$body") || return 1
  if jq -e 'has("errors")' <<<"$response" >/dev/null; then
    echo 'Antidote API error:' >&2
    jq -r '.errors[].message' <<<"$response" >&2
    return 1
  fi
  printf '%s\n' "$response"
}
```

> **Important.** Access tokens are short-lived (about 5 minutes). Don't fetch one token at the top of a long job and reuse it: `duku_gql` above fetches a fresh token per call, which is the simplest safe pattern.

> **Important.** Most GraphQL errors come back with HTTP status 200, so a bare `curl -f` will not catch them. Always check the response for an `errors` array, as `duku_gql` does. A variable with the wrong type or enum value returns HTTP 400 instead.

{% hint style="info" %}
To sign in as one of your personas, pass its ID or name as `credentialSetId` on `startExploration`. A pull request test ignores it.
{% endhint %}

### Adapting the scripts to your CI

The helper scripts on this page use CircleCI environment variable names (`CIRCLE_*`) as examples. If you run a different CI, substitute your provider's equivalents. The GraphQL calls and each script stay exactly the same.

| What it is                  | CircleCI (used in the scripts)                              | GitHub Actions                                                      | GitLab CI               | Jenkins                                 | Buildkite                                               | Bitbucket                                   |
| --------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------- | ----------------------- | --------------------------------------- | ------------------------------------------------------- | ------------------------------------------- |
| Repository (`owner/repo`)   | `$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME`         | `$GITHUB_REPOSITORY`                                                | `$CI_PROJECT_PATH`      | derive from `$GIT_URL`, or set manually | `$BUILDKITE_ORGANIZATION_SLUG/$BUILDKITE_PIPELINE_SLUG` | `$BITBUCKET_REPO_FULL_NAME`                 |
| Pull / merge request number | parsed from `$CIRCLE_PULL_REQUEST` (or `$CIRCLE_PR_NUMBER`) | `github.event.pull_request.number`                                  | `$CI_MERGE_REQUEST_IID` | `$CHANGE_ID`                            | `$BUILDKITE_PULL_REQUEST`                               | `$BITBUCKET_PR_ID`                          |
| Commit SHA                  | `$CIRCLE_SHA1`                                              | `$GITHUB_SHA`                                                       | `$CI_COMMIT_SHA`        | `$GIT_COMMIT`                           | `$BUILDKITE_COMMIT`                                     | `$BITBUCKET_COMMIT`                         |
| Branch name                 | `$CIRCLE_BRANCH`                                            | `$GITHUB_HEAD_REF` (PRs) / `$GITHUB_REF_NAME`                       | `$CI_COMMIT_REF_NAME`   | `$BRANCH_NAME`                          | `$BUILDKITE_BRANCH`                                     | `$BITBUCKET_BRANCH`                         |
| Build number                | `$CIRCLE_BUILD_NUM`                                         | `$GITHUB_RUN_NUMBER`                                                | `$CI_PIPELINE_IID`      | `$BUILD_NUMBER`                         | `$BUILDKITE_BUILD_NUMBER`                               | `$BITBUCKET_BUILD_NUMBER`                   |
| Build / job URL             | `$CIRCLE_BUILD_URL`                                         | `$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID` | `$CI_JOB_URL`           | `$BUILD_URL`                            | `$BUILDKITE_BUILD_URL`                                  | construct from `$BITBUCKET_GIT_HTTP_ORIGIN` |

### Flow A: preview deployments

Before the first run, an org admin adds **Preview deployments** in **Product settings → Environments** (**Add environment**, **Type**: **Preview deployments**). Until it exists, registering a preview build fails with `FORBIDDEN`.

Run two API calls per pipeline after your preview deploy step:

1. `upsertSimulationTarget` registers the pull request's preview build under your product. The `buildKey` deduplicates reruns. Every pipeline on the same PR updates the same preview build instead of creating a new one. If you also send `commitSha`, give each commit its own `buildKey` by appending `:sha=<commit sha>`. Otherwise, the second commit returns `CONFLICT`.
2. `startExploration` asks Antidote to test the pull request on the preview URL straight away. Naming the pull request with `changeRequest` makes Antidote post and maintain the PR comment and check run. The older `githubRepository` and `githubPrNumber` fields still work.

{% hint style="warning" %}
**`triggerSource: "CI"` is required in this flow.** The per-run `url` is treated as an override, and Antidote only honours it for CI callers. If you omit `triggerSource`, your API key is treated as a generic key. The `url` you send is ignored and the exploration runs against the product's configured base URL. It fails if the product has no base URL set. The script below includes it.
{% endhint %}

Unlike the GitHub Action, which discovers the preview URL from the GitHub Deployments, Checks, and Statuses APIs, your CI job supplies the preview URL directly. Your deploy step already knows it: `vercel deploy` prints it, `netlify deploy --json` returns it as `deploy_url`, or you may construct it from the PR number.

```bash
#!/usr/bin/env bash
# scripts/duku-preview.sh: register a PR build with Antidote and start an
# exploration against its preview deployment.
#
# Required environment:
#   DUKU_API_KEY     Antidote API key (Settings -> API keys)
#   DUKU_PRODUCT_ID  Antidote product ID (the part after /p/ in the dashboard address)
#   PREVIEW_URL      URL of the deployed preview for this PR
set -euo pipefail
source "$(dirname "$0")/duku-lib.sh"

: "${DUKU_API_KEY:?}" "${DUKU_PRODUCT_ID:?}" "${PREVIEW_URL:?}"

REPO="${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}"
PR_NUMBER=${CIRCLE_PR_NUMBER:-}
if [ -z "$PR_NUMBER" ] && [ -n "${CIRCLE_PULL_REQUEST:-}" ]; then
  PR_NUMBER=${CIRCLE_PULL_REQUEST##*/}
fi
: "${PR_NUMBER:?No pull request associated with this pipeline}"
SHORT_SHA=${CIRCLE_SHA1:0:7}

# 1. Register (or refresh) the preview build under your product.
UPSERT='mutation UpsertSimulationTarget($input: UpsertSimulationTargetInput!) {
  upsertSimulationTarget(input: $input) { id name version }
}'
VARS=$(jq -n \
  --arg subjectId "$DUKU_PRODUCT_ID" \
  --arg buildKey "github:repo=${REPO}:pr=${PR_NUMBER}" \
  --arg name "PR #${PR_NUMBER} (${SHORT_SHA})" \
  --arg description "Build from ${CIRCLE_BRANCH:-unknown} (${SHORT_SHA})" \
  --arg version "$SHORT_SHA" \
  --arg environment "pr-${PR_NUMBER}" \
  --argjson buildNumber "${CIRCLE_BUILD_NUM:-null}" \
  --arg ciRunUrl "${CIRCLE_BUILD_URL:-}" \
  '{input: {subjectId: $subjectId, buildKey: $buildKey, name: $name,
           description: $description, version: $version, environment: $environment,
           buildNumber: $buildNumber, metadata: {ciRunUrl: $ciRunUrl}}}')
TARGET_ID=$(duku_gql "$UPSERT" "$VARS" | jq -r '.data.upsertSimulationTarget.id')
echo "Registered preview build ${TARGET_ID}"

# 2. Ask Antidote to test the pull request on the preview. Naming the pull
#    request makes the Antidote GitHub App post the PR comment and check run.
#    triggerSource: "CI" authorises the per-run url override (see note above).
START='mutation StartExploration($input: StartExplorationInput!) {
  startExploration(input: $input) { id status warnings }
}'
VARS=$(jq -n --arg targetId "$TARGET_ID" --arg url "$PREVIEW_URL" --arg repo "$REPO" \
  --argjson pr "$PR_NUMBER" \
  '{input: {targetId: $targetId, url: $url, serverManagedComment: true, triggerSource: "CI",
           changeRequest: {provider: "GITHUB", repository: $repo, number: $pr}}}')
RESPONSE=$(duku_gql "$START" "$VARS")
jq -r '.data.startExploration.warnings // [] | .[]' <<<"$RESPONSE" >&2
```

To have Antidote mark the check **Not tested** when it cannot test this commit, add `headSha` with the pull request's head commit to `changeRequest`. Never send a merge commit: a `headSha` that is not the pull request's current head is not tested.

`waitForTargetSeconds` applies to runs outside a pull request. A pull request test ignores it, so run this step once the preview serves.

The test runs asynchronously. The script exits in seconds, and the result appears on the PR comment, the check run and in the Antidote dashboard when the test finishes.

If one pull request triggers explorations for several products, each product gets its own PR comment.

> **GitLab merge requests.** Send `changeRequest` with `provider: "GITLAB"`, `repository` set to the project path, `repositoryId` set to the project's numeric ID, and `number` set to the merge request IID (`$CI_MERGE_REQUEST_IID`). For a self-managed instance, add `host`. Antidote posts its results as a note on the merge request. Connect GitLab under **Source control & CI/CD** first; see [GitLab](https://docs.getantidote.com/welcome-to-antidote/integrations/gitlab.md).

> **Vercel Deployment Protection.** If your previews are protected, pass the bypass secret when registering the build. Add `--arg bypass "$VERCEL_AUTOMATION_BYPASS_SECRET"` to the first `jq` call and `metadata: {vercelAutomationBypassSecret: $bypass}` to its input object.

> **Not on a PR?** For pushes without a pull request, use `buildKey: "github:repo=${REPO}:sha=${CIRCLE_SHA1}"` and omit `changeRequest` and `serverManagedComment`. Keep `triggerSource: "CI"` so the preview `url` is still honoured. `startExploration` then starts Antidote's run on that build, so drop the `PR_NUMBER` check.

On GitHub, keep the `github:repo=...` `buildKey` convention shown above even though you're not on GitHub Actions. If you also send `commitSha`, use `github:repo=<owner/repo>:pr=<number>:sha=<commit sha>`, the same key the Antidote GitHub Actions use, so if you ever run both, they land on the same release.

On GitLab, build keys name the project instead of the repository. For a merge request, use `gitlab:project=<project path>:mr=<merge request IID>`, and once you also send `commitSha`, add `:sha=<commit sha>`. For a build with no merge request, use `gitlab:project=<project path>:sha=<commit sha>`, and for a release on an environment, `gitlab:project=<project path>:env=<environment name>:sha=<commit sha>`. These are the keys Antidote's GitLab components use, so builds from both land on the same release.

For the full list of input fields on `upsertSimulationTarget` and `startExploration`, see the [GraphQL API reference](https://docs.getantidote.com/welcome-to-antidote/integrations/graphql-api.md).

### Flow B: environment deployments

For staging, a prod canary or any environment declared in **Product settings → Environments**, record the build you deployed as a release on that environment, then start Antidote's run on it. Antidote runs your flows on the release and queues an exploration of it; while the product has no flows yet, the run is an exploration.

```bash
#!/usr/bin/env bash
# scripts/duku-environment.sh: record the build deployed to an environment
# and start Antidote's run against it.
#
# Required environment:
#   DUKU_API_KEY         Antidote API key (Settings -> API keys)
#   DUKU_PRODUCT_ID      Antidote product ID
#   DUKU_ENVIRONMENT_ID  The environment's ID
#   DUKU_ENVIRONMENT     The environment's name, such as staging
#   VERSION              The release name, such as your git tag
set -euo pipefail
source "$(dirname "$0")/duku-lib.sh"

: "${DUKU_API_KEY:?}" "${DUKU_PRODUCT_ID:?}" "${DUKU_ENVIRONMENT_ID:?}" "${DUKU_ENVIRONMENT:?}" "${VERSION:?}"
REPO="${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}"

# 1. Record the build as a release on the environment.
UPSERT='mutation UpsertSimulationTarget($input: UpsertSimulationTargetInput!) {
  upsertSimulationTarget(input: $input) { id }
}'
VARS=$(jq -n \
  --arg subjectId "$DUKU_PRODUCT_ID" \
  --arg buildKey "github:repo=${REPO}:env=${DUKU_ENVIRONMENT}:sha=${CIRCLE_SHA1}" \
  --arg name "${DUKU_ENVIRONMENT} ${VERSION}" \
  --arg version "$VERSION" \
  --arg environmentId "$DUKU_ENVIRONMENT_ID" \
  --arg environment "$DUKU_ENVIRONMENT" \
  --arg commitSha "$CIRCLE_SHA1" \
  '{input: {subjectId: $subjectId, buildKey: $buildKey, name: $name, version: $version,
           label: $version, environmentId: $environmentId, environment: $environment,
           commitSha: $commitSha}}')
duku_gql "$UPSERT" "$VARS" >/dev/null

# 2. Start Antidote's run on what the environment now serves.
START='mutation StartExploration($input: StartExplorationInput!) {
  startExploration(input: $input) { id status warnings }
}'
VARS=$(jq -n --arg environmentId "$DUKU_ENVIRONMENT_ID" \
  '{input: {environmentId: $environmentId, triggerSource: "CI"}}')
RESPONSE=$(duku_gql "$START" "$VARS")
jq -r '.data.startExploration.warnings // [] | .[]' <<<"$RESPONSE" >&2
RUN_ID=$(jq -r '.data.startExploration.id' <<<"$RESPONSE")
echo "Run started: ${RUN_ID}"
```

{% hint style="info" %}
Send `triggerSource: "CI"`. It labels the run as CI-triggered in your dashboards and lets it use the `url` you pass.
{% endhint %}

* **Pull request mode:** to test a pull request against a fixed environment and get the PR comment and check run, add `changeRequest` to the `startExploration` input, exactly as in the preview flow.

#### Record a release after each deploy

To record a version by name rather than by commit, call `recordManualRelease` after the deploy, in place of the Flow B script. It records the version as deployed to the environment and starts Antidote's run on it. Sending the same version for the same environment again records one release, but each call starts a new run, so a retried job runs again.

Find each environment's ID once:

```bash
QUERY='query Environments($subjectId: ID!) { environments(subjectId: $subjectId) { id name url } }'
VARS=$(jq -n --arg subjectId "$DUKU_PRODUCT_ID" '{subjectId: $subjectId}')
duku_gql "$QUERY" "$VARS" | jq '.data.environments'
```

Then, after the deploy:

```bash
RECORD='mutation RecordRelease($input: RecordManualReleaseInput!) {
  recordManualRelease(input: $input) { id }
}'
VARS=$(jq -n --arg environmentId "$DUKU_ENVIRONMENT_ID" --arg label "$VERSION" \
  '{input: {environmentId: $environmentId, label: $label}}')
duku_gql "$RECORD" "$VARS" | jq -r '.data.recordManualRelease.id'
```

A release recorded this way starts one run for each of your product's flows, and a product can start up to 10 such runs in any 10 minutes. Past that, `recordManualRelease` returns `CONFLICT`: wait a few minutes. A product with more than 10 flows always gets `CONFLICT` here, so use the Flow B script. `recordManualRelease` does not return the run's ID either, so use the Flow B script when your pipeline waits for the result.

Set `VERSION` to the name you release under, such as your git tag. To run against what an environment already serves, without recording a new release, call `startExploration` with only `environmentId` and `triggerSource: "CI"`. The environment needs a release recorded first.

### Where results appear

On a GitHub pull request, Antidote posts its comment and a **GitHub check run** with the result. On a GitLab merge request, it posts a note. Every run also appears in the Antidote dashboard. See [GitHub check runs](https://docs.getantidote.com/welcome-to-antidote/integrations/github-check-runs.md).

### Putting it together in CircleCI

Store `DUKU_API_KEY` (and `DUKU_PRODUCT_ID`, plus `DUKU_ENVIRONMENT_ID` and `DUKU_ENVIRONMENT` for Flow B) in a context named `duku` under **Organization Settings → Contexts**, then:

```yaml
version: 2.1

jobs:
  duku-preview:
    docker:
      - image: cimg/base:current   # includes curl and jq
    steps:
      - checkout
      # ... your existing preview deploy; capture the URL it produces ...
      - run:
          name: Deploy preview
          command: ./scripts/deploy-preview.sh > preview-url.txt
      - run:
          name: Start Antidote run
          command: |
            export PREVIEW_URL=$(cat preview-url.txt)
            ./scripts/duku-preview.sh

workflows:
  preview:
    jobs:
      - duku-preview:
          context: duku
```

> **Note.** CircleCI only populates `CIRCLE_PULL_REQUEST` / `CIRCLE_PR_NUMBER` when the pipeline is associated with a pull request. If those are empty on your PR pipelines, check **Project Settings → Advanced → Only build pull requests**, or pass the PR number into the script yourself.

### Troubleshooting

#### `CONFLICT`: already pinned to deployment

You re-sent a `buildKey` with a different `commitSha`. Put the commit in the build key.

#### `CONFLICT`: Release run limit reached for this product

The call would take the product past 10 runs in 10 minutes; each `recordManualRelease` call counts one run per flow. Wait a few minutes, or use the Flow B script.

**`FORBIDDEN`: Add Preview deployments**

Your product has no **Preview deployments** slot. An org admin adds it in **Product settings → Environments**.

**Token request fails with HTTP 401 (`invalid_client`).** The API key is malformed, revoked, or expired. Check that the secret contains the full base64 string from the Antidote dashboard with no line breaks, or generate a new key in Settings → API keys.

**`Authentication required` in a GraphQL error.** The access token expired mid-job; tokens last about 5 minutes. Fetch a fresh token per call (the `duku_gql` helper does this) rather than reusing one.

**`url is required`.** The product has no base URL and the run sent no `url`. Set the product's base URL in the Antidote dashboard, or pass `url` with `triggerSource: "CI"`.

**`Not found` when referencing a build, environment or product.** The ID is wrong, or it belongs to a different organisation: API keys only see resources in the organisation they were created in.

**The preview `url` is ignored / the run uses the wrong URL.** For an API-key caller, the per-run `url` is only honoured when you send `triggerSource: "CI"`. Without it the run falls back to the product's configured base URL. Add `triggerSource: "CI"` to the `startExploration` input, as shown in Flow A.

**The PR comment never appears.** Verify the Antidote GitHub App is installed on the repository and linked in **Settings → Integrations**, that `changeRequest.repository` is exactly `owner/repo` and `changeRequest.number` is an integer, and read the `warnings` that `startExploration` returned.

**Antidote can't reach your preview.** If your site sits behind a firewall, WAF, or bot protection, see [Firewall & WAF Allowlisting](https://docs.getantidote.com/welcome-to-antidote/integrations/firewall-and-waf-allowlisting.md). For protected Vercel previews, use the Deployment Protection bypass described above.
