# Incoming CI/CD and ticket webhooks / Входящие события CI/CD и тикетов

## Русский

Компания отправляет планируемое изменение в `POST /api/integrations/changes`. Это
нормализованный контракт: CI job или правило автоматизации тикетов собирает JSON из
полей своей системы. Готовые тела запроса: [CI/CD](../integrations/ci-change.json) и
[тикет](../integrations/ticket-change.json). Встроенных обработчиков собственных форматов
GitHub, GitLab, Jira и их подписей здесь нет: если платформа не умеет такое тело и Bearer,
преобразование и проверку подписи делает адаптер компании перед Deconflictor.

Сначала импортируйте настоящий граф компании и настройте модель по
[инструкции развёртывания](company-deployment.md). Для удалённого доступа задайте
`DECONFLICTOR_API_TOKEN` и HTTPS на reverse proxy. Интеграция отправляет токен заголовком
`Authorization: Bearer …`; токен в URL не принимается. Это общий токен организации с
доступом ко всему API, отдельного разграничения прав по `source` пока нет. Держите его в
секретах CI или хранилище подключений системы тикетов; не включайте трассировку команд.

```sh
curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $DECONFLICTOR_API_TOKEN" \
  -H 'Content-Type: application/json' \
  --data-binary @docs/integrations/ci-change.json \
  "$DECONFLICTOR_URL/api/integrations/changes"
```

Перед отправкой замените окно, описание, владельца и ссылку примера реальными данными.
`declared_surfaces` необязателен; если известны затронутые сервисы, передайте их refs из
`GET /api/surfaces`. Их наличие в актуальном графе проверяет код. В примерах refs опущены,
потому что каталог у каждой компании свой. Роль Intake также извлекает поверхности из текста.

Идентичность изменения задаёт пара `source` + `external_id`:

- `source`: стабильное имя интеграции, 1–64 символа, строчные латинские буквы, цифры,
  `.`, `_`, `-`; первый символ — буква или цифра. Примеры: `ci-orders`, `tickets-platform`.
- `external_id`: стабильная версия изменения, 1–200 ASCII-символов из букв, цифр,
  `. _ : / @ + -`, первый — буква или цифра. Регистр значим. Примеры:
  `orders/deploy/8142`, `OPS-42:revision-3`. Номер попытки доставки сюда не входит.
- `change`: обычная заявка из `POST /api/changes`, без заданного клиентом `id`.
  Тело — до 20 000 символов, окно с часовым поясом, до 31 дня по умолчанию. Все правила
  обычного API сохранены. Лимит HTTP-тела — `DECONFLICTOR_API_MAX_BODY_BYTES`, по умолчанию
  1 МиБ; авторизация проверяется до чтения тела.

| Ответ | Что произошло | Что делать интеграции |
|---|---|---|
| `202`, `duplicate: false` | Заявка и связь с внешним id записаны; оценка поставлена в очередь | Сохранить `id`, читать `card` или `events` |
| `200`, `duplicate: true` | Такое же содержимое уже принято | Использовать тот же `id`; пропущенная первоначальная оценка восстановится |
| `409 external_identity_conflict` | Под этим ключом уже хранится другое содержимое | Исправить ошибку отправителя либо завести осмысленную новую ревизию |
| `422` | Неверные поля или неизвестная поверхность | Исправить данные; ключ ещё не занят |
| `401` / `403` | Нет доступа | Проверить токен и сетевые настройки |
| `413 body_too_large` | Слишком большое тело | Отправить краткую заявку со ссылками вместо полного лога |
| `503` / сетевой сбой | Сервис недоступен или ответ потерян | Повторить то же тело и ключ с задержкой |

`202` не означает разрешения на развёртывание. Режим advisory информирует команду;
остановку CI по результату компания явно реализует в своём job. Для автоматического
разрешения на развёртывание прочитайте свежую `card` и проверьте все условия:

- `status = active` и `evaluation.state = done`;
- `record` и `outcome` присутствуют, `record.content_version = content_version`,
  `record.id = outcome.record_id`: решение относится к текущей версии заявки;
- `record.chair.status` — `ok` или `carried`. `not_asked` и `skipped_standard`
  допустимы лишь тогда, когда политика компании разрешает соответствующий режим без Chair;
- `record.final_verdict = outcome.final_verdict = approve` и нет действующего `override`,
  который должен обрабатываться отдельным процессом согласования компании.

`done` означает окончание прохода оценки, но ответ Chair ещё может иметь статус `pending`.
Поздний ответ способен изменить `approve` на `escalate`. Поэтому `pending`, `failed`,
неизвестный статус Chair, неактивная заявка, устаревшее решение или отсутствие обязательного
поля не разрешают автоматическое развёртывание. `reject` останавливает его, `escalate`
требует человека. Для ожидания задайте конечный тайм-аут; при ошибке или его истечении
оставьте запуск заблокированным и передайте ситуацию человеку. Повтор webhook восстанавливает
только отсутствующую первоначальную оценку и не перезапускает ожидающий или неудачный Chair.

Повторно прочитайте карточку непосредственно перед развёртыванием: решение может измениться
при появлении другой заявки или ручном действии. Чтение API не блокирует календарь и не
выдаёт атомарного разрешения на внешний запуск. Поток `events` показывает этапы совета;
терминальное SSE-событие `done` тоже не заменяет эти проверки. Живой веб-интерфейс показывает
ту же заявку и календарь.

После потери ответа можно найти заявку без повторной отправки:

```sh
curl --fail-with-body --silent --show-error --get \
  -H "Authorization: Bearer $DECONFLICTOR_API_TOKEN" \
  --data-urlencode 'source=ci-orders' \
  --data-urlencode 'external_id=orders/deploy/8142' \
  "$DECONFLICTOR_URL/api/integrations/changes"
```

`404 integration_change_not_found` означает, что такого принятого ключа ещё нет. `source`
не является секретом и не разграничивает доступ. По возвращённому `id` работают обычные
операции `PATCH /api/changes/{id}/status` и `POST /api/changes/{id}/reschedule`.
Автоматического преобразования статусов внешних систем нет. Изменившийся тикет — новая
ревизия `external_id`; предыдущую активную заявку сначала отзовите явным API-вызовом,
чтобы обе версии не считались одновременно запланированными.

### Почему повтор безопасен

Миграция `0007` добавляет `integration_receipts`. В одной транзакции сохраняются заявка,
её событие `change.submitted`, исходный SHA-256 и внешняя пара. Блокировка PostgreSQL по
этой паре сериализует конкурентные доставки; составной первичный ключ дополнительно
защищает уникальность. При сбое записи откатывается всё. Внутри блокировки модель не вызывается.

Хеш вычисляется по полям исходной заявки: порядок JSON-ключей и эквивалентные часовые
пояса не влияют, пробелы вокруг заголовка и автора обрезаются как при хранении. Порядок
списков и пробелы в основном тексте значимы. Смена статуса и перенос окна после приёма
не меняют исходный хеш. Повтор не отменяет эти действия и не проверяет заново граф,
который к этому времени мог измениться. Ключ хранится столько же, сколько сама заявка.
Удаление данных вручную снимает гарантию для удалённых ключей; сохраняйте всю БД в бэкапе.

Очередь использует существующий worker: один процесс сервиса, оценка вне HTTP-запроса.
Первая доставка и повторы ставят одно проверяемое задание. Перед выполнением worker
проверяет наличие решения: готовая оценка не повторяется, в том числе если она завершилась
между повторной доставкой и постановкой задания. Если HTTP-запрос оборвался между
фиксацией заявки и постановкой в память, повтор восстанавливает первоначальную оценку
без перезапуска сервиса. Неактивные заявки пропускаются. При остановке процесса штатное
восстановление подхватывает заявку без вердикта при следующем старте. Гарантия касается
одной сохранённой заявки; число вызовов модели при аварии во время оценки не обещает exactly-once.

## English

Send planned changes to `POST /api/integrations/changes`. CI jobs and ticket automations map
their fields into this normalized contract. Ready-to-adapt bodies:
[CI/CD](../integrations/ci-change.json) and [ticket](../integrations/ticket-change.json).
These are not native GitHub/GitLab/Jira event handlers. A company-owned adapter must translate
vendor payloads and verify vendor signatures when the source cannot send this JSON with Bearer
authentication. Import the company catalog and configure live models before integration.

Use HTTPS and `Authorization: Bearer $DECONFLICTOR_API_TOKEN` as in the curl examples above.
Keep the token in the CI secret store or ticket connection credentials. The shared token grants
access to the complete company API; `source` is a namespace, not an authorization boundary.
Query-string tokens are not accepted here. Authentication runs before body parsing; the default
HTTP limit is 1 MiB (`DECONFLICTOR_API_MAX_BODY_BYTES`).

`source` is a stable integration name: 1–64 lowercase ASCII letters, digits, dots, underscores
or hyphens, beginning with a letter/digit. `external_id` identifies an immutable rollout or
ticket revision: 1–200 ASCII letters, digits or `. _ : / @ + -`, beginning with a letter/digit.
Both values are case-sensitive. Keep them unchanged across delivery retries; do not use an
attempt counter. A new ticket revision needs a new external id. Withdraw its previous active
calendar change explicitly before submitting the replacement.

`change` uses the normal change request fields, without a client-supplied `id`: title, body,
kind, timezone-aware window and author; environment, change class, links and declared surfaces
are optional. Body text is limited to 20,000 characters and the default maximum window is
31 days. Supply declared surface refs from `GET /api/surfaces` when known; examples omit them
because each company's catalog differs. All normal request validation remains in force.

| Response | Meaning | Sender action |
|---|---|---|
| `202`, `duplicate: false` | Stored durably; queued for evaluation | Save `id`, read `card` or `events` |
| `200`, `duplicate: true` | Identical content was already accepted | Reuse the same id; missing initial evaluation is recovered |
| `409 external_identity_conflict` | Same identity, different original content | Fix the sender or create an intentional new revision |
| `422` | Invalid fields or unknown declared surface | Correct payload; identity was not consumed |
| `401` / `403` | Access denied | Correct credentials/network setup |
| `413 body_too_large` | HTTP body too large | Send a concise description and links instead of raw logs |
| `503` / network failure | Service unavailable or response lost | Retry the exact payload and identity with backoff |

Acceptance is not rollout approval. Advisory mode informs teams; a CI job must explicitly
implement any rollout gate. Before allowing an automatic rollout, read a fresh `card` and
require all of the following:

- `status = active` and `evaluation.state = done`;
- both `record` and `outcome` exist, `record.content_version = content_version` and
  `record.id = outcome.record_id`: the decision evaluates the current change version;
- `record.chair.status` is `ok` or `carried`. Accept `not_asked` or `skipped_standard` only
  when the company policy explicitly permits the corresponding mode without a Chair;
- `record.final_verdict = outcome.final_verdict = approve` and there is no current `override`,
  which must be handled by the company's separate approval process.

`done` ends an evaluation pass, but the Chair may still be `pending`. A late answer can change
`approve` to `escalate`. Pending, failed or unknown Chair status, an inactive change, a stale
decision or a missing required field must not authorize an automatic rollout. Reject blocks it;
escalation requires a person. Use a finite polling timeout; errors and timeouts keep the rollout
blocked and require human follow-up. Retrying the webhook only recovers a missing initial
evaluation; it does not retry a pending or failed Chair.

Read the card again immediately before deploying: another submission or human action may change
the decision. Reading the API neither locks the calendar nor grants atomic permission for an
external rollout. The terminal SSE `done` event does not replace these checks. The existing web
interface and SSE timeline show the same stored change. Links in requests are data; the webhook
handler does not fetch them.

`GET /api/integrations/changes?source=…&external_id=…` resolves the external identity after a
lost response; use URL encoding as in the example above. It returns `id`, `card` and `events`,
or `404 integration_change_not_found`. Use ordinary status/reschedule endpoints on that id.
External status synchronization is explicit, not inferred from vendor event names.

Migration `0007` stores a receipt, original-content SHA-256, change and submission event in
one transaction. A PostgreSQL advisory transaction lock serializes each identity; the composite
primary key enforces uniqueness. A failed write rolls everything back. No model call runs while
this lock is held. JSON object order, equivalent time zones and title/author outer whitespace
are normalized; array order and body whitespace remain significant. The original hash survives
later status changes and rescheduling. A duplicate never reverses those actions or revalidates
a catalog that may have changed since acceptance.

Keep the whole database in backups: receipts live as long as changes, and manual deletion
removes deduplication for deleted identities. The service uses its existing single worker.
First deliveries and retries enqueue the same guarded job. The worker checks for an existing
decision immediately before execution, so completed evaluations are not rerun even if the
previous job finished between a duplicate delivery and its enqueue. If an HTTP request was
cancelled after commit but before enqueue, a retry recovers the initial evaluation without a
server restart. Inactive changes are skipped. Startup recovery also queues changes left without
a verdict after a process stop. This guarantees one stored change per identity, not exactly-once
model execution when a process crashes during evaluation.
