Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(pulse): per-brand Daily Pulse digest with highlights, warnings and email/webhook delivery (#561)

Gökhan Geyike04836ce41fc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4c37d2134..ede898fb5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- **Daily Pulse** — a per-brand digest generated after the daily tracking run: KPI strip (visibility rate, 7-day trend, mentions, citations, sentiment), highlights (first-time citations, top prompt gains, leaderboard overtakes, first appearance on a new engine) and anomaly warnings (sharp visibility drop, competitor surge, high-volume prompt losing citations) with a platform-outage guard and a 7-day warning cooldown. Email via Resend on cloud (active/trialing orgs only), a `daily_pulse.created` webhook event everywhere, and Settings → Notifications for per-brand frequency and recipients (#540)
+
## [0.1.7] - 2026-07-25
### Added
diff --git a/README.md b/README.md
index 08b3246ee..8dcb65046 100644
--- a/README.md
+++ b/README.md
@@ -174,7 +174,7 @@ What we're planning to build next. React with 👍 on the linked issue (or open
- [x] **In-product conversational AI assistant** — chat with your dashboard about visibility trends, competitor moves, and content gaps without leaving the page
- [ ] **ScrapeLLM integration** — add ScrapeLLM as an alternative scraping backend alongside Cloro for users who prefer it or need a fallback
- [x] **PostHog integration** — pipe AI-referred sessions and tracking events into PostHog for users already running it as their product analytics layer
-- [ ] **Anomaly alerts** — get an email / Slack ping when a brand's visibility drops sharply, a competitor surges, or a high-volume prompt suddenly stops citing you
+- [x] **Daily Pulse** — a per-brand daily digest email after each tracking run: KPI strip, highlights (first citations, prompt gains, leaderboard overtakes) and anomaly warnings (sharp visibility drops, competitor surges, lost citations), plus a `daily_pulse.created` webhook event for Slack/Notion delivery ([#540](https://github.com/ansvisor/ansvisor/issues/540))
- [ ] **BYO LLM keys** — bring your own OpenAI / Anthropic / Gemini API key for tracking and content generation, so you control cost and data handling
- [ ] **Webhook recipe library** — one-click Notion / Linear / Asana / Slack templates so a Content Brief can land in your editorial workflow with zero glue code
diff --git a/docs/api-reference/webhooks.mdx b/docs/api-reference/webhooks.mdx
index 09f3fe095..c4790e7be 100644
--- a/docs/api-reference/webhooks.mdx
+++ b/docs/api-reference/webhooks.mdx
@@ -10,7 +10,7 @@ Webhooks are configured per-brand via the `webhook_configs` table. The dashboard
Required fields:
- `webhook_url` — your endpoint
- `webhook_secret` — used to HMAC-sign payloads (recommended)
-- `events` — array of subscribed events (currently: `content_brief.sent`, `opportunity.created`, `opportunity.status_changed`)
+- `events` — array of subscribed events (currently: `content_brief.sent`, `opportunity.created`, `opportunity.status_changed`, `daily_pulse.created`)
- `is_active` — toggle without deleting
## Payload format
@@ -83,6 +83,35 @@ Fired when the content optimization worker generates a new opportunity.
Fired when an opportunity moves between statuses (`new` → `sent` → `in_progress` → `done` / `dismissed`).
+### `daily_pulse.created`
+
+Fired after a brand's daily tracking run when a Daily Pulse digest is generated. Sent as a flat payload (works on cloud and self-host):
+
+```json
+{
+ "event": "daily_pulse.created",
+ "brand": { "id": "uuid", "name": "Acme Corp" },
+ "pulse": {
+ "date": "2026-07-30",
+ "frequency": "daily",
+ "kpis": {
+ "visibilityRate": 42.5,
+ "visiblePrompts": 17,
+ "promptCount": 40,
+ "weekRate": 44.1,
+ "weekTrend": -1.2,
+ "mentions": 31,
+ "citations": 12,
+ "sentimentPct": 68
+ },
+ "highlights": [{ "type": "first_citation", "url": "https://..." }],
+ "warnings": [{ "type": "competitor_surge", "competitorName": "..." }],
+ "degraded_platforms": [],
+ "insights_url": "https://app.../dashboard/insights"
+ }
+}
+```
+
## Retries
Failed deliveries (non-2xx response, timeout, connection error) retry with exponential backoff:
diff --git a/server/.env.example b/server/.env.example
index 7ae473760..4fb305d39 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -76,3 +76,11 @@ AI_VOLUME_MULTIPLIER=0.15
# STRIPE_SECRET_KEY=sk_test_...
# STRIPE_WEBHOOK_SECRET=whsec_...
+# Daily Pulse email via Resend (cloud only — self-hosted deployments never
+# send pulse emails; the daily_pulse.created webhook event works everywhere)
+# RESEND_API_KEY=re_...
+# RESEND_FROM_EMAIL="Ansvisor <[email protected]>"
+
+# Public URL of the web app, used for links in Daily Pulse emails
+# PUBLIC_APP_URL=https://app.example.com
+
diff --git a/server/src/lib/job-runner.js b/server/src/lib/job-runner.js
index e80974bf9..703eae906 100644
--- a/server/src/lib/job-runner.js
+++ b/server/src/lib/job-runner.js
@@ -15,6 +15,7 @@ import {
} from './job-manager.js';
import { processTrackingJob } from '../workers/tracking-worker.js';
import { processContentJob } from '../workers/content-worker.js';
+import { generatePulseForBrand } from './pulse/engine.js';
import logger from './logger.js';
// Concurrency counters (matches previous Bull concurrency of 2 per queue)
@@ -68,6 +69,15 @@ export async function runTrackingJob(jobId, io) {
immediate: !!immediate,
});
}
+
+ // Daily Pulse (#540): fire-and-forget after a full daily run — never
+ // for immediate/manual runs or single-prompt refreshes. The engine is
+ // self-contained: eligibility checks, dedup and error handling inside.
+ if (!immediate && !promptId && !promptIds?.length) {
+ generatePulseForBrand(brandId).catch((err) => {
+ logger.error({ err, brandId }, 'daily pulse trigger failed');
+ });
+ }
} catch (err) {
if (abortController.signal.aborted) {
logger.info({ jobId }, 'tracking job was cancelled');
diff --git a/server/src/lib/pulse/email.js b/server/src/lib/pulse/email.js
new file mode 100644
index 000000000..0fa61643a
--- /dev/null
+++ b/server/src/lib/pulse/email.js
@@ -0,0 +1,206 @@
+import { logger } from '../logger.js';
+
+/**
+ * Daily Pulse email rendering + delivery via the Resend HTTP API (#540).
+ *
+ * Cloud-only: the caller gates on isCloud(). No SDK — a single fetch to
+ * https://api.resend.com/emails with RESEND_API_KEY. When the key is
+ * missing the send is a silent no-op so self-host / misconfigured
+ * environments never crash the tracking pipeline.
+ */
+
+// Display names for platform slugs used in email copy. Keep in sync with
+// PLATFORM_LABELS in web/src/config/platform-labels.ts.
+const PLATFORM_LABELS = {
+ 'chatgpt-web': 'ChatGPT',
+ 'google-aio': 'Google AI Overview',
+ 'google-aimode': 'Google AI Mode',
+ 'copilot-web': 'Microsoft Copilot',
+ 'grok-web': 'Grok',
+ 'perplexity-web': 'Perplexity',
+ 'gemini-web': 'Google Gemini',
+};
+
+function platformLabel(slug) {
+ return PLATFORM_LABELS[slug] ?? slug;
+}
+
+function escapeHtml(value) {
+ return String(value ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+function signed(n, suffix = '') {
+ const v = Math.round(n * 10) / 10;
+ if (v > 0) return `+${v}${suffix}`;
+ return `${v}${suffix}`;
+}
+
+function kpiCell(label, value, change) {
+ const changeHtml =
+ change === null
+ ? ''
+ : `<div style="font-size:12px;color:${change >= 0 ? '#059669' : '#dc2626'};">${escapeHtml(change >= 0 ? '▲' : '▼')} ${escapeHtml(signed(change))}</div>`;
+ return `<td style="padding:12px 16px;border:1px solid #e5e7eb;border-radius:8px;text-align:center;">
+ <div style="font-size:12px;color:#6b7280;text-transform:uppercase;letter-spacing:0.04em;">${escapeHtml(label)}</div>
+ <div style="font-size:22px;font-weight:600;color:#111827;">${escapeHtml(value)}</div>
+ ${changeHtml}
+ </td>`;
+}
+
+function listItem(text) {
+ return `<li style="margin:0 0 8px 0;color:#374151;font-size:14px;line-height:1.5;">${text}</li>`;
+}
+
+function highlightLine(h) {
+ switch (h.type) {
+ case 'first_citation':
+ return listItem(
+ `First citation for <a href="${escapeHtml(h.url)}" style="color:#2563eb;">${escapeHtml(h.label || h.url)}</a>${h.promptText ? ` — “${escapeHtml(h.promptText)}”` : ''}`,
+ );
+ case 'prompt_gain':
+ return listItem(
+ `“${escapeHtml(h.promptText)}” gained <strong>${escapeHtml(signed(h.gain, ' pts'))}</strong> visibility this week`,
+ );
+ case 'competitor_overtaken':
+ return listItem(
+ `You overtook <strong>${escapeHtml(h.competitorName)}</strong> on the leaderboard (${escapeHtml(String(h.brandRate))}% vs ${escapeHtml(String(h.competitorRate))}%)`,
+ );
+ case 'new_engine':
+ return listItem(
+ `First appearance on <strong>${escapeHtml(platformLabel(h.platform))}</strong>`,
+ );
+ default:
+ return '';
+ }
+}
+
+function warningLine(w) {
+ switch (w.type) {
+ case 'sharp_drop':
+ return listItem(
+ `Visibility rate dropped sharply: <strong>${escapeHtml(String(w.from))}% → ${escapeHtml(String(w.to))}%</strong> week-over-week`,
+ );
+ case 'competitor_surge':
+ return listItem(
+ `<strong>${escapeHtml(w.competitorName)}</strong> surged from ${escapeHtml(String(w.from))}% to ${escapeHtml(String(w.to))}% week-over-week`,
+ );
+ case 'competitor_crossed':
+ return listItem(
+ `<strong>${escapeHtml(w.competitorName)}</strong> crossed above your visibility rate (${escapeHtml(String(w.competitorRate))}% vs ${escapeHtml(String(w.brandRate))}%)`,
+ );
+ case 'lost_citations':
+ return listItem(
+ `High-volume prompt “${escapeHtml(w.promptText)}” has stopped citing you for 3 runs in a row`,
+ );
+ default:
+ return '';
+ }
+}
+
+/**
+ * Render the pulse into { subject, html }.
+ */
+export function renderPulseEmail({ brandName, metrics, insightsUrl, settingsUrl }) {
+ const { kpis, highlights, warnings, degradedPlatforms, windowDays } = metrics;
+ const windowLabel = windowDays === 7 ? 'last 7 days' : 'last 24 hours';
+
+ const trend = kpis.weekTrend;
+ const subject = `${brandName} Daily Pulse — visibility ${kpis.visibilityRate}% (${signed(trend)} pts this week)`;
+
+ const highlightItems = highlights.map(highlightLine).filter(Boolean).join('');
+ const warningItems = warnings.map(warningLine).filter(Boolean).join('');
+
+ const degradedNote = degradedPlatforms.length
+ ? `<p style="font-size:12px;color:#92400e;background:#fef3c7;border-radius:6px;padding:8px 12px;">
+ Data collection was degraded on ${escapeHtml(degradedPlatforms.map(platformLabel).join(', '))} today, so drop detection was paused — numbers for ${degradedPlatforms.length > 1 ? 'these platforms' : 'this platform'} may look artificially low.
+ </p>`
+ : '';
+
+ const html = `<div style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;max-width:600px;margin:0 auto;padding:24px;">
+ <h1 style="font-size:18px;color:#111827;margin:0 0 4px 0;">Daily Pulse — ${escapeHtml(brandName)}</h1>
+ <p style="font-size:13px;color:#6b7280;margin:0 0 20px 0;">How your brand showed up in AI answers over the ${windowLabel}.</p>
+
+ <table role="presentation" cellspacing="8" style="border-collapse:separate;width:100%;margin-bottom:8px;">
+ <tr>
+ ${kpiCell('Visibility rate', `${kpis.visibilityRate}%`, null)}
+ ${kpiCell('7-day trend', `${kpis.weekRate}%`, kpis.weekTrend)}
+ </tr>
+ <tr>
+ ${kpiCell('Mentions', String(kpis.mentions), kpis.mentionsChange)}
+ ${kpiCell('Citations', String(kpis.citations), kpis.citationsChange)}
+ </tr>
+ <tr>
+ ${kpiCell('Positive sentiment', `${kpis.sentimentPct}%`, kpis.sentimentChange)}
+ ${kpiCell('Prompts covered', `${kpis.visiblePrompts}/${kpis.promptCount}`, null)}
+ </tr>
+ </table>
+
+ ${degradedNote}
+
+ ${
+ highlightItems
+ ? `<h2 style="font-size:14px;color:#059669;margin:20px 0 8px 0;">✦ Highlights</h2>
+ <ul style="margin:0;padding-left:20px;">${highlightItems}</ul>`
+ : ''
+ }
+
+ ${
+ warningItems
+ ? `<h2 style="font-size:14px;color:#dc2626;margin:20px 0 8px 0;">⚠ Needs attention</h2>
+ <ul style="margin:0;padding-left:20px;">${warningItems}</ul>`
+ : ''
+ }
+
+ <div style="margin:28px 0;">
+ <a href="${escapeHtml(insightsUrl)}" style="background:#111827;color:#ffffff;text-decoration:none;padding:10px 18px;border-radius:8px;font-size:14px;display:inline-block;">Open Insights</a>
+ </div>
+
+ <p style="font-size:12px;color:#9ca3af;border-top:1px solid #e5e7eb;padding-top:16px;">
+ You're receiving this because Daily Pulse is enabled for ${escapeHtml(brandName)}.
+ <a href="${escapeHtml(settingsUrl)}" style="color:#6b7280;">Manage notification settings</a>
+ </p>
+</div>`;
+
+ return { subject, html };
+}
+
+/**
+ * Send a pulse email through the Resend HTTP API.
+ * Returns true when accepted, false otherwise (missing key, HTTP error).
+ */
+export async function sendPulseEmail({ to, subject, html, settingsUrl }) {
+ const apiKey = process.env.RESEND_API_KEY;
+ const from = process.env.RESEND_FROM_EMAIL;
+ if (!apiKey || !from || !to.length) return false;
+
+ try {
+ const res = await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ from,
+ to,
+ subject,
+ html,
+ headers: { 'List-Unsubscribe': `<${settingsUrl}>` },
+ }),
+ signal: AbortSignal.timeout(15000),
+ });
+ if (!res.ok) {
+ const body = await res.text().catch(() => '');
+ logger.warn({ status: res.status, body: body.slice(0, 500) }, 'resend send failed');
+ return false;
+ }
+ return true;
+ } catch (err) {
+ logger.warn({ err }, 'resend send errored');
+ return false;
+ }
+}
diff --git a/server/src/lib/pulse/engine.js b/server/src/lib/pulse/engine.js
new file mode 100644
index 000000000..3a4d5b0bc
--- /dev/null
+++ b/server/src/lib/pulse/engine.js
@@ -0,0 +1,192 @@
+import supabaseAdmin from '../../config/supabase.js';
+import { logger } from '../logger.js';
+import { isCloud, isSubscriptionActive } from '../../config/plans.js';
+import { dispatchBrandWebhook } from '../webhook-dispatch.js';
+import { computePulseMetrics } from './metrics.js';
+import { renderPulseEmail, sendPulseEmail } from './email.js';
+
+/**
+ * Daily Pulse orchestration (#540).
+ *
+ * generatePulseForBrand runs after a brand's daily tracking job finishes.
+ * It decides eligibility, computes the digest, records it in sent_pulses
+ * (which doubles as the "already sent today" dedup and the 7-day warning
+ * cooldown log), then delivers: email via Resend on cloud, and the
+ * `daily_pulse.created` webhook event everywhere.
+ *
+ * Everything is best-effort — a pulse failure must never fail the
+ * tracking job that triggered it.
+ */
+
+const WEEKLY_SEND_UTC_DAY = 1; // Monday
+
+function appUrl() {
+ return (process.env.PUBLIC_APP_URL || 'http://localhost:3000').replace(/\/$/, '');
+}
+
+/** Recipient emails: explicit list from settings, else every org member. */
+async function resolveRecipients(organizationId, settings) {
+ if (settings?.recipients?.length) return settings.recipients;
+
+ const { data: members } = await supabaseAdmin
+ .from('profiles')
+ .select('id')
+ .eq('organization_id', organizationId);
+
+ const emails = [];
+ for (const member of members ?? []) {
+ const { data: authUser } = await supabaseAdmin.auth.admin.getUserById(member.id);
+ if (authUser?.user?.email) emails.push(authUser.user.email);
+ }
+ return emails;
+}
+
+/** Warning keys already sent for this brand in the last 7 days. */
+async function recentWarningKeys(brandId, now) {
+ const since = new Date(now.getTime() - 7 * 86_400_000).toISOString();
+ const { data } = await supabaseAdmin
+ .from('sent_pulses')
+ .select('warning_keys')
+ .eq('brand_id', brandId)
+ .gte('created_at', since);
+ const keys = new Set();
+ for (const row of data ?? []) {
+ for (const key of row.warning_keys ?? []) keys.add(key);
+ }
+ return keys;
+}
+
+export async function generatePulseForBrand(brandId) {
+ try {
+ const now = new Date();
+ const pulseDate = now.toISOString().slice(0, 10);
+
+ const { data: brand } = await supabaseAdmin
+ .from('brands')
+ .select('id, name, organization_id, is_active')
+ .eq('id', brandId)
+ .single();
+ if (!brand?.is_active) return { skipped: 'brand_inactive' };
+
+ // Hard requirement: never generate for orgs without an active or
+ // trialing subscription (self-host always passes — isSubscriptionActive
+ // short-circuits when not cloud).
+ const { data: org } = await supabaseAdmin
+ .from('organizations')
+ .select('subscription_status')
+ .eq('id', brand.organization_id)
+ .single();
+ if (!isSubscriptionActive(org?.subscription_status)) {
+ return { skipped: 'subscription_inactive' };
+ }
+
+ const { data: settings } = await supabaseAdmin
+ .from('pulse_settings')
+ .select('frequency, recipients')
+ .eq('brand_id', brandId)
+ .maybeSingle();
+ const frequency = settings?.frequency ?? 'daily';
+
+ if (frequency === 'off') return { skipped: 'off' };
+ if (frequency === 'weekly' && now.getUTCDay() !== WEEKLY_SEND_UTC_DAY) {
+ return { skipped: 'not_weekly_day' };
+ }
+
+ // Dedup: at most one pulse per brand per day.
+ const { data: existing } = await supabaseAdmin
+ .from('sent_pulses')
+ .select('id')
+ .eq('brand_id', brandId)
+ .eq('pulse_date', pulseDate)
+ .maybeSingle();
+ if (existing) return { skipped: 'already_sent' };
+
+ const windowDays = frequency === 'weekly' ? 7 : 1;
+ const metrics = await computePulseMetrics(brandId, { windowDays, now });
+
+ // Skip brands with no fresh tracking results in the window.
+ if (metrics.kpis.totalResults === 0) return { skipped: 'no_fresh_results' };
+
+ // Warning cooldown: don't repeat the same warning for the same subject
+ // within 7 days.
+ const cooldown = await recentWarningKeys(brandId, now);
+ metrics.warnings = metrics.warnings.filter((w) => !cooldown.has(w.key));
+
+ if (frequency === 'notable' && !metrics.highlights.length && !metrics.warnings.length) {
+ return { skipped: 'nothing_notable' };
+ }
+
+ // Record first — the unique (brand_id, pulse_date) constraint makes
+ // this the race-safe claim on "today's pulse".
+ const { data: pulseRow, error: insertError } = await supabaseAdmin
+ .from('sent_pulses')
+ .insert({
+ brand_id: brandId,
+ pulse_date: pulseDate,
+ frequency,
+ payload: metrics,
+ warning_keys: metrics.warnings.map((w) => w.key),
+ })
+ .select('id')
+ .single();
+ if (insertError) {
+ // 23505 = another worker claimed today's pulse between our check and
+ // this insert.
+ if (insertError.code === '23505') return { skipped: 'already_sent' };
+ throw new Error(insertError.message);
+ }
+
+ const insightsUrl = `${appUrl()}/dashboard/insights`;
+ const settingsUrl = `${appUrl()}/dashboard/settings?tab=notifications`;
+
+ // Email leg — cloud only.
+ let emailSent = false;
+ let recipientCount = 0;
+ if (isCloud()) {
+ const recipients = await resolveRecipients(brand.organization_id, settings);
+ recipientCount = recipients.length;
+ if (recipients.length) {
+ const { subject, html } = renderPulseEmail({
+ brandName: brand.name,
+ metrics,
+ insightsUrl,
+ settingsUrl,
+ });
+ emailSent = await sendPulseEmail({ to: recipients, subject, html, settingsUrl });
+ }
+ }
+
+ // Webhook leg — cloud and self-host alike.
+ const { sent } = await dispatchBrandWebhook(brandId, {
+ event: 'daily_pulse.created',
+ brand: { id: brand.id, name: brand.name },
+ pulse: {
+ date: pulseDate,
+ frequency,
+ kpis: metrics.kpis,
+ highlights: metrics.highlights,
+ warnings: metrics.warnings,
+ degraded_platforms: metrics.degradedPlatforms,
+ insights_url: insightsUrl,
+ },
+ });
+
+ await supabaseAdmin
+ .from('sent_pulses')
+ .update({
+ email_sent: emailSent,
+ email_recipient_count: emailSent ? recipientCount : 0,
+ webhook_sent: sent > 0,
+ })
+ .eq('id', pulseRow.id);
+
+ logger.info(
+ { brandId, pulseDate, frequency, emailSent, recipientCount, webhooksSent: sent },
+ 'daily pulse generated',
+ );
+ return { generated: true, emailSent, webhooksSent: sent };
+ } catch (err) {
+ logger.error({ err, brandId }, 'daily pulse generation failed');
+ return { error: true };
+ }
+}
diff --git a/server/src/lib/pulse/metrics.js b/server/src/lib/pulse/metrics.js
new file mode 100644
index 000000000..7e339a2a4
--- /dev/null
+++ b/server/src/lib/pulse/metrics.js
@@ -0,0 +1,450 @@
+import supabaseAdmin from '../../config/supabase.js';
+
+/**
+ * Daily Pulse metric computation (#540).
+ *
+ * Everything here reads through the same RPCs the Insights dashboard uses
+ * (visible_prompt_stats, tracked_prompt_count, insights_aggregates,
+ * competitor_aggregates, prompt_performance_aggregates) with the same
+ * rounding, so the email and the dashboard always agree for the same
+ * window. Pure computation — no sending, no persistence.
+ */
+
+const DAY_MS = 86_400_000;
+
+// Detector thresholds (issue #540 v1 scope).
+const DROP_MIN_POINTS = 15;
+const DROP_MIN_RELATIVE = 0.3;
+const DROP_MIN_PROMPTS = 10;
+const SURGE_MIN_POINTS = 15;
+const LOST_CITED_RATIO = 0.6;
+const LOST_CONSECUTIVE_DAYS = 3;
+const MOVER_MIN_GAIN = 5;
+const MOVER_LIMIT = 3;
+// A platform is considered degraded (data-collection incident, not a real
+// visibility change) when its result volume across ALL orgs collapses below
+// this fraction of its trailing 7-day daily average.
+const OUTAGE_COLLAPSE_RATIO = 0.25;
+const OUTAGE_MIN_BASELINE = 20;
+
+// Cloro scraper platforms, as stored in prompt_results.platform. Keep in
+// sync with SCRAPER_TASK_TYPES in ../cloro-scraper.js (minus shopping,
+// which is excluded from Insights per #155).
+const TRACKED_PLATFORMS = [
+ 'chatgpt-web',
+ 'google-aio',
+ 'google-aimode',
+ 'copilot-web',
+ 'grok-web',
+ 'perplexity-web',
+ 'gemini-web',
+];
+
+/** Same rounding as the Insights headline: one decimal. */
+function rateOf(visible, prompts) {
+ if (!prompts) return 0;
+ return Math.round((visible / prompts) * 1000) / 10;
+}
+
+function round1(n) {
+ return Math.round(n * 10) / 10;
+}
+
+async function rpc(name, params) {
+ const { data, error } = await supabaseAdmin.rpc(name, params);
+ if (error) throw new Error(`${name} failed: ${error.message}`);
+ return data;
+}
+
+async function visibilityRate(brandId, from, to) {
+ const params = {
+ p_brand_id: brandId,
+ p_date_from: from.toISOString(),
+ p_date_to: to.toISOString(),
+ };
+ const [stats, tracked] = await Promise.all([
+ rpc('visible_prompt_stats', params),
+ rpc('tracked_prompt_count', params),
+ ]);
+ const visible = stats?.visible_prompts ?? 0;
+ const total = tracked ?? 0;
+ return { visible, total, rate: rateOf(visible, total) };
+}
+
+async function insightsWindow(brandId, from, to) {
+ const agg = await rpc('insights_aggregates', {
+ p_brand_id: brandId,
+ p_date_from: from.toISOString(),
+ p_date_to: to.toISOString(),
+ });
+ const mentioning = agg?.mentioning_results ?? 0;
+ return {
+ totalResults: agg?.total_results ?? 0,
+ mentions: agg?.total_mentions ?? 0,
+ citations: agg?.total_citations ?? 0,
+ sentimentPct: mentioning > 0 ? Math.round(((agg?.positive_count ?? 0) / mentioning) * 100) : 0,
+ };
+}
+
+async function competitorRates(brandId, from, to) {
+ const agg = await rpc('competitor_aggregates', {
+ p_brand_id: brandId,
+ p_date_from: from.toISOString(),
+ p_date_to: to.toISOString(),
+ });
+ // Shared denominator, same as getCompetitorComparison in the web app.
+ const promptCount = agg?.brand_prompt_count ?? 0;
+ const brandRate = rateOf(agg?.brand_visible_prompts ?? 0, promptCount);
+ const competitors = new Map();
+ for (const c of agg?.by_competitor ?? []) {
+ competitors.set(c.competitor_id, {
+ id: c.competitor_id,
+ name: c.name,
+ rate: rateOf(c.visible_prompts ?? 0, promptCount),
+ });
+ }
+ return { brandRate, competitors };
+}
+
+async function promptAverages(brandId, from, to) {
+ const rows = await rpc('prompt_performance_aggregates', {
+ p_brand_id: brandId,
+ p_date_from: from.toISOString(),
+ p_date_to: to.toISOString(),
+ });
+ const map = new Map();
+ for (const row of rows ?? []) {
+ if (!row.result_count) continue;
+ map.set(row.prompt_id, {
+ text: row.prompt_text,
+ avg: round1((row.sum_visibility ?? 0) / row.result_count),
+ });
+ }
+ return map;
+}
+
+/** All prompt ids (and texts) belonging to a brand. */
+async function brandPrompts(brandId) {
+ const { data: sets } = await supabaseAdmin
+ .from('prompt_sets')
+ .select('id')
+ .eq('brand_id', brandId);
+ const setIds = (sets ?? []).map((s) => s.id);
+ if (!setIds.length) return [];
+ const { data: prompts } = await supabaseAdmin
+ .from('prompts')
+ .select('id, text')
+ .in('prompt_set_id', setIds);
+ return prompts ?? [];
+}
+
+/** Target URLs cited for the first time inside the window. */
+async function firstTimeCitations(promptById, from) {
+ const promptIds = [...promptById.keys()];
+ if (!promptIds.length) return [];
+ const { data } = await supabaseAdmin
+ .from('prompt_target_urls')
+ .select('url, label, prompt_id, first_cited_at')
+ .in('prompt_id', promptIds)
+ .gte('first_cited_at', from.toISOString())
+ .order('first_cited_at', { ascending: false })
+ .limit(5);
+ return (data ?? []).map((row) => ({
+ url: row.url,
+ label: row.label,
+ promptText: promptById.get(row.prompt_id)?.text ?? '',
+ }));
+}
+
+/** Platforms where the brand became visible for the first time ever. */
+async function newEngineAppearances(brandId, from) {
+ const { data: recent } = await supabaseAdmin
+ .from('prompt_results')
+ .select('platform')
+ .eq('brand_id', brandId)
+ .neq('platform', 'chatgpt-shopping')
+ .gte('created_at', from.toISOString())
+ .or('mention_count.gt.0,citation_count.gt.0')
+ .limit(1000);
+ const platforms = [...new Set((recent ?? []).map((r) => r.platform).filter(Boolean))];
+ const firsts = [];
+ for (const platform of platforms) {
+ const { count } = await supabaseAdmin
+ .from('prompt_results')
+ .select('id', { count: 'exact', head: true })
+ .eq('brand_id', brandId)
+ .eq('platform', platform)
+ .lt('created_at', from.toISOString())
+ .or('mention_count.gt.0,citation_count.gt.0');
+ if (!count) firsts.push(platform);
+ }
+ return firsts;
+}
+
+/**
+ * High-volume prompts that stopped being cited: cited on >= 60% of the
+ * days with results over the last 14 days, but 0 citations on the most
+ * recent 3 result-days. "Runs" are bucketed per UTC day because a daily
+ * run inserts one row per platform.
+ */
+async function lostCitationPrompts(brandId, promptById, now) {
+ const promptIds = [...promptById.keys()];
+ if (!promptIds.length) return [];
+ const { data: volumes } = await supabaseAdmin
+ .from('prompt_volumes')
+ .select('prompt_id')
+ .in('prompt_id', promptIds)
+ .gt('est_ai_volume', 0);
+ const volumeIds = (volumes ?? []).map((v) => v.prompt_id);
+ if (!volumeIds.length) return [];
+
+ const since = new Date(now.getTime() - 14 * DAY_MS).toISOString();
+ const PAGE = 1000;
+ const rows = [];
+ for (let pageStart = 0; pageStart < 20000; pageStart += PAGE) {
+ const { data: page, error } = await supabaseAdmin
+ .from('prompt_results')
+ .select('prompt_id, citation_count, created_at')
+ .eq('brand_id', brandId)
+ .neq('platform', 'chatgpt-shopping')
+ .in('prompt_id', volumeIds)
+ .gte('created_at', since)
+ .order('created_at', { ascending: true })
+ .range(pageStart, pageStart + PAGE - 1);
+ if (error) throw new Error(`lost-citations scan failed: ${error.message}`);
+ rows.push(...(page ?? []));
+ if (!page || page.length < PAGE) break;
+ }
+
+ const byPrompt = new Map();
+ for (const row of rows) {
+ if (!row.prompt_id) continue;
+ const day = row.created_at.slice(0, 10);
+ const days = byPrompt.get(row.prompt_id) ?? new Map();
+ days.set(day, (days.get(day) ?? false) || (row.citation_count ?? 0) > 0);
+ byPrompt.set(row.prompt_id, days);
+ }
+
+ const lost = [];
+ for (const [promptId, days] of byPrompt) {
+ const ordered = [...days.entries()].sort(([a], [b]) => a.localeCompare(b));
+ if (ordered.length < LOST_CONSECUTIVE_DAYS + 2) continue;
+ const tail = ordered.slice(-LOST_CONSECUTIVE_DAYS);
+ if (tail.some(([, cited]) => cited)) continue;
+ const head = ordered.slice(0, -LOST_CONSECUTIVE_DAYS);
+ const citedDays = head.filter(([, cited]) => cited).length;
+ if (citedDays / head.length >= LOST_CITED_RATIO) {
+ lost.push({ promptId, promptText: promptById.get(promptId)?.text ?? '' });
+ }
+ }
+ return lost;
+}
+
+/**
+ * Platform-outage guard: platforms whose result volume across ALL orgs
+ * collapsed today vs their trailing 7-day daily average — a
+ * data-collection incident on our side, not a real visibility change.
+ */
+async function degradedPlatforms(now) {
+ const dayAgo = new Date(now.getTime() - DAY_MS).toISOString();
+ const weekAgo = new Date(now.getTime() - 8 * DAY_MS).toISOString();
+ const degraded = [];
+ for (const platform of TRACKED_PLATFORMS) {
+ const [{ count: today }, { count: baseline }] = await Promise.all([
+ supabaseAdmin
+ .from('prompt_results')
+ .select('id', { count: 'exact', head: true })
+ .eq('platform', platform)
+ .gte('created_at', dayAgo),
+ supabaseAdmin
+ .from('prompt_results')
+ .select('id', { count: 'exact', head: true })
+ .eq('platform', platform)
+ .gte('created_at', weekAgo)
+ .lt('created_at', dayAgo),
+ ]);
+ const dailyBaseline = (baseline ?? 0) / 7;
+ if (
+ dailyBaseline >= OUTAGE_MIN_BASELINE &&
+ (today ?? 0) < dailyBaseline * OUTAGE_COLLAPSE_RATIO
+ ) {
+ degraded.push(platform);
+ }
+ }
+ return degraded;
+}
+
+/**
+ * Compute the full pulse payload for a brand.
+ *
+ * @param {string} brandId
+ * @param {{ windowDays?: number, now?: Date }} [options] windowDays is 1 for
+ * daily pulses, 7 for weekly ones — it stretches the KPI comparison
+ * windows, while the detector windows (7d vs previous 7d, 14d citation
+ * history) stay fixed per the issue spec.
+ */
+export async function computePulseMetrics(brandId, { windowDays = 1, now = new Date() } = {}) {
+ const curFrom = new Date(now.getTime() - windowDays * DAY_MS);
+ const prevFrom = new Date(now.getTime() - 2 * windowDays * DAY_MS);
+ const weekFrom = new Date(now.getTime() - 7 * DAY_MS);
+ const twoWeekFrom = new Date(now.getTime() - 14 * DAY_MS);
+
+ const prompts = await brandPrompts(brandId);
+ const promptById = new Map(prompts.map((p) => [p.id, p]));
+
+ const [
+ curRate,
+ weekRate,
+ prevWeekRate,
+ curInsights,
+ prevInsights,
+ weekComp,
+ prevWeekComp,
+ weekPromptAvg,
+ prevWeekPromptAvg,
+ firstCited,
+ newEngines,
+ lostCitations,
+ degraded,
+ ] = await Promise.all([
+ visibilityRate(brandId, curFrom, now),
+ visibilityRate(brandId, weekFrom, now),
+ visibilityRate(brandId, twoWeekFrom, weekFrom),
+ insightsWindow(brandId, curFrom, now),
+ insightsWindow(brandId, prevFrom, curFrom),
+ competitorRates(brandId, weekFrom, now),
+ competitorRates(brandId, twoWeekFrom, weekFrom),
+ promptAverages(brandId, weekFrom, now),
+ promptAverages(brandId, twoWeekFrom, weekFrom),
+ firstTimeCitations(promptById, curFrom),
+ newEngineAppearances(brandId, curFrom),
+ lostCitationPrompts(brandId, promptById, now),
+ degradedPlatforms(now),
+ ]);
+
+ const kpis = {
+ visibilityRate: curRate.rate,
+ visiblePrompts: curRate.visible,
+ promptCount: curRate.total,
+ weekRate: weekRate.rate,
+ prevWeekRate: prevWeekRate.rate,
+ weekTrend: round1(weekRate.rate - prevWeekRate.rate),
+ mentions: curInsights.mentions,
+ mentionsChange: curInsights.mentions - prevInsights.mentions,
+ citations: curInsights.citations,
+ citationsChange: curInsights.citations - prevInsights.citations,
+ sentimentPct: curInsights.sentimentPct,
+ sentimentChange: curInsights.sentimentPct - prevInsights.sentimentPct,
+ totalResults: curInsights.totalResults,
+ };
+
+ // ── Highlights ─────────────────────────────────────────────────────────
+ const highlights = [];
+ for (const cite of firstCited) {
+ highlights.push({
+ type: 'first_citation',
+ key: `first_citation:${cite.url}`,
+ url: cite.url,
+ label: cite.label,
+ promptText: cite.promptText,
+ });
+ }
+
+ const movers = [];
+ for (const [promptId, cur] of weekPromptAvg) {
+ const prev = prevWeekPromptAvg.get(promptId);
+ if (!prev) continue;
+ const gain = round1(cur.avg - prev.avg);
+ if (gain >= MOVER_MIN_GAIN) movers.push({ promptId, text: cur.text, gain });
+ }
+ movers.sort((a, b) => b.gain - a.gain);
+ for (const mover of movers.slice(0, MOVER_LIMIT)) {
+ highlights.push({
+ type: 'prompt_gain',
+ key: `prompt_gain:${mover.promptId}`,
+ promptText: mover.text,
+ gain: mover.gain,
+ });
+ }
+
+ for (const [id, comp] of weekComp.competitors) {
+ const prev = prevWeekComp.competitors.get(id);
+ if (!prev) continue;
+ if (prevWeekComp.brandRate <= prev.rate && weekComp.brandRate > comp.rate) {
+ highlights.push({
+ type: 'competitor_overtaken',
+ key: `competitor_overtaken:${id}`,
+ competitorName: comp.name,
+ brandRate: weekComp.brandRate,
+ competitorRate: comp.rate,
+ });
+ }
+ }
+
+ for (const platform of newEngines) {
+ highlights.push({ type: 'new_engine', key: `new_engine:${platform}`, platform });
+ }
+
+ // ── Warnings ───────────────────────────────────────────────────────────
+ const warnings = [];
+ const outage = degraded.length > 0;
+
+ const drop = round1(prevWeekRate.rate - weekRate.rate);
+ if (
+ !outage &&
+ weekRate.total >= DROP_MIN_PROMPTS &&
+ drop >= DROP_MIN_POINTS &&
+ prevWeekRate.rate > 0 &&
+ drop / prevWeekRate.rate >= DROP_MIN_RELATIVE
+ ) {
+ warnings.push({
+ type: 'sharp_drop',
+ key: 'sharp_drop',
+ from: prevWeekRate.rate,
+ to: weekRate.rate,
+ drop,
+ });
+ }
+
+ for (const [id, comp] of weekComp.competitors) {
+ const prev = prevWeekComp.competitors.get(id);
+ if (!prev) continue;
+ const surge = round1(comp.rate - prev.rate);
+ if (surge >= SURGE_MIN_POINTS) {
+ warnings.push({
+ type: 'competitor_surge',
+ key: `competitor_surge:${id}`,
+ competitorName: comp.name,
+ from: prev.rate,
+ to: comp.rate,
+ });
+ } else if (prev.rate <= prevWeekComp.brandRate && comp.rate > weekComp.brandRate) {
+ warnings.push({
+ type: 'competitor_crossed',
+ key: `competitor_crossed:${id}`,
+ competitorName: comp.name,
+ competitorRate: comp.rate,
+ brandRate: weekComp.brandRate,
+ });
+ }
+ }
+
+ if (!outage) {
+ for (const lost of lostCitations) {
+ warnings.push({
+ type: 'lost_citations',
+ key: `lost_citations:${lost.promptId}`,
+ promptText: lost.promptText,
+ });
+ }
+ }
+
+ return {
+ windowDays,
+ computedAt: now.toISOString(),
+ kpis,
+ highlights,
+ warnings,
+ degradedPlatforms: degraded,
+ };
+}
diff --git a/server/src/lib/webhook-dispatch.js b/server/src/lib/webhook-dispatch.js
new file mode 100644
index 000000000..f8137d575
--- /dev/null
+++ b/server/src/lib/webhook-dispatch.js
@@ -0,0 +1,58 @@
+import supabaseAdmin from '../config/supabase.js';
+import { logger } from './logger.js';
+
+/**
+ * Deliver an event payload to a brand's active webhook configs.
+ *
+ * Same wire format as the Content Optimization send routes: a flat JSON
+ * payload with an `event` field, plus the shared secret echoed in the
+ * `X-Webhook-Secret` header when one is configured. Delivery is
+ * best-effort — failures are logged, never thrown.
+ *
+ * Returns { sent, failed } delivery counts.
+ */
+export async function dispatchBrandWebhook(brandId, payload) {
+ const { data: configs } = await supabaseAdmin
+ .from('webhook_configs')
+ .select('id, webhook_url, webhook_secret')
+ .eq('brand_id', brandId)
+ .eq('is_active', true);
+
+ if (!configs?.length) return { sent: 0, failed: 0 };
+
+ let sent = 0;
+ let failed = 0;
+
+ for (const config of configs) {
+ const headers = { 'Content-Type': 'application/json' };
+ if (config.webhook_secret) {
+ headers['X-Webhook-Secret'] = config.webhook_secret;
+ }
+
+ try {
+ const res = await fetch(config.webhook_url, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(15000),
+ });
+ if (res.ok) {
+ sent++;
+ } else {
+ failed++;
+ logger.warn(
+ { brandId, configId: config.id, status: res.status, event: payload?.event },
+ 'webhook delivery got non-2xx response',
+ );
+ }
+ } catch (err) {
+ failed++;
+ logger.warn(
+ { err, brandId, configId: config.id, event: payload?.event },
+ 'webhook delivery failed',
+ );
+ }
+ }
+
+ return { sent, failed };
+}
diff --git a/server/src/scripts/test-pulse.js b/server/src/scripts/test-pulse.js
new file mode 100644
index 000000000..2c827b06c
--- /dev/null
+++ b/server/src/scripts/test-pulse.js
@@ -0,0 +1,16 @@
+/**
+ * One-off manual test for the Daily Pulse engine (#540).
+ * Run: node src/scripts/test-pulse.js <brandId>
+ */
+import 'dotenv/config';
+import { generatePulseForBrand } from '../lib/pulse/engine.js';
+
+const brandId = process.argv[2];
+if (!brandId) {
+ console.error('Usage: node src/scripts/test-pulse.js <brandId>');
+ process.exit(1);
+}
+
+const result = await generatePulseForBrand(brandId);
+console.log(JSON.stringify(result, null, 2));
+process.exit(0);
diff --git a/supabase/migrations/00036_daily_pulse.sql b/supabase/migrations/00036_daily_pulse.sql
new file mode 100644
index 000000000..b595c74a8
--- /dev/null
+++ b/supabase/migrations/00036_daily_pulse.sql
@@ -0,0 +1,103 @@
+-- 00036_daily_pulse.sql
+-- Daily Pulse (#540): per-brand daily digest sent after the tracking run.
+--
+-- pulse_settings — per-brand delivery preferences (frequency + recipients).
+-- sent_pulses — send log: dedup ("already sent today"), the content
+-- snapshot that went out, and the warning keys used for the
+-- 7-day warning cooldown.
+--
+-- All writes go through the Express server's service-role client; RLS below
+-- covers the web app's direct reads plus settings writes by admin/manager.
+
+CREATE TABLE IF NOT EXISTS "public"."pulse_settings" (
+ "brand_id" "uuid" NOT NULL,
+ "frequency" "text" DEFAULT 'daily'::"text" NOT NULL,
+ "recipients" "text"[],
+ "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ CONSTRAINT "pulse_settings_pkey" PRIMARY KEY ("brand_id"),
+ CONSTRAINT "pulse_settings_frequency_check" CHECK (
+ "frequency" = ANY (ARRAY['daily'::"text", 'weekly'::"text", 'notable'::"text", 'off'::"text"])
+ ),
+ CONSTRAINT "pulse_settings_brand_id_fkey" FOREIGN KEY ("brand_id")
+ REFERENCES "public"."brands"("id") ON DELETE CASCADE
+);
+
+ALTER TABLE "public"."pulse_settings" OWNER TO "postgres";
+
+CREATE TABLE IF NOT EXISTS "public"."sent_pulses" (
+ "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
+ "brand_id" "uuid" NOT NULL,
+ "pulse_date" "date" NOT NULL,
+ "frequency" "text" NOT NULL,
+ "payload" "jsonb" DEFAULT '{}'::"jsonb" NOT NULL,
+ "warning_keys" "text"[] DEFAULT '{}'::"text"[] NOT NULL,
+ "email_sent" boolean DEFAULT false NOT NULL,
+ "email_recipient_count" integer DEFAULT 0 NOT NULL,
+ "webhook_sent" boolean DEFAULT false NOT NULL,
+ "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ CONSTRAINT "sent_pulses_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "sent_pulses_brand_id_fkey" FOREIGN KEY ("brand_id")
+ REFERENCES "public"."brands"("id") ON DELETE CASCADE,
+ CONSTRAINT "sent_pulses_brand_date_key" UNIQUE ("brand_id", "pulse_date")
+);
+
+ALTER TABLE "public"."sent_pulses" OWNER TO "postgres";
+
+CREATE INDEX IF NOT EXISTS "idx_sent_pulses_brand_created"
+ ON "public"."sent_pulses" ("brand_id", "created_at" DESC);
+
+ALTER TABLE "public"."pulse_settings" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "public"."sent_pulses" ENABLE ROW LEVEL SECURITY;
+
+-- Same policy shape as topic_suggestions: every org member can read;
+-- admin/manager can change delivery preferences from Settings.
+CREATE POLICY "pulse_settings: member select" ON "public"."pulse_settings"
+ FOR SELECT USING (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ )
+ );
+
+CREATE POLICY "pulse_settings: admin/manager insert" ON "public"."pulse_settings"
+ FOR INSERT WITH CHECK (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ AND "p"."role" = ANY (ARRAY['admin'::"public"."user_role", 'manager'::"public"."user_role"])
+ )
+ );
+
+CREATE POLICY "pulse_settings: admin/manager update" ON "public"."pulse_settings"
+ FOR UPDATE USING (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ AND "p"."role" = ANY (ARRAY['admin'::"public"."user_role", 'manager'::"public"."user_role"])
+ )
+ );
+
+CREATE POLICY "sent_pulses: member select" ON "public"."sent_pulses"
+ FOR SELECT USING (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ )
+ );
+
+GRANT ALL ON TABLE "public"."pulse_settings" TO "anon";
+GRANT ALL ON TABLE "public"."pulse_settings" TO "authenticated";
+GRANT ALL ON TABLE "public"."pulse_settings" TO "service_role";
+
+GRANT ALL ON TABLE "public"."sent_pulses" TO "anon";
+GRANT ALL ON TABLE "public"."sent_pulses" TO "authenticated";
+GRANT ALL ON TABLE "public"."sent_pulses" TO "service_role";
diff --git a/supabase/schema.sql b/supabase/schema.sql
index cbf3da905..ecc9249a2 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -4080,3 +4080,110 @@ AS $$
FROM brand_totals b;
$$;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00036_daily_pulse.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- 00036_daily_pulse.sql
+-- Daily Pulse (#540): per-brand daily digest sent after the tracking run.
+--
+-- pulse_settings — per-brand delivery preferences (frequency + recipients).
+-- sent_pulses — send log: dedup ("already sent today"), the content
+-- snapshot that went out, and the warning keys used for the
+-- 7-day warning cooldown.
+--
+-- All writes go through the Express server's service-role client; RLS below
+-- covers the web app's direct reads plus settings writes by admin/manager.
+
+CREATE TABLE IF NOT EXISTS "public"."pulse_settings" (
+ "brand_id" "uuid" NOT NULL,
+ "frequency" "text" DEFAULT 'daily'::"text" NOT NULL,
+ "recipients" "text"[],
+ "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ CONSTRAINT "pulse_settings_pkey" PRIMARY KEY ("brand_id"),
+ CONSTRAINT "pulse_settings_frequency_check" CHECK (
+ "frequency" = ANY (ARRAY['daily'::"text", 'weekly'::"text", 'notable'::"text", 'off'::"text"])
+ ),
+ CONSTRAINT "pulse_settings_brand_id_fkey" FOREIGN KEY ("brand_id")
+ REFERENCES "public"."brands"("id") ON DELETE CASCADE
+);
+
+ALTER TABLE "public"."pulse_settings" OWNER TO "postgres";
+
+CREATE TABLE IF NOT EXISTS "public"."sent_pulses" (
+ "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
+ "brand_id" "uuid" NOT NULL,
+ "pulse_date" "date" NOT NULL,
+ "frequency" "text" NOT NULL,
+ "payload" "jsonb" DEFAULT '{}'::"jsonb" NOT NULL,
+ "warning_keys" "text"[] DEFAULT '{}'::"text"[] NOT NULL,
+ "email_sent" boolean DEFAULT false NOT NULL,
+ "email_recipient_count" integer DEFAULT 0 NOT NULL,
+ "webhook_sent" boolean DEFAULT false NOT NULL,
+ "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ CONSTRAINT "sent_pulses_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "sent_pulses_brand_id_fkey" FOREIGN KEY ("brand_id")
+ REFERENCES "public"."brands"("id") ON DELETE CASCADE,
+ CONSTRAINT "sent_pulses_brand_date_key" UNIQUE ("brand_id", "pulse_date")
+);
+
+ALTER TABLE "public"."sent_pulses" OWNER TO "postgres";
+
+CREATE INDEX IF NOT EXISTS "idx_sent_pulses_brand_created"
+ ON "public"."sent_pulses" ("brand_id", "created_at" DESC);
+
+ALTER TABLE "public"."pulse_settings" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "public"."sent_pulses" ENABLE ROW LEVEL SECURITY;
+
+-- Same policy shape as topic_suggestions: every org member can read;
+-- admin/manager can change delivery preferences from Settings.
+CREATE POLICY "pulse_settings: member select" ON "public"."pulse_settings"
+ FOR SELECT USING (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ )
+ );
+
+CREATE POLICY "pulse_settings: admin/manager insert" ON "public"."pulse_settings"
+ FOR INSERT WITH CHECK (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ AND "p"."role" = ANY (ARRAY['admin'::"public"."user_role", 'manager'::"public"."user_role"])
+ )
+ );
+
+CREATE POLICY "pulse_settings: admin/manager update" ON "public"."pulse_settings"
+ FOR UPDATE USING (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ AND "p"."role" = ANY (ARRAY['admin'::"public"."user_role", 'manager'::"public"."user_role"])
+ )
+ );
+
+CREATE POLICY "sent_pulses: member select" ON "public"."sent_pulses"
+ FOR SELECT USING (
+ "brand_id" IN (
+ SELECT "b"."id"
+ FROM "public"."brands" "b"
+ JOIN "public"."profiles" "p" ON "p"."organization_id" = "b"."organization_id"
+ WHERE "p"."id" = "auth"."uid"()
+ )
+ );
+
+GRANT ALL ON TABLE "public"."pulse_settings" TO "anon";
+GRANT ALL ON TABLE "public"."pulse_settings" TO "authenticated";
+GRANT ALL ON TABLE "public"."pulse_settings" TO "service_role";
+
+GRANT ALL ON TABLE "public"."sent_pulses" TO "anon";
+GRANT ALL ON TABLE "public"."sent_pulses" TO "authenticated";
+GRANT ALL ON TABLE "public"."sent_pulses" TO "service_role";
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 069efbc5b..b20d83579 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -609,6 +609,19 @@
"project": "Project",
"apiKeys": "API Keys",
"team": "Team",
+ "notifications": "Notifications",
+ "notificationsDescription": "Daily Pulse — a short digest per brand after each tracking run, with highlights and warnings.",
+ "pulseFrequency_daily": "Daily",
+ "pulseFrequency_weekly": "Weekly",
+ "pulseFrequency_notable": "Only when notable",
+ "pulseFrequency_off": "Off",
+ "pulseRecipients": "Recipients",
+ "pulseRecipientsPlaceholder": "[email protected], [email protected]",
+ "pulseRecipientsHint": "Comma-separated email addresses. Leave empty to send to every organization member.",
+ "pulseSaved": "Notification settings saved",
+ "pulseSaveFailed": "Could not save notification settings. Please try again.",
+ "pulseLoadFailed": "Could not load notification settings.",
+ "pulseNoBrands": "No active brands yet — add a brand to configure its Daily Pulse.",
"billing": "Billing",
"danger": "Danger Zone",
"projectName": "Project Name",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx
index 6ecd0e140..324ac84d2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx
@@ -17,8 +17,17 @@ import { BillingSection } from '@/components/settings/billing-section';
import { TeamSection } from '@/components/settings/team-section';
import { ApiKeysSection } from '@/components/settings/api-keys-section';
import { AgentSection } from '@/components/settings/agent-section';
-
-type Section = 'account' | 'theme' | 'project' | 'team' | 'api-keys' | 'agent' | 'billing';
+import { NotificationsSection } from '@/components/settings/notifications-section';
+
+type Section =
+ | 'account'
+ | 'theme'
+ | 'project'
+ | 'team'
+ | 'notifications'
+ | 'api-keys'
+ | 'agent'
+ | 'billing';
export default function SettingsPage() {
const t = useTranslations('settings');
@@ -30,6 +39,8 @@ export default function SettingsPage() {
const [active, setActive] = useState<Section>(() => {
if (tabParam === 'billing' && isCloud) return 'billing';
if (tabParam === 'agent' && isCloud) return 'agent';
+ // Deep-linked from the Daily Pulse email's "manage notifications" footer.
+ if (tabParam === 'notifications') return 'notifications';
return 'account';
});
const [displayName, setDisplayName] = useState('');
@@ -55,6 +66,7 @@ export default function SettingsPage() {
{ id: 'theme', label: t('theme') },
{ id: 'project', label: t('project') },
{ id: 'team', label: t('team') },
+ { id: 'notifications', label: t('notifications') },
{ id: 'api-keys', label: 'API Keys' },
// Agent BYOK is a cloud-only concern — self-host operators configure
// ANTHROPIC_API_KEY in their own env, no UI needed.
@@ -172,6 +184,8 @@ export default function SettingsPage() {
{/* Team */}
{active === 'team' && <TeamSection />}
+ {active === 'notifications' && <NotificationsSection />}
+
{/* API Keys */}
{active === 'api-keys' && <ApiKeysSection />}
diff --git a/web/src/app/api/settings/pulse/route.ts b/web/src/app/api/settings/pulse/route.ts
new file mode 100644
index 000000000..0e64c6df8
--- /dev/null
+++ b/web/src/app/api/settings/pulse/route.ts
@@ -0,0 +1,140 @@
+import { NextResponse } from 'next/server';
+import { createClient } from '@/lib/supabase/server';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+
+/**
+ * GET / PUT /api/settings/pulse
+ *
+ * Daily Pulse delivery preferences (#540), per brand.
+ *
+ * Auth model (same bar as the webhook config RLS):
+ * - GET: any signed-in org member sees each brand's frequency/recipients.
+ * - PUT: admins and managers change them.
+ */
+
+const FREQUENCIES = ['daily', 'weekly', 'notable', 'off'] as const;
+type Frequency = (typeof FREQUENCIES)[number];
+
+async function getCallerAndOrg() {
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) return { error: 'Unauthorized' as const };
+
+ const { data: profile } = await supabase
+ .from('profiles')
+ .select('id, role, organization_id')
+ .eq('id', user.id)
+ .single();
+
+ if (!profile?.organization_id) return { error: 'No organization' as const };
+
+ return {
+ user,
+ profile: profile as { id: string; role: string; organization_id: string },
+ };
+}
+
+export async function GET() {
+ const ctx = await getCallerAndOrg();
+ if ('error' in ctx) {
+ return NextResponse.json(
+ { error: ctx.error },
+ { status: ctx.error === 'Unauthorized' ? 401 : 400 },
+ );
+ }
+
+ const { data: brands, error } = await supabaseAdmin
+ .from('brands')
+ .select('id, name')
+ .eq('organization_id', ctx.profile.organization_id)
+ .eq('is_active', true)
+ .order('created_at', { ascending: true });
+ if (error) {
+ return NextResponse.json({ error: error.message }, { status: 500 });
+ }
+
+ const brandIds = (brands ?? []).map((b) => b.id);
+ const { data: settings } = brandIds.length
+ ? await supabaseAdmin
+ .from('pulse_settings')
+ .select('brand_id, frequency, recipients')
+ .in('brand_id', brandIds)
+ : { data: [] };
+
+ const settingsByBrand = new Map((settings ?? []).map((s) => [s.brand_id, s]));
+
+ return NextResponse.json({
+ brands: (brands ?? []).map((brand) => {
+ const s = settingsByBrand.get(brand.id);
+ return {
+ brandId: brand.id,
+ brandName: brand.name,
+ frequency: s?.frequency ?? 'daily',
+ recipients: s?.recipients ?? [],
+ };
+ }),
+ });
+}
+
+export async function PUT(request: Request) {
+ const ctx = await getCallerAndOrg();
+ if ('error' in ctx) {
+ return NextResponse.json(
+ { error: ctx.error },
+ { status: ctx.error === 'Unauthorized' ? 401 : 400 },
+ );
+ }
+ if (ctx.profile.role !== 'admin' && ctx.profile.role !== 'manager') {
+ return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
+ }
+
+ let body: { brandId?: string; frequency?: string; recipients?: unknown };
+ try {
+ body = await request.json();
+ } catch {
+ return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
+ }
+
+ const { brandId, frequency } = body;
+ if (!brandId || !frequency || !FREQUENCIES.includes(frequency as Frequency)) {
+ return NextResponse.json(
+ { error: 'brandId and a valid frequency are required' },
+ { status: 400 },
+ );
+ }
+
+ const recipients = Array.isArray(body.recipients)
+ ? body.recipients
+ .filter((r): r is string => typeof r === 'string')
+ .map((r) => r.trim())
+ .filter((r) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r))
+ .slice(0, 50)
+ : [];
+
+ // The brand must belong to the caller's org.
+ const { data: brand } = await supabaseAdmin
+ .from('brands')
+ .select('id, organization_id')
+ .eq('id', brandId)
+ .single();
+ if (!brand || brand.organization_id !== ctx.profile.organization_id) {
+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
+ }
+
+ const { error } = await supabaseAdmin.from('pulse_settings').upsert(
+ {
+ brand_id: brandId,
+ frequency,
+ recipients: recipients.length ? recipients : null,
+ updated_at: new Date().toISOString(),
+ },
+ { onConflict: 'brand_id' },
+ );
+ if (error) {
+ return NextResponse.json({ error: error.message }, { status: 500 });
+ }
+
+ return NextResponse.json({ success: true });
+}
diff --git a/web/src/components/settings/notifications-section.tsx b/web/src/components/settings/notifications-section.tsx
new file mode 100644
index 000000000..5749cc930
--- /dev/null
+++ b/web/src/components/settings/notifications-section.tsx
@@ -0,0 +1,168 @@
+'use client';
+
+import { useCallback, useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Loader2 } from 'lucide-react';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Skeleton } from '@/components/ui/skeleton';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { useUserRole } from '@/hooks/use-user-role';
+
+/**
+ * Settings → Notifications: Daily Pulse delivery preferences per brand
+ * (#540). Frequency + optional explicit recipient list; an empty list
+ * means every organization member receives the pulse.
+ */
+
+interface BrandPulseSettings {
+ brandId: string;
+ brandName: string;
+ frequency: string;
+ recipients: string[];
+}
+
+const FREQUENCIES = ['daily', 'weekly', 'notable', 'off'] as const;
+
+export function NotificationsSection() {
+ const t = useTranslations('settings');
+ const { canManage } = useUserRole();
+ const [brands, setBrands] = useState<BrandPulseSettings[]>([]);
+ const [recipientDrafts, setRecipientDrafts] = useState<Record<string, string>>({});
+ const [loading, setLoading] = useState(true);
+ const [savingBrand, setSavingBrand] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await fetch('/api/settings/pulse');
+ const body = (await res.json().catch(() => ({}))) as {
+ brands?: BrandPulseSettings[];
+ error?: string;
+ };
+ if (!res.ok) throw new Error(body.error || 'Failed to load notification settings');
+ const rows = body.brands ?? [];
+ setBrands(rows);
+ setRecipientDrafts(
+ Object.fromEntries(rows.map((row) => [row.brandId, row.recipients.join(', ')])),
+ );
+ } catch {
+ toast.error(t('pulseLoadFailed'));
+ } finally {
+ setLoading(false);
+ }
+ }, [t]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ async function save(brandId: string, frequency: string) {
+ if (savingBrand) return;
+ setSavingBrand(brandId);
+ try {
+ const recipients = (recipientDrafts[brandId] ?? '')
+ .split(',')
+ .map((r) => r.trim())
+ .filter(Boolean);
+ const res = await fetch('/api/settings/pulse', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ brandId, frequency, recipients }),
+ });
+ const body = (await res.json().catch(() => ({}))) as { error?: string };
+ if (!res.ok) throw new Error(body.error || 'Save failed');
+ setBrands((prev) =>
+ prev.map((b) => (b.brandId === brandId ? { ...b, frequency, recipients } : b)),
+ );
+ toast.success(t('pulseSaved'));
+ } catch {
+ toast.error(t('pulseSaveFailed'));
+ } finally {
+ setSavingBrand(null);
+ }
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('notifications')}</CardTitle>
+ <CardDescription>{t('notificationsDescription')}</CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-6">
+ {loading ? (
+ <div className="space-y-3">
+ <Skeleton className="h-16 w-full" />
+ <Skeleton className="h-16 w-full" />
+ </div>
+ ) : brands.length === 0 ? (
+ <p className="text-sm text-muted-foreground">{t('pulseNoBrands')}</p>
+ ) : (
+ brands.map((brand) => (
+ <div key={brand.brandId} className="space-y-3 rounded-md border p-4">
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-sm font-medium">{brand.brandName}</p>
+ <Select
+ value={brand.frequency}
+ onValueChange={(value) => {
+ if (!value) return;
+ setBrands((prev) =>
+ prev.map((b) =>
+ b.brandId === brand.brandId ? { ...b, frequency: value } : b,
+ ),
+ );
+ }}
+ disabled={!canManage}
+ >
+ <SelectTrigger size="sm" className="w-44">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {FREQUENCIES.map((freq) => (
+ <SelectItem key={freq} value={freq}>
+ {t(`pulseFrequency_${freq}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor={`pulse-recipients-${brand.brandId}`}>{t('pulseRecipients')}</Label>
+ <Input
+ id={`pulse-recipients-${brand.brandId}`}
+ value={recipientDrafts[brand.brandId] ?? ''}
+ onChange={(e) =>
+ setRecipientDrafts((prev) => ({ ...prev, [brand.brandId]: e.target.value }))
+ }
+ placeholder={t('pulseRecipientsPlaceholder')}
+ disabled={!canManage}
+ />
+ <p className="text-xs text-muted-foreground">{t('pulseRecipientsHint')}</p>
+ </div>
+ {canManage && (
+ <Button
+ size="sm"
+ onClick={() => save(brand.brandId, brand.frequency)}
+ disabled={savingBrand !== null}
+ className="gap-2"
+ >
+ {savingBrand === brand.brandId && <Loader2 className="h-4 w-4 animate-spin" />}
+ {t('save')}
+ </Button>
+ )}
+ </div>
+ ))
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index b9ca51b0a..c5f584293 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1026,6 +1026,85 @@ export type Database = {
},
];
};
+ pulse_settings: {
+ Row: {
+ brand_id: string;
+ created_at: string;
+ frequency: string;
+ recipients: string[] | null;
+ updated_at: string;
+ };
+ Insert: {
+ brand_id: string;
+ created_at?: string;
+ frequency?: string;
+ recipients?: string[] | null;
+ updated_at?: string;
+ };
+ Update: {
+ brand_id?: string;
+ created_at?: string;
+ frequency?: string;
+ recipients?: string[] | null;
+ updated_at?: string;
+ };
+ Relationships: [
+ {
+ foreignKeyName: 'pulse_settings_brand_id_fkey';
+ columns: ['brand_id'];
+ isOneToOne: true;
+ referencedRelation: 'brands';
+ referencedColumns: ['id'];
+ },
+ ];
+ };
+ sent_pulses: {
+ Row: {
+ brand_id: string;
+ created_at: string;
+ email_recipient_count: number;
+ email_sent: boolean;
+ frequency: string;
+ id: string;
+ payload: Json;
+ pulse_date: string;
+ warning_keys: string[];
+ webhook_sent: boolean;
+ };
+ Insert: {
+ brand_id: string;
+ created_at?: string;
+ email_recipient_count?: number;
+ email_sent?: boolean;
+ frequency: string;
+ id?: string;
+ payload?: Json;
+ pulse_date: string;
+ warning_keys?: string[];
+ webhook_sent?: boolean;
+ };
+ Update: {
+ brand_id?: string;
+ created_at?: string;
+ email_recipient_count?: number;
+ email_sent?: boolean;
+ frequency?: string;
+ id?: string;
+ payload?: Json;
+ pulse_date?: string;
+ warning_keys?: string[];
+ webhook_sent?: boolean;
+ };
+ Relationships: [
+ {
+ foreignKeyName: 'sent_pulses_brand_id_fkey';
+ columns: ['brand_id'];
+ isOneToOne: false;
+ referencedRelation: 'brands';
+ referencedColumns: ['id'];
+ },
+ ];
+ };
reports: {
Row: {
brand_id: string;