Files
superbrain/db/migrations/013_notifications.sql
Andrew S Erwin 451312c3cf
release gate / check (push) Failing after 6m54s
Add notification engine phase 1: channels, rules, plan-gated delivery
When something happens in the brain, tell the user (PLAN_PRICING_TIERS
step 3). The engine is a SCANNER, not a hook system: producers are never
instrumented; exactly-once comes solely from UNIQUE(ruleId,dedupeKey) +
ON CONFLICT DO NOTHING, so rescans are free and restarts are safe.

Schema (migration 013 + schema.sql, converge-verified):
NotificationChannel (secrets encrypted at rest via internal/crypto, the
IMAP-password format), NotificationRule (one channel per rule in phase 1,
cooldown, version column), Notification (dedupe ledger + delivery state:
pending/sent/failed/suppressed, attempts, backoff timestamp).

internal/notify: two triggers — signal_created (fires only for signals
newer than the rule, never retro-notifying history) and bookmark_due
(lead-hours window, dedupe key carries the UTC due date so moving a
dueDate re-notifies and same-day rescans do not). Delivery claims rows in
one short transaction (FOR UPDATE SKIP LOCKED, batch 10) so multiple app
instances never double-send; exponential backoff to 5 attempts; per-rule
cooldown; per-owner pending cap. Channels: email (internal/mailer,
falls back to the account email), Slack webhook, Matrix room, Telegram
bot — webhooks dial through netguard inside outbound.Reserve budgets.
The plan gate re-checks at delivery: a downgraded tenant's rows become
'suppressed' instead of sending. Signal-app delivery deliberately absent
(needs a daemon; see plan doc hard truths).

API: channel/rule CRUD with the house version contract (409 on stale
base), write-only secrets (masked in every response; a PATCH echoing the
mask keeps the stored value), test-send endpoint with its own budget,
owner-scoped delivery history. Channel kinds gate on the ENTITLEMENT
CATALOG (403 'Not available on your plan') — never on TIER, per the
tenancy invariant.

Web: Settings -> Notifications tab (channels with per-kind forms and
Test button, rule builder, recent-delivery strip). Data loading uses the
house promise-chain shape; setState only in async callbacks (SSR lint).

Fixes along the way: mailer send budget raised 5->20/min (shared by
resets and notifications; 5/min would throttle a hosted instance) and
outbound gains ResetBudget() wired into the test harness — the global
'smtp' window made password-reset and notification tests collide when
the package ran as a whole.

Tests: full channel/rule/engine integration pass (masking + encryption
round-trip, masked-PATCH preservation, version contract, plan gating via
a forced 'free' tenant, dedupe across rescans, cooldown, real SMTP and
webhook delivery via loopback fakes, backoff recording, downgrade
suppression, history). Full suite green with -race; web lint/SSR-eslint/
build clean. Docs: API.md endpoint table, RUNNING.md, AGENTS.md
invariants, DESIGN_NOTIFICATIONS.md (local).
2026-10-26 14:43:15 -05:00

66 lines
3.0 KiB
SQL

-- 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');