# Integrate Ogat as an agent

Ogat applies reusable, plain-language rules to product inputs and returns
structured per-input checks plus an overall `approve`, `reject`, or
`needs_review` decision.

This is the shortest reliable integration path for coding agents.

**Sources of truth (in order):**

1. [`openapi.yaml`](./openapi.yaml) for request/response schemas and status codes
2. This file for the working recipe and control-flow rules
3. [`llms.txt`](./llms.txt) for the compact product map
4. `/developers/docs` for the human guide

Do not scrape marketing copy for API behavior. Do not invent endpoints, fields,
or credentials.

## What the human must provide

Ask for these values if they are not already available:

1. An app-scoped Ogat API key beginning with `ogt_`.
2. A policy handle from the same app.
3. The policy's configured input keys and representative test values.
4. Any `context` keys used by Only-when rules, and any `$placeholder` keys
   needed in rule text (`data`).
5. The desired product behavior for approve, reject, and needs-review outcomes.

Account creation, app creation, policy/rule configuration, and API-key creation
happen in the Ogat console. Do not automate console UI or invent credentials.

## Integration contract

- Base URL: `https://api.ogat.ai/functions/v1`
- Method: `POST` only
- Auth header: `Authorization: Bearer <OGAT_API_KEY>`
- Content type: `application/json`
- Recommended secret variable: `OGAT_API_KEY`
- Recommended policy variable: `OGAT_POLICY`
- Official SDK: none yet; use HTTP
- Public schemas: `https://ogat.ai/openapi.yaml`

Keep `OGAT_API_KEY` in server-side environment configuration. Do not commit it,
render it into client-side code, print it in logs, or include it in fixtures.
Never send third-party LLM provider keys to Ogat.

## First working review

For most integrations, call `review-submission` once. Omitting `submissionId`
creates the submission and reviews it in the same request.

```bash
export OGAT_API_KEY="ogt_..."
export OGAT_POLICY="marketplace-listing"

curl -sS "https://api.ogat.ai/functions/v1/review-submission" \
  -H "Authorization: Bearer ${OGAT_API_KEY}" \
  -H "Content-Type: application/json" \
  -d "{
    \"policy\": \"${OGAT_POLICY}\",
    \"inputs\": {
      \"title\": \"Vintage camera\",
      \"description\": \"Barely used, ships next day.\"
    }
  }"
```

Replace `OGAT_POLICY` and the `inputs` keys with the human's real policy handle
and input keys. Do not assume the example policy or keys exist in their app.

Minimal server-side JavaScript:

```js
const response = await fetch(
  "https://api.ogat.ai/functions/v1/review-submission",
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.OGAT_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      policy: process.env.OGAT_POLICY,
      inputs: {
        title,
        description,
      },
    }),
  },
);

const body = await response.json();
if (!response.ok) throw new Error(body.error || `Ogat HTTP ${response.status}`);

switch (body.decision) {
  case "approve":
    // Continue the product action.
    break;
  case "reject":
    // Block or request changes; use inputs/checks to explain why.
    break;
  case "needs_review":
    // Stop automation and route to a human.
    break;
}
```

## Read the response

Treat these as three distinct signals:

1. `checks[].result` / `inputs[].result`: whether rule criteria matched
   (`pass` / `fail`; input may also be `skipped`).
2. `certainty`: confidence in that result, from 0 to 100 (independent of result).
3. Top-level `decision`: product action after policy settings
   (`approve` / `reject` / `needs_review`). Present only on `review-submission`
   and webhooks.

Always branch control flow on top-level `decision`. HTTP `200` means the review
completed, including reject and needs-review. A check `pass` with low certainty
can correctly produce `decision: "needs_review"`.

Common submission `reasonCode` values:

| reasonCode | Typical decision |
| --- | --- |
| *(omitted)* | `approve` |
| `required_input_failed` | `reject` |
| `optional_input_failed` | `needs_review` |
| `low_certainty` | `needs_review` |
| `too_many_optional_failures` | `reject` (advanced) |

Input/check `reasonCode` values include `low_certainty` and `waiting_for_data`
(when an input is `skipped` because a `$placeholder` could not be resolved).

## Choose an endpoint

| Endpoint | Use when | Decision / webhooks |
| --- | --- | --- |
| `POST /review-submission` | Complete payload, job, message, or agent action (default) | Returns `decision`; emits webhooks |
| `POST /review-input` | One field (e.g. blur) | Per-input result only |
| `POST /review-inputs` | Several fields without finalizing (e.g. wizard step) | Per-input results only |
| `POST /create-submission` | Mint a draft id up front (optional) | No review |

Interactive draft flow: create (optional) → `review-input` and/or
`review-inputs` → `review-submission`. Reuse the platform-minted `submissionId`.

`inputs` may be an object map (preferred) or an array of `{ key, value }`.
Values must be non-empty strings. Prefer the object map.

## Context and data

Optional on review/create calls. Merged into the submission; later calls
overwrite earlier keys. Neither is reviewed as an input.

- `context`: selects which conditional (Only-when) rules run.
- `data`: fills `$placeholders` in rule text. Lookup also considers input
  values; if the same key exists in both, the **input value wins**.

Missing placeholders can yield `result: "skipped"` with
`reasonCode: "waiting_for_data"`. Supply the missing `data` (or input) and retry.

Example:

```json
{
  "policy": "marketplace-listing",
  "inputs": {
    "title": "Vintage camera",
    "description": "Barely used, ships next day."
  },
  "context": { "listingType": "physical_goods" },
  "data": { "store_name": "Acme Market" }
}
```

`externalId` is an optional customer reconciliation reference (create /
review-submission when creating).

## Errors, credits, and retries

Non-2xx responses contain `error` and may contain a machine-readable `code`.

| Status | Meaning |
| --- | --- |
| 400 | Invalid request (missing policy, unknown input, empty value, bad shape) |
| 401 | Missing or invalid API key |
| 403 | Policy is not in this app (`review-inputs` / `review-submission`) |
| 429 | `code: rate_limited` (back off) or `credit_quota_exceeded` (wait / top up / upgrade) |
| 5xx | Server or transport failure |

New checks consume plan credits. Unchanged cached results on the same submission
do not. If every input is already cached, finalizing with `review-submission`
costs no extra credits (you still get `decision` and webhooks if configured).

There is no public idempotency-key parameter. Retry ambiguous transport or 5xx
failures with bounded exponential backoff. When a workflow already has a
`submissionId`, reuse it. Do not loop on 400, 401, 403, or credit-quota errors.

## Webhooks

Emitted only after `review-submission` completes. Console subscriptions are
exact: `review.completed` and/or `review.needs_review`.

- Header `X-Ogat-Event`: event name
- Header `X-Ogat-Signature`: HMAC-SHA256 of the **raw** request body, lowercase hex
- Body: same public fields as `review-submission`, plus `event` and `policy`

Verify the signature with the endpoint secret before acting. The secret is never
sent in the POST. Automatic delivery retries are not currently guaranteed.

## Verification before declaring success

1. Run one known-good value and confirm `decision: "approve"`.
2. Run one known-bad value and confirm the expected reject or needs-review path.
3. Assert all three decision branches in code.
4. Confirm secrets are server-side and absent from source control and logs.
5. Record `submissionId` (and `externalId` if used) for reconciliation.
6. If webhooks are used, verify `X-Ogat-Signature` over the raw body with the
   endpoint secret using HMAC-SHA256 hex.

## Do not

- Invent endpoints, SDK methods, policy handles, input keys, or credentials.
- Use console JWTs as customer integration credentials.
- Send third-party LLM keys or expose the Ogat key to client code.
- Treat HTTP 200 as approval; inspect `decision`.
- Treat check `pass` as approval; certainty and policy can require human review.
- Branch product logic on `review-input` / `review-inputs` as if they returned
  a final decision.
- Delete or change policies and rules without an explicit user request.
- Claim webhook retries or API idempotency that the service does not provide.
