Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4744: restore Autopilot webhook response contract (#5397)
Multica Eve6b4d69066497
diff --git a/apps/docs/content/docs/autopilots.ja.mdx b/apps/docs/content/docs/autopilots.ja.mdxindex 4b4706cffe..516144c02e 100644--- a/apps/docs/content/docs/autopilots.ja.mdx+++ b/apps/docs/content/docs/autopilots.ja.mdx@@ -58,7 +58,7 @@ multica autopilot trigger <autopilot-id>https://<your-multica-host>/api/webhooks/autopilots/awt_…```-その URL に任意の JSON を POST してください。Multica はまず配信を永続化して `202 Accepted` を返し、その後データベース-backed worker が `source = webhook` の実行を記録してエージェントをディスパッチします。受付とディスパッチの間にサーバーが再起動しても、キュー済みの配信は失われません。+その URL に任意の JSON を POST してください。Multica はまず配信を永続化し、冪等な実行を同期的に受け付け、`status = accepted | skipped` と `run_id` を含む `200 OK` を返します。その後データベース-backed worker が accepted の実行を再開してエージェントをディスパッチします。受付とディスパッチの間にサーバーが再起動しても、キュー済みの配信は失われません。```bashcurl -X POST "$MULTICA_WEBHOOK_URL" \@@ -173,7 +173,7 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \-H 'X-GitHub-Event: workflow_run' \-H 'Content-Type: application/json' \-d '{"action":"completed"}'-# → 202 {"status":"queued", "delivery_id":"…", ...}+# → 200 {"status":"accepted", "delivery_id":"…", "run_id":"…", ...}# Filtered — same event, action not in allowlistcurl -X POST "$MULTICA_WEBHOOK_URL" \@@ -194,9 +194,14 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \### ステータスコードの意味-有効でアクティブな配信は、永続化された後に `202 Accepted` で確認されます。`{"status":"queued","delivery_id":"…"}` は worker がディスパッチを所有したことを示します。no-op と重複は `200 OK` を返します。+有効でアクティブな配信は、配信と冪等な実行の両方が永続化された後に `200 OK` で確認されます。-- `{"status":"duplicate","delivery_id":"…","run_id":"…"}` — 同じ冪等キーの配信は既に受け付け済みです。元の配信がまだキュー中なら `run_id` はありません。+- `{"status":"accepted","delivery_id":"…","run_id":"…","autopilot_id":"…","trigger_id":"…"}` — 受付が成功し、worker が復旧可能なディスパッチを所有します。+- `{"status":"skipped","delivery_id":"…","run_id":"…","reason":"…"}` — たとえば担当エージェントのランタイムがオフラインの場合に、永続化された skipped の実行が作成されました。++no-op と重複も `200 OK` を返します。++- `{"status":"duplicate","delivery_id":"…","run_id":"…"}` — 同じ冪等キーの配信は既に受け付け済みです。元のリクエストが実行の受付前に終了した場合のみ `run_id` はなく、worker が復旧します。- `{"status":"ignored","reason":"trigger_disabled"}` — トリガーが無効になっています。- `{"status":"ignored","reason":"autopilot_paused"}` — オートパイロットが一時停止しています。- `{"status":"ignored","reason":"autopilot_archived"}` — オートパイロットがアーカイブされています。diff --git a/apps/docs/content/docs/autopilots.ko.mdx b/apps/docs/content/docs/autopilots.ko.mdxindex 5428f2c860..89e75c3bc0 100644--- a/apps/docs/content/docs/autopilots.ko.mdx+++ b/apps/docs/content/docs/autopilots.ko.mdx@@ -58,7 +58,7 @@ multica autopilot trigger <autopilot-id>https://<your-multica-host>/api/webhooks/autopilots/awt_…```-그 URL로 아무 JSON이나 POST하세요. Multica는 먼저 전달을 영구 저장하고 `202 Accepted`를 반환한 뒤, 데이터베이스-backed worker가 `source = webhook` 실행을 기록하고 에이전트를 디스패치합니다. 수신과 디스패치 사이에 서버가 재시작되어도 큐에 저장된 전달은 유실되지 않습니다.+그 URL로 아무 JSON이나 POST하세요. Multica는 먼저 전달을 영구 저장하고 멱등 실행을 동기적으로 승인한 뒤, `status = accepted | skipped`와 `run_id`가 포함된 `200 OK`를 반환합니다. 이후 데이터베이스-backed worker가 accepted 실행을 재개하고 에이전트를 디스패치합니다. 수신과 디스패치 사이에 서버가 재시작되어도 큐에 저장된 전달은 유실되지 않습니다.```bashcurl -X POST "$MULTICA_WEBHOOK_URL" \@@ -173,7 +173,7 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \-H 'X-GitHub-Event: workflow_run' \-H 'Content-Type: application/json' \-d '{"action":"completed"}'-# → 202 {"status":"queued", "delivery_id":"…", ...}+# → 200 {"status":"accepted", "delivery_id":"…", "run_id":"…", ...}# Filtered — same event, action not in allowlistcurl -X POST "$MULTICA_WEBHOOK_URL" \@@ -194,9 +194,14 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \### 상태 코드 의미-유효하고 활성 상태인 전달은 영구 저장된 뒤 `202 Accepted`로 확인됩니다. `{"status":"queued","delivery_id":"…"}`는 worker가 디스패치를 맡았음을 뜻합니다. no-op과 중복은 `200 OK`를 반환합니다.+유효하고 활성 상태인 전달은 전달과 멱등 실행이 모두 영구 저장된 뒤 `200 OK`로 확인됩니다.-- `{"status":"duplicate","delivery_id":"…","run_id":"…"}` — 같은 멱등 키의 전달이 이미 수신되었습니다. 원본 전달이 아직 큐에 있으면 `run_id`는 생략됩니다.+- `{"status":"accepted","delivery_id":"…","run_id":"…","autopilot_id":"…","trigger_id":"…"}` — 승인이 완료되었고 worker가 복구 가능한 디스패치를 맡습니다.+- `{"status":"skipped","delivery_id":"…","run_id":"…","reason":"…"}` — 예를 들어 담당 에이전트의 런타임이 오프라인인 경우 영구 저장된 skipped 실행이 생성되었습니다.++no-op과 중복도 `200 OK`를 반환합니다.++- `{"status":"duplicate","delivery_id":"…","run_id":"…"}` — 같은 멱등 키의 전달이 이미 수신되었습니다. 원본 요청이 실행 승인 전에 종료된 경우에만 `run_id`가 생략되며 worker가 이를 복구합니다.- `{"status":"ignored","reason":"trigger_disabled"}` — 트리거가 비활성화되어 있습니다.- `{"status":"ignored","reason":"autopilot_paused"}` — 오토파일럿이 일시 정지되어 있습니다.- `{"status":"ignored","reason":"autopilot_archived"}` — 오토파일럿이 보관되어 있습니다.diff --git a/apps/docs/content/docs/autopilots.mdx b/apps/docs/content/docs/autopilots.mdxindex f60dd438ea..72650f09b2 100644--- a/apps/docs/content/docs/autopilots.mdx+++ b/apps/docs/content/docs/autopilots.mdx@@ -59,9 +59,10 @@ on the autopilot detail page; Multica generates a unique URL of the shape:https://<your-multica-host>/api/webhooks/autopilots/awt_…```-POST any JSON to that URL. Multica first stores a durable delivery and returns-`202 Accepted`, then a database-backed worker records a run with-`source = webhook`, stores the body as the run's `trigger_payload`, and+POST any JSON to that URL. Multica first stores a durable delivery and+synchronously admits an idempotent run, returning `200 OK` with+`status = accepted | skipped` and its `run_id`. A database-backed worker then+resumes accepted runs, stores the body as the run's `trigger_payload`, anddispatches the agent exactly the way a schedule trigger would. A server restartbetween admission and dispatch does not lose the queued delivery.@@ -216,7 +217,7 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \-H 'X-GitHub-Event: workflow_run' \-H 'Content-Type: application/json' \-d '{"action":"completed"}'-# → 202 {"status":"queued", "delivery_id":"…", ...}+# → 200 {"status":"accepted", "delivery_id":"…", "run_id":"…", ...}# Filtered — same event, action not in allowlistcurl -X POST "$MULTICA_WEBHOOK_URL" \@@ -242,18 +243,21 @@ autopilot. Treat it like a token:### Status-code semantics-Multica acknowledges an active, valid delivery only after it is durable:+Multica acknowledges an active, valid delivery only after both its delivery and+idempotent run are durable:-- `202 {"status":"queued","delivery_id":"…","autopilot_id":"…","trigger_id":"…"}`- — the delivery is stored and the worker owns dispatch. The eventual run and- any admission skip are visible in delivery/run history.+- `200 {"status":"accepted","delivery_id":"…","run_id":"…","autopilot_id":"…","trigger_id":"…"}`+ — admission succeeded and the worker owns recoverable dispatch.+- `200 {"status":"skipped","delivery_id":"…","run_id":"…","reason":"…"}`+ — admission produced a durable skipped run, for example when the assignee's+ runtime is offline.Normal no-op and deduplication outcomes return `200 OK` so providers do notretry them indefinitely:- `{"status":"duplicate","delivery_id":"…","run_id":"…"}` — the provider's- idempotency key was already admitted. `run_id` is omitted while the original- delivery is still queued.+ idempotency key was already admitted. `run_id` is omitted only if the original+ request ended before its run could be admitted; the worker will recover it.- `{"status":"ignored","reason":"trigger_disabled"}` — the trigger is disabled.- `{"status":"ignored","reason":"autopilot_paused"}` — the autopilot is paused.- `{"status":"ignored","reason":"autopilot_archived"}` — the autopilot is archived.diff --git a/apps/docs/content/docs/autopilots.zh.mdx b/apps/docs/content/docs/autopilots.zh.mdxindex 81b08f25cc..d3eae8e624 100644--- a/apps/docs/content/docs/autopilots.zh.mdx+++ b/apps/docs/content/docs/autopilots.zh.mdx@@ -59,10 +59,11 @@ Autopilot 也可以由入站 HTTP webhook 触发。在详情页添加一个 **Wehttps://<你的 Multica host>/api/webhooks/autopilots/awt_…```-向这个 URL POST 任意 JSON。Multica 会先持久化投递并返回-`202 Accepted`,再由数据库 worker 记录一条 `source = webhook` 的 run,-把请求体保存为 run 的 `trigger_payload`,然后按和 schedule 触发器完全-一致的方式派发给智能体。接收与派发之间即使服务重启,已排队的投递也不会丢失。+向这个 URL POST 任意 JSON。Multica 会先持久化投递,并同步准入一条+幂等 run,返回带有 `status = accepted | skipped` 和 `run_id` 的 `200 OK`。+数据库 worker 随后恢复 accepted run,把请求体保存为 run 的+`trigger_payload`,再按和 schedule 触发器完全一致的方式派发给智能体。+接收与派发之间即使服务重启,已排队的投递也不会丢失。```bashcurl -X POST "$MULTICA_WEBHOOK_URL" \@@ -203,7 +204,7 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \-H 'X-GitHub-Event: workflow_run' \-H 'Content-Type: application/json' \-d '{"action":"completed"}'-# → 202 {"status":"queued", "delivery_id":"…", ...}+# → 200 {"status":"accepted", "delivery_id":"…", "run_id":"…", ...}# 被过滤 —— 同样的事件,但 action 不在白名单curl -X POST "$MULTICA_WEBHOOK_URL" \@@ -228,16 +229,18 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \### 状态码语义-有效且活跃的投递只有持久化后才会确认:+有效且活跃的投递只有在投递和幂等 run 都持久化后才会确认:-- `202 {"status":"queued","delivery_id":"…","autopilot_id":"…","trigger_id":"…"}`- —— 投递已经持久化,后续派发由 worker 接管。最终 run 和准入跳过原因可以在- 投递 / run 历史里查看。+- `200 {"status":"accepted","delivery_id":"…","run_id":"…","autopilot_id":"…","trigger_id":"…"}`+ —— 准入成功,后续派发由 worker 接管并可恢复。+- `200 {"status":"skipped","delivery_id":"…","run_id":"…","reason":"…"}`+ —— 准入生成了持久化的 skipped run,例如负责人运行时离线。正常 no-op 和去重路径返回 `200 OK`,避免外部 webhook 无限重试:- `{"status":"duplicate","delivery_id":"…","run_id":"…"}` —— 发送方的- 幂等 key 已经接收;原投递仍排队时不带 `run_id`。+ 幂等 key 已经接收。只有原请求在 run 准入前中断时才不带 `run_id`;worker+ 会恢复它。- `{"status":"ignored","reason":"trigger_disabled"}` —— 触发器已禁用。- `{"status":"ignored","reason":"autopilot_paused"}` —— Autopilot 已暂停。- `{"status":"ignored","reason":"autopilot_archived"}` —— Autopilot 已归档。diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.goindex ba8ed66a9b..2426984a9d 100644--- a/server/internal/handler/autopilot_webhook.go+++ b/server/internal/handler/autopilot_webhook.go@@ -308,7 +308,7 @@ func selectedHeadersJSON(headers http.Header) []byte {// autopilots. It runs OUTSIDE the authenticated route group: the bearer// token in the URL path IS the credential.//-// Flow (persist-first, durable async dispatch):+// Flow (persist-first, synchronous admission + durable async dispatch)://// 1. High absolute per-IP ceiling plus a non-consuming check for prior// bad-credential debt (both before DB I/O).@@ -326,12 +326,14 @@ func selectedHeadersJSON(headers http.Header) []byte {// delivery → rejected, return 401.// 9. If trigger disabled / autopilot paused / archived: UPDATE delivery →// ignored, return 200.-// 10. Persist the 202 acknowledgement and wake the database-leased worker.-// The worker re-checks state/filter scope, dispatches idempotently, and-// bumps last_fired_at after it owns a run.+// 10. Create or reuse the delivery's idempotent run, persist the compatible+// 200 accepted/skipped acknowledgement, and wake the database-leased+// worker. The worker re-checks state/filter scope, dispatches idempotently,+// and bumps last_fired_at.//// Response shapes:-// - 202 {"status":"queued", "delivery_id", "autopilot_id", "trigger_id"}+// - 200 {"status":"accepted", "delivery_id", "run_id", "autopilot_id", "trigger_id"}+// - 200 {"status":"skipped", "delivery_id", "run_id", "reason"}// - 200 {"status":"ignored", "delivery_id", "reason"}// - 200 {"status":"duplicate", "delivery_id", "run_id?"}// - 400 {"error":"..."} — invalid JSON / scalar / empty@@ -429,6 +431,11 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusBadRequest, err.Error())return}+ envelopeBytes, err := json.Marshal(envelope)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to encode envelope")+ return+ }// 6. Provider + dedupe + signature.provider := trigRow.Providerif provider == "" {@@ -461,14 +468,31 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)}if dup {// A previous delivery already covered this dedupe key. Return the- // original delivery_id + (possibly empty) run_id with 200 so the- // caller can correlate.+ // original delivery_id + admitted run_id with 200 so the caller can+ // correlate. The delivery row is not linked until worker completion,+ // so retrying before then must fall back to the run's durable delivery+ // anchor.resp := map[string]any{"status": "duplicate","delivery_id": uuidToString(delivery.ID),}- if delivery.AutopilotRunID.Valid {- resp["run_id"] = uuidToString(delivery.AutopilotRunID)+ runID := delivery.AutopilotRunID+ if !runID.Valid {+ run, runErr := h.Queries.GetAutopilotRunByWebhookDelivery(r.Context(), delivery.ID)+ switch {+ case runErr == nil:+ runID = run.ID+ case !errors.Is(runErr, pgx.ErrNoRows):+ slog.Error("webhook: resolve duplicate run failed",+ "delivery_id", uuidToString(delivery.ID),+ "error", runErr,+ )+ writeError(w, http.StatusInternalServerError, "internal error")+ return+ }+ }+ if runID.Valid {+ resp["run_id"] = uuidToString(runID)}if delivery.Status == deliveryStatusQueued && h.WebhookDeliveryWorker != nil {h.WebhookDeliveryWorker.Notify()@@ -535,20 +559,52 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)return}- // 11. The queued INSERT above is the durable admission point. Best-effort- // persist the exact acknowledgement for operator correlation, then wake- // the worker. An acknowledgement metadata write failure must not turn an- // already-durable delivery into an HTTP failure.+ // 11. Allocate the idempotent run synchronously so existing webhook clients+ // keep the v0.4.0 response contract. The queued delivery remains the+ // durable dispatch source: the worker resumes this run after the response+ // and can recover it after a process crash.+ run, err := h.AutopilotService.AdmitAutopilotWebhookDelivery(+ r.Context(),+ autopilot,+ trigRow.ID,+ envelopeBytes,+ delivery.ID,+ )+ if err != nil {+ slog.Warn("webhook admission failed",+ "trigger_id", uuidToString(trigRow.ID),+ "autopilot_id", uuidToString(autopilot.ID),+ "delivery_id", uuidToString(delivery.ID),+ "error", err,+ )+ if h.WebhookDeliveryWorker != nil {+ h.WebhookDeliveryWorker.Notify()+ }+ writeError(w, http.StatusInternalServerError, "failed to admit autopilot")+ return+ }+respBody := map[string]any{- "status": "queued",+ "status": "accepted","delivery_id": uuidToString(delivery.ID),+ "run_id": uuidToString(run.ID),"autopilot_id": uuidToString(autopilot.ID),"trigger_id": uuidToString(trigRow.ID),}+ if run.Status == "skipped" {+ respBody = map[string]any{+ "status": "skipped",+ "delivery_id": uuidToString(delivery.ID),+ "run_id": uuidToString(run.ID),+ }+ if run.FailureReason.Valid {+ respBody["reason"] = run.FailureReason.String+ }+ }bodyJSON, _ := json.Marshal(respBody)if _, err := h.Queries.AcknowledgeWebhookDelivery(r.Context(), db.AcknowledgeWebhookDeliveryParams{ID: delivery.ID,- ResponseStatus: pgtype.Int4{Int32: http.StatusAccepted, Valid: true},+ ResponseStatus: pgtype.Int4{Int32: http.StatusOK, Valid: true},ResponseBody: pgtype.Text{String: string(bodyJSON), Valid: true},}); err != nil {slog.Warn("webhook: persist acknowledgement metadata failed",@@ -559,7 +615,7 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)if h.WebhookDeliveryWorker != nil {h.WebhookDeliveryWorker.Notify()}- writeJSON(w, http.StatusAccepted, respBody)+ writeJSON(w, http.StatusOK, respBody)}// ── Event filter helpers ────────────────────────────────────────────────────diff --git a/server/internal/handler/autopilot_webhook_handler_test.go b/server/internal/handler/autopilot_webhook_handler_test.goindex d8cda5bd5a..a51f92a371 100644--- a/server/internal/handler/autopilot_webhook_handler_test.go+++ b/server/internal/handler/autopilot_webhook_handler_test.go@@ -153,7 +153,7 @@ func TestWebhookHandler_AllowsDeclaredEvent(t *testing.T) {"action": "completed","workflow_run": map[string]any{"id": 123},}, map[string]string{"X-GitHub-Event": "workflow_run"})- delivery := processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))+ delivery := processQueuedWebhookDelivery(t, requireAcceptedWebhookResponse(t, w))if delivery.Status != deliveryStatusDispatched || !delivery.AutopilotRunID.Valid {t.Fatalf("expected worker dispatch, got status=%s run=%v", delivery.Status, delivery.AutopilotRunID.Valid)}@@ -168,7 +168,7 @@ func TestWebhookHandler_EmptyFiltersAllowsAll(t *testing.T) {"action": "in_progress","workflow_run": map[string]any{"id": 123},}, map[string]string{"X-GitHub-Event": "workflow_run"})- delivery := processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))+ delivery := processQueuedWebhookDelivery(t, requireAcceptedWebhookResponse(t, w))if delivery.Status != deliveryStatusDispatched || !delivery.AutopilotRunID.Valid {t.Fatalf("expected worker dispatch, got status=%s run=%v", delivery.Status, delivery.AutopilotRunID.Valid)}@@ -400,21 +400,24 @@ func postWebhook(t *testing.T, token string, body any, headers map[string]stringreturn w}-func requireQueuedWebhookResponse(t *testing.T, w *httptest.ResponseRecorder) string {+func requireAcceptedWebhookResponse(t *testing.T, w *httptest.ResponseRecorder) string {t.Helper()- if w.Code != http.StatusAccepted {- t.Fatalf("expected 202 queued, got %d body=%s", w.Code, w.Body.String())+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200 accepted/skipped, got %d body=%s", w.Code, w.Body.String())}var resp map[string]anyif err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode queued response: %v", err)+ t.Fatalf("decode accepted response: %v", err)}- if resp["status"] != "queued" {- t.Fatalf("expected queued status, got %#v", resp)+ if resp["status"] != "accepted" && resp["status"] != "skipped" {+ t.Fatalf("expected accepted or skipped status, got %#v", resp)}deliveryID, _ := resp["delivery_id"].(string)if deliveryID == "" {- t.Fatalf("queued response missing delivery_id: %#v", resp)+ t.Fatalf("accepted response missing delivery_id: %#v", resp)+ }+ if runID, _ := resp["run_id"].(string); runID == "" {+ t.Fatalf("accepted response missing run_id: %#v", resp)}return deliveryID}@@ -601,8 +604,22 @@ func TestWebhookHandler_ActiveDispatchesRunWithPayload(t *testing.T) {"event": "demo.received","eventPayload": map[string]any{"k": "v"},}, nil)- delivery := processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))- runID := uuidToString(delivery.AutopilotRunID)+ deliveryID := requireAcceptedWebhookResponse(t, w)+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode accepted response: %v", err)+ }+ if resp["status"] != "accepted" {+ t.Fatalf("expected accepted, got %#v", resp)+ }+ runID := resp["run_id"].(string)++ // The run ID is allocated synchronously, while durable dispatch remains+ // owned by the queued delivery worker.+ delivery := processQueuedWebhookDelivery(t, deliveryID)+ if got := uuidToString(delivery.AutopilotRunID); got != runID {+ t.Fatalf("delivery run_id mismatch: got %q want %q", got, runID)+ }// Validate the persisted run carries the normalized envelope.run, err := testHandler.Queries.GetAutopilotRun(context.Background(), parseUUID(runID))@@ -639,6 +656,55 @@ func TestWebhookHandler_ActiveDispatchesRunWithPayload(t *testing.T) {}}+func TestWebhookHandler_ActiveSkippedRunReturnsLegacyContract(t *testing.T) {+ var offlineRuntimeID string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO agent_runtime (+ workspace_id, daemon_id, name, runtime_mode, provider, status,+ device_info, metadata, owner_id, last_seen_at+ ) VALUES ($1, NULL, $2, 'cloud', $3, 'offline', $4, '{}'::jsonb, $5, now())+ RETURNING id+ `, testWorkspaceID, "Webhook Offline Runtime", "webhook_test_runtime", "Webhook test runtime", testUserID).Scan(&offlineRuntimeID); err != nil {+ t.Fatalf("create offline runtime: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, offlineRuntimeID)+ })++ agentID := createWebhookTestAgent(t, "WebhookSkipped Agent")+ if _, err := testPool.Exec(context.Background(), `UPDATE agent SET runtime_id = $1 WHERE id = $2`, offlineRuntimeID, agentID); err != nil {+ t.Fatalf("bind offline agent runtime: %v", err)+ }+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ w := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "demo.skipped"}, nil)+ deliveryID := requireAcceptedWebhookResponse(t, w)+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode skipped response: %v", err)+ }+ if resp["status"] != "skipped" {+ t.Fatalf("expected skipped, got %#v", resp)+ }+ if reason, _ := resp["reason"].(string); reason == "" {+ t.Fatalf("skipped response missing reason: %#v", resp)+ }+ runID := resp["run_id"].(string)+ run, err := testHandler.Queries.GetAutopilotRun(context.Background(), parseUUID(runID))+ if err != nil {+ t.Fatalf("load skipped run: %v", err)+ }+ if run.Status != "skipped" {+ t.Fatalf("run status: got %q want skipped", run.Status)+ }++ delivery := processQueuedWebhookDelivery(t, deliveryID)+ if delivery.Status != deliveryStatusDispatched || uuidToString(delivery.AutopilotRunID) != runID {+ t.Fatalf("skipped run was not linked to delivery: status=%s run_id=%s", delivery.Status, uuidToString(delivery.AutopilotRunID))+ }+}+func TestWebhookHandler_GitHubHeaderInferredEvent(t *testing.T) {agentID := createWebhookTestAgent(t, "WebhookGH Agent")apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")@@ -650,7 +716,7 @@ func TestWebhookHandler_GitHubHeaderInferredEvent(t *testing.T) {"number": 42,},}, map[string]string{"X-GitHub-Event": "pull_request"})- delivery := processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))+ delivery := processQueuedWebhookDelivery(t, requireAcceptedWebhookResponse(t, w))runID := uuidToString(delivery.AutopilotRunID)run, err := testHandler.Queries.GetAutopilotRun(context.Background(), parseUUID(runID))if err != nil {@@ -676,9 +742,7 @@ func TestWebhookHandler_ValidBurstPersistsWithoutHTTP429(t *testing.T) {for i := 0; i < 3; i++ {w := postWebhook(t, *trig.WebhookToken, map[string]any{"i": i}, nil)- if w.Code != http.StatusAccepted {- t.Fatalf("request %d: expected durable 202, got %d body=%s", i, w.Code, w.Body.String())- }+ requireAcceptedWebhookResponse(t, w)}if got := len(listDeliveries(t, apID)); got != 3 {t.Fatalf("all valid burst deliveries must be persisted, got %d", got)@@ -711,9 +775,7 @@ func TestRotateWebhookToken_ReplacesOldToken(t *testing.T) {}// New token should accept.resNew := postWebhook(t, *rotated.WebhookToken, map[string]any{"x": 1}, nil)- if resNew.Code != http.StatusAccepted {- t.Fatalf("new token should be 202, got %d body=%s", resNew.Code, resNew.Body.String())- }+ requireAcceptedWebhookResponse(t, resNew)}// ── Additional coverage (PR #2348 review) ──────────────────────────────────@@ -827,9 +889,7 @@ func TestWebhookHandler_AbsoluteIPRateLimitRetainsEmergencyCeiling(t *testing.T)testHandler.WebhookAbsoluteIPRateLimiter = NewMemoryWebhookAbsoluteIPRateLimiter(WebhookRateLimit{Limit: 1, Window: time.Minute})t.Cleanup(func() { testHandler.WebhookAbsoluteIPRateLimiter = prev })- if first := postWebhook(t, *trig.WebhookToken, map[string]any{"n": 1}, nil); first.Code != http.StatusAccepted {- t.Fatalf("first valid request: expected 202, got %d", first.Code)- }+ requireAcceptedWebhookResponse(t, postWebhook(t, *trig.WebhookToken, map[string]any{"n": 1}, nil))second := postWebhook(t, *trig.WebhookToken, map[string]any{"n": 2}, nil)if second.Code != http.StatusTooManyRequests {t.Fatalf("absolute ceiling: expected 429, got %d body=%s", second.Code, second.Body.String())@@ -965,7 +1025,7 @@ func TestGetAutopilotRun_ReturnsFullPayload(t *testing.T) {"event": "demo.x","eventPayload": map[string]any{"answer": 42},}, nil)- delivery := processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, post))+ delivery := processQueuedWebhookDelivery(t, requireAcceptedWebhookResponse(t, post))runID := uuidToString(delivery.AutopilotRunID)// LIST: trigger_payload should be omitted (slim response).diff --git a/server/internal/handler/webhook_delivery_test.go b/server/internal/handler/webhook_delivery_test.goindex 17b348fcbc..4afc6ccf50 100644--- a/server/internal/handler/webhook_delivery_test.go+++ b/server/internal/handler/webhook_delivery_test.go@@ -62,7 +62,7 @@ func installWebhookAcknowledgementFailure(t *testing.T) {if _, err := testPool.Exec(ctx, fmt.Sprintf(`CREATE FUNCTION %s() RETURNS trigger LANGUAGE plpgsql AS $$BEGIN- IF NEW.event = 'test.ack_failure' AND NEW.response_status = 202 THEN+ IF NEW.event = 'test.ack_failure' AND NEW.response_status = 200 THENRAISE EXCEPTION 'forced webhook acknowledgement metadata failure';END IF;RETURN NEW;@@ -107,7 +107,7 @@ func TestWebhookHandler_PersistsDeliveryOnAccept(t *testing.T) {trig := createWebhookTriggerViaHandler(t, apID)w := postWebhook(t, *trig.WebhookToken, map[string]any{"hello": "world"}, nil)- processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))+ processQueuedWebhookDelivery(t, requireAcceptedWebhookResponse(t, w))deliveries := listDeliveries(t, apID)if len(deliveries) != 1 {@@ -120,8 +120,8 @@ func TestWebhookHandler_PersistsDeliveryOnAccept(t *testing.T) {if d["autopilot_run_id"] == nil {t.Fatal("delivery should link to run")}- if got := int(d["response_status"].(float64)); got != http.StatusAccepted {- t.Fatalf("terminal delivery must retain ingress 202 acknowledgement, got %d", got)+ if got := int(d["response_status"].(float64)); got != http.StatusOK {+ t.Fatalf("terminal delivery must retain ingress 200 acknowledgement, got %d", got)}if got := int(d["dispatch_attempts"].(float64)); got != 1 {t.Fatalf("expected one worker dispatch attempt, got %d", got)@@ -131,7 +131,7 @@ func TestWebhookHandler_PersistsDeliveryOnAccept(t *testing.T) {}}-func TestWebhookHandler_AcknowledgementMetadataFailureStillReturns202(t *testing.T) {+func TestWebhookHandler_AcknowledgementMetadataFailureStillReturns200(t *testing.T) {agentID := createWebhookTestAgent(t, "AckMetadataFailure Agent")apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")trig := createWebhookTriggerViaHandler(t, apID)@@ -140,7 +140,7 @@ func TestWebhookHandler_AcknowledgementMetadataFailureStillReturns202(t *testingw := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "test.ack_failure"}, map[string]string{"Idempotency-Key": "ack-metadata-failure",})- deliveryID := requireQueuedWebhookResponse(t, w)+ deliveryID := requireAcceptedWebhookResponse(t, w)delivery, err := testHandler.Queries.GetWebhookDelivery(context.Background(), parseUUID(deliveryID))if err != nil {t.Fatalf("load durably queued delivery: %v", err)@@ -164,11 +164,18 @@ func TestWebhookHandler_DedupeViaIdempotencyKey(t *testing.T) {headers := map[string]string{"Idempotency-Key": "demo-key-1"}w1 := postWebhook(t, *trig.WebhookToken, body, headers)- firstDeliveryID := requireQueuedWebhookResponse(t, w1)- firstDelivery := processQueuedWebhookDelivery(t, firstDeliveryID)- firstRunID := uuidToString(firstDelivery.AutopilotRunID)+ firstDeliveryID := requireAcceptedWebhookResponse(t, w1)+ var r1 map[string]any+ if err := json.Unmarshal(w1.Body.Bytes(), &r1); err != nil {+ t.Fatalf("decode first response: %v", err)+ }+ firstRunID, ok := r1["run_id"].(string)+ if !ok || firstRunID == "" {+ t.Fatalf("first response missing run_id: %s", w1.Body.String())+ }- // Second identical delivery should be a duplicate.+ // Retry before the worker processes the queued delivery. The admitted run+ // must already be discoverable so the duplicate returns the same run_id.w2 := postWebhook(t, *trig.WebhookToken, body, headers)if w2.Code != http.StatusOK {t.Fatalf("second: %d body=%s", w2.Code, w2.Body.String())@@ -184,6 +191,10 @@ func TestWebhookHandler_DedupeViaIdempotencyKey(t *testing.T) {if r2["run_id"] != firstRunID {t.Fatalf("duplicate run_id mismatch: %v != %v", r2["run_id"], firstRunID)}+ firstDelivery := processQueuedWebhookDelivery(t, firstDeliveryID)+ if got := uuidToString(firstDelivery.AutopilotRunID); got != firstRunID {+ t.Fatalf("processed delivery run_id mismatch: %v != %v", got, firstRunID)+ }// Only one delivery should exist; attempt_count must be 2.deliveries := listDeliveries(t, apID)@@ -208,7 +219,7 @@ func TestWebhookHandler_DedupeViaGitHubDelivery(t *testing.T) {}w1 := postWebhook(t, *trig.WebhookToken, body, headers)- processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w1))+ processQueuedWebhookDelivery(t, requireAcceptedWebhookResponse(t, w1))w2 := postWebhook(t, *trig.WebhookToken, body, headers)var r2 map[string]any@@ -296,7 +307,7 @@ func TestWebhookHandler_ValidSignatureDispatches(t *testing.T) {w := postWebhook(t, *trig.WebhookToken, bodyBytes, map[string]string{"X-Hub-Signature-256": sig,})- processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))+ processQueuedWebhookDelivery(t, requireAcceptedWebhookResponse(t, w))deliveries := listDeliveries(t, apID)if len(deliveries) != 1 {t.Fatalf("expected 1 delivery, got %d", len(deliveries))@@ -365,9 +376,7 @@ func TestSigningSecret_EmptyClearsSecret(t *testing.T) {}// Unsigned request should now go through (back to not_required).post := postWebhook(t, *trig.WebhookToken, map[string]any{"x": 1}, nil)- if post.Code != http.StatusAccepted {- t.Fatalf("post after clear: %d body=%s", post.Code, post.Body.String())- }+ requireAcceptedWebhookResponse(t, post)}func TestReplay_CreatesNewDeliveryAndDispatchesRun(t *testing.T) {@@ -379,7 +388,7 @@ func TestReplay_CreatesNewDeliveryAndDispatchesRun(t *testing.T) {w := postWebhook(t, *trig.WebhookToken, map[string]any{"hello": "world"}, map[string]string{"Idempotency-Key": "replay-original",})- originalID := requireQueuedWebhookResponse(t, w)+ originalID := requireAcceptedWebhookResponse(t, w)originalDelivery := processQueuedWebhookDelivery(t, originalID)originalRunID := uuidToString(originalDelivery.AutopilotRunID)@@ -445,7 +454,7 @@ func TestGetDelivery_ReturnsFullPayload(t *testing.T) {trig := createWebhookTriggerViaHandler(t, apID)w := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "demo", "eventPayload": map[string]any{"answer": 42}}, nil)- deliveryID := requireQueuedWebhookResponse(t, w)+ deliveryID := requireAcceptedWebhookResponse(t, w)// List response should NOT include raw_body / selected_headers.wList := httptest.NewRecorder()@@ -567,7 +576,7 @@ func TestWebhookHandler_RunOnlyDedupeOnGitHubDelivery(t *testing.T) {first := postWebhook(t, *trig.WebhookToken, body, headers)postWebhook(t, *trig.WebhookToken, body, headers)postWebhook(t, *trig.WebhookToken, body, headers)- processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, first))+ processQueuedWebhookDelivery(t, requireAcceptedWebhookResponse(t, first))// Count autopilot_run rows linked to this trigger.rows, err := testHandler.Queries.ListAutopilotRuns(context.Background(), db.ListAutopilotRunsParams{@@ -605,10 +614,10 @@ func TestWebhookDeliveryWorker_PerTriggerLimitDefersWithoutDropping(t *testing.TtestHandler.WebhookRateLimiter = NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 1, Window: time.Minute})t.Cleanup(func() { testHandler.WebhookRateLimiter = prev })- firstID := requireQueuedWebhookResponse(t, postWebhook(t, *trig.WebhookToken, map[string]any{"n": 1}, map[string]string{+ firstID := requireAcceptedWebhookResponse(t, postWebhook(t, *trig.WebhookToken, map[string]any{"n": 1}, map[string]string{"Idempotency-Key": "worker-pacing-1",}))- secondID := requireQueuedWebhookResponse(t, postWebhook(t, *trig.WebhookToken, map[string]any{"n": 2}, map[string]string{+ secondID := requireAcceptedWebhookResponse(t, postWebhook(t, *trig.WebhookToken, map[string]any{"n": 2}, map[string]string{"Idempotency-Key": "worker-pacing-2",}))@@ -648,14 +657,40 @@ func TestWebhookDeliveryWorker_PerTriggerLimitDefersWithoutDropping(t *testing.Tt.Fatalf("paced delivery was not released with a future availability: %#v", deferred)}- var runCount int+ var runCount, dispatchedRunCount intif err := testPool.QueryRow(context.Background(), `- SELECT count(*) FROM autopilot_run WHERE webhook_delivery_id IN ($1, $2)- `, firstID, secondID).Scan(&runCount); err != nil {+ SELECT count(*), count(task_id)+ FROM autopilot_run+ WHERE webhook_delivery_id IN ($1, $2)+ `, firstID, secondID).Scan(&runCount, &dispatchedRunCount); err != nil {t.Fatalf("count paced runs: %v", err)}- if runCount != 1 {- t.Fatalf("pacing should dispatch one run and retain one delivery, got %d runs", runCount)+ if runCount != 2 || dispatchedRunCount != 1 {+ t.Fatalf("pacing should admit both runs but dispatch only one: runs=%d dispatched=%d", runCount, dispatchedRunCount)+ }+}++func TestWebhookDeliveryWorker_DispatchesRunAdmittedBeforePause(t *testing.T) {+ agentID := createWebhookTestAgent(t, "WorkerAdmittedBeforePause Agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ trig := createWebhookTriggerViaHandler(t, apID)++ post := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "accepted.before_pause"}, nil)+ deliveryID := requireAcceptedWebhookResponse(t, post)+ if _, err := testPool.Exec(context.Background(), `UPDATE autopilot SET status = 'paused' WHERE id = $1`, apID); err != nil {+ t.Fatalf("pause admitted autopilot: %v", err)+ }++ delivery := processQueuedWebhookDelivery(t, deliveryID)+ if delivery.Status != deliveryStatusDispatched || !delivery.AutopilotRunID.Valid {+ t.Fatalf("accepted delivery was stranded after pause: status=%s run=%v", delivery.Status, delivery.AutopilotRunID.Valid)+ }+ run, err := testHandler.Queries.GetAutopilotRun(context.Background(), delivery.AutopilotRunID)+ if err != nil {+ t.Fatalf("load admitted run: %v", err)+ }+ if !run.TaskID.Valid {+ t.Fatalf("accepted run was not dispatched after pause: %#v", run)}}@@ -667,7 +702,7 @@ func TestWebhookDeliveryWorker_RecoversExpiredLeaseAndReusesRun(t *testing.T) {post := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "recovery"}, map[string]string{"Idempotency-Key": "worker-recovery",})- deliveryID := requireQueuedWebhookResponse(t, post)+ deliveryID := requireAcceptedWebhookResponse(t, post)if _, err := testPool.Exec(context.Background(), `UPDATE webhook_deliverySET lease_token = gen_random_uuid(), lease_expires_at = now() - interval '1 second'@@ -722,7 +757,7 @@ func TestWebhookDeliveryWorker_LeaseOwnershipChangeIsBenign(t *testing.T) {post := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "lease-change"}, map[string]string{"Idempotency-Key": "worker-lease-change",})- deliveryID := requireQueuedWebhookResponse(t, post)+ deliveryID := requireAcceptedWebhookResponse(t, post)if _, err := testPool.Exec(context.Background(), `UPDATE webhook_deliverySET lease_token = gen_random_uuid(), lease_expires_at = now() + interval '2 minutes'@@ -774,7 +809,7 @@ func TestWebhookDeliveryWorker_RepairsCreateIssueTaskCrashWindow(t *testing.T) {post := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "issue-recovery"}, map[string]string{"Idempotency-Key": "worker-issue-recovery",})- deliveryID := requireQueuedWebhookResponse(t, post)+ deliveryID := requireAcceptedWebhookResponse(t, post)first := processQueuedWebhookDelivery(t, deliveryID)run, err := testHandler.Queries.GetAutopilotRun(context.Background(), first.AutopilotRunID)if err != nil || !run.IssueID.Valid {diff --git a/server/internal/handler/webhook_delivery_worker.go b/server/internal/handler/webhook_delivery_worker.goindex fec12852b3..f859846336 100644--- a/server/internal/handler/webhook_delivery_worker.go+++ b/server/internal/handler/webhook_delivery_worker.go@@ -165,15 +165,26 @@ func (w *WebhookDeliveryWorker) ProcessNext(ctx context.Context) (bool, error) {return true, w.retryOrFail(ctx, delivery, fmt.Errorf("encode envelope: %w", err))}- switch {- case !trigger.Enabled:- return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "trigger_disabled")- case autopilot.Status == "archived":- return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "autopilot_archived")- case autopilot.Status != "active":- return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "autopilot_paused")- case !webhookEventAllowedByTriggerScope(trigger.EventFilters, envelope):- return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "event_filtered")+ // Once ingress has synchronously admitted a run and returned accepted or+ // skipped, that decision is durable. Re-check mutable trigger/autopilot+ // state only for deliveries recovered from the pre-admission crash window;+ // otherwise a pause immediately after the response could strand the run.+ _, admissionErr := w.h.Queries.GetAutopilotRunByWebhookDelivery(ctx, delivery.ID)+ hasAdmittedRun := admissionErr == nil+ if admissionErr != nil && !errors.Is(admissionErr, pgx.ErrNoRows) {+ return true, w.retryOrFail(ctx, delivery, fmt.Errorf("load admitted run: %w", admissionErr))+ }+ if !hasAdmittedRun {+ switch {+ case !trigger.Enabled:+ return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "trigger_disabled")+ case autopilot.Status == "archived":+ return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "autopilot_archived")+ case autopilot.Status != "active":+ return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "autopilot_paused")+ case !webhookEventAllowedByTriggerScope(trigger.EventFilters, envelope):+ return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "event_filtered")+ }}run, dispatchErr := w.h.AutopilotService.DispatchAutopilotForWebhookDelivery(diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 357129bf95..3d6049bb4d 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -11,6 +11,7 @@ import ("time""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/events"@@ -74,11 +75,12 @@ func (s *AutopilotService) DispatchAutopilot(return s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, pgtype.Timestamptz{}, pgtype.UUID{})}-// DispatchAutopilotForWebhookDelivery is the durable webhook worker entry-// point. webhook_delivery_id is persisted on the run and protected by a-// partial unique index, so reclaiming a queued delivery after a process crash-// reuses the original run instead of creating a second issue or task.-func (s *AutopilotService) DispatchAutopilotForWebhookDelivery(+// AdmitAutopilotWebhookDelivery creates or reuses the idempotent run for a+// durable webhook delivery without executing its downstream issue/task side+// effect. The HTTP ingress calls this synchronously so the public webhook+// response can retain its 200 accepted/skipped + run_id contract while the+// database-backed worker still owns recoverable dispatch.+func (s *AutopilotService) AdmitAutopilotWebhookDelivery(ctx context.Context,autopilot db.Autopilot,triggerID pgtype.UUID,@@ -86,45 +88,129 @@ func (s *AutopilotService) DispatchAutopilotForWebhookDelivery(deliveryID pgtype.UUID,) (*db.AutopilotRun, error) {if !deliveryID.Valid {- return nil, fmt.Errorf("dispatch for webhook delivery: delivery_id is required")+ return nil, fmt.Errorf("admit webhook delivery: delivery_id is required")}existing, err := s.Queries.GetAutopilotRunByWebhookDelivery(ctx, deliveryID)switch {- case err == nil && isAutopilotRunComplete(existing):- if autopilot.ExecutionMode == "create_issue" && existing.IssueID.Valid {- if repairErr := s.ensureWebhookCreateIssueTask(ctx, autopilot, existing); repairErr != nil {- return &existing, repairErr- }+ case err == nil:+ return &existing, nil+ case !errors.Is(err, pgx.ErrNoRows):+ return nil, fmt.Errorf("admit webhook delivery: lookup existing run: %w", err)+ }++ if reason, skip := s.shouldSkipDispatch(ctx, autopilot); skip {+ run, err := s.recordSkippedRun(+ ctx,+ autopilot,+ triggerID,+ "webhook",+ payload,+ pgtype.Timestamptz{},+ deliveryID,+ reason,+ )+ if err != nil {+ return s.recoverConcurrentWebhookAdmission(+ ctx,+ deliveryID,+ fmt.Errorf("admit webhook delivery: create skipped run: %w", err),+ )}+ return run, nil+ }++ initialStatus := "issue_created"+ if autopilot.ExecutionMode == "run_only" {+ initialStatus = "running"+ }+ run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{+ AutopilotID: autopilot.ID,+ TriggerID: triggerID,+ Source: "webhook",+ Status: initialStatus,+ TriggerPayload: payload,+ SquadID: autopilotSquadAttribution(autopilot),+ WebhookDeliveryID: deliveryID,+ })+ if err != nil {+ return s.recoverConcurrentWebhookAdmission(+ ctx,+ deliveryID,+ fmt.Errorf("admit webhook delivery: create run: %w", err),+ )+ }+ s.captureAutopilotRunStarted(autopilot, run, "webhook")+ return &run, nil+}++func (s *AutopilotService) recoverConcurrentWebhookAdmission(+ ctx context.Context,+ deliveryID pgtype.UUID,+ cause error,+) (*db.AutopilotRun, error) {+ // Another server replica may have claimed the durable delivery after+ // ingress persisted it but before the admission lookup. The unique+ // delivery/run index chooses one winner; the loser reuses that run.+ var pgErr *pgconn.PgError+ if !errors.As(cause, &pgErr) || pgErr.Code != "23505" {+ return nil, cause+ }+ existing, err := s.Queries.GetAutopilotRunByWebhookDelivery(ctx, deliveryID)+ if err == nil {return &existing, nil- case err == nil:- // A run_only task may have committed immediately before the process- // died while linking task_id back to the run. Repair that linkage and- // wake the daemon; otherwise continue the same partial run below.- if autopilot.ExecutionMode == "run_only" && !existing.TaskID.Valid {- task, taskErr := s.Queries.GetAutopilotTaskByRun(ctx, existing.ID)- switch {- case taskErr == nil:- updated, updateErr := s.Queries.UpdateAutopilotRunRunning(ctx, db.UpdateAutopilotRunRunningParams{- ID: existing.ID,- TaskID: task.ID,- })- if updateErr != nil {- return &existing, fmt.Errorf("dispatch for webhook delivery: repair task linkage: %w", updateErr)- }- s.TaskSvc.NotifyTaskEnqueued(ctx, task)- return &updated, nil- case !errors.Is(taskErr, pgx.ErrNoRows):- return &existing, fmt.Errorf("dispatch for webhook delivery: lookup linked task: %w", taskErr)+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return nil, fmt.Errorf("admit webhook delivery: reload concurrent run: %w", err)+ }+ return nil, cause+}++// DispatchAutopilotForWebhookDelivery is the durable webhook worker entry+// point. webhook_delivery_id is persisted on the run and protected by a+// partial unique index, so reclaiming a queued delivery after a process crash+// reuses the original run instead of creating a second issue or task.+func (s *AutopilotService) DispatchAutopilotForWebhookDelivery(+ ctx context.Context,+ autopilot db.Autopilot,+ triggerID pgtype.UUID,+ payload []byte,+ deliveryID pgtype.UUID,+) (*db.AutopilotRun, error) {+ run, err := s.AdmitAutopilotWebhookDelivery(ctx, autopilot, triggerID, payload, deliveryID)+ if err != nil {+ return nil, err+ }+ if isAutopilotRunComplete(*run) {+ if autopilot.ExecutionMode == "create_issue" && run.IssueID.Valid {+ if repairErr := s.ensureWebhookCreateIssueTask(ctx, autopilot, *run); repairErr != nil {+ return run, repairErr}}- return s.dispatchAutopilotRun(ctx, autopilot, triggerID, "webhook", &existing)- case !errors.Is(err, pgx.ErrNoRows):- return nil, fmt.Errorf("dispatch for webhook delivery: lookup existing run: %w", err)+ return run, nil}- return s.dispatchAutopilot(ctx, autopilot, triggerID, "webhook", payload, pgtype.Timestamptz{}, deliveryID)+ // A run_only task may have committed immediately before the process died+ // while linking task_id back to the run. Repair that linkage and wake the+ // daemon; otherwise continue the same partial run below.+ if autopilot.ExecutionMode == "run_only" && !run.TaskID.Valid {+ task, taskErr := s.Queries.GetAutopilotTaskByRun(ctx, run.ID)+ switch {+ case taskErr == nil:+ updated, updateErr := s.Queries.UpdateAutopilotRunRunning(ctx, db.UpdateAutopilotRunRunningParams{+ ID: run.ID,+ TaskID: task.ID,+ })+ if updateErr != nil {+ return run, fmt.Errorf("dispatch for webhook delivery: repair task linkage: %w", updateErr)+ }+ s.TaskSvc.NotifyTaskEnqueued(ctx, task)+ return &updated, nil+ case !errors.Is(taskErr, pgx.ErrNoRows):+ return run, fmt.Errorf("dispatch for webhook delivery: lookup linked task: %w", taskErr)+ }+ }+ return s.dispatchAutopilotRun(ctx, autopilot, triggerID, "webhook", run)}// ensureWebhookCreateIssueTask repairs the create_issue crash window after thediff --git a/server/internal/service/builtin_skills/multica-autopilots/SKILL.md b/server/internal/service/builtin_skills/multica-autopilots/SKILL.mdindex aae5b89080..428c3180af 100644--- a/server/internal/service/builtin_skills/multica-autopilots/SKILL.md+++ b/server/internal/service/builtin_skills/multica-autopilots/SKILL.md@@ -23,7 +23,7 @@ Do not run `trigger`, `delete`, `trigger-delete`, or `trigger-rotate-url` to tesAn autopilot is not an agent. It is a rule that dispatches work to an agent, or to a squad's leader agent.-The chain is: trigger fires (`schedule`, `webhook`, or `manual`) -> `autopilot_run` row -> `execution_mode` decides output -> assignee readiness check -> issue/task execution -> run status sync. Webhooks have a durable admission step in front: HTTP ingress stores a queued `webhook_delivery` and returns `202`; a database-leased worker creates or reuses the delivery's idempotent run.+The chain is: trigger fires (`schedule`, `webhook`, or `manual`) -> `autopilot_run` row -> `execution_mode` decides output -> assignee readiness check -> issue/task execution -> run status sync. Webhooks have a durable admission step in front: HTTP ingress stores a queued `webhook_delivery`, synchronously creates or reuses its idempotent run, and returns `200` with `status=accepted|skipped` plus `run_id`; a database-leased worker then resumes accepted runs and owns recoverable issue/task dispatch.Execution modes:diff --git a/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md b/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.mdindex 434dd611af..e33fa08d09 100644--- a/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md+++ b/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md@@ -2,11 +2,12 @@- `server/cmd/multica/cmd_autopilot.go` registers `list`, `get`, `create`, `update`, `delete`, `trigger`, `runs`, `trigger-add`, `trigger-update`, `trigger-delete`, and `trigger-rotate-url`.- The CLI maps reads/writes to `/api/autopilots`, `/api/autopilots/{id}`, `/api/autopilots/{id}/trigger`, `/api/autopilots/{id}/runs`, and trigger subroutes.-- `server/internal/service/autopilot.go` has `DispatchAutopilot` plus the delivery-idempotent `DispatchAutopilotForWebhookDelivery`, creates `autopilot_run`, and switches on `execution_mode`.+- `server/internal/service/autopilot.go` has `DispatchAutopilot`, synchronous delivery-idempotent `AdmitAutopilotWebhookDelivery`, and worker-side `DispatchAutopilotForWebhookDelivery`; it creates `autopilot_run` and switches on `execution_mode`.- `create_issue` calls `dispatchCreateIssue`; `run_only` calls `dispatchRunOnly`.- `resolveAutopilotLeader` resolves squad-assigned autopilots to the squad leader.- `AgentReadiness` blocks archived/runtime-unready agents before enqueue.- `server/cmd/server/router.go` exposes authenticated `/api/autopilots` routes and unauthenticated webhook ingress `/api/webhooks/autopilots/{token}`.-- `server/internal/handler/webhook_delivery_worker.go` claims queued deliveries with expiring database leases, applies per-trigger dispatch pacing, and resumes them using `autopilot_run.webhook_delivery_id` so recovery cannot duplicate a run/task.+- `server/internal/handler/autopilot_webhook.go` durably stores public webhook deliveries, synchronously admits an idempotent run for the compatible `200 accepted|skipped` + `run_id` response, and wakes the worker.+- `server/internal/handler/webhook_delivery_worker.go` claims queued deliveries with expiring database leases, applies per-trigger dispatch pacing, and resumes admitted runs using `autopilot_run.webhook_delivery_id` so recovery cannot duplicate a run/task.- Write/execute authorization lives in `autopilotWriteByOwnership` / `memberCanWriteAutopilot` / `requireAutopilotWrite` (`server/internal/handler/autopilot.go`): editing, deleting, triggering, replaying deliveries, and managing triggers/webhook secrets require the autopilot's creator, a workspace owner/admin, or an explicit collaborator. Reads (list/get/runs/deliveries) stay open to any workspace member, but `GetAutopilot` redacts `webhook_token`/`webhook_path`/`webhook_url` for callers who lack write access, since the token alone can trigger the autopilot. Creating a new autopilot is still open to any member (they become its creator). This is the autopilot-level View/Write layer; it is independent of, and ANDed with, the private-assignee-agent gate enforced at dispatch time in `shouldSkipDispatch`.- Explicit write grants ("collaborators") are stored in the `autopilot_collaborator` table (migration 128, members-only, no FK — deleted alongside the autopilot in the delete transaction). Endpoints: `POST /api/autopilots/{id}/collaborators` (body `{user_id}`) and `DELETE /api/autopilots/{id}/collaborators/{userId}`, both gated by the NARROWER `requireAutopilotAccessManagement` (creator or workspace owner/admin only — a granted collaborator keeps write/execute but cannot re-grant or revoke peers, preventing privilege escalation), both returning the updated `{collaborators}` list. `GetAutopilot` embeds the `collaborators` array and stamps two per-caller booleans: `can_write` (gates edit/run/trigger controls) and the narrower `can_manage_access` (gates the "Manage access" entry). The web/desktop "Manage access" UI lives in `packages/views/autopilots/components/manage-access-dialog.tsx`.diff --git a/server/pkg/db/generated/webhook_delivery.sql.go b/server/pkg/db/generated/webhook_delivery.sql.goindex bf17096d05..94148209a2 100644--- a/server/pkg/db/generated/webhook_delivery.sql.go+++ b/server/pkg/db/generated/webhook_delivery.sql.go@@ -26,9 +26,9 @@ type AcknowledgeWebhookDeliveryParams struct {ResponseBody pgtype.Text `json:"response_body"`}-// Best-effort operator metadata for the HTTP acknowledgement. Admission is-// already durable once the initial queued row exists, so callers still return-// 202 if this metadata-only update fails.+// Best-effort operator metadata for the HTTP acknowledgement. The delivery and+// run are already durable, so callers still return their response if this+// metadata-only update fails.func (q *Queries) AcknowledgeWebhookDelivery(ctx context.Context, arg AcknowledgeWebhookDeliveryParams) (WebhookDelivery, error) {row := q.db.QueryRow(ctx, acknowledgeWebhookDelivery, arg.ID, arg.ResponseStatus, arg.ResponseBody)var i WebhookDeliverydiff --git a/server/pkg/db/queries/webhook_delivery.sql b/server/pkg/db/queries/webhook_delivery.sqlindex 1de65216a1..6f3795ba2c 100644--- a/server/pkg/db/queries/webhook_delivery.sql+++ b/server/pkg/db/queries/webhook_delivery.sql@@ -52,9 +52,9 @@ WHERE id = $1RETURNING *;-- name: AcknowledgeWebhookDelivery :one--- Best-effort operator metadata for the HTTP acknowledgement. Admission is--- already durable once the initial queued row exists, so callers still return--- 202 if this metadata-only update fails.+-- Best-effort operator metadata for the HTTP acknowledgement. The delivery and+-- run are already durable, so callers still return their response if this+-- metadata-only update fails.UPDATE webhook_deliverySET response_status = $2,response_body = $3,