-- R560 — Add idempotency key to events ledger.
-- Per codex audit: recordEvent always mints a fresh ULID, so producer
-- retries land duplicate rows that fire subscriptions twice. Idempotency
-- key (caller-supplied, optional) plus partial UNIQUE constraint
-- collapses retries to a single row via INSERT OR IGNORE.

ALTER TABLE events ADD COLUMN idempotency_key TEXT;
-- Partial unique: NULLs are allowed (legacy producers and any event
-- that's genuinely unique each call don't need a key).
CREATE UNIQUE INDEX IF NOT EXISTS idx_events_idempotency
  ON events(idempotency_key) WHERE idempotency_key IS NOT NULL;

INSERT OR IGNORE INTO migration_history (migration_id, description) VALUES
  ('127_events_idempotency', 'R560 — idempotency_key on events ledger (codex audit hardening)');
