An open-source, faster Devin alternative
TypeScript
fix(webhooks): address review — P0 inline-on-remote, races, idempotency, taxonomy
Igor Zalutski84d7ef0a893e
diff --git a/.agents/work/sandbox-lifecycle-webhooks.md b/.agents/work/sandbox-lifecycle-webhooks.mdindex 94de71e2..e09aa1e1 100644--- a/.agents/work/sandbox-lifecycle-webhooks.md+++ b/.agents/work/sandbox-lifecycle-webhooks.md@@ -47,6 +47,18 @@ polish (per-type payload normalization at the ingress, LISTEN/NOTIFY latency) trworker via a stream ingress), and **one materializer** creates delivery rows from it — noper-origin delivery logic to drift. Dedupe happens once (`sandbox_lifecycle_events.id`); thewatermark unifies to a DB-assigned `seq` (drops the Redis-stream-id scheme).+- **Rev 7 — post-build review fixes (2026-06-24).** (P0) inline webhooks now register on the+ **remote** create path too (`createSandboxRemote`, before the gRPC call using the pre-generated+ id → reliably catches `created`; cleaned up on create failure). (P1) `RecordDeliveryResult` now+ guards `WHERE status='delivering' AND locked_by=$me` so a stale sender can't revive a+ canceled/redelivered row; `Idempotency-Key` is now a transactional **reserve → create →+ finalize/release** (no double-create, secret never silently lost). (P1) producers reconciled with+ the taxonomy: `resumed` wired (worker `woke`→ingress), dead `running`→ready map removed, docs mark+ unshipped types **Coming soon**. (P2) `ReconcileWorkerSessions` records canonical events in-tx+ (crash-recovery stop/hibernate now fire webhooks); delivery **history survives soft-delete**+ (list tolerates deleted dests); `eventTypes` validated against the taxonomy + `prefix.*` and+ `sandboxId` validated to belong to the org. (P3) destinations list returns canonical+ `{ data: [...] }`.## Goal@@ -203,7 +215,7 @@ double-delivery and no per-origin logic. Names are crisp (P2-g): `created` = res| `sandbox.created` | worker | ✅ (`"created"`) | worker create → `redis_event_publisher.go` | resource accepted; memory/cpu/template. **Verified delivered e2e (dev VM, 2026-06-24).** || `sandbox.ready` | worker | ❌ **gap (P3)** | worker post-boot health (net-new) | **Corrected 2026-06-24:** the worker does NOT emit a post-boot event today — `CreateSandboxSession` inserts status `running` directly and the only worker stream event is `created`. A distinct "VM usable" signal needs a net-new worker emit (P3). Do NOT fake it at create (it would duplicate `created`). || `sandbox.hibernated` | CP | ✅ (`"hibernated"`) | `api/sandbox.go:hibernateSandbox` (DB status write) + `OnSandboxHibernate` | durable capture (P2-b) |-| `sandbox.resumed` | CP | ✅ (`"woke"`) | `api/sandbox.go:wakeSandbox` (DB status write) + `OnSandboxWake` | renamed from `woke`; durable capture (P2-b) |+| `sandbox.resumed` | worker | ✅ (`"woke"`) | worker `grpc_server.go:WakeSandbox` emits `"woke"` → ingress maps `"woke"`→`sandbox.resumed` | **Corrected (review):** the worker emits `woke` on the stream (not a CP DB write), so this is worker-origin via the ingress, not CP in-tx. || `sandbox.migrated` | worker | ✅ (`"migrated"`) | worker migrate | || `sandbox.stopped` | CP | ✅ (`"stopped"`) | `db/store.go:UpdateSandboxSessionStatus` (record in-tx) | `data.reason` incl. `user_requested`, `expired`, `crash` (P2-g/O6: no separate `crashed` type). **Verified delivered e2e (dev VM, 2026-06-24).** || `sandbox.checkpoint.created` | CP | ❌ **gap** | `api/sandbox.go:createCheckpoint` | net-new emit |diff --git a/docs/sandboxes/webhooks.mdx b/docs/sandboxes/webhooks.mdxindex e9b4fbb4..a6746cd2 100644--- a/docs/sandboxes/webhooks.mdx+++ b/docs/sandboxes/webhooks.mdx@@ -30,20 +30,20 @@ The envelope is camelCase, with top-level routing fields, your sandbox [`metadat## Events-Subscribe to all events, or filter with `eventTypes` (exact like `sandbox.stopped`, or a prefix like `sandbox.*`).--| Event | When | `event.data` |-| --- | --- | --- |-| `sandbox.created` | the sandbox resource is accepted | `template`, `cpuCount`, `memoryMB` |-| `sandbox.ready` | the VM has booted and can run commands | — |-| `sandbox.hibernated` | the sandbox was paused (disk persisted) | — |-| `sandbox.resumed` | a hibernated sandbox woke | — |-| `sandbox.stopped` | the sandbox stopped | `reason`: `user_requested` \| `expired` \| `crash` |-| `sandbox.migrated` | the sandbox moved to new infrastructure | — |-| `sandbox.checkpoint.created` | a checkpoint was taken | `checkpointId` |-| `sandbox.forked` | a sandbox was forked from a checkpoint | `parentId` |-| `sandbox.scaled` | the sandbox's resources changed | `cpuCount`, `memoryMB` |-| `sandbox.preview_url.changed` | a preview-URL port mapping changed | `port`, `url` |+Subscribe to all events, or filter with `eventTypes` (exact like `sandbox.stopped`, or a prefix like `sandbox.*`). You can subscribe to a **Coming soon** type now; it simply won't deliver until that event ships.++| Event | When | `event.data` | Status |+| --- | --- | --- | --- |+| `sandbox.created` | the sandbox resource is accepted | `template`, `cpuCount`, `memoryMB` | Live |+| `sandbox.stopped` | the sandbox stopped | `reason`: `user_requested` \| `expired` \| `crash` | Live |+| `sandbox.hibernated` | the sandbox was paused (disk persisted) | — | Live |+| `sandbox.resumed` | a hibernated sandbox woke | — | Live |+| `sandbox.migrated` | the sandbox moved to new infrastructure | — | Live |+| `sandbox.ready` | the VM has booted and can run commands | — | Coming soon |+| `sandbox.checkpoint.created` | a checkpoint was taken | `checkpointId` | Coming soon |+| `sandbox.forked` | a sandbox was forked from a checkpoint | `parentId` | Coming soon |+| `sandbox.scaled` | the sandbox's resources changed | `cpuCount`, `memoryMB` | Coming soon |+| `sandbox.preview_url.changed` | a preview-URL port mapping changed | `port`, `url` | Coming soon |## Destinationsdiff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 657e2ae7..037db525 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -645,6 +645,15 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty}}+ // Register inline webhooks BEFORE the worker boots, pinned to the+ // pre-generated sandbox id — so they reliably catch sandbox.created (the+ // worker can't emit it before the destination exists). Cleaned up below if+ // the gRPC create fails.+ var inlineWebhooks []types.SandboxWebhookResult+ if s.store != nil && hasOrg && len(cfg.Webhooks) > 0 {+ inlineWebhooks = s.registerInlineWebhooks(ctx, orgID, sandboxID, cfg.Webhooks)+ }+grpcResp, err := grpcClient.CreateSandbox(grpcCtx, &pb.CreateSandboxRequest{SandboxId: sandboxID,Template: cfg.Template,@@ -664,6 +673,10 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tyif s.store != nil {errMsg := err.Error()_ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "failed", &errMsg)+ // Clean up inline webhooks registered for a sandbox that never started.+ for _, w := range inlineWebhooks {+ _ = s.store.SoftDeleteWebhookDestination(ctx, orgID, w.ID)+ }}return c.JSON(http.StatusInternalServerError, map[string]string{"error": "worker create failed: " + err.Error(),@@ -753,6 +766,9 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tyif previewAuthPlaintext != "" {resp["previewAuthToken"] = previewAuthPlaintext}+ if len(inlineWebhooks) > 0 {+ resp["webhooks"] = inlineWebhooks+ }return c.JSON(http.StatusCreated, resp)}diff --git a/internal/api/webhooks.go b/internal/api/webhooks.goindex a12f6203..b3e62bbe 100644--- a/internal/api/webhooks.go+++ b/internal/api/webhooks.go@@ -185,16 +185,41 @@ func (s *Server) createWebhook(c echo.Context) error {if err := webhook.ValidateURL(ctx, req.URL); err != nil {return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid webhook url: " + err.Error()})}+ if bad := firstInvalidEventType(req.EventTypes); bad != "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "unknown event type: " + bad})+ }+ if req.SandboxID != nil {+ owned, err := store.SandboxBelongsToOrg(ctx, orgID, *req.SandboxID)+ if err != nil {+ return webhookStoreError(c, err)+ }+ if !owned {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandboxId not found for this org"})+ }+ }idemKey := c.Request().Header.Get("Idempotency-Key")- reqHash := webhookRequestHash(req)+ claimed := falseif idemKey != "" {- stored, found, err := store.GetWebhookIdempotentResponse(ctx, orgID, idemKey, reqHash)+ outcome, stored, err := store.ReserveIdempotencyKey(ctx, orgID, idemKey, webhookRequestHash(req))if err != nil {return webhookStoreError(c, err)}- if found {+ switch outcome {+ case db.WebhookIdemReplay:return c.JSONBlob(http.StatusCreated, stored)+ case db.WebhookIdemConflict:+ return c.JSON(http.StatusConflict, map[string]string{"error": "Idempotency-Key reused with a different request"})+ case db.WebhookIdemInProgress:+ return c.JSON(http.StatusConflict, map[string]string{"error": "a request with this Idempotency-Key is already in progress"})+ case db.WebhookIdemClaimed:+ claimed = true+ }+ }+ // From here on, any early return must release the claim so a retry can proceed.+ release := func() {+ if claimed {+ _ = store.ReleaseIdempotencyKey(ctx, orgID, idemKey)}}@@ -203,6 +228,7 @@ func (s *Server) createWebhook(c echo.Context) error {if secret == "" {gen, err := webhook.GenerateSecret()if err != nil {+ release()return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to generate signing secret"})}secret = gen@@ -214,6 +240,7 @@ func (s *Server) createWebhook(c echo.Context) error {}seq, err := store.CurrentLifecycleSeq(ctx)if err != nil {+ release()return webhookStoreError(c, err)}@@ -228,23 +255,43 @@ func (s *Server) createWebhook(c echo.Context) error {CreatedAfterEventSeq: seq,})if err != nil {+ release()return webhookStoreError(c, err)}- if reused {- // Name matched an existing destination — return it without a secret.- return c.JSON(http.StatusOK, toWireDestination(row, ""))- }echoSecret := ""- if generated {+ status := http.StatusCreated+ if reused {+ status = http.StatusOK // existing destination matched by name — no secret echo+ } else if generated {echoSecret = secret}resp := toWireDestination(row, echoSecret)- if idemKey != "" {++ if claimed {body, _ := json.Marshal(resp)- _ = store.PutWebhookIdempotentResponse(ctx, orgID, idemKey, reqHash, row.ID, body)+ if ferr := store.FinalizeIdempotencyKey(ctx, orgID, idemKey, row.ID, body); ferr != nil {+ // The one-time secret would otherwise be unrecoverable — fail the+ // request and clean up so the client can safely retry.+ if !reused {+ _ = store.SoftDeleteWebhookDestination(ctx, orgID, row.ID)+ }+ _ = store.ReleaseIdempotencyKey(ctx, orgID, idemKey)+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to persist idempotent response; please retry"})+ }}- return c.JSON(http.StatusCreated, resp)+ return c.JSON(status, resp)+}++// firstInvalidEventType returns the first eventTypes entry that isn't a valid+// exact type or "prefix.*" wildcard, or "" if all are valid.+func firstInvalidEventType(ets []string) string {+ for _, e := range ets {+ if !types.ValidWebhookEventFilter(e) {+ return e+ }+ }+ return ""}// GET /api/webhooks@@ -261,7 +308,8 @@ func (s *Server) listWebhooks(c echo.Context) error {for _, r := range rows {out = append(out, toWireDestination(r, ""))}- return c.JSON(http.StatusOK, out)+ // Canonical shape: { "data": [...] } (matches the docs + deliveries list).+ return c.JSON(http.StatusOK, map[string][]types.WebhookDestination{"data": out})}// GET /api/webhooks/:id@@ -316,6 +364,9 @@ func (s *Server) updateWebhook(c echo.Context) error {if err := json.Unmarshal(v, &et); err != nil {return badField("eventTypes")}+ if bad := firstInvalidEventType(et); bad != "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "unknown event type: " + bad})+ }if len(et) == 0 {p.ClearEventTypes = true} else {diff --git a/internal/controlplane/lifecycle_ingress.go b/internal/controlplane/lifecycle_ingress.goindex a362eda0..cc18c66b 100644--- a/internal/controlplane/lifecycle_ingress.go+++ b/internal/controlplane/lifecycle_ingress.go@@ -45,9 +45,14 @@ type LifecycleIngress struct {// ingressTypeMap maps the internal worker event strings to public lifecycle// types. Only these worker-origin events become webhooks via the ingress; every// other stream entry is acked and ignored by this consumer group.+//+// Note: there is intentionally NO "running" entry — the worker does not emit a+// post-boot "running"/"ready" stream event (sessions are created directly as+// running), so sandbox.ready has no producer yet (P3 gap). "woke" is the+// worker's wake signal (grpc_server.go WakeSandbox) → sandbox.resumed.var ingressTypeMap = map[string]string{"created": types.WebhookEventCreated,- "running": types.WebhookEventReady,+ "woke": types.WebhookEventResumed,"migrated": types.WebhookEventMigrated,}diff --git a/internal/controlplane/webhook_dispatcher.go b/internal/controlplane/webhook_dispatcher.goindex 44fc48a1..a4ad7628 100644--- a/internal/controlplane/webhook_dispatcher.go+++ b/internal/controlplane/webhook_dispatcher.go@@ -184,7 +184,7 @@ func (d *WebhookDispatcher) sendOne(ctx context.Context, dd db.DueDelivery) {code := resp.StatusCodeswitch {case code >= 200 && code < 300:- if err := d.store.RecordDeliveryResult(ctx, dd.ID, db.DeliveryResult{+ if _, err := d.store.RecordDeliveryResult(ctx, dd.ID, dd.LockedBy, db.DeliveryResult{Status: "delivered", ResponseCode: &code,}); err != nil {log.Printf("webhook_dispatcher: record delivered %s: %v", dd.ID, err)@@ -210,7 +210,7 @@ func (d *WebhookDispatcher) recordRetryable(ctx context.Context, dd db.DueDelive}next := time.Now().Add(wait)e := capErr(msg)- if err := d.store.RecordDeliveryResult(ctx, dd.ID, db.DeliveryResult{+ if _, err := d.store.RecordDeliveryResult(ctx, dd.ID, dd.LockedBy, db.DeliveryResult{Status: "failed", ResponseCode: code, Error: &e, NextAttemptAt: &next,}); err != nil {log.Printf("webhook_dispatcher: record failed %s: %v", dd.ID, err)@@ -223,7 +223,7 @@ func (d *WebhookDispatcher) recordTerminal(ctx context.Context, dd db.DueDeliverfunc (d *WebhookDispatcher) recordTerminalCode(ctx context.Context, dd db.DueDelivery, code *int, msg string) {e := capErr(msg)- if err := d.store.RecordDeliveryResult(ctx, dd.ID, db.DeliveryResult{+ if _, err := d.store.RecordDeliveryResult(ctx, dd.ID, dd.LockedBy, db.DeliveryResult{Status: "dead_letter", ResponseCode: code, Error: &e,}); err != nil {log.Printf("webhook_dispatcher: record dead_letter %s: %v", dd.ID, err)diff --git a/internal/db/migrations/049_sandbox_webhooks.up.sql b/internal/db/migrations/049_sandbox_webhooks.up.sqlindex c67c9400..a3495b87 100644--- a/internal/db/migrations/049_sandbox_webhooks.up.sql+++ b/internal/db/migrations/049_sandbox_webhooks.up.sql@@ -79,12 +79,16 @@ CREATE INDEX IF NOT EXISTS webhook_deliveries_dest_idx-- → replay the stored ORIGINAL RESPONSE (incl. the one-time generated secret);-- same key + different request → 409. response_enc is the rendered create-- response, encrypted (it carries the plaintext secret). Prune past a ~24h TTL.+-- Two-phase: a request first RESERVES (org_id,key,request_hash) atomically (so a+-- concurrent same-key create can't double-create), then FINALIZES with the+-- destination + encrypted response. destination_id/response_enc are therefore+-- NULL between reserve and finalize (and a never-finalized claim is released).CREATE TABLE IF NOT EXISTS webhook_idempotency_keys (org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,key TEXT NOT NULL, -- caller's Idempotency-Key headerrequest_hash TEXT NOT NULL, -- fingerprint of the create body- destination_id TEXT NOT NULL REFERENCES webhook_destinations(id) ON DELETE CASCADE,- response_enc BYTEA NOT NULL, -- the original create response (incl. secret), encrypted+ destination_id TEXT REFERENCES webhook_destinations(id) ON DELETE CASCADE,+ response_enc BYTEA, -- the original create response (incl. secret), encrypted; NULL until finalizedcreated_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (org_id, key));diff --git a/internal/db/store.go b/internal/db/store.goindex aa88aba0..6083532e 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -1777,6 +1777,32 @@ func (s *Store) ReconcileWorkerSessions(ctx context.Context, workerID string) (hreturn hibernated, stopped, fmt.Errorf("failed to close scale events: %w", err)}+ // Record canonical lifecycle events in THIS tx so webhooks fire for+ // crash-recovery transitions too (worker restart while a sandbox was+ // running). Without this, exactly the failure cases users want webhooks for+ // would silently bypass the ledger.+ for _, o := range hibernated {+ if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{+ ID: fmt.Sprintf("%s:sandbox.hibernated:reconcile:%d", o.SandboxID, time.Now().UnixNano()),+ OrgID: o.OrgID,+ SandboxID: o.SandboxID,+ Type: "sandbox.hibernated",+ }); err != nil {+ return nil, nil, fmt.Errorf("record reconcile hibernated event: %w", err)+ }+ }+ for _, o := range stopped {+ if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{+ ID: fmt.Sprintf("%s:sandbox.stopped:reconcile:%d", o.SandboxID, time.Now().UnixNano()),+ OrgID: o.OrgID,+ SandboxID: o.SandboxID,+ Type: "sandbox.stopped",+ Data: json.RawMessage(`{"reason":"crash"}`),+ }); err != nil {+ return nil, nil, fmt.Errorf("record reconcile stopped event: %w", err)+ }+ }+if err := tx.Commit(ctx); err != nil {return nil, nil, fmt.Errorf("failed to commit reconcile tx: %w", err)}diff --git a/internal/db/webhooks.go b/internal/db/webhooks.goindex 5916c8be..52d58d3b 100644--- a/internal/db/webhooks.go+++ b/internal/db/webhooks.go@@ -381,36 +381,66 @@ func (s *Store) SoftDeleteWebhookDestination(ctx context.Context, orgID uuid.UUI// Idempotency-Key storage// ----------------------------------------------------------------------------// GetWebhookIdempotentResponse looks up a stored create response by (org,key).-// found+matching hash → returns the decrypted response JSON. found+different-// hash → ErrWebhookIdempotencyConflict. not found → (nil, false, nil).-func (s *Store) GetWebhookIdempotentResponse(ctx context.Context, orgID uuid.UUID, key, requestHash string) ([]byte, bool, error) {+// WebhookIdemOutcome is the result of reserving an Idempotency-Key.+type WebhookIdemOutcome int++const (+ WebhookIdemClaimed WebhookIdemOutcome = iota // we own a fresh claim; proceed to create + finalize+ WebhookIdemReplay // a finalized response exists (same request) → return it+ WebhookIdemInProgress // same key+request, claim held by a concurrent request, not finalized yet+ WebhookIdemConflict // same key, different request body+)++// ReserveIdempotencyKey atomically claims (org_id, key) for this create request+// BEFORE any destination is created, so two concurrent same-key requests can't+// both create. The unique PK makes the claim INSERT the single arbiter:+// - we win the INSERT → WebhookIdemClaimed (caller must Finalize or Release)+// - row exists, different hash → WebhookIdemConflict+// - row exists, same hash, response stored → WebhookIdemReplay (+ decrypted body)+// - row exists, same hash, not finalized → WebhookIdemInProgress+func (s *Store) ReserveIdempotencyKey(ctx context.Context, orgID uuid.UUID, key, requestHash string) (WebhookIdemOutcome, []byte, error) {if s.encryptor == nil {- return nil, false, ErrEncryptionNotConfigured+ return 0, nil, ErrEncryptionNotConfigured+ }+ tag, err := s.pool.Exec(ctx,+ `INSERT INTO webhook_idempotency_keys (org_id, key, request_hash)+ VALUES ($1, $2, $3) ON CONFLICT (org_id, key) DO NOTHING`,+ orgID, key, requestHash)+ if err != nil {+ return 0, nil, err+ }+ if tag.RowsAffected() == 1 {+ return WebhookIdemClaimed, nil, nil}var storedHash string- var enc []byte- err := s.pool.QueryRow(ctx,+ var enc []byte // nullable until finalized+ err = s.pool.QueryRow(ctx,`SELECT request_hash, response_enc FROM webhook_idempotency_keys WHERE org_id = $1 AND key = $2`,orgID, key).Scan(&storedHash, &enc)if err != nil {if errors.Is(err, pgx.ErrNoRows) {- return nil, false, nil+ return WebhookIdemInProgress, nil, nil // raced with a release; ask the client to retry}- return nil, false, err+ return 0, nil, err}if storedHash != requestHash {- return nil, false, ErrWebhookIdempotencyConflict+ return WebhookIdemConflict, nil, nil+ }+ if enc == nil {+ return WebhookIdemInProgress, nil, nil}plain, err := s.encryptor.Decrypt(enc)if err != nil {- return nil, false, fmt.Errorf("decrypt idempotent response: %w", err)+ return 0, nil, fmt.Errorf("decrypt idempotent response: %w", err)}- return plain, true, nil+ return WebhookIdemReplay, plain, nil}-// PutWebhookIdempotentResponse stores the encrypted original create response.-func (s *Store) PutWebhookIdempotentResponse(ctx context.Context, orgID uuid.UUID, key, requestHash, destinationID string, responseJSON []byte) error {+// FinalizeIdempotencyKey attaches the destination + encrypted response to a claim+// we own. Returns an error if the claim is missing or already finalized — the+// caller MUST treat a finalize failure as fatal (the one-time secret would+// otherwise be unrecoverable).+func (s *Store) FinalizeIdempotencyKey(ctx context.Context, orgID uuid.UUID, key, destinationID string, responseJSON []byte) error {if s.encryptor == nil {return ErrEncryptionNotConfigured}@@ -418,11 +448,25 @@ func (s *Store) PutWebhookIdempotentResponse(ctx context.Context, orgID uuid.UUIif err != nil {return fmt.Errorf("encrypt idempotent response: %w", err)}- _, err = s.pool.Exec(ctx,- `INSERT INTO webhook_idempotency_keys (org_id, key, request_hash, destination_id, response_enc)- VALUES ($1, $2, $3, $4, $5)- ON CONFLICT (org_id, key) DO NOTHING`,- orgID, key, requestHash, destinationID, enc)+ tag, err := s.pool.Exec(ctx,+ `UPDATE webhook_idempotency_keys SET destination_id = $3, response_enc = $4+ WHERE org_id = $1 AND key = $2 AND response_enc IS NULL`,+ orgID, key, destinationID, enc)+ if err != nil {+ return err+ }+ if tag.RowsAffected() == 0 {+ return fmt.Errorf("idempotency claim missing or already finalized")+ }+ return nil+}++// ReleaseIdempotencyKey drops an unfinalized claim so a later retry can proceed+// (used when create or finalize fails).+func (s *Store) ReleaseIdempotencyKey(ctx context.Context, orgID uuid.UUID, key string) error {+ _, err := s.pool.Exec(ctx,+ `DELETE FROM webhook_idempotency_keys WHERE org_id = $1 AND key = $2 AND response_enc IS NULL`,+ orgID, key)return err}@@ -654,7 +698,8 @@ type DueDelivery struct {URL stringSecret stringPayload []byte- RetryCount int // post-claim value (already incremented)+ RetryCount int // post-claim value (already incremented)+ LockedBy string // this dispatcher's lock token; used to record results safely}// ClaimDueDeliveries atomically claims up to `batch` due deliveries for enabled,@@ -729,6 +774,7 @@ func (s *Store) ClaimDueDeliveries(ctx context.Context, lockedBy string, batch iSecret: string(secret),Payload: c.payload,RetryCount: c.retry + 1,+ LockedBy: lockedBy,})}if err := tx.Commit(ctx); err != nil {@@ -746,21 +792,28 @@ type DeliveryResult struct {}// RecordDeliveryResult writes the outcome of a send attempt and clears the lock.-func (s *Store) RecordDeliveryResult(ctx context.Context, id string, r DeliveryResult) error {+// It only updates a row THIS dispatcher still owns (status='delivering' AND+// locked_by=lockedBy), so a stale sender can't revive a row that was meanwhile+// canceled (destination deleted) or redelivered (reset to pending by a manual+// redeliver or the reconciler). Returns whether the row was updated.+func (s *Store) RecordDeliveryResult(ctx context.Context, id, lockedBy string, r DeliveryResult) (bool, error) {var delivered *time.Timeif r.Status == "delivered" {now := time.Now()delivered = &now}- _, err := s.pool.Exec(ctx,+ tag, err := s.pool.Exec(ctx,`UPDATE webhook_deliveries- SET status = $2, response_code = $3, error = $4,- next_attempt_at = COALESCE($5, next_attempt_at),- delivered_at = COALESCE($6, delivered_at),+ SET status = $3, response_code = $4, error = $5,+ next_attempt_at = COALESCE($6, next_attempt_at),+ delivered_at = COALESCE($7, delivered_at),locked_by = NULL, locked_until = NULL, updated_at = now()- WHERE id = $1`,- id, r.Status, r.ResponseCode, r.Error, r.NextAttemptAt, delivered)- return err+ WHERE id = $1 AND status = 'delivering' AND locked_by = $2`,+ id, lockedBy, r.Status, r.ResponseCode, r.Error, r.NextAttemptAt, delivered)+ if err != nil {+ return false, err+ }+ return tag.RowsAffected() > 0, nil}// ReclaimStaleDeliveries returns deliveries stuck in 'delivering' past their@@ -809,14 +862,42 @@ func (s *Store) GetWebhookDelivery(ctx context.Context, orgID uuid.UUID, destID,return r, nil}+// destinationOwnedByOrg verifies a destination belongs to the org, INCLUDING+// soft-deleted ones (for delivery-history access after deletion). Returns+// ErrWebhookNotFound if no such row exists for the org.+func (s *Store) destinationOwnedByOrg(ctx context.Context, orgID uuid.UUID, id string) error {+ var exists bool+ err := s.pool.QueryRow(ctx,+ `SELECT true FROM webhook_destinations WHERE id = $1 AND org_id = $2`, id, orgID).Scan(&exists)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return ErrWebhookNotFound+ }+ return err+ }+ return nil+}++// SandboxBelongsToOrg reports whether sandboxID is owned by orgID — used to+// validate a webhook's sandbox scope at registration.+func (s *Store) SandboxBelongsToOrg(ctx context.Context, orgID uuid.UUID, sandboxID string) (bool, error) {+ var exists bool+ err := s.pool.QueryRow(ctx,+ `SELECT EXISTS(SELECT 1 FROM sandbox_sessions WHERE sandbox_id = $1 AND org_id = $2)`,+ sandboxID, orgID).Scan(&exists)+ return exists, err+}+// ListWebhookDeliveries returns a destination's deliveries, newest first,// cursor-paginated on (created_at, id). An optional status filter narrows it.func (s *Store) ListWebhookDeliveries(ctx context.Context, orgID uuid.UUID, destID, status, cursor string, limit int) ([]*WebhookDeliveryRow, *string, bool, error) {if limit <= 0 || limit > 200 {limit = 50}- // Verify the destination belongs to the org (so an unknown id 404s, not empties).- if _, err := s.GetWebhookDestination(ctx, orgID, destID); err != nil {+ // Verify the destination belongs to the org (so an unknown id 404s, not+ // empties). Soft-deleted destinations are allowed here — their delivery+ // history is retained and remains queryable.+ if err := s.destinationOwnedByOrg(ctx, orgID, destID); err != nil {return nil, nil, false, err}diff --git a/pkg/types/webhook.go b/pkg/types/webhook.goindex 97d65446..1021d986 100644--- a/pkg/types/webhook.go+++ b/pkg/types/webhook.go@@ -2,6 +2,7 @@ package typesimport ("encoding/json"+ "strings""time")@@ -22,6 +23,36 @@ const (WebhookEventTest = "sandbox.test")+// WebhookEventTypes is the full set of subscribable lifecycle types (excludes+// the synthetic sandbox.test, which is only sent by /test). Some are not emitted+// yet (P3) but are valid to subscribe to in advance.+var WebhookEventTypes = []string{+ WebhookEventCreated, WebhookEventReady, WebhookEventHibernated, WebhookEventResumed,+ WebhookEventStopped, WebhookEventMigrated, WebhookEventCheckpointCreated,+ WebhookEventForked, WebhookEventScaled, WebhookEventPreviewURLChanged,+}++// ValidWebhookEventFilter reports whether s is a valid eventTypes entry: an exact+// known type, or a "prefix.*" wildcard that matches at least one known type+// (e.g. "sandbox.*", "sandbox.checkpoint.*").+func ValidWebhookEventFilter(s string) bool {+ if strings.HasSuffix(s, ".*") {+ prefix := strings.TrimSuffix(s, "*") // keep the trailing dot, e.g. "sandbox."+ for _, t := range WebhookEventTypes {+ if strings.HasPrefix(t, prefix) {+ return true+ }+ }+ return false+ }+ for _, t := range WebhookEventTypes {+ if t == s {+ return true+ }+ }+ return false+}+// Delivery statuses. failed = retryable (future next_attempt_at); dead_letter &// canceled are terminal.const (diff --git a/pkg/types/webhook_test.go b/pkg/types/webhook_test.gonew file mode 100644index 00000000..cc48f265--- /dev/null+++ b/pkg/types/webhook_test.go@@ -0,0 +1,27 @@+package types++import "testing"++func TestValidWebhookEventFilter(t *testing.T) {+ valid := []string{+ "sandbox.created", "sandbox.stopped", "sandbox.hibernated", "sandbox.resumed",+ "sandbox.migrated", "sandbox.ready", "sandbox.checkpoint.created",+ "sandbox.forked", "sandbox.scaled", "sandbox.preview_url.changed",+ "sandbox.*", // matches the whole namespace+ "sandbox.checkpoint.*", // matches checkpoint.created+ }+ for _, s := range valid {+ if !ValidWebhookEventFilter(s) {+ t.Errorf("expected VALID: %q", s)+ }+ }+ invalid := []string{+ "", "sandbox.stoped", "sandbox.create", "stopped", "sandbox.test",+ "sandbox.bogus.*", "other.*", "sandbox", "*",+ }+ for _, s := range invalid {+ if ValidWebhookEventFilter(s) {+ t.Errorf("expected INVALID: %q", s)+ }+ }+}