# Guide to Trunk Webhooks: Features and Best Practices

[Trunk](https://trunk.io/) builds CI tooling for engineering teams, and two of its products send webhooks. **Merge Queue** reports each pull request and batch as it moves through the queue: submitted, testing, merged, failed. **Flaky Tests** reports when a test turns flaky or broken, when a monitor fires, when someone overrides quarantine, and when an AI investigation of a flaky test finishes. You can use them to post to chat, open a ticket when a test turns flaky, or feed a dashboard.

| Aspect | Value |
| --- | --- |
| Method | `POST`, JSON body |
| Signature headers | `svix-id`, `svix-timestamp`, `svix-signature` (Standard Webhooks) |
| Delivery | Delivered by Svix; `svix-id` is stable across retries |
| Retries | Trunk retries with exponential backoff when the delivery provider rate-limits a request. No endpoint retry schedule or timeout is documented |

## What are Trunk webhooks?

Trunk's webhooks run on Svix. You manage endpoints in the **Svix App Portal**, which is embedded in the Trunk web app, and the full event list with JSON Schemas lives in Trunk's Svix event catalogue. Each delivery is a JSON `POST` signed with Svix's `svix-*` headers.

Trunk itself doesn't document the headers, the signing steps or the secret format. Everything about verification on this page comes from Svix, which Trunk names as its delivery platform.

## Trunk webhook features

| Feature | Details |
| --- | --- |
| Configuration | Svix App Portal inside the Trunk web app |
| Signature | Standard Webhooks HMAC-SHA256, via Svix |
| Signature header | `svix-signature` |
| Secret | Per endpoint, `whsec_...` (Svix default; Trunk doesn't state it) |
| Body | JSON, flat, no event ID |
| Event routing | Body field `type` |
| Ordering | Not guaranteed; order by the body `timestamp` |
| Retries | Exponential backoff on provider rate-limits; endpoint schedule not documented |
| Source IPs | Not published |

The skill's [reference applications](https://github.com/hookdeck/webhook-skills/tree/main/skills/trunk-webhooks/examples) route all twenty catalogue events.

## Events and payloads

Every body has a top-level `type`, equal to the event name, and an ISO 8601 `timestamp`. Merge Queue bodies add `action`, `status`, `pr_number` and `repository`. Don't route on `action`: it's the lifecycle step without the family prefix, so `merged` could be a PR or a batch.

### Merge Queue

| Event | Triggered When |
| --- | --- |
| `pull_request.queued` | The PR is added to the queue. `queued_reason` is `BISECTION_REQUIRED` when it enters bisection and `BISECTION_TEST_RUN_PASSED` when it returns to the queue |
| `pull_request.submitted` | The PR is submitted to the queue |
| `pull_request.testing` | Trunk starts testing the PR, alone or in a batch (a 4-PR batch sends four) |
| `pull_request.merged` | The PR merged after a clean run |
| `pull_request.failed` | The PR was kicked from the queue (fires per PR) |
| `pull_request.pending_failure` | The PR has a pending failure |
| `pull_request.canceled` | The PR was cancelled |
| `pull_request_batch.queued`, `.submitted`, `.testing`, `.merged`, `.failed`, `.canceled`, `.pending_failure` | Same lifecycle for a batch of PRs tested together. `pull_request_batch.pending_failure` does not always lead to bisection |

### Flaky Tests

| Event | Triggered When | Key fields |
| --- | --- | --- |
| `v2.test_case.status_changed` | A test changes status, as triggered by a monitor (for example `new_status` is `FLAKY`) | `previous_status`, `new_status`, `triggered_by.monitor_id` / `.monitor_type` / `.monitor_status`, `repository`, `test_case` |
| `test_case.status_changed` | The original event, being phased out. Aggregate metrics such as `failure_rate_last_7d` are `0` or missing | as above |
| `test_case.monitor_status_changed` | A monitor activates or resolves for a test case | `monitor.id`, `monitor.type`, `monitor.status` (`active` or `resolved`), `evidence`, `repository`, `test_case` |
| `test_case.quarantining_setting_changed`, `v2.test_case.quarantining_setting_changed` | A quarantine setting is manually overridden to `ALWAYS_QUARANTINE` or `NEVER_QUARANTINE`. Does not fire on auto-quarantine (listen to `v2.test_case.status_changed` and check `new_status == "FLAKY"`) | `repository`, `test_case` |
| `test_case.investigation_completed` | An AI flaky-test analysis finishes (beta) | `investigation_id`, `trigger` (`AUTOMATIC`, `MANUAL` or `MCP`), `confidence`, `created_at`, `markdown_summary`, `failure_message`, `facts[]`, `repository`, `test_case` |

If you want to know when a test has just become flaky, subscribe to `v2.test_case.status_changed` and check `new_status`. The investigation event is a separate, later analysis.

Trunk is moving Flaky Tests to test collections. Collection events have the same types plus a `test_collection` object, which is how you tell them apart from repository events. They're behind an organisation-level switch, and `test_case.id` differs between the two, so don't deduplicate across them on it.

The catalogue's examples are generated from the schemas, with values like `"string"` and `0`, so this guide doesn't reproduce one. Log a real delivery of each type before you depend on optional fields.

## Setting up Trunk webhooks

1. In the Trunk web app, go to **Merge Queue** > **Settings** > **Webhooks** for Merge Queue events, or **Settings** > **Organisation** > **Webhooks** for Flaky Tests events.
2. In the Svix App Portal, add an endpoint, for example `https://example.com/webhooks/trunk`.
3. Select the events. Merge Queue's `pull_request.*` and `pull_request_batch.*` families each need to be subscribed explicitly. `pull_request.merged`, `pull_request.failed`, `pull_request_batch.pending_failure` and `v2.test_case.status_changed` make a reasonable start.
4. Copy the endpoint's signing secret from the portal into `TRUNK_WEBHOOK_SECRET`. Svix secrets start with `whsec_`; keep the prefix.

Deleting and recreating an endpoint issues a new secret.

To put Hookdeck in front, create a source with the **Trunk** type, paste the secret, and register the source URL in the portal. The [Hookdeck CLI](/docs/cli) forwards it locally:

```bash
npx hookdeck-cli listen 3000 trunk --path /webhooks/trunk

```

The Svix App Portal can send an example event to the endpoint, which is a quick way to check the route.

## Securing Trunk webhooks

Svix signs `svix-id`, a dot, `svix-timestamp`, another dot and the raw body with HMAC-SHA256, using the base64-decoded secret after `whsec_` as the key. `svix-signature` holds one or more space-separated `v1,` entries; accept any match. Trunk's docs tell you to pass the raw request body exactly as received. This function also accepts `webhook-*` header names:

```javascript
const crypto = require('node:crypto');

function decodeBase64(value) {
  if (typeof value !== 'string' || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return null;
  const bytes = Buffer.from(value, 'base64');
  return bytes.length > 0 && bytes.toString('base64').replace(/=+$/, '') === value.replace(/=+$/, '')
    ? bytes : null;
}

function verifySignature(rawBody, headers, secret) {
  if (!Buffer.isBuffer(rawBody) || typeof secret !== 'string' || !secret) return false;
  const prefix = headers['svix-id'] ? 'svix' : 'webhook';
  const id = headers[`${prefix}-id`];
  const timestamp = headers[`${prefix}-timestamp`];
  const signature = headers[`${prefix}-signature`];
  if (typeof id !== 'string' || !id || typeof timestamp !== 'string' ||
      !/^[0-9]+$/.test(timestamp) || typeof signature !== 'string') return false;
  const key = decodeBase64(secret.replace(/^whsec_/, ''));
  if (!key) return false;
  const message = Buffer.concat([Buffer.from(`${id}.${timestamp}.`, 'utf8'), rawBody]);
  const candidates = signature.split(/\s+/).filter((item) => item.startsWith('v1,')).map((item) => item.slice(3));
  const expected = crypto.createHmac('sha256', key).update(message).digest();
  return candidates.some((candidate) => {
    const received = decodeBase64(candidate);
    if (!received) return false;
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}

```

The Svix libraries reject timestamps more than five minutes old. Hookdeck keeps the original `svix-timestamp` when it retries or replays and sets no tolerance of its own, so behind Hookdeck those libraries would reject real deliveries. The function above doesn't check age.

Trunk bodies carry no event ID, so the receiver keys on `svix-id`, which Svix keeps the same across retries:

```javascript
const express = require('express');

// Returns the parsed body when it is a JSON object, otherwise null.
function parseJsonObject(rawBody) {
  try {
    const value = JSON.parse(rawBody.toString('utf8'));
    return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
  } catch {
    return null;
  }
}

// ciEvents.record(messageId, event) stores the event once per messageId and resolves when durable.
function createTrunkReceiver(ciEvents) {
  const app = express();
  app.post('/webhooks/trunk', express.raw({ type: '*/*' }), async (req, res) => {
    const secret = process.env.TRUNK_WEBHOOK_SECRET;
    if (!secret) return res.sendStatus(500);
    if (!verifySignature(req.body, req.headers, secret)) return res.sendStatus(401);

    const event = parseJsonObject(req.body);
    if (!event) return res.sendStatus(400); // signed, but not a JSON object
    const messageId = req.headers['svix-id'] || req.headers['webhook-id'];
    try {
      await ciEvents.record(messageId, event); // order later by event.timestamp, not arrival
    } catch {
      return res.sendStatus(503);
    }
    return res.sendStatus(200);
  });
  return app;
}

```

A Hookdeck Trunk source returns `200` to Svix whether or not the signature matches. Failures are logged as failed verification and go no further.

> **Make Trunk webhooks production-ready.** [Hookdeck Event Gateway](/event-gateway) verifies every Trunk event and can send merge queue and flaky test events to different services from one endpoint.

## Trunk webhook limitations and pain points

### Trunk doesn't document verification

**The Problem:** There's no Trunk page that tells you which headers to read or how the signature is built.

**Why It Happens:** Trunk delegates delivery to Svix and points you to Svix's docs. Header names, the algorithm and the `whsec_` format are Svix's defaults, not statements from Trunk.

**Workarounds:**

* Follow Svix's manual verification steps, and confirm the header names on your first delivery.

**How Hookdeck Can Help:** Hookdeck's Trunk source accepts both `svix-*` and `webhook-*` headers, and its request log shows exactly what arrived.

### Endpoint retry policy is undocumented

**The Problem:** You don't know how long a failed merge notification will be retried.

**Why It Happens:** Trunk only says it retries with exponential backoff when the delivery provider rate-limits a request. It doesn't restate the retry schedule or timeout for a failing endpoint.

**Workarounds:**

* Return `2xx` once the event is stored, and rebuild state from Trunk's web app after an outage.

**How Hookdeck Can Help:** Hookdeck accepts each event straight away and [retries](/docs/retries) your service on a schedule you control.

### Two generations of test-case events

**The Problem:** Your flaky-test handler receives events with missing metrics, or two events for one change.

**Why It Happens:** `test_case.status_changed` is being phased out and reports aggregate metrics such as `failure_rate_last_7d` as `0` or not at all. Its `v2` successor carries the monitor that triggered it. The Flaky Tests page says three event types are published, while the catalogue lists six.

**Workarounds:**

* Subscribe to the `v2.` events where they exist and drop the originals.

**How Hookdeck Can Help:** Hookdeck [filters](/docs/filters) on `type` can drop the legacy events before they reach your service.

### No usable payload examples

**The Problem:** You can't tell from the docs what a real `test_case.investigation_completed` looks like.

**Why It Happens:** The catalogue's examples are generated from JSON Schemas, and the Flaky Tests page has field tables only.

**Workarounds:**

* Write handlers against the schemas and validate the first real deliveries.

**How Hookdeck Can Help:** Hookdeck stores every payload it receives, so you can inspect real Trunk events and replay them while you build.

## Best practices

### Subscribe to batch events too

Merge Queue can test PRs together in batches, and batch events are a separate family. If only `pull_request.*` events arrive, the endpoint isn't subscribed to `pull_request_batch.*`.

### Don't wait for a quarantine event on auto-quarantine

`test_case.quarantining_setting_changed` fires only on manual overrides to `ALWAYS_QUARANTINE` or `NEVER_QUARANTINE`. To act on automatic quarantine, watch `v2.test_case.status_changed` for `FLAKY`.

### Order by the body `timestamp`

Retries and out-of-order delivery make arrival time unreliable. Trunk tells you to sort on the payload's `timestamp`.

### Deduplicate on `svix-id`

With no ID in the body, the Svix message ID is the key. Store it with each change; our guide to [webhook idempotency](/webhooks/guides/implement-webhook-idempotency) covers the details.

## Conclusion

Trunk's webhooks connect your merge queue and test health to the rest of your tooling. Because Trunk leaves verification and delivery details to Svix, check your first real deliveries against Svix's documentation.

[Hookdeck Event Gateway](https://hookdeck.com) verifies, filters and replays Trunk's CI events. [Try Hookdeck free](https://dashboard.hookdeck.com/signup).