# Gate a change with policy experiments in CI

Run a dataset of policy cases as an experiment from your pipeline, read the result and fail the build when a case stops passing.

A policy experiment checks a list of expected outcomes against the policy for one authority level and reports which no longer hold. It calls no model and answers in one request, which makes it a natural pipeline gate.

## What an experiment run does

- **Policy only.** `POST /api/experiments/{id}/run` calls no model: it needs no model key, writes no receipt and adds no model spend. It is not an agent run, so it takes no launch ticket and no `X-CoA-Model-Request` header.

- **One request.** The response, HTTP `201`, is the complete result. Every call stores a new run.

- **Two inputs.** The result depends only on the dataset's stored cases and the `authority` you send. Workspace settings, agents and the content of a pull request have no effect: the same cases at the same level give the same result until Center of Agentic changes the policy behind that level.

## What a case asserts

A case has a `title`, a `dimension`, a `request` and an `expect`. The request is one policy question: an `action`, the `object` it acts on and the `placement` where it would execute. A run evaluates it with the policy engine that decides agent runs, using the grants of the chosen authority level, and compares the decision with `expect`. Every field set in `expect` must hold.

| `expect` field | Asserts |
| --- | --- |
| `decision` | `allow` or `deny`: a must-allow or must-deny case. A limited outcome is an `allow` with the reason code `LIMITED_OUTPUT`. Without `decision` a case cannot pass. |
| `reasonCode` | The exact reason code, such as `ALLOWED`, `LIMITED_OUTPUT` or `PKG_CEILING_NO_GRANT`. |
| `obligations` | Obligation kinds that must all be attached, such as `logging`. |
| `survivingPlacements` | Placements that must remain allowed. |
| `deniedPlacements` | Placements that must not remain allowed. |

- Always send `request.object`, even as `{}`: a stored case without it makes every run of the dataset fail with a server error.

- `request.object.dataClass` is the data class under test.

- `dimension` is `in_scope`, `default_deny`, `manifest_ceiling`, `data_residency`, `connector_scope`, `approval_required`, `obligations` or `delegation_containment`. It does not change the evaluation.

In an experiment run, `answer` grants `summarize`; `draft` adds `draft`; `recommend` adds `recommend`; `prepare_action` adds `prepare_cloud_record` and `create_task`; both `execute` levels add `update_record` and `send_message`. Every other action, including `connector_read`, is denied at every level, as are the cloud placements for `restricted` or `secrets` data.

## The scope each step needs

| Step | Scope |
| --- | --- |
| Create a dataset, case, experiment or schedule; delete a dataset, case or schedule; import a dataset; **start a run** | `admin` |
| Read datasets, experiments, runs and schedules; export a dataset; compare two runs | `read` |

The pipeline key is an admin key

Starting a run needs `admin`, so a pipeline that only runs and reads needs it too; a `read` or `run` key gets `403 insufficient_scope` (see [scopes](https://centerofagentic.com/docs/authentication#scopes)). `admin` includes every other write open to keys, so give this job its own key. To keep `admin` out of CI, let a [scheduled re-run](https://centerofagentic.com/docs/guides/evaluations-in-ci#scheduled-re-runs) create the runs and read them with a `read` key.

## Create the dataset

Keep the cases in your repository as JSON. Import reads the envelope that `GET /api/datasets/{id}/export` produces, or a bare array of cases. These three cases pass at `recommend`; at `execute_with_approval` the second fails, because that level grants `update_record`.

```json
{
  "version": 1,
  "name": "Renewal brief policy",
  "description": "Outcomes the renewal agents must keep",
  "cases": [
    {
      "title": "Summarising internal notes is allowed",
      "dimension": "in_scope",
      "request": { "action": "summarize", "object": { "dataClass": "internal" }, "placement": "cloud_model" },
      "expect": { "decision": "allow", "reasonCode": "ALLOWED" }
    },
    {
      "title": "Record updates stay out of reach",
      "dimension": "manifest_ceiling",
      "request": {
        "action": "update_record",
        "object": { "connector": "crm", "type": "Record", "dataClass": "confidential" },
        "placement": "cloud_connector_write"
      },
      "expect": { "decision": "deny", "reasonCode": "PKG_CEILING_NO_GRANT" }
    },
    {
      "title": "Restricted data stays off the cloud model",
      "dimension": "data_residency",
      "request": { "action": "summarize", "object": { "resource": "local", "dataClass": "restricted" }, "placement": "cloud_model" },
      "expect": {
        "decision": "allow",
        "reasonCode": "LIMITED_OUTPUT",
        "survivingPlacements": ["local"],
        "deniedPlacements": ["cloud_model"]
      }
    }
  ]
}
```

Import always creates a new dataset, so a changed file needs a new experiment. Send the file's content as one string in `text`, then create the experiment. The commands below need an `admin`-scope key and `jq` 1.6 or later.

```bash
BASE="https://centerofagentic.com"

# 1. Import the file as a new dataset. Check that "skipped" is 0.
DATASET_ID=$(jq -n --rawfile text policy/renewal-policy.json '{text: $text}' \
  | curl -sS -X POST "$BASE/api/datasets/import?format=json" \
      -H "Authorization: Bearer $COA_API_KEY" \
      -H "Content-Type: application/json" -d @- \
  | tee import.json | jq -r '.datasetId')
jq . import.json

# 2. Create the experiment over that dataset. Keep its id for the pipeline.
jq -cn --arg datasetId "$DATASET_ID" --arg name "Renewal policy gate" \
    '{datasetId: $datasetId, name: $name}' \
  | curl -sS -X POST "$BASE/api/experiments" \
      -H "Authorization: Bearer $COA_API_KEY" \
      -H "Content-Type: application/json" -d @- \
  | jq '{id, datasetName, runCount}'
```

- **Skipped cases.** A case without a title, with an unknown dimension, or whose `request` or `expect` is not an object is skipped with a warning. Treat `skipped` above 0 as an error.

- **CSV.** With `?format=csv` the header needs `title`, `dimension`, `request_json` and `expect_json`; the last two hold JSON text. Leave out the `source_receipt_id` column: an empty cell fails the import with a server error.

- **Case by case.** `POST /api/datasets` creates an empty dataset and `POST /api/datasets/{id}/cases` adds one case. A case cannot be edited, only deleted and added again.

## Run the experiment

| Field | Notes |
| --- | --- |
| `authority` | Required. `answer`, `draft`, `recommend`, `prepare_action`, `execute_with_approval` or `execute_automatically`. Not validated: an unrecognised value is evaluated like `answer`, so check it before sending. |
| `agentId` | Optional. An agent in the workspace to attach the run to. An unknown id returns `404 not_found`. |
| `label` | Optional. Defaults to the authority, or with `agentId` to a form like `Renewal brief writer @ recommend`. |

`agentId` does not change the evaluation. It is stored on the run, appears in the default label and becomes `result.packageId`; the agent's authority level, data classes, connections and active version are not read. To test at an agent's saved level, read `authority` from [Get one agent](https://centerofagentic.com/docs/api/agents#get-agents-id) and send it.

## Read the result and decide

This response, from a run at `execute_with_approval`, shows only the failed case and leaves out most other fields.

```json
{
  "id": "d1a7e5c3-9f2b-4e86-a4c0-6b8d2f0e7a95",
  "experimentId": "6e2b8c4f-1a9d-4f30-8b7e-3c5d0a9f2e14",
  "label": "ci 2026-11-28T09:21:30Z",
  "agentId": null,
  "authority": "execute_with_approval",
  "result": {
    "total": 3,
    "passed": 2,
    "failed": 1,
    "byDimension": {
      "in_scope": { "passed": 1, "total": 1 },
      "manifest_ceiling": { "passed": 0, "total": 1 },
      "data_residency": { "passed": 1, "total": 1 }
    },
    "cases": [
      {
        "case": {
          "id": "b7e2c9a4-5f1d-4b83-9c6e-0d4a8f2e1b57",
          "title": "Record updates stay out of reach",
          "dimension": "manifest_ceiling",
          "expect": { "decision": "deny", "reasonCode": "PKG_CEILING_NO_GRANT" }
        },
        "decision": { "decision": "allow", "reason_code": "ALLOWED" },
        "passed": false,
        "failures": [
          "expected decision 'deny', got 'allow' (ALLOWED)",
          "expected reason_code 'PKG_CEILING_NO_GRANT', got 'ALLOWED'"
        ]
      }
    ]
  },
  "passed": 2,
  "failed": 1
}
```

`result.cases` has one entry per case: the `case`, the full policy `decision`, `passed` and `failures`, one sentence per mismatch.

Pass the job only when the status is `201`, `result.total` is above 0 and `failed` is 0. An empty dataset reports a `passRate` of 1, so do not gate on the rate. Keep the run `id`: comparisons and schedule baselines use it.

## A script for CI

The script starts one run and exits `0` only when every case passed, `1` when a case failed or the dataset is empty, and `2` when there is no result. It needs `curl`, `jq` and an `admin`-scope key in `COA_API_KEY`.

```bash
#!/usr/bin/env bash
# Usage: policy-gate.sh <experiment-id> <authority> [label]
# Exit 0: the run has at least one case and none failed.
# Exit 1: a case failed, or the dataset has no cases.
# Exit 2: no result to judge (missing key or argument, refused or failed request).
set -euo pipefail
BASE="https://centerofagentic.com"
fail() { echo "$*" >&2; exit 2; }

[ -n "${COA_API_KEY:-}" ] || fail "COA_API_KEY is not set"
[ -n "${1:-}" ] && [ -n "${2:-}" ] || fail "usage: policy-gate.sh <experiment-id> <authority> [label]"
EXPERIMENT_ID="$1"
AUTHORITY="$2"
LABEL="${3:-ci $(date -u +%Y-%m-%dT%H:%M:%SZ)}"

# The server does not validate the level: a typo would be evaluated like "answer".
case "$AUTHORITY" in
  answer|draft|recommend|prepare_action|execute_with_approval|execute_automatically) ;;
  *) fail "Unknown authority level: $AUTHORITY" ;;
esac

BODY=$(jq -cn --arg authority "$AUTHORITY" --arg label "$LABEL" \
  '{authority: $authority, label: $label}')

# One attempt, no retry: every successful call stores a new run, and a run
# cannot be deleted on its own.
rm -f run.json
HTTP_CODE=$(curl -sS -o run.json -w '%{http_code}' --max-time 60 \
  -X POST "$BASE/api/experiments/$EXPERIMENT_ID/run" \
  -H "Authorization: Bearer $COA_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$BODY") || HTTP_CODE=000

if [ "$HTTP_CODE" != "201" ]; then
  fail "Run request failed with HTTP $HTTP_CODE: $(head -c 300 run.json 2>/dev/null || true)"
fi
jq -e 'type == "object"' run.json > /dev/null 2>&1 || fail "The response is not a JSON object."

PASSED=$(jq -r '.passed' run.json)
TOTAL=$(jq -r '.result.total' run.json)
echo "Run $(jq -r '.id' run.json) at $AUTHORITY: $PASSED of $TOTAL cases passed"

# Anything but a non-empty result without failures fails the gate.
if jq -e '.result.total > 0 and .failed == 0' run.json > /dev/null; then
  exit 0
fi

jq -r '.result.cases[]? | select(.passed | not)
  | "FAIL [\(.case.dimension)] \(.case.title): \(.failures | join("; "))"' run.json >&2
[ "$TOTAL" != "0" ] || echo "The dataset has no cases, so the run proves nothing." >&2
exit 1
```

## GitHub Actions

Save the script as `scripts/policy-gate.sh`, the key as the repository secret `COA_EVAL_KEY` and the experiment id as the repository variable `COA_EXPERIMENT_ID`. The job runs the stored experiment at `recommend` on every pull request and keeps the result as an artifact. It does not read the pull request: an edit to `policy/renewal-policy.json` changes nothing until you import the file as a new dataset, create an experiment over it and set `COA_EXPERIMENT_ID` to the new id.

```text
name: Policy gate
on:
  pull_request:
  workflow_dispatch:

permissions:
  contents: read

jobs:
  policy-gate:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v4
      - name: Run the policy experiment
        env:
          COA_API_KEY: ${{ secrets.COA_EVAL_KEY }}
          EXPERIMENT_ID: ${{ vars.COA_EXPERIMENT_ID }}
        run: bash scripts/policy-gate.sh "$EXPERIMENT_ID" recommend "ci $GITHUB_SHA"
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: policy-gate-run
          path: run.json
          if-no-files-found: ignore
          retention-days: 7
```

Who can use the secret

A pull request from a branch of the same repository runs that branch's workflow with the secret, so everyone who can push a branch can use the `admin` key. Pull requests from forks receive no secret, so the job fails there.

## The same check in Python

The same gate in Python 3.9 or later, standard library only: `python3 scripts/policy_gate.py <experiment-id> recommend`. It decides and exits like the shell script, but writes no `run.json` and sends a label only when you pass one, so remove the artifact step if the workflow calls it.

```python
#!/usr/bin/env python3
"""Run a policy experiment; exit 0 only when every case passed. Python 3.9+."""
import json
import os
import sys
import urllib.error
import urllib.request

BASE = "https://centerofagentic.com"
LEVELS = {"answer", "draft", "recommend", "prepare_action",
          "execute_with_approval", "execute_automatically"}


def main() -> int:
    """Return 0 (all passed), 1 (a case failed or none exist) or 2 (no result)."""
    key = os.environ.get("COA_API_KEY")
    if not key:
        print("COA_API_KEY is not set", file=sys.stderr)
        return 2
    if len(sys.argv) < 3 or not sys.argv[1]:
        print("usage: policy_gate.py <experiment-id> <authority> [label]", file=sys.stderr)
        return 2
    experiment_id, authority = sys.argv[1], sys.argv[2]
    if authority not in LEVELS:  # the server does not validate the level
        print(f"Unknown authority level: {authority}", file=sys.stderr)
        return 2
    body = {"authority": authority}
    if len(sys.argv) > 3:
        body["label"] = sys.argv[3]

    request = urllib.request.Request(
        f"{BASE}/api/experiments/{experiment_id}/run",
        data=json.dumps(body).encode(),
        method="POST",
        headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            http_code, run = response.status, json.load(response)
    except urllib.error.HTTPError as err:
        detail = err.read().decode(errors="replace")[:300]
        print(f"Run request failed with HTTP {err.code}: {detail}", file=sys.stderr)
        return 2
    except (OSError, ValueError) as err:  # no connection, a timeout, or a body that is not JSON
        print(f"Run request failed: {err}", file=sys.stderr)
        return 2
    if http_code != 201 or not isinstance(run, dict):
        print(f"Unexpected response with HTTP {http_code}", file=sys.stderr)
        return 2

    result = run.get("result") or {}
    total, failed = result.get("total", 0), run.get("failed")
    print(f"Run {run.get('id')} at {authority}: {run.get('passed')} of {total} cases passed", flush=True)
    for entry in result.get("cases", []):
        if not entry["passed"]:
            case = entry["case"]
            reasons = "; ".join(entry["failures"])
            print(f"FAIL [{case['dimension']}] {case['title']}: {reasons}", file=sys.stderr)
    if total == 0:
        print("The dataset has no cases, so the run proves nothing.", file=sys.stderr)
    # Anything but a non-empty result without failures fails the gate.
    return 0 if total > 0 and failed == 0 else 1


if __name__ == "__main__":
    sys.exit(main())
```

## Compare two runs

`GET /api/experiments/{id}/diff` lines two runs of one experiment up by case id and needs only `read`. To see what raising an authority level would change, run the dataset at both levels and compare the runs.

```bash
# Your experiment id and the ids of two of its runs:
# A made at "recommend", B at "execute_with_approval".
EXPERIMENT_ID="6e2b8c4f-1a9d-4f30-8b7e-3c5d0a9f2e14"
RUN_A="7c0e4b62-8a1f-4d3e-b5c9-1f6a2d8e0b47"
RUN_B="d1a7e5c3-9f2b-4e86-a4c0-6b8d2f0e7a95"

curl -sS "https://centerofagentic.com/api/experiments/$EXPERIMENT_ID/diff?a=$RUN_A&b=$RUN_B" \
  -H "Authorization: Bearer $COA_API_KEY" \
  | jq -r '"changed: \(.changed)", (.rows[] | select(.changed) | "\(.title): \(.a.decision) -> \(.b.decision)")'
```

```text
changed: 1
Record updates stay out of reach: deny -> allow
```

A row is `changed` when the decision or the pass state differs, not when only the reason code does.

## Scheduled re-runs

An experiment can have one schedule. `POST /api/experiments/{id}/schedule` takes `authority` (required), `agentId`, `baselineRunId`, `cadenceHours` and `enabled`, and replaces an existing schedule as a whole: fields you leave out return to their defaults.

```bash
# Once, with the admin key: re-run at "recommend" every 24 hours and compare
# each re-run with a baseline run made at the same level.
EXPERIMENT_ID="6e2b8c4f-1a9d-4f30-8b7e-3c5d0a9f2e14"
BASELINE_RUN_ID="7c0e4b62-8a1f-4d3e-b5c9-1f6a2d8e0b47"
jq -cn --arg baseline "$BASELINE_RUN_ID" \
    '{authority: "recommend", baselineRunId: $baseline, cadenceHours: 24}' \
  | curl -sS -X POST "https://centerofagentic.com/api/experiments/$EXPERIMENT_ID/schedule" \
      -H "Authorization: Bearer $COA_API_KEY" \
      -H "Content-Type: application/json" -d @- \
  | jq '{id, targetAuthority, baselineRunId, cadenceHours, nextRunAt}'

# Later, with a read key. Step 1: the newest re-run must be "ok", which means
# that no case regressed against the baseline, and at most two days old, so a
# schedule that stopped running fails the check. Keep the id of the run it stored.
RUN_ID=$(curl -sS "https://centerofagentic.com/api/experiments/$EXPERIMENT_ID/schedule" \
  -H "Authorization: Bearer $COA_API_KEY" \
  | jq -r '.runs[0] | select(.status == "ok")
      | select((.completedAt[0:19] + "Z" | fromdateiso8601) > now - 172800)
      | .experimentRunId')

# Step 2: that run must have cases and no failures. Exits non-zero otherwise.
curl -sS "https://centerofagentic.com/api/experiments/$EXPERIMENT_ID" \
  -H "Authorization: Bearer $COA_API_KEY" \
  | jq -e --arg id "$RUN_ID" '.runs[] | select(.id == $id) | .result.total > 0 and .failed == 0'
```

- **Cadence.** A job checks for due schedules once an hour, so `cadenceHours` (whole hours, default 24) is the minimum gap between re-runs, not a time of day. A new schedule is due at the next check.

- **Regression.** Each re-run stores a run labelled `scheduled re-run`. Against a baseline, a case regresses when it goes from passing to failing or from `allow` to `deny`; in `default_deny`, `manifest_ceiling` or `data_residency` that is critical.

- **Status.** `GET /api/experiments/{id}/schedule` returns the 20 most recent re-runs, newest first, with `status` (`ok`, `regressed`, `no_baseline` or `error`), `regressedCount`, `criticalCount`, `experimentRunId`, `triggeredAt` and `completedAt`. `ok` means no case regressed against the baseline, not that every case passed. No webhook event or alert is raised, and nothing tells you when re-runs stop, for example after the schedule is disabled: poll it and check the age of the newest re-run.

## What a passing run proves

- **Policy decisions.** Each case shows how one action, on one data class, at one placement, is decided at this authority level. With `LIMITED_OUTPUT` the requested placement is denied, so an agent run that needs it is refused.

- **Not model output.** No model runs, so quality, accuracy and tone are untested.

- **Not an agent.** An agent's configuration, active version and tool policy are not read, nor are the budgets, pausing or revocation that can refuse its runs.

- **Not `approval`.** An agent run's decision can carry an `approval` obligation; an experiment run never attaches it. A case that expects it fails, and both `execute` levels give the same results.

## Next steps

- [**Datasets, experiments and annotations** Every operation used here, with full examples.](https://centerofagentic.com/docs/api/evaluations)

- [**Automation and CI** Key handling, safe retries and what cannot be automated.](https://centerofagentic.com/docs/guides/automation)

Source: https://centerofagentic.com/docs/guides/evaluations-in-ci

## Related pages

- [scopes](https://centerofagentic.com/docs/authentication#scopes)
- [scheduled re-run](https://centerofagentic.com/docs/guides/evaluations-in-ci#scheduled-re-runs)
- [Get one agent](https://centerofagentic.com/docs/api/agents#get-agents-id)
- [Datasets, experiments and annotations Every operation used here, with full examples.](https://centerofagentic.com/docs/api/evaluations)
- [Automation and CI Key handling, safe retries and what cannot be automated.](https://centerofagentic.com/docs/guides/automation)
