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.

fix(tracking): read more fan-out shapes and report an engine whose fan-out stops (#1056)

Cihan3670918e3855
diff --git a/server/src/lib/cloro-scraper.js b/server/src/lib/cloro-scraper.js
index 9e6e1f739..e3d569f5e 100644
--- a/server/src/lib/cloro-scraper.js
+++ b/server/src/lib/cloro-scraper.js
@@ -12,7 +12,7 @@ import { stripEntityMarkup } from './entity-markup.js';
const CLORO_API = 'https://api.cloro.dev';
-const SCRAPER_TASK_TYPES = {
+export const SCRAPER_TASK_TYPES = {
'chatgpt-web': 'CHATGPT',
'chatgpt-shopping': 'CHATGPT',
'google-aio': 'GOOGLE',
@@ -88,9 +88,10 @@ export function buildRequestBody(promptText, scraperId, region, state) {
html: false,
markdown: true,
rawResponse: false,
- // Opt in to the observed query fan-out (#332). Copilot/Perplexity
- // populate it; ChatGPT surfaces the key but returns it empty in
- // practice — enabling it is free and harmless.
+ // Opt in to the observed query fan-out (#332). Copilot and Perplexity
+ // populate it; ChatGPT does too (a +2 credit add-on), though its came
+ // back empty from 2026-09-30 — the health report's fan-out section
+ // flags an engine that stops. Gemini documents no fan-out field.
searchQueries: true,
},
};
@@ -106,40 +107,39 @@ export function buildRequestBody(promptText, scraperId, region, state) {
* accepted so a potential upstream revert can't silently zero the field
* again.
* - Copilot / ChatGPT / Grok / Gemini → `searchQueries: string[]`
- * Anything else (or missing) → `[]`. This is OBSERVED data only — we never
- * synthesize sub-queries.
+ * - ChatGPT also → `mapSearchQueries: string[]`, the searches it ran on its
+ * map (kept with `engine: 'maps'`).
+ * Entries are read as strings or as `{ query }` objects in every field: when
+ * ChatGPT's fan-out went silent on 2026-09-30, nothing told an emptied field
+ * from one that changed shape, and the strings-only read would have dropped
+ * the second without a trace. Anything else (or missing) → `[]`. This is
+ * OBSERVED data only — we never synthesize sub-queries.
*/
function normalizeSearchQueries(result, scraperId) {
// Trim on write so the same sub-query never fragments into whitespace
// variants — the #333 aggregation groups by query string. `engine` is only
// kept when it's a non-empty string (never a stray non-string value).
- if (Array.isArray(result.search_model_queries)) {
- return result.search_model_queries
- .map((entry) => {
- if (typeof entry === 'string') {
- return { query: entry.trim(), source_platform: scraperId };
- }
- if (typeof entry?.query === 'string') {
- return {
- query: entry.query.trim(),
- ...(typeof entry.engine === 'string' && entry.engine.trim() !== ''
- ? { engine: entry.engine.trim() }
- : {}),
- source_platform: scraperId,
- };
- }
- return null;
- })
- .filter((item) => item !== null && item.query !== '');
- }
+ const toItem = (entry, fallbackEngine) => {
+ const query =
+ typeof entry === 'string' ? entry : typeof entry?.query === 'string' ? entry.query : null;
+ if (query === null || query.trim() === '') return null;
+ const engine =
+ typeof entry?.engine === 'string' && entry.engine.trim() !== ''
+ ? entry.engine.trim()
+ : fallbackEngine;
+ return { query: query.trim(), ...(engine ? { engine } : {}), source_platform: scraperId };
+ };
+ const read = (list, fallbackEngine) =>
+ Array.isArray(list)
+ ? list.map((entry) => toItem(entry, fallbackEngine)).filter((item) => item !== null)
+ : [];
- if (Array.isArray(result.searchQueries)) {
- return result.searchQueries
- .filter((q) => typeof q === 'string' && q.trim() !== '')
- .map((q) => ({ query: q.trim(), source_platform: scraperId }));
- }
+ // Perplexity's field first. An empty one falls through, so it can't hide a
+ // populated `searchQueries` beside it.
+ const perplexity = read(result.search_model_queries);
+ if (perplexity.length > 0) return perplexity;
- return [];
+ return [...read(result.searchQueries), ...read(result.mapSearchQueries, 'maps')];
}
/**
diff --git a/server/src/lib/cloro-scraper.test.js b/server/src/lib/cloro-scraper.test.js
index ef04f2f44..a9997f87a 100644
--- a/server/src/lib/cloro-scraper.test.js
+++ b/server/src/lib/cloro-scraper.test.js
@@ -280,7 +280,45 @@ describe('cloro-scraper – parseScraperResponse', () => {
]);
});
- it('defaults to an empty array when the engine returns none (ChatGPT in practice)', () => {
+ it('reads { query } objects in searchQueries too, so a shape change cannot empty it', () => {
+ const parsed = parseScraperResponse(
+ {
+ markdown: 't',
+ sources: [],
+ searchQueries: [{ query: ' chatgpt query ' }, { query: '' }, { text: 'no query key' }],
+ },
+ 'chatgpt-web',
+ );
+ expect(parsed.search_queries).toEqual([
+ { query: 'chatgpt query', source_platform: 'chatgpt-web' },
+ ]);
+ });
+
+ it("adds ChatGPT's map searches, labelled as maps", () => {
+ const parsed = parseScraperResponse(
+ {
+ markdown: 't',
+ sources: [],
+ searchQueries: ['coffee subscription'],
+ mapSearchQueries: ['coffee shops near me'],
+ },
+ 'chatgpt-web',
+ );
+ expect(parsed.search_queries).toEqual([
+ { query: 'coffee subscription', source_platform: 'chatgpt-web' },
+ { query: 'coffee shops near me', engine: 'maps', source_platform: 'chatgpt-web' },
+ ]);
+ });
+
+ it('does not let an empty search_model_queries hide a populated searchQueries', () => {
+ const parsed = parseScraperResponse(
+ { markdown: 't', sources: [], search_model_queries: [], searchQueries: ['kept'] },
+ 'copilot-web',
+ );
+ expect(parsed.search_queries).toEqual([{ query: 'kept', source_platform: 'copilot-web' }]);
+ });
+
+ it('defaults to an empty array when the engine returns none', () => {
expect(
parseScraperResponse({ markdown: 't', sources: [], searchQueries: [] }, 'chatgpt-web')
.search_queries,
diff --git a/server/src/lib/health/report.js b/server/src/lib/health/report.js
index 6da19dd94..d64b4b247 100644
--- a/server/src/lib/health/report.js
+++ b/server/src/lib/health/report.js
@@ -136,6 +136,78 @@ async function checkCloro(now) {
return { pendingOverAnHour: count ?? 0 };
}
+/**
+ * Query fan-out. ChatGPT's went from about a quarter of answers to none on
+ * 2026-09-30 and nothing noticed for two weeks. A platform is flagged when:
+ * - Cloro documents fan-out for it (FANOUT_EXPECTED) and a whole day of its
+ * answers carried none. This catches an outage however long it has run,
+ * which a comparison with the days before stops doing once they are empty
+ * too; or
+ * - its share over the last day fell below FANOUT_DROP_RATIO of its share
+ * over the BASELINE_DAYS before, for any other platform that fans out.
+ */
+export const FANOUT_EXPECTED = ['chatgpt-web', 'copilot-web', 'perplexity-web'];
+export const FANOUT_DROP_RATIO = 0.25;
+/** Fewer answers than this, on either side, are too few to judge. */
+export const FANOUT_MIN_ANSWERS = 20;
+/** A platform under this share before (it rarely fans out) is not flagged on a drop. */
+export const FANOUT_MIN_BASELINE = 0.05;
+/** Days before the last one that make the baseline. Kept short: the read scans every brand. */
+export const BASELINE_DAYS = 3;
+
+/** Each platform's fan-out share over the last day and over the days before. */
+async function checkFanout(now) {
+ const day = new Date(now - DAY_MS).toISOString();
+ const week = new Date(now - (1 + BASELINE_DAYS) * DAY_MS).toISOString();
+ const read = async (since, until) => {
+ const { data, error } = await supabaseAdmin.rpc('fanout_coverage_by_platform', {
+ p_since: since,
+ p_until: until,
+ });
+ if (error) throw new Error(error.message);
+ return new Map(
+ (data ?? []).map((r) => [
+ r.platform,
+ { answers: Number(r.answers), withFanout: Number(r.answers_with_fanout) },
+ ]),
+ );
+ };
+ const [recent, before] = await Promise.all([
+ read(day, new Date(now).toISOString()),
+ read(week, day),
+ ]);
+
+ const platforms = [...new Set([...recent.keys(), ...before.keys()])].sort().map((platform) => {
+ const r = recent.get(platform) ?? { answers: 0, withFanout: 0 };
+ const b = before.get(platform) ?? { answers: 0, withFanout: 0 };
+ return {
+ platform,
+ answers: r.answers,
+ withFanout: r.withFanout,
+ rate: r.answers ? r.withFanout / r.answers : null,
+ baselineRate: b.answers ? b.withFanout / b.answers : null,
+ baselineAnswers: b.answers,
+ };
+ });
+ return { platforms };
+}
+
+/** A platform whose fan-out stopped or collapsed (see FANOUT_EXPECTED). */
+export function fanoutDropped(p) {
+ if (p.answers < FANOUT_MIN_ANSWERS) return false;
+ if (FANOUT_EXPECTED.includes(p.platform) && p.withFanout === 0) return true;
+ return (
+ p.baselineAnswers >= FANOUT_MIN_ANSWERS &&
+ p.baselineRate != null &&
+ p.baselineRate >= FANOUT_MIN_BASELINE &&
+ (p.rate ?? 0) < p.baselineRate * FANOUT_DROP_RATIO
+ );
+}
+
+/** A share as a whole percent; a small non-zero one says so rather than "0%". */
+const percent = (rate) =>
+ rate == null ? '–' : rate > 0 && rate < 0.01 ? '<1%' : `${Math.round(rate * 100)}%`;
+
async function section(name, fn) {
try {
return await fn();
@@ -149,12 +221,14 @@ 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));
+ const fanout = await section('fanout', () => checkFanout(now));
return {
generatedAt: new Date(now).toISOString(),
serverUptimeHours: Math.round((process.uptime() / 3600) * 10) / 10,
probes,
nightly,
cloro,
+ fanout,
};
}
@@ -185,6 +259,19 @@ export function findIssues(report) {
if (cloro.pendingOverAnHour > 0) {
issues.push(`${cloro.pendingOverAnHour} Cloro task(s) pending for over an hour`);
}
+
+ // Reports from before the fan-out section have none.
+ const fanout = report.fanout ?? {};
+ if (fanout.error) issues.push(`Query fan-out could not be checked: ${fanout.error}`);
+ for (const p of (fanout.platforms ?? []).filter(fanoutDropped)) {
+ issues.push(
+ p.withFanout === 0
+ ? `${p.platform} returned no query fan-out on any of its ${p.answers} answers ` +
+ `in the last 24h (${percent(p.baselineRate)} the days before) — check what Cloro returns`
+ : `${p.platform} query fan-out fell to ${percent(p.rate)} of answers ` +
+ `(${percent(p.baselineRate)} the days before) — check what Cloro returns`,
+ );
+ }
return issues;
}
@@ -198,6 +285,22 @@ function escapeHtml(value) {
const STATUS_COLOR = { green: '#059669', yellow: '#d97706', red: '#dc2626' };
+function fanoutTable(fanout) {
+ if (!fanout) return '<p>Not checked.</p>';
+ if (fanout.error) return `<p>Could not check: ${escapeHtml(fanout.error)}</p>`;
+ const rows = (fanout.platforms ?? [])
+ .map(
+ (p) =>
+ `<tr><td>${escapeHtml(p.platform)}</td>` +
+ `<td style="${fanoutDropped(p) ? 'color:#dc2626;font-weight:600;' : ''}">${percent(p.rate)} ` +
+ `(${p.withFanout} / ${p.answers})</td><td>${percent(p.baselineRate)}</td></tr>`,
+ )
+ .join('');
+ return rows
+ ? `<table cellpadding="4" style="border-collapse:collapse;"><tr><th align="left">Platform</th><th align="left">Last 24h</th><th align="left">${BASELINE_DAYS} days before</th></tr>${rows}</table>`
+ : '<p>No answers.</p>';
+}
+
export function renderHealthEmail(report) {
const issues = findIssues(report);
const date = report.generatedAt.slice(0, 10);
@@ -237,6 +340,8 @@ export function renderHealthEmail(report) {
<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>Query fan-out (answers with observed sub-queries)</h3>
+ ${fanoutTable(report.fanout)}
<h3>Server</h3>
<p>Uptime: ${report.serverUptimeHours}h. Cloro tasks pending over an hour: ${
report.cloro.pendingOverAnHour ?? 'unknown'
diff --git a/server/src/lib/health/report.test.js b/server/src/lib/health/report.test.js
index ac3b3bd1b..e507ce86e 100644
--- a/server/src/lib/health/report.test.js
+++ b/server/src/lib/health/report.test.js
@@ -25,9 +25,12 @@ vi.mock('../../config/supabase.js', () => ({
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 } =
+const { probeStatus, findIssues, renderHealthEmail, collectHealthReport, fanoutDropped, PROBES } =
await import('./report.js');
+/** The read probes' calls, without the fan-out check's. */
+const probeCalls = () => db.rpc.mock.calls.filter(([name]) => name === 'health_probe');
+
const NOW = Date.parse('2026-10-06T06:00:00Z');
const hoursAgo = (h) => new Date(NOW - h * 3600_000).toISOString();
@@ -58,7 +61,7 @@ describe('collectHealthReport', () => {
db.rpc.mockResolvedValue({ data: 0.5, error: null });
const report = await collectHealthReport(NOW);
- expect(db.rpc).toHaveBeenCalledTimes(PROBES.length);
+ expect(probeCalls()).toHaveLength(PROBES.length);
expect(db.rpc).toHaveBeenCalledWith('health_probe', {
p_user_id: 'user-probe',
p_brand_id: 'brand-probe',
@@ -72,7 +75,7 @@ describe('collectHealthReport', () => {
delete process.env.HEALTH_PROBE_BRAND_ID;
const report = await collectHealthReport(NOW);
expect(report.probes.skipped).toBeTruthy();
- expect(db.rpc).not.toHaveBeenCalled();
+ expect(probeCalls()).toHaveLength(0);
});
it('reports failed, stuck and missing nightly runs, ignoring manual ones', async () => {
@@ -164,6 +167,87 @@ describe('collectHealthReport', () => {
});
});
+describe('query fan-out', () => {
+ const coverage = (recent, before) => (name, args) => {
+ if (name !== 'fanout_coverage_by_platform') return Promise.resolve({ data: 0.1, error: null });
+ const rows = args.p_until === new Date(NOW).toISOString() ? recent : before;
+ return Promise.resolve({ data: rows, error: null });
+ };
+
+ it("compares each platform's share of answers with fan-out to the week before", async () => {
+ db.rpc.mockImplementation(
+ coverage(
+ [
+ { platform: 'chatgpt-web', answers: 200, answers_with_fanout: 0 },
+ { platform: 'copilot-web', answers: 200, answers_with_fanout: 40 },
+ { platform: 'gemini-web', answers: 200, answers_with_fanout: 0 },
+ ],
+ [
+ { platform: 'chatgpt-web', answers: 1400, answers_with_fanout: 350 },
+ { platform: 'copilot-web', answers: 1400, answers_with_fanout: 280 },
+ { platform: 'gemini-web', answers: 1400, answers_with_fanout: 0 },
+ ],
+ ),
+ );
+ const report = await collectHealthReport(NOW);
+
+ expect(db.rpc).toHaveBeenCalledWith('fanout_coverage_by_platform', {
+ p_since: hoursAgo(24),
+ p_until: new Date(NOW).toISOString(),
+ });
+ expect(db.rpc).toHaveBeenCalledWith('fanout_coverage_by_platform', {
+ p_since: hoursAgo(24 * 4),
+ p_until: hoursAgo(24),
+ });
+ expect(report.fanout.platforms).toEqual([
+ expect.objectContaining({ platform: 'chatgpt-web', rate: 0, baselineRate: 0.25 }),
+ expect.objectContaining({ platform: 'copilot-web', rate: 0.2, baselineRate: 0.2 }),
+ expect.objectContaining({ platform: 'gemini-web', rate: 0, baselineRate: 0 }),
+ ]);
+ // ChatGPT stopped; Copilot held; Gemini never fans out, so it isn't news.
+ expect(findIssues(report).filter((i) => i.includes('fan-out'))).toEqual([
+ 'chatgpt-web returned no query fan-out on any of its 200 answers in the last 24h (25% the days before) — check what Cloro returns',
+ ]);
+ expect(renderHealthEmail(report).html).toContain('Query fan-out');
+ });
+
+ it('flags a partial collapse too, but not a platform with too few answers to judge', () => {
+ const base = { platform: 'x', withFanout: 5, baselineAnswers: 500 };
+ expect(fanoutDropped({ ...base, answers: 100, rate: 0.05, baselineRate: 0.3 })).toBe(true);
+ expect(fanoutDropped({ ...base, answers: 100, rate: 0.2, baselineRate: 0.3 })).toBe(false);
+ expect(fanoutDropped({ ...base, answers: 5, rate: 0, baselineRate: 0.3 })).toBe(false);
+ expect(fanoutDropped({ ...base, answers: 100, rate: 0, baselineRate: 0.02 })).toBe(false);
+ });
+
+ it('keeps flagging an engine that should fan out, however long it has been silent', () => {
+ // ChatGPT on the day this check shipped: nothing for two weeks, so the
+ // days before are empty too.
+ const silent = {
+ platform: 'chatgpt-web',
+ answers: 400,
+ withFanout: 0,
+ rate: 0,
+ baselineAnswers: 1200,
+ baselineRate: 0,
+ };
+ expect(fanoutDropped(silent)).toBe(true);
+ // Gemini documents no fan-out, so a silent day is normal for it.
+ expect(fanoutDropped({ ...silent, platform: 'gemini-web' })).toBe(false);
+ });
+
+ it('says so when the check cannot run', async () => {
+ db.rpc.mockImplementation((name) =>
+ Promise.resolve(
+ name === 'fanout_coverage_by_platform'
+ ? { data: null, error: { message: 'timeout' } }
+ : { data: 0.1, error: null },
+ ),
+ );
+ const report = await collectHealthReport(NOW);
+ expect(findIssues(report)).toContain('Query fan-out could not be checked: timeout');
+ });
+});
+
describe('renderHealthEmail', () => {
const clean = {
generatedAt: '2026-10-06T06:00:00.000Z',
diff --git a/server/src/scripts/probe-cloro-fanout.js b/server/src/scripts/probe-cloro-fanout.js
new file mode 100644
index 000000000..522d0197e
--- /dev/null
+++ b/server/src/scripts/probe-cloro-fanout.js
@@ -0,0 +1,121 @@
+/**
+ * Ask Cloro for one answer and show its query fan-out (#332): the raw fields,
+ * and what we would store. For when the daily health report says an engine's
+ * fan-out fell away (as ChatGPT's did on 2026-09-30) — it tells an emptied
+ * field from one that changed shape or moved.
+ *
+ * Run from server/, with CLORO_API_KEY in .env. Sends ONE async task, billed
+ * by Cloro (ChatGPT with fan-out: about 9 credits):
+ * node src/scripts/probe-cloro-fanout.js [platform] ["prompt"] [country]
+ * platform defaults to chatgpt-web; e.g. copilot-web, perplexity-web, gemini-web
+ *
+ * Prints a summary and writes the full response to a temp file. Never prints
+ * the API key.
+ */
+import 'dotenv/config';
+import { writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ buildRequestBody,
+ parseScraperResponse,
+ SCRAPER_TASK_TYPES,
+} from '../lib/cloro-scraper.js';
+
+const CLORO_API = 'https://api.cloro.dev';
+const platform = process.argv[2] ?? 'chatgpt-web';
+const prompt = process.argv[3] ?? 'How can I track my website ranking in Google AI overviews?';
+const country = process.argv[4] ?? 'US';
+
+const key = process.env.CLORO_API_KEY;
+const taskType = SCRAPER_TASK_TYPES[platform];
+if (!key) {
+ console.error('CLORO_API_KEY is not set (server/.env).');
+ process.exit(1);
+}
+if (!taskType) {
+ console.error(
+ `Unknown platform "${platform}". One of: ${Object.keys(SCRAPER_TASK_TYPES).join(', ')}`,
+ );
+ process.exit(1);
+}
+
+// The request production sends, plus the raw stream where the engine takes
+// it (Google's endpoints don't), to look for queries outside the documented
+// fields. On ChatGPT it shares the fan-out add-on's +2 credits.
+const payload = buildRequestBody(prompt, platform, country);
+if (!['google-aio', 'google-aimode'].includes(platform)) {
+ payload.include = { ...payload.include, rawResponse: true };
+}
+
+const headers = { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' };
+const submit = await fetch(`${CLORO_API}/v1/async/task`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ taskType, payload }),
+});
+const submitted = await submit.json().catch(() => ({}));
+if (!submitted.success || !submitted.task?.id) {
+ console.error(`Submit failed (${submit.status}):`, JSON.stringify(submitted).slice(0, 300));
+ process.exit(1);
+}
+console.log(`Submitted ${platform} task; waiting for Cloro…`);
+
+let data = {};
+for (let i = 0; i < 90; i++) {
+ await new Promise((resolve) => setTimeout(resolve, 4000));
+ const res = await fetch(`${CLORO_API}/v1/async/task/${submitted.task.id}`, { headers });
+ data = await res.json().catch(() => ({}));
+ const status = String(data.task?.status ?? data.status ?? '').toUpperCase();
+ if (status === 'COMPLETED' || status === 'FAILED') break;
+}
+
+const file = join(tmpdir(), `cloro-fanout-${platform}-${Date.now()}.json`);
+writeFileSync(file, JSON.stringify(data, null, 2));
+
+const response = data.response ?? {};
+const result = response.result ?? response;
+const describe = (value) =>
+ Array.isArray(value)
+ ? `array(${value.length}) ${JSON.stringify(value.slice(0, 3)).slice(0, 200)}`
+ : typeof value;
+
+// Every key that looks like a query, wherever it sits — the raw stream included.
+const queryKeys = [];
+const walk = (value, path) => {
+ if (!value || typeof value !== 'object' || queryKeys.length >= 30) return;
+ for (const [k, v] of Object.entries(value)) {
+ const p = path ? `${path}.${k}` : k;
+ if (/search|quer|fan.?out/i.test(k)) queryKeys.push(`${p}: ${describe(v)}`.slice(0, 240));
+ walk(v, p);
+ }
+};
+walk(result, '');
+
+let stored = [];
+try {
+ stored = parseScraperResponse(response, platform).search_queries ?? [];
+} catch (err) {
+ stored = `parse failed: ${err.message}`;
+}
+
+console.log(
+ JSON.stringify(
+ {
+ platform,
+ status: data.task?.status ?? data.status,
+ model: result.model,
+ sources: Array.isArray(result.sources) ? result.sources.length : typeof result.sources,
+ searchQueries: describe(result.searchQueries),
+ mapSearchQueries: describe(result.mapSearchQueries),
+ search_model_queries: describe(result.search_model_queries),
+ rawResponse: describe(result.rawResponse),
+ queryLikeKeys: queryKeys,
+ weWouldStore: Array.isArray(stored) ? `${stored.length} sub-queries` : stored,
+ fullResponse: file,
+ },
+ null,
+ 2,
+ ),
+);
+process.exit(0);
diff --git a/supabase/migrations/00140_fanout_coverage_by_platform.sql b/supabase/migrations/00140_fanout_coverage_by_platform.sql
new file mode 100644
index 000000000..ed26e58e0
--- /dev/null
+++ b/supabase/migrations/00140_fanout_coverage_by_platform.sql
@@ -0,0 +1,43 @@
+-- Query fan-out coverage per platform, for the daily health report.
+--
+-- ChatGPT's observed fan-out came back empty from 2026-09-30 while its
+-- answers still carried sources: the engine was searching, the field just
+-- stopped arriving. Nothing noticed for two weeks, because an empty field
+-- reads exactly like an answer that ran no search. The health report now
+-- reads each platform's share of answers with fan-out over the last day and
+-- the days before, and flags one that stops (server/src/lib/health/report.js).
+--
+-- One aggregate over the window (idx_prompt_results_created_at), across every
+-- brand; no rows leave the database. Service role only.
+create or replace function public.fanout_coverage_by_platform(
+ p_since timestamptz,
+ p_until timestamptz
+)
+returns table (platform text, answers bigint, answers_with_fanout bigint)
+language sql
+stable
+security definer
+set search_path = public
+as $$
+ select
+ r.platform,
+ count(*)::bigint,
+ count(*) filter (
+ where case
+ when jsonb_typeof(r.search_queries) = 'array' then jsonb_array_length(r.search_queries)
+ else 0
+ end > 0
+ )::bigint
+ from public.prompt_results r
+ where r.created_at >= p_since
+ and r.created_at < p_until
+ group by r.platform;
+$$;
+
+revoke all on function public.fanout_coverage_by_platform(timestamptz, timestamptz)
+ from public, anon, authenticated;
+grant execute on function public.fanout_coverage_by_platform(timestamptz, timestamptz)
+ to service_role;
+
+comment on function public.fanout_coverage_by_platform(timestamptz, timestamptz) is
+ 'Answers and answers with observed query fan-out per platform in [p_since, p_until), across all brands (00140). Read by the daily health report.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index f58e5e7a5..1afc6ee00 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -17425,6 +17425,53 @@ comment on table public.prompt_usage_counters is
comment on function public.prompt_usage_summary(uuid) is
'One brand''s active/paused prompts and its account''s active prompts, brands and active prompt locations, from prompt_usage_counters only (PROMPT-012). Security invoker.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00140_fanout_coverage_by_platform.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Query fan-out coverage per platform, for the daily health report.
+--
+-- ChatGPT's observed fan-out came back empty from 2026-09-30 while its
+-- answers still carried sources: the engine was searching, the field just
+-- stopped arriving. Nothing noticed for two weeks, because an empty field
+-- reads exactly like an answer that ran no search. The health report now
+-- reads each platform's share of answers with fan-out over the last day and
+-- the days before, and flags one that stops (server/src/lib/health/report.js).
+--
+-- One aggregate over the window (idx_prompt_results_created_at), across every
+-- brand; no rows leave the database. Service role only.
+create or replace function public.fanout_coverage_by_platform(
+ p_since timestamptz,
+ p_until timestamptz
+)
+returns table (platform text, answers bigint, answers_with_fanout bigint)
+language sql
+stable
+security definer
+set search_path = public
+as $$
+ select
+ r.platform,
+ count(*)::bigint,
+ count(*) filter (
+ where case
+ when jsonb_typeof(r.search_queries) = 'array' then jsonb_array_length(r.search_queries)
+ else 0
+ end > 0
+ )::bigint
+ from public.prompt_results r
+ where r.created_at >= p_since
+ and r.created_at < p_until
+ group by r.platform;
+$$;
+
+revoke all on function public.fanout_coverage_by_platform(timestamptz, timestamptz)
+ from public, anon, authenticated;
+grant execute on function public.fanout_coverage_by_platform(timestamptz, timestamptz)
+ to service_role;
+
+comment on function public.fanout_coverage_by_platform(timestamptz, timestamptz) is
+ 'Answers and answers with observed query fan-out per platform in [p_since, p_until), across all brands (00140). Read by the daily health report.';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00147_insights_same_prompts_definer.sql
-- ─────────────────────────────────────────────────────────────────────────