-- 013_notifications.sql — notification engine phase 1 -- (DESIGN_NOTIFICATIONS.md): channels, rules, and fired notifications. -- -- Additive and idempotent; schema.sql carries identical structures so this -- is a structural no-op on a fresh database (db-converge proves both paths -- land the same). No existing table gains a constraint here, so the -- converge pass-2 CASCADE-drop simulation has nothing external to repair. -- -- Design invariants encoded in the DDL: -- * UNIQUE("ruleId","dedupeKey") on Notification is the exactly-once -- ledger — the scanner inserts with ON CONFLICT DO NOTHING and re-runs -- are free. -- * NotificationChannel.config holds secrets encrypted with -- internal/crypto (same format as IMAP passwords); the API never echoes -- them back. -- * The partial delivery index keeps the every-60s send scan cheap on -- large histories. CREATE TABLE IF NOT EXISTS "NotificationChannel" ( id text PRIMARY KEY, "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, kind text NOT NULL CHECK (kind IN ('email','slack','matrix','telegram')), name text NOT NULL, config jsonb NOT NULL DEFAULT '{}', enabled boolean NOT NULL DEFAULT true, version integer NOT NULL DEFAULT 1, "createdAt" timestamptz NOT NULL DEFAULT now(), "updatedAt" timestamptz NOT NULL DEFAULT now() ); CREATE INDEX IF NOT EXISTS "NotificationChannel_ownerId_idx" ON "NotificationChannel"("ownerId"); CREATE TABLE IF NOT EXISTS "NotificationRule" ( id text PRIMARY KEY, "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, name text NOT NULL, trigger text NOT NULL CHECK (trigger IN ('signal_created','bookmark_due')), config jsonb NOT NULL DEFAULT '{}', "channelId" text NOT NULL REFERENCES "NotificationChannel"(id) ON DELETE CASCADE, "cooldownMinutes" integer NOT NULL DEFAULT 60, enabled boolean NOT NULL DEFAULT true, "lastFiredAt" timestamptz, version integer NOT NULL DEFAULT 1, "createdAt" timestamptz NOT NULL DEFAULT now(), "updatedAt" timestamptz NOT NULL DEFAULT now() ); CREATE INDEX IF NOT EXISTS "NotificationRule_ownerId_idx" ON "NotificationRule"("ownerId"); CREATE TABLE IF NOT EXISTS "Notification" ( id text PRIMARY KEY, "ruleId" text NOT NULL REFERENCES "NotificationRule"(id) ON DELETE CASCADE, "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, "dedupeKey" text NOT NULL, title text NOT NULL, body text NOT NULL, status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','sent','failed','suppressed')), attempts integer NOT NULL DEFAULT 0, "lastError" text, "nextAttemptAt" timestamptz NOT NULL DEFAULT now(), "sentAt" timestamptz, "createdAt" timestamptz NOT NULL DEFAULT now(), UNIQUE ("ruleId", "dedupeKey") ); CREATE INDEX IF NOT EXISTS "Notification_ownerId_createdAt_idx" ON "Notification"("ownerId", "createdAt" DESC); CREATE INDEX IF NOT EXISTS "Notification_delivery_due_idx" ON "Notification"("status", "nextAttemptAt") WHERE status IN ('pending','failed');