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(ops): daily health report email (#949)

Gökhan Geyikbb6041c5f6ad
diff --git a/server/src/lib/email.js b/server/src/lib/email.js
new file mode 100644
index 000000000..164a99d4a
--- /dev/null
+++ b/server/src/lib/email.js
@@ -0,0 +1,33 @@
+import { logger } from './logger.js';
+
+/**
+ * Send one email through the Resend HTTP API (RESEND_API_KEY,
+ * RESEND_FROM_EMAIL). Returns true when accepted. Missing config is a silent
+ * no-op, so self-host and misconfigured environments never fail a caller.
+ */
+export async function sendEmail({ to, subject, html, headers }) {
+ 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 ? { headers } : {}) }),
+ 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/health/report.js b/server/src/lib/health/report.js
new file mode 100644
index 000000000..3a3932381
--- /dev/null
+++ b/server/src/lib/health/report.js
@@ -0,0 +1,257 @@
+/**
+ * Daily health report: one email each morning saying whether the night went
+ * right and whether the dashboard's heaviest reads still fit their budget.
+ *
+ * Reports, never repairs. Each section degrades to a "could not check" line
+ * instead of failing the report, so a broken check still produces an email
+ * — silence would read as "all fine".
+ *
+ * Config (env):
+ * HEALTH_REPORT_RECIPIENTS comma-separated addresses; no email without it
+ * HEALTH_PROBE_BRAND_ID brand whose reads are timed (the largest we own)
+ * HEALTH_PROBE_USER_ID a member of that brand's organization
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+import { logger } from '../logger.js';
+import { sendEmail } from '../email.js';
+
+/** The page reads' statement timeout, and the share of it that warns. */
+export const READ_BUDGET_S = 8;
+export const WARN_AT_S = 4;
+
+/** Reads timed against the probe brand: the page default, then a long window. */
+export const PROBES = [
+ { probe: 'citations_window_stats', days: 1 },
+ { probe: 'citations_domains', days: 1 },
+ { probe: 'citations_urls', days: 1 },
+ { probe: 'citations_domains', days: 30 },
+ { probe: 'citations_urls', days: 30 },
+ { probe: 'insights_aggregates_daily', days: 30 },
+ { probe: 'competitor_aggregates_daily', days: null },
+ { probe: 'topics_overview_aggregates', days: null },
+];
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const STUCK_AFTER_MS = 2 * 60 * 60 * 1000;
+const RESTART_REASON = 'Server restarted during execution';
+
+/** green / yellow / red for one timed read. */
+export function probeStatus(seconds) {
+ if (seconds == null) return 'red';
+ if (seconds >= READ_BUDGET_S) return 'red';
+ if (seconds >= WARN_AT_S) return 'yellow';
+ return 'green';
+}
+
+async function runProbes() {
+ const brandId = process.env.HEALTH_PROBE_BRAND_ID;
+ const userId = process.env.HEALTH_PROBE_USER_ID;
+ if (!brandId || !userId)
+ return { skipped: 'HEALTH_PROBE_BRAND_ID / HEALTH_PROBE_USER_ID not set' };
+
+ const results = [];
+ // One at a time: this runs on the shared database after the nightly runs.
+ for (const { probe, days } of PROBES) {
+ const { data, error } = await supabaseAdmin.rpc('health_probe', {
+ p_user_id: userId,
+ p_brand_id: brandId,
+ p_probe: probe,
+ p_days: days,
+ });
+ const seconds = error ? null : Number(data);
+ results.push({
+ probe,
+ days,
+ seconds,
+ error: error?.message ?? null,
+ status: probeStatus(seconds),
+ });
+ }
+ return { results };
+}
+
+async function brandNames(ids) {
+ if (ids.length === 0) return new Map();
+ const { data } = await supabaseAdmin.from('brands').select('id, name').in('id', ids);
+ return new Map((data ?? []).map((b) => [b.id, b.name]));
+}
+
+/**
+ * The last 24h of nightly (non-manual) tracking jobs, and the brands that ran
+ * nightly in the week before but have no completed run in the last 24h.
+ */
+async function checkNightlyRuns(now) {
+ const since = new Date(now - DAY_MS).toISOString();
+ const weekAgo = new Date(now - 8 * DAY_MS).toISOString();
+
+ const { data: jobs, error } = await supabaseAdmin
+ .from('jobs')
+ .select('id, brand_id, status, failed_reason, created_at, updated_at, data')
+ .eq('type', 'tracking')
+ .gte('created_at', weekAgo);
+ if (error) throw new Error(error.message);
+
+ const nightly = (jobs ?? []).filter((j) => j.data?.immediate !== true);
+ const recent = nightly.filter((j) => j.created_at >= since);
+ const counts = {};
+ for (const j of recent) counts[j.status] = (counts[j.status] ?? 0) + 1;
+
+ const failed = recent.filter((j) => j.status === 'failed');
+ const stuck = recent.filter(
+ (j) =>
+ (j.status === 'waiting' || j.status === 'active') &&
+ now - Date.parse(j.updated_at) > STUCK_AFTER_MS,
+ );
+
+ const ranBefore = new Set(nightly.filter((j) => j.created_at < since).map((j) => j.brand_id));
+ const completedRecently = new Set(
+ recent.filter((j) => j.status === 'completed').map((j) => j.brand_id),
+ );
+ const missing = [...ranBefore].filter((id) => !completedRecently.has(id));
+
+ const names = await brandNames([
+ ...new Set([...failed, ...stuck].map((j) => j.brand_id).concat(missing)),
+ ]);
+ const label = (id) => names.get(id) ?? id;
+
+ return {
+ counts,
+ failed: failed.map((j) => ({ brand: label(j.brand_id), reason: j.failed_reason })),
+ stuck: stuck.map((j) => ({ brand: label(j.brand_id), status: j.status })),
+ missing: missing.map(label),
+ restartKills: failed.filter((j) => j.failed_reason === RESTART_REASON).length,
+ };
+}
+
+async function checkCloro(now) {
+ const { count, error } = await supabaseAdmin
+ .from('cloro_pending_tasks')
+ .select('task_id', { count: 'exact', head: true })
+ .lt('submitted_at', new Date(now - 60 * 60 * 1000).toISOString());
+ if (error) throw new Error(error.message);
+ return { pendingOverAnHour: count ?? 0 };
+}
+
+async function section(name, fn) {
+ try {
+ return await fn();
+ } catch (err) {
+ logger.error({ err, section: name }, '[health] check failed');
+ return { error: err.message };
+ }
+}
+
+export async function collectHealthReport(now = Date.now()) {
+ const probes = await section('probes', runProbes);
+ const nightly = await section('nightly', () => checkNightlyRuns(now));
+ const cloro = await section('cloro', () => checkCloro(now));
+ return {
+ generatedAt: new Date(now).toISOString(),
+ serverUptimeHours: Math.round((process.uptime() / 3600) * 10) / 10,
+ probes,
+ nightly,
+ cloro,
+ };
+}
+
+/** Problems worth a person's attention, as short lines. Empty means all clear. */
+export function findIssues(report) {
+ const issues = [];
+ const { probes, nightly, cloro } = report;
+
+ if (probes.error) issues.push(`Read probes could not run: ${probes.error}`);
+ for (const r of probes.results ?? []) {
+ if (r.status === 'green') continue;
+ const window = r.days == null ? 'all time' : `${r.days}d`;
+ issues.push(
+ r.seconds == null
+ ? `${r.probe} (${window}) failed: ${r.error}`
+ : `${r.probe} (${window}) took ${r.seconds}s of its ${READ_BUDGET_S}s budget`,
+ );
+ }
+
+ if (nightly.error) issues.push(`Nightly runs could not be checked: ${nightly.error}`);
+ if (nightly.failed?.length) issues.push(`${nightly.failed.length} nightly run(s) failed`);
+ if (nightly.stuck?.length) issues.push(`${nightly.stuck.length} nightly run(s) stuck`);
+ if (nightly.missing?.length) {
+ issues.push(`${nightly.missing.length} brand(s) had no completed nightly run`);
+ }
+
+ if (cloro.error) issues.push(`Cloro tasks could not be checked: ${cloro.error}`);
+ if (cloro.pendingOverAnHour > 0) {
+ issues.push(`${cloro.pendingOverAnHour} Cloro task(s) pending for over an hour`);
+ }
+ return issues;
+}
+
+function escapeHtml(value) {
+ return String(value ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+const STATUS_COLOR = { green: '#059669', yellow: '#d97706', red: '#dc2626' };
+
+export function renderHealthEmail(report) {
+ const issues = findIssues(report);
+ const date = report.generatedAt.slice(0, 10);
+ const subject = `${issues.length ? '[ISSUES]' : '[OK]'} Ansvisor daily health — ${date}`;
+
+ const list = (items) =>
+ items.length
+ ? `<ul>${items.map((i) => `<li>${escapeHtml(i)}</li>`).join('')}</ul>`
+ : '<p>None.</p>';
+
+ const probeRows = (report.probes.results ?? [])
+ .map(
+ (r) =>
+ `<tr><td>${escapeHtml(r.probe)}</td><td>${r.days == null ? 'all' : `${r.days}d`}</td>` +
+ `<td style="color:${STATUS_COLOR[r.status]};font-weight:600;">${
+ r.seconds == null ? 'error' : `${r.seconds}s`
+ }</td></tr>`,
+ )
+ .join('');
+ const probes = report.probes.skipped
+ ? `<p>Skipped: ${escapeHtml(report.probes.skipped)}</p>`
+ : `<table cellpadding="4" style="border-collapse:collapse;">${probeRows}</table>`;
+
+ const n = report.nightly;
+ const counts = Object.entries(n.counts ?? {})
+ .map(([status, count]) => `${escapeHtml(status)}: ${count}`)
+ .join(', ');
+
+ const html = `<div style="font-family:-apple-system,Segoe UI,sans-serif;font-size:14px;color:#111827;">
+ <h2 style="margin:0 0 8px 0;">${issues.length ? 'Needs attention' : 'All clear'}</h2>
+ ${list(issues)}
+ <h3>Page reads (budget ${READ_BUDGET_S}s, warn at ${WARN_AT_S}s)</h3>
+ ${probes}
+ <h3>Nightly tracking (last 24h)</h3>
+ <p>${counts || 'No nightly jobs.'}</p>
+ <p>Failed:</p>${list((n.failed ?? []).map((f) => `${f.brand}: ${f.reason ?? 'no reason'}`))}
+ <p>Stuck:</p>${list((n.stuck ?? []).map((s) => `${s.brand} (${s.status})`))}
+ <p>No completed run:</p>${list(n.missing ?? [])}
+ <p>Runs failed by a server restart: ${n.restartKills ?? 0}</p>
+ <h3>Server</h3>
+ <p>Uptime: ${report.serverUptimeHours}h. Cloro tasks pending over an hour: ${
+ report.cloro.pendingOverAnHour ?? 'unknown'
+ }.</p>
+</div>`;
+
+ return { subject, html, issues };
+}
+
+/** Collect, render and send. Returns the report with its issues. */
+export async function sendHealthReport() {
+ const report = await collectHealthReport();
+ const { subject, html, issues } = renderHealthEmail(report);
+ const to = (process.env.HEALTH_REPORT_RECIPIENTS ?? '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+ const sent = to.length ? await sendEmail({ to, subject, html }) : false;
+ logger.info({ issues: issues.length, sent }, '[health] daily report');
+ return { ...report, issues, sent };
+}
diff --git a/server/src/lib/health/report.test.js b/server/src/lib/health/report.test.js
new file mode 100644
index 000000000..e76ee1296
--- /dev/null
+++ b/server/src/lib/health/report.test.js
@@ -0,0 +1,207 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const db = vi.hoisted(() => ({ tables: {}, rpc: vi.fn() }));
+
+/** Minimal chainable stand-in for the supabase query builder. */
+function query(rows) {
+ const result = { data: rows, error: null, count: rows.length };
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ gte: () => chain,
+ lt: () => chain,
+ in: () => chain,
+ then: (resolve) => resolve(result),
+ };
+ return chain;
+}
+
+vi.mock('../../config/supabase.js', () => ({
+ default: {
+ from: (table) => query(db.tables[table] ?? []),
+ rpc: (...args) => db.rpc(...args),
+ },
+}));
+vi.mock('../logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+vi.mock('../email.js', () => ({ sendEmail: vi.fn() }));
+
+const { probeStatus, findIssues, renderHealthEmail, collectHealthReport, PROBES } =
+ await import('./report.js');
+
+const NOW = Date.parse('2026-10-06T06:00:00Z');
+const hoursAgo = (h) => new Date(NOW - h * 3600_000).toISOString();
+
+beforeEach(() => {
+ db.tables = {};
+ db.rpc.mockReset();
+ process.env.HEALTH_PROBE_BRAND_ID = 'brand-probe';
+ process.env.HEALTH_PROBE_USER_ID = 'user-probe';
+});
+
+afterEach(() => {
+ delete process.env.HEALTH_PROBE_BRAND_ID;
+ delete process.env.HEALTH_PROBE_USER_ID;
+});
+
+describe('probeStatus', () => {
+ it('is green under 4s, yellow from 4s, red from the 8s budget or on error', () => {
+ expect(probeStatus(3.99)).toBe('green');
+ expect(probeStatus(4)).toBe('yellow');
+ expect(probeStatus(7.99)).toBe('yellow');
+ expect(probeStatus(8)).toBe('red');
+ expect(probeStatus(null)).toBe('red');
+ });
+});
+
+describe('collectHealthReport', () => {
+ it('times every probe as the configured member and brand', async () => {
+ db.rpc.mockResolvedValue({ data: 0.5, error: null });
+ const report = await collectHealthReport(NOW);
+
+ expect(db.rpc).toHaveBeenCalledTimes(PROBES.length);
+ expect(db.rpc).toHaveBeenCalledWith('health_probe', {
+ p_user_id: 'user-probe',
+ p_brand_id: 'brand-probe',
+ p_probe: 'citations_domains',
+ p_days: 1,
+ });
+ expect(report.probes.results.every((r) => r.status === 'green')).toBe(true);
+ });
+
+ it('skips the probes when they are not configured', async () => {
+ delete process.env.HEALTH_PROBE_BRAND_ID;
+ const report = await collectHealthReport(NOW);
+ expect(report.probes.skipped).toBeTruthy();
+ expect(db.rpc).not.toHaveBeenCalled();
+ });
+
+ it('reports failed, stuck and missing nightly runs, ignoring manual ones', async () => {
+ db.rpc.mockResolvedValue({ data: 0.1, error: null });
+ db.tables.jobs = [
+ // ran last week and last night
+ {
+ brand_id: 'ok',
+ status: 'completed',
+ created_at: hoursAgo(30),
+ updated_at: hoursAgo(29),
+ data: {},
+ },
+ {
+ brand_id: 'ok',
+ status: 'completed',
+ created_at: hoursAgo(4),
+ updated_at: hoursAgo(3),
+ data: {},
+ },
+ // killed by a restart last night
+ {
+ brand_id: 'killed',
+ status: 'completed',
+ created_at: hoursAgo(30),
+ updated_at: hoursAgo(29),
+ data: {},
+ },
+ {
+ brand_id: 'killed',
+ status: 'failed',
+ failed_reason: 'Server restarted during execution',
+ created_at: hoursAgo(4),
+ updated_at: hoursAgo(3),
+ data: {},
+ },
+ // waiting since the night began
+ {
+ brand_id: 'stuck',
+ status: 'completed',
+ created_at: hoursAgo(30),
+ updated_at: hoursAgo(29),
+ data: {},
+ },
+ {
+ brand_id: 'stuck',
+ status: 'waiting',
+ created_at: hoursAgo(4),
+ updated_at: hoursAgo(4),
+ data: {},
+ },
+ // a manual run does not count as the night's run
+ {
+ brand_id: 'manual',
+ status: 'completed',
+ created_at: hoursAgo(30),
+ updated_at: hoursAgo(29),
+ data: {},
+ },
+ {
+ brand_id: 'manual',
+ status: 'completed',
+ created_at: hoursAgo(2),
+ updated_at: hoursAgo(1),
+ data: { immediate: true },
+ },
+ ];
+ db.tables.brands = [
+ { id: 'killed', name: 'Killed Co' },
+ { id: 'stuck', name: 'Stuck Co' },
+ { id: 'manual', name: 'Manual Co' },
+ ];
+
+ const { nightly } = await collectHealthReport(NOW);
+
+ expect(nightly.failed).toEqual([
+ { brand: 'Killed Co', reason: 'Server restarted during execution' },
+ ]);
+ expect(nightly.restartKills).toBe(1);
+ expect(nightly.stuck).toEqual([{ brand: 'Stuck Co', status: 'waiting' }]);
+ expect(nightly.missing.sort()).toEqual(['Killed Co', 'Manual Co', 'Stuck Co']);
+ });
+
+ it('keeps reporting when one check fails', async () => {
+ db.rpc.mockResolvedValue({ data: null, error: { message: 'statement timeout' } });
+ const report = await collectHealthReport(NOW);
+ expect(report.probes.results[0]).toMatchObject({ status: 'red', error: 'statement timeout' });
+ expect(report.nightly.counts).toEqual({});
+ });
+});
+
+describe('renderHealthEmail', () => {
+ const clean = {
+ generatedAt: '2026-10-06T06:00:00.000Z',
+ serverUptimeHours: 5,
+ probes: { results: [{ probe: 'citations_domains', days: 1, seconds: 0.2, status: 'green' }] },
+ nightly: { counts: { completed: 25 }, failed: [], stuck: [], missing: [], restartKills: 0 },
+ cloro: { pendingOverAnHour: 0 },
+ };
+
+ it('says OK when nothing needs attention', () => {
+ const { subject, issues } = renderHealthEmail(clean);
+ expect(issues).toEqual([]);
+ expect(subject).toBe('[OK] Ansvisor daily health — 2026-10-06');
+ });
+
+ it('lists slow reads and nightly problems, and escapes brand names', () => {
+ const report = {
+ ...clean,
+ probes: {
+ results: [{ probe: 'citations_domains', days: 30, seconds: 9.1, status: 'red' }],
+ },
+ nightly: { ...clean.nightly, failed: [{ brand: '<b>Acme</b>', reason: 'x' }] },
+ cloro: { pendingOverAnHour: 3 },
+ };
+ const { subject, html, issues } = renderHealthEmail(report);
+ expect(subject.startsWith('[ISSUES]')).toBe(true);
+ expect(issues).toEqual([
+ 'citations_domains (30d) took 9.1s of its 8s budget',
+ '1 nightly run(s) failed',
+ '3 Cloro task(s) pending for over an hour',
+ ]);
+ expect(html).toContain('&lt;b&gt;Acme&lt;/b&gt;');
+ expect(html).not.toContain('<b>Acme</b>');
+ });
+
+ it('flags a check that could not run', () => {
+ expect(findIssues({ ...clean, nightly: { error: 'boom' } })).toEqual([
+ 'Nightly runs could not be checked: boom',
+ ]);
+ });
+});
diff --git a/server/src/lib/pulse/email.js b/server/src/lib/pulse/email.js
index 7aef2381c..8e6b2a661 100644
--- a/server/src/lib/pulse/email.js
+++ b/server/src/lib/pulse/email.js
@@ -1,4 +1,4 @@
-import { logger } from '../logger.js';
+import { sendEmail } from '../email.js';
/**
* Daily Pulse email rendering + delivery via the Resend HTTP API (#540).
@@ -173,35 +173,6 @@ export function renderPulseEmail({ brandName, metrics, insightsUrl, settingsUrl
* 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;
- }
+export function sendPulseEmail({ to, subject, html, settingsUrl }) {
+ return sendEmail({ to, subject, html, headers: { 'List-Unsubscribe': `<${settingsUrl}>` } });
}
diff --git a/server/src/server.js b/server/src/server.js
index 4ca05b45a..529fa36f4 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -38,6 +38,7 @@ import { runPageOpportunityDetection } from './lib/page-opportunities.js';
import { runPulseCatchUp } from './lib/pulse/engine.js';
import { runSignalCatchUp } from './lib/signals/pass.js';
import { sweepTaskExecution } from './lib/action-center/execution/run.js';
+import { sendHealthReport } from './lib/health/report.js';
const app = express();
app.set('trust proxy', 1);
@@ -249,6 +250,19 @@ async function runDailyTracking() {
return { triggered, total: brands.length };
}
+// --- Daily health report (CRON_SECRET auth, Vercel Cron) ---
+// Answers at once and reports in the background: timing the page reads can
+// take longer than a cron request may stay open.
+app.post('/api/internal/health-report', (req, res) => {
+ const secret = req.headers.authorization?.replace('Bearer ', '');
+ if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {
+ return res.status(401).json({ success: false, message: 'Unauthorized' });
+ }
+
+ sendHealthReport().catch((err) => logger.error({ err }, '[health] daily report failed'));
+ return res.status(202).json({ success: true });
+});
+
// --- Internal cron endpoint (CRON_SECRET auth, used by Vercel Cron in cloud mode) ---
app.post('/api/internal/daily-tracking', async (req, res) => {
const secret = req.headers.authorization?.replace('Bearer ', '');
diff --git a/supabase/migrations/00108_health_probe.sql b/supabase/migrations/00108_health_probe.sql
new file mode 100644
index 000000000..45050ae05
--- /dev/null
+++ b/supabase/migrations/00108_health_probe.sql
@@ -0,0 +1,76 @@
+-- Daily health report: time the dashboard's heaviest reads.
+--
+-- The Citations page once stopped opening on the largest brand: one read had
+-- drifted past the 8 s statement timeout, and only a user noticed. The daily
+-- health report (server/src/lib/health) times those reads every morning and
+-- flags any that are getting close.
+--
+-- Most of them check membership through auth.uid(), so a service-role call
+-- would return nothing in no time. health_probe runs one read the way the
+-- page does — as the `authenticated` role, with a given organization
+-- member's claims, both for this transaction only — and returns how long it
+-- took. The role matters as much as the claims: run with row security
+-- bypassed, the Competitors read planned differently and ran past 120 s,
+-- against 6.9 s as the page runs it. Only the server's service role may call
+-- it, and only for the reads named below.
+
+create or replace function public.health_probe(
+ p_user_id uuid,
+ p_brand_id uuid,
+ p_probe text,
+ p_days integer default null
+)
+returns numeric
+language plpgsql
+volatile
+security invoker
+set search_path = public
+as $$
+declare
+ t0 timestamptz;
+ ts_from timestamptz := case when p_days is null then null else now() - make_interval(days => p_days) end;
+ day_from date := (now() at time zone 'utc')::date - coalesce(p_days, 0);
+ n bigint;
+begin
+ perform set_config('role', 'authenticated', true);
+ perform set_config(
+ 'request.jwt.claims',
+ json_build_object('sub', p_user_id, 'role', 'authenticated')::text,
+ true
+ );
+ t0 := clock_timestamp();
+
+ case p_probe
+ when 'citations_window_stats' then
+ select count(*) into n from public.citations_window_stats(
+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,
+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null);
+ when 'citations_domains' then
+ select count(*) into n from public.citations_domains(
+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,
+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null);
+ when 'citations_urls' then
+ select count(*) into n from public.citations_urls(
+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,
+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null,
+ p_limit => 100, p_domains => null, p_exclude_domains => null);
+ when 'insights_aggregates_daily' then
+ select count(*) into n from public.insights_aggregates_daily(
+ p_brand_id => p_brand_id, p_platform => null, p_models => null, p_region => null,
+ p_day_from => case when p_days is null then null else day_from end, p_day_to => null);
+ when 'competitor_aggregates_daily' then
+ select count(*) into n from public.competitor_aggregates_daily(
+ p_brand_id => p_brand_id, p_platform => null, p_models => null, p_region => null,
+ p_day_from => case when p_days is null then null else day_from end, p_day_to => null);
+ when 'topics_overview_aggregates' then
+ select count(*) into n from public.topics_overview_aggregates(p_brand_id => p_brand_id);
+ else
+ raise exception 'unknown health probe: %', p_probe;
+ end case;
+
+ return round(extract(epoch from clock_timestamp() - t0)::numeric, 2);
+end;
+$$;
+
+revoke all on function public.health_probe(uuid, uuid, text, integer) from public, anon, authenticated;
+grant execute on function public.health_probe(uuid, uuid, text, integer) to service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 37a72f7ce..e14d535b1 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -12362,3 +12362,83 @@ grant execute on function public.citations_domains(
uuid, timestamptz, timestamptz, text[], text[], uuid[], uuid[]
) to authenticated, service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00108_health_probe.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Daily health report: time the dashboard's heaviest reads.
+--
+-- The Citations page once stopped opening on the largest brand: one read had
+-- drifted past the 8 s statement timeout, and only a user noticed. The daily
+-- health report (server/src/lib/health) times those reads every morning and
+-- flags any that are getting close.
+--
+-- Most of them check membership through auth.uid(), so a service-role call
+-- would return nothing in no time. health_probe runs one read the way the
+-- page does — as the `authenticated` role, with a given organization
+-- member's claims, both for this transaction only — and returns how long it
+-- took. The role matters as much as the claims: run with row security
+-- bypassed, the Competitors read planned differently and ran past 120 s,
+-- against 6.9 s as the page runs it. Only the server's service role may call
+-- it, and only for the reads named below.
+
+create or replace function public.health_probe(
+ p_user_id uuid,
+ p_brand_id uuid,
+ p_probe text,
+ p_days integer default null
+)
+returns numeric
+language plpgsql
+volatile
+security invoker
+set search_path = public
+as $$
+declare
+ t0 timestamptz;
+ ts_from timestamptz := case when p_days is null then null else now() - make_interval(days => p_days) end;
+ day_from date := (now() at time zone 'utc')::date - coalesce(p_days, 0);
+ n bigint;
+begin
+ perform set_config('role', 'authenticated', true);
+ perform set_config(
+ 'request.jwt.claims',
+ json_build_object('sub', p_user_id, 'role', 'authenticated')::text,
+ true
+ );
+ t0 := clock_timestamp();
+
+ case p_probe
+ when 'citations_window_stats' then
+ select count(*) into n from public.citations_window_stats(
+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,
+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null);
+ when 'citations_domains' then
+ select count(*) into n from public.citations_domains(
+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,
+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null);
+ when 'citations_urls' then
+ select count(*) into n from public.citations_urls(
+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,
+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null,
+ p_limit => 100, p_domains => null, p_exclude_domains => null);
+ when 'insights_aggregates_daily' then
+ select count(*) into n from public.insights_aggregates_daily(
+ p_brand_id => p_brand_id, p_platform => null, p_models => null, p_region => null,
+ p_day_from => case when p_days is null then null else day_from end, p_day_to => null);
+ when 'competitor_aggregates_daily' then
+ select count(*) into n from public.competitor_aggregates_daily(
+ p_brand_id => p_brand_id, p_platform => null, p_models => null, p_region => null,
+ p_day_from => case when p_days is null then null else day_from end, p_day_to => null);
+ when 'topics_overview_aggregates' then
+ select count(*) into n from public.topics_overview_aggregates(p_brand_id => p_brand_id);
+ else
+ raise exception 'unknown health probe: %', p_probe;
+ end case;
+
+ return round(extract(epoch from clock_timestamp() - t0)::numeric, 2);
+end;
+$$;
+
+revoke all on function public.health_probe(uuid, uuid, text, integer) from public, anon, authenticated;
+grant execute on function public.health_probe(uuid, uuid, text, integer) to service_role;
+
diff --git a/web/src/app/api/cron/health-report/route.ts b/web/src/app/api/cron/health-report/route.ts
new file mode 100644
index 000000000..63643823a
--- /dev/null
+++ b/web/src/app/api/cron/health-report/route.ts
@@ -0,0 +1,33 @@
+import { NextResponse } from 'next/server';
+import { API_BASE_URL } from '@/config/api';
+
+const AEO_SERVER_URL = API_BASE_URL;
+
+export async function GET(request: Request) {
+ const cronSecret = process.env.CRON_SECRET;
+
+ const authHeader = request.headers.get('authorization');
+ const vercelHeader = request.headers.get('x-vercel-cron-auth');
+
+ const token = vercelHeader ?? authHeader?.replace('Bearer ', '');
+
+ if (!cronSecret || token !== cronSecret) {
+ return NextResponse.json({ success: false, message: 'Unauthorized' }, { status: 401 });
+ }
+
+ try {
+ const res = await fetch(`${AEO_SERVER_URL}/api/internal/health-report`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${cronSecret}`,
+ },
+ });
+
+ const data = await res.json();
+ return NextResponse.json(data);
+ } catch (err) {
+ console.error('[cron] health-report failed:', err);
+ return NextResponse.json({ success: false, message: 'Internal error' }, { status: 500 });
+ }
+}
diff --git a/web/vercel.json b/web/vercel.json
index 5b0cd3c73..48199dee5 100644
--- a/web/vercel.json
+++ b/web/vercel.json
@@ -3,6 +3,10 @@
{
"path": "/api/cron/daily-tracking",
"schedule": "0 2 * * *"
+ },
+ {
+ "path": "/api/cron/health-report",
+ "schedule": "0 6 * * *"
}
],
"headers": [