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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(signals): show where a competitor beats you, prompt by prompt (#1063)
Cihancb6886589c9d
diff --git a/server/src/lib/signals/competitor-evidence.js b/server/src/lib/signals/competitor-evidence.jsnew file mode 100644index 000000000..f320ec744--- /dev/null+++ b/server/src/lib/signals/competitor-evidence.js@@ -0,0 +1,137 @@+/**+ * Where a competitor beats the brand (AC-001): per prompt and platform, the+ * competitor's position against the brand's, this week and last, and the+ * sources cited in the answers that name the competitor and not the brand.+ *+ * A competitor signal ("is gaining fast", "is mentioned far more than you",+ * "cited far more often") was recorded with the competitor's name and one+ * number. The positions come from the daily rollups through+ * ae_competitor_positions (00142); the sources from the newest answers on the+ * prompts where the competitor leads, read back for those prompts only.+ */++import supabaseAdmin from '../../config/supabase.js';+import { chunkIds } from '../chunked-in.js';+import { extractHostname, ownDomainMatcher } from '../response-parser.js';++const DAY_MS = 86_400_000;++/** Prompt rows per competitor: the panel shows a few, not every prompt. */+const POSITIONS_PER_COMPETITOR = 5;++/** Sources listed, and the newest answers read to find them. */+const MAX_SOURCES = 3;+const ANSWERS_READ = 60;++function isoDay(now, daysAgo) {+ return new Date(now.getTime() - daysAgo * DAY_MS).toISOString().slice(0, 10);+}++/**+ * The domains most cited in the answers a competitor wins: it is named, the+ * brand is not. The brand's own domains never count; the competitor's do,+ * since its own pages are part of why it wins.+ */+export function winningSources(answers, competitorId, isOwn) {+ const won = answers.filter((answer) => {+ const entry = (answer.competitor_mentions ?? []).find(+ (m) => String(m?.competitor_id) === String(competitorId),+ );+ return (entry?.mention_count ?? 0) > 0 && (answer.mention_count ?? 0) === 0;+ });+ const counts = new Map();+ for (const answer of won) {+ const domains = new Set(+ (answer.citations ?? [])+ .map((cite) => (cite?.url && !isOwn(cite.url) ? extractHostname(cite.url) : null))+ .filter(Boolean),+ );+ for (const domain of domains) counts.set(domain, (counts.get(domain) ?? 0) + 1);+ }+ return [...counts.entries()]+ .sort(([a, x], [b, y]) => y - x || a.localeCompare(b))+ .slice(0, MAX_SOURCES)+ .map(([domain, count]) => ({ domain, answers: count, answersRead: won.length }));+}++/** One position row, named for the panel. */+export function toPosition(row, texts) {+ return {+ promptId: row.prompt_id,+ promptText: texts.get(row.prompt_id) ?? '',+ platform: row.platform,+ competitor: { now: row.competitor_now, before: row.competitor_before },+ you: { now: row.brand_now, before: row.brand_before },+ };+}++/**+ * The evidence for each competitor, by competitor id: its positions against+ * the brand's on the prompts where it leads most, and the sources behind its+ * wins there. Four reads: the positions, the prompts' texts, the brand's+ * domains, and the newest answers per competitor.+ */+export async function competitorEvidence(brandId, competitorIds, { now, windowDays }) {+ const evidence = new Map();+ if (competitorIds.length === 0) return evidence;++ const { data: rows, error } = await supabaseAdmin.rpc('ae_competitor_positions', {+ p_brand_id: brandId,+ p_competitor_ids: competitorIds,+ p_cur_from: isoDay(now, windowDays - 1),+ p_cur_to: isoDay(now, 0),+ p_prev_from: isoDay(now, 2 * windowDays - 1),+ p_prev_to: isoDay(now, windowDays),+ p_limit: POSITIONS_PER_COMPETITOR,+ });+ if (error) throw new Error(`competitor positions read failed: ${error.message}`);++ const byCompetitor = new Map();+ for (const row of rows ?? []) {+ const list = byCompetitor.get(row.competitor_id);+ if (list) list.push(row);+ else byCompetitor.set(row.competitor_id, [row]);+ }+ const promptIds = [...new Set((rows ?? []).map((row) => row.prompt_id))];++ const [texts, domainsRes] = await Promise.all([+ promptTexts(promptIds),+ supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brandId),+ ]);+ if (domainsRes.error) throw new Error(domainsRes.error.message);+ const isOwn = ownDomainMatcher((domainsRes.data ?? []).map((r) => r.domain));+ const since = new Date(now.getTime() - windowDays * DAY_MS).toISOString();++ // Only answers that leave the brand out can be the competitor's wins, so+ // only those are read, the newest first, for every competitor at once.+ await Promise.all(+ [...byCompetitor].map(async ([competitorId, list]) => {+ const { data: answers, error: answersErr } = await supabaseAdmin+ .from('prompt_results')+ .select('mention_count, competitor_mentions, citations')+ .eq('brand_id', brandId)+ .neq('platform', 'chatgpt-shopping')+ .eq('mention_count', 0)+ .in('prompt_id', [...new Set(list.map((row) => row.prompt_id))])+ .gte('created_at', since)+ .order('created_at', { ascending: false })+ .limit(ANSWERS_READ);+ if (answersErr) throw new Error(`competitor answers read failed: ${answersErr.message}`);+ evidence.set(competitorId, {+ positions: list.map((row) => toPosition(row, texts)),+ winningSources: winningSources(answers ?? [], competitorId, isOwn),+ });+ }),+ );+ return evidence;+}++async function promptTexts(ids) {+ const texts = new Map();+ for (const chunk of chunkIds(ids)) {+ const { data, error } = await supabaseAdmin.from('prompts').select('id, text').in('id', chunk);+ if (error) throw new Error(`prompt texts read failed: ${error.message}`);+ for (const row of data ?? []) texts.set(row.id, String(row.text ?? '').slice(0, 160));+ }+ return texts;+}diff --git a/server/src/lib/signals/competitor-evidence.test.js b/server/src/lib/signals/competitor-evidence.test.jsnew file mode 100644index 000000000..4c6cec497--- /dev/null+++ b/server/src/lib/signals/competitor-evidence.test.js@@ -0,0 +1,128 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * A competitor signal's evidence (AC-001): per prompt and platform, the+ * competitor's position against the brand's, and the sources cited in the+ * answers the competitor wins.+ */++let rpcCalls = [];+let tables = {};++function builder(table) {+ const chain = {+ select: () => chain,+ eq: () => chain,+ neq: () => chain,+ in: () => chain,+ gte: () => chain,+ order: () => chain,+ limit: () => chain,+ then: (resolve) => resolve({ data: tables[table] ?? [], error: null }),+ };+ return chain;+}++vi.mock('../../config/supabase.js', () => ({+ default: {+ from: (table) => builder(table),+ rpc: async (name, params) => {+ rpcCalls.push({ name, params });+ return { data: tables.positions ?? [], error: null };+ },+ },+}));++const { competitorEvidence, winningSources } = await import('./competitor-evidence.js');+const { ownDomainMatcher } = await import('../response-parser.js');++const isOwn = ownDomainMatcher(['coffee.example']);+const answer = (competitorMentions, brandMentions, urls) => ({+ mention_count: brandMentions,+ competitor_mentions: Object.entries(competitorMentions).map(([id, count]) => ({+ competitor_id: id,+ mention_count: count,+ })),+ citations: urls.map((url) => ({ url })),+});++describe('winningSources', () => {+ it('counts the domains cited where the competitor is named and the brand is not', () => {+ const answers = [+ answer({ c1: 1 }, 0, [+ 'https://g2.example/a',+ 'https://rival.example/x',+ 'https://g2.example/b',+ ]),+ answer({ c1: 2 }, 0, ['https://g2.example/c', 'https://coffee.example/own']),+ // The brand is named here too: not a win for the competitor.+ answer({ c1: 1 }, 1, ['https://reddit.example/r']),+ // Another competitor's win.+ answer({ c2: 1 }, 0, ['https://reddit.example/r']),+ ];+ expect(winningSources(answers, 'c1', isOwn)).toEqual([+ { domain: 'g2.example', answers: 2, answersRead: 2 },+ { domain: 'rival.example', answers: 1, answersRead: 2 },+ ]);+ });+});++describe('competitorEvidence', () => {+ beforeEach(() => {+ rpcCalls = [];+ tables = {+ positions: [+ {+ competitor_id: 'c1',+ prompt_id: 'p1',+ platform: 'chatgpt-web',+ competitor_now: 1,+ competitor_before: 3,+ brand_now: 3,+ brand_before: 2,+ },+ ],+ prompts: [{ id: 'p1', text: 'Best AI rank tracker?' }],+ brand_domains: [{ domain: 'coffee.example' }],+ prompt_results: [answer({ c1: 1 }, 0, ['https://g2.example/a'])],+ };+ });++ it("reads the week's positions against last week's and names each prompt", async () => {+ const evidence = await competitorEvidence('b1', ['c1'], {+ now: new Date('2026-10-15T12:00:00Z'),+ windowDays: 7,+ });+ expect(rpcCalls).toEqual([+ {+ name: 'ae_competitor_positions',+ params: {+ p_brand_id: 'b1',+ p_competitor_ids: ['c1'],+ p_cur_from: '2026-10-09',+ p_cur_to: '2026-10-15',+ p_prev_from: '2026-10-02',+ p_prev_to: '2026-10-08',+ p_limit: 5,+ },+ },+ ]);+ expect(evidence.get('c1')).toEqual({+ positions: [+ {+ promptId: 'p1',+ promptText: 'Best AI rank tracker?',+ platform: 'chatgpt-web',+ competitor: { now: 1, before: 3 },+ you: { now: 3, before: 2 },+ },+ ],+ winningSources: [{ domain: 'g2.example', answers: 1, answersRead: 1 }],+ });+ });++ it('reads nothing when no competitor signal needs it', async () => {+ expect((await competitorEvidence('b1', [], { now: new Date(), windowDays: 7 })).size).toBe(0);+ expect(rpcCalls).toEqual([]);+ });+});diff --git a/server/src/lib/signals/nightly-reads.test.js b/server/src/lib/signals/nightly-reads.test.jsindex 8f27ed967..9d1249c1b 100644--- a/server/src/lib/signals/nightly-reads.test.js+++ b/server/src/lib/signals/nightly-reads.test.js@@ -20,6 +20,7 @@ import { describe, expect, it } from 'vitest';const NIGHTLY_MODULES = ['src/lib/signals/record.js','src/lib/signals/lost-citation-evidence.js',+ 'src/lib/signals/competitor-evidence.js','src/lib/pulse/metrics.js','src/lib/action-center/generate.js','src/lib/action-center/validate.js',diff --git a/server/src/lib/signals/record-evidence.test.js b/server/src/lib/signals/record-evidence.test.jsindex 7f3dedbcd..ac95ef5d6 100644--- a/server/src/lib/signals/record-evidence.test.js+++ b/server/src/lib/signals/record-evidence.test.js@@ -25,7 +25,17 @@ vi.mock('./lost-citation-evidence.js', () => ({},}));-const { attachLostCitationEvidence, keepRecordedEvidence } = await import('./record.js');+let competitorRead = { calls: [], result: new Map(), fail: false };+vi.mock('./competitor-evidence.js', () => ({+ competitorEvidence: async (...args) => {+ competitorRead.calls.push(args);+ if (competitorRead.fail) throw new Error('timeout');+ return competitorRead.result;+ },+}));++const { attachCompetitorEvidence, attachLostCitationEvidence, keepRecordedEvidence } =+ await import('./record.js');const lost = (promptId) => ({kind: 'lost_citations',@@ -45,6 +55,7 @@ const evidence = {beforeEach(() => {read = { calls: [], result: new Map(), fail: false };+ competitorRead = { calls: [], result: new Map(), fail: false };});describe('attachLostCitationEvidence', () => {@@ -112,3 +123,71 @@ describe('keepRecordedEvidence', () => {expect(fresh.payload.citedDays).toBe(10);});});++describe('attachCompetitorEvidence', () => {+ const found = {+ positions: [+ { promptId: 'p1', platform: 'chatgpt-web', competitor: { now: 1 }, you: { now: 3 } },+ ],+ winningSources: [{ domain: 'g2.example', answers: 2, answersRead: 3 }],+ };++ it('finds the competitor in the payload or the key, and writes its evidence', async () => {+ competitorRead.result = new Map([+ ['c1', found],+ ['c2', found],+ ]);+ const candidates = [+ {+ kind: 'competitor_momentum',+ dedupKey: 'competitor_momentum:c1',+ payload: { competitorId: 'c1' },+ },+ {+ kind: 'competitor_surge',+ dedupKey: 'competitor_surge:c2',+ payload: { competitorName: 'Rival' },+ },+ { kind: 'topic_drop', dedupKey: 'topic_drop:t1', payload: {} },+ ];+ await attachCompetitorEvidence('b1', candidates, new Date('2026-10-15T00:00:00Z'));+ expect(competitorRead.calls).toEqual([+ ['b1', ['c1', 'c2'], { now: new Date('2026-10-15T00:00:00Z'), windowDays: 7 }],+ ]);+ expect(candidates[0].payload).toEqual({ competitorId: 'c1', ...found });+ expect(candidates[1].payload).toEqual({+ competitorName: 'Rival',+ competitorId: 'c2',+ ...found,+ });+ expect(candidates[2].payload).toEqual({});+ });++ it('records the signals without evidence when the read fails', async () => {+ competitorRead.fail = true;+ const candidates = [+ {+ kind: 'competitor_leads',+ dedupKey: 'competitor_leads:c1',+ payload: { competitorId: 'c1' },+ },+ ];+ await expect(attachCompetitorEvidence('b1', candidates, new Date())).resolves.toBeUndefined();+ expect(candidates[0].payload).toEqual({ competitorId: 'c1' });+ });++ it("keeps an earlier night's competitor evidence", () => {+ const candidates = [+ {+ kind: 'competitor_leads',+ dedupKey: 'competitor_leads:c1',+ payload: { competitorId: 'c1' },+ },+ ];+ keepRecordedEvidence(+ candidates,+ new Map([['competitor_leads:c1', { payload: { competitorId: 'c1', ...found } }]]),+ );+ expect(candidates[0].payload).toEqual({ competitorId: 'c1', ...found });+ });+});diff --git a/server/src/lib/signals/record.js b/server/src/lib/signals/record.jsindex b642cecfa..affbcd8a8 100644--- a/server/src/lib/signals/record.js+++ b/server/src/lib/signals/record.js@@ -29,6 +29,7 @@import supabaseAdmin from '../../config/supabase.js';import { computePulseMetrics, LOST_CITATION_WINDOW_DAYS } from '../pulse/metrics.js';import { lostCitationEvidence } from './lost-citation-evidence.js';+import { competitorEvidence } from './competitor-evidence.js';import { logger } from '../logger.js';import { readAllRpcRows } from '../rpc-pages.js';import { resolve } from '../../config/action-engine.js';@@ -575,33 +576,78 @@ export async function attachLostCitationEvidence(brandId, candidates, now) {}}-const EVIDENCE_FIELDS = [- 'platforms',- 'regions',- 'citedDays',- 'days',- 'quietDays',- 'lostUrls',- 'citedNow',-];+// What each kind's evidence step writes, and the field that marks it written.+const EVIDENCE = {+ lost_citations: {+ marker: 'citedDays',+ fields: ['platforms', 'regions', 'citedDays', 'days', 'quietDays', 'lostUrls', 'citedNow'],+ },+};++// Signals about one competitor, which get its positions and winning sources.+const COMPETITOR_KINDS = new Set([+ 'competitor_leads',+ 'competitor_momentum',+ 'competitor_surge',+ 'competitor_crossed',+ 'competitor_overtaken',+ 'competitor_citation_gap',+]);+for (const kind of COMPETITOR_KINDS) {+ EVIDENCE[kind] = { marker: 'positions', fields: ['positions', 'winningSources'] };+}/**- * A night whose evidence read failed refreshes a lost citation with the bare- * pulse payload. Keep what an earlier night recorded instead: it is older,+ * A night whose evidence read failed refreshes a signal with its bare+ * detector payload. Keep what an earlier night recorded instead: it is older,* and still truer than nothing.*/export function keepRecordedEvidence(candidates, existing) {for (const candidate of candidates) {- if (candidate.kind !== 'lost_citations' || 'citedDays' in (candidate.payload ?? {})) continue;+ const evidence = EVIDENCE[candidate.kind];+ if (!evidence || evidence.marker in (candidate.payload ?? {})) continue;const recorded = existing.get(candidate.dedupKey)?.payload ?? {};- if (!('citedDays' in recorded)) continue;+ if (!(evidence.marker in recorded)) continue;const kept = Object.fromEntries(- EVIDENCE_FIELDS.filter((key) => key in recorded).map((key) => [key, recorded[key]]),+ evidence.fields.filter((key) => key in recorded).map((key) => [key, recorded[key]]),);candidate.payload = { ...candidate.payload, ...kept };}}+/** The competitor a signal is about: the library names it, the others key on it. */+function competitorOf(candidate) {+ const named = candidate.payload?.competitorId;+ if (typeof named === 'string' && named) return named;+ return subjectOf(candidate.dedupKey);+}++/**+ * Competitor signals arrive naming the competitor and one number. Before they+ * are written they get what the drawer shows (AC-001): per prompt and+ * platform, the competitor's position against the brand's, and the sources+ * behind its wins. Best effort, like the lost-citation evidence.+ */+export async function attachCompetitorEvidence(brandId, candidates, now) {+ const about = candidates+ .filter((c) => COMPETITOR_KINDS.has(c.kind))+ .map((candidate) => ({ candidate, id: competitorOf(candidate) }))+ .filter(({ id }) => id);+ if (about.length === 0) return;+ try {+ const evidence = await competitorEvidence(brandId, [...new Set(about.map(({ id }) => id))], {+ now,+ windowDays: libraryThresholds.windowDays,+ });+ for (const { candidate, id } of about) {+ const found = evidence.get(id);+ if (found) candidate.payload = { ...candidate.payload, competitorId: id, ...found };+ }+ } catch (err) {+ logger.warn({ brandId, err: err.message }, '[signals] competitor evidence unavailable');+ }+}+/*** Open, persistent signals nothing detected tonight, split by why.*@@ -690,6 +736,7 @@ export async function recordSignalsForBrand(brandId, { now = new Date() } = {})const overflow = library.overflow.filter((candidate) => !(outage && DECLINE_KINDS.has(candidate.kind)),);+ await attachCompetitorEvidence(brandId, [...candidates, ...overflow], now);// Existing rows decide insert vs update vs reopen. A brand's signal set is// small (tens), so reading it whole is cheaper than being clever.@@ -700,7 +747,7 @@ export async function recordSignalsForBrand(brandId, { now = new Date() } = {}).limit(1000);if (readErr) throw new Error(readErr.message);const existing = new Map((existingRows ?? []).map((row) => [row.dedup_key, row]));- keepRecordedEvidence(candidates, existing);+ keepRecordedEvidence([...candidates, ...overflow], existing);const nowIso = now.toISOString();let inserted = 0;diff --git a/supabase/migrations/00142_competitor_signal_positions.sql b/supabase/migrations/00142_competitor_signal_positions.sqlnew file mode 100644index 000000000..7d152d636--- /dev/null+++ b/supabase/migrations/00142_competitor_signal_positions.sql@@ -0,0 +1,111 @@+-- Where a competitor beats the brand, prompt by prompt (AC-001).+--+-- A competitor signal ("Profound is gaining fast", "… is mentioned far more+-- than you") said who and how much, never where: the panel is to show, per+-- prompt and platform, the competitor's position against the brand's, this+-- week and last. The daily rollups already hold mention positions per+-- prompt, platform and day for the brand (insights_prompt_daily) and per+-- competitor (insights_competitor_prompt_daily), so this reads those rather+-- than the answers, like the other ae_* detector reads (00091).+--+-- A position is the harmonic mean over the answers that name the entity:+-- position_count / sum_inv_position, from the same columns for both sides so+-- the two compare like with like. Only rows where the competitor is level+-- with or ahead of the brand (or the brand is not named) are evidence of a+-- competitor signal; those where it leads by most come first, and only the+-- first p_limit are returned per competitor.+--+-- plpgsql with force_custom_plan, as 00147, 00148 and 00152: a SQL-language+-- function is planned without its argument values, so the day range was a+-- guess. On the largest brand, with its 19 competitors over two weeks, the+-- read took 28.6 s that way and 0.16 s planned with its arguments.++create or replace function public.ae_competitor_positions(+ p_brand_id uuid,+ p_competitor_ids text[],+ p_cur_from date,+ p_cur_to date,+ p_prev_from date,+ p_prev_to date,+ p_limit integer default 5+) returns jsonb+language plpgsql+stable+set search_path = public+set work_mem to '64MB'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_result jsonb;+begin+ with competitor as (+ select competitor_id, prompt_id, platform,+ sum(position_count) filter (where day between p_cur_from and p_cur_to) as cur_n,+ sum(sum_inv_position) filter (where day between p_cur_from and p_cur_to) as cur_inv,+ sum(position_count) filter (where day between p_prev_from and p_prev_to) as prev_n,+ sum(sum_inv_position) filter (where day between p_prev_from and p_prev_to) as prev_inv+ from insights_competitor_prompt_daily+ where brand_id = p_brand_id+ and competitor_id = any(p_competitor_ids)+ and day between p_prev_from and p_cur_to+ and platform is not null+ group by competitor_id, prompt_id, platform+ ),+ brand as (+ select prompt_id, platform,+ sum(position_count) filter (where day between p_cur_from and p_cur_to) as cur_n,+ sum(sum_inv_position) filter (where day between p_cur_from and p_cur_to) as cur_inv,+ sum(position_count) filter (where day between p_prev_from and p_prev_to) as prev_n,+ sum(sum_inv_position) filter (where day between p_prev_from and p_prev_to) as prev_inv+ from insights_prompt_daily+ where brand_id = p_brand_id+ and day between p_prev_from and p_cur_to+ and prompt_id in (select prompt_id from competitor)+ and platform is not null+ group by prompt_id, platform+ ),+ positions as (+ select c.competitor_id, c.prompt_id, c.platform,+ round(c.cur_n / nullif(c.cur_inv, 0), 1) as competitor_now,+ round(c.prev_n / nullif(c.prev_inv, 0), 1) as competitor_before,+ round(b.cur_n / nullif(b.cur_inv, 0), 1) as brand_now,+ round(b.prev_n / nullif(b.prev_inv, 0), 1) as brand_before+ from competitor c+ left join brand b on b.prompt_id = c.prompt_id and b.platform = c.platform+ where coalesce(c.cur_n, 0) > 0 and coalesce(c.cur_inv, 0) > 0+ ),+ ahead as (+ select * from positions+ where brand_now is null or competitor_now <= brand_now+ ),+ ranked as (+ select p.*, row_number() over (+ partition by p.competitor_id+ order by coalesce(p.brand_now, 99) - p.competitor_now desc, p.competitor_now, p.prompt_id+ ) as rank+ from ahead p+ )+ select coalesce(jsonb_agg(+ jsonb_build_object(+ 'competitor_id', competitor_id,+ 'prompt_id', prompt_id,+ 'platform', platform,+ 'competitor_now', competitor_now,+ 'competitor_before', competitor_before,+ 'brand_now', brand_now,+ 'brand_before', brand_before+ ) order by competitor_id, rank+ ), '[]'::jsonb)+ into v_result+ from ranked+ where rank <= p_limit;++ return v_result;+end;+$$;++-- Service-role only, like the other detector reads.+revoke all on function public.ae_competitor_positions(uuid, text[], date, date, date, date, integer)+ from public, anon, authenticated;+grant execute on function public.ae_competitor_positions(uuid, text[], date, date, date, date, integer)+ to service_role;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex c3f9be966..228f38fc5 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -17646,6 +17646,121 @@ as $$where brand_id = p_brand_id and status = 'new';$$;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00142_competitor_signal_positions.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Where a competitor beats the brand, prompt by prompt (AC-001).+--+-- A competitor signal ("Profound is gaining fast", "… is mentioned far more+-- than you") said who and how much, never where: the panel is to show, per+-- prompt and platform, the competitor's position against the brand's, this+-- week and last. The daily rollups already hold mention positions per+-- prompt, platform and day for the brand (insights_prompt_daily) and per+-- competitor (insights_competitor_prompt_daily), so this reads those rather+-- than the answers, like the other ae_* detector reads (00091).+--+-- A position is the harmonic mean over the answers that name the entity:+-- position_count / sum_inv_position, from the same columns for both sides so+-- the two compare like with like. Only rows where the competitor is level+-- with or ahead of the brand (or the brand is not named) are evidence of a+-- competitor signal; those where it leads by most come first, and only the+-- first p_limit are returned per competitor.+--+-- plpgsql with force_custom_plan, as 00147, 00148 and 00152: a SQL-language+-- function is planned without its argument values, so the day range was a+-- guess. On the largest brand, with its 19 competitors over two weeks, the+-- read took 28.6 s that way and 0.16 s planned with its arguments.++create or replace function public.ae_competitor_positions(+ p_brand_id uuid,+ p_competitor_ids text[],+ p_cur_from date,+ p_cur_to date,+ p_prev_from date,+ p_prev_to date,+ p_limit integer default 5+) returns jsonb+language plpgsql+stable+set search_path = public+set work_mem to '64MB'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_result jsonb;+begin+ with competitor as (+ select competitor_id, prompt_id, platform,+ sum(position_count) filter (where day between p_cur_from and p_cur_to) as cur_n,+ sum(sum_inv_position) filter (where day between p_cur_from and p_cur_to) as cur_inv,+ sum(position_count) filter (where day between p_prev_from and p_prev_to) as prev_n,+ sum(sum_inv_position) filter (where day between p_prev_from and p_prev_to) as prev_inv+ from insights_competitor_prompt_daily+ where brand_id = p_brand_id+ and competitor_id = any(p_competitor_ids)+ and day between p_prev_from and p_cur_to+ and platform is not null+ group by competitor_id, prompt_id, platform+ ),+ brand as (+ select prompt_id, platform,+ sum(position_count) filter (where day between p_cur_from and p_cur_to) as cur_n,+ sum(sum_inv_position) filter (where day between p_cur_from and p_cur_to) as cur_inv,+ sum(position_count) filter (where day between p_prev_from and p_prev_to) as prev_n,+ sum(sum_inv_position) filter (where day between p_prev_from and p_prev_to) as prev_inv+ from insights_prompt_daily+ where brand_id = p_brand_id+ and day between p_prev_from and p_cur_to+ and prompt_id in (select prompt_id from competitor)+ and platform is not null+ group by prompt_id, platform+ ),+ positions as (+ select c.competitor_id, c.prompt_id, c.platform,+ round(c.cur_n / nullif(c.cur_inv, 0), 1) as competitor_now,+ round(c.prev_n / nullif(c.prev_inv, 0), 1) as competitor_before,+ round(b.cur_n / nullif(b.cur_inv, 0), 1) as brand_now,+ round(b.prev_n / nullif(b.prev_inv, 0), 1) as brand_before+ from competitor c+ left join brand b on b.prompt_id = c.prompt_id and b.platform = c.platform+ where coalesce(c.cur_n, 0) > 0 and coalesce(c.cur_inv, 0) > 0+ ),+ ahead as (+ select * from positions+ where brand_now is null or competitor_now <= brand_now+ ),+ ranked as (+ select p.*, row_number() over (+ partition by p.competitor_id+ order by coalesce(p.brand_now, 99) - p.competitor_now desc, p.competitor_now, p.prompt_id+ ) as rank+ from ahead p+ )+ select coalesce(jsonb_agg(+ jsonb_build_object(+ 'competitor_id', competitor_id,+ 'prompt_id', prompt_id,+ 'platform', platform,+ 'competitor_now', competitor_now,+ 'competitor_before', competitor_before,+ 'brand_now', brand_now,+ 'brand_before', brand_before+ ) order by competitor_id, rank+ ), '[]'::jsonb)+ into v_result+ from ranked+ where rank <= p_limit;++ return v_result;+end;+$$;++-- Service-role only, like the other detector reads.+revoke all on function public.ae_competitor_positions(uuid, text[], date, date, date, date, integer)+ from public, anon, authenticated;+grant execute on function public.ae_competitor_positions(uuid, text[], date, date, date, date, integer)+ to service_role;+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00147_insights_same_prompts_definer.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 887ae938d..bf32e53c8 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -350,6 +350,13 @@"viewPrompt": "View prompt","notAvailable": "Not available","allPlatforms": "All tracked platforms",+ "positions": {+ "you": "You",+ "new": "new",+ "lost": "lost",+ "untitled": "Untitled prompt",+ "sourceAnswers": "cited in {count} of the {of, plural, one {# latest answer} other {# latest answers}} they win"+ },"cited": {"position": "#{position}","lastCited": "last cited {date}",diff --git a/web/src/components/action-center/signal-detail-blocks.test.tsx b/web/src/components/action-center/signal-detail-blocks.test.tsxindex 8b979fdad..ebffd1d20 100644--- a/web/src/components/action-center/signal-detail-blocks.test.tsx+++ b/web/src/components/action-center/signal-detail-blocks.test.tsx@@ -209,6 +209,57 @@ describe('a lost citation with its evidence', () => {});});+describe('a competitor signal with its evidence', () => {+ it('shows positions by prompt and the sources behind its wins', () => {+ render(+ <SignalWhereBlock+ signal={signal({+ category: 'competitor',+ kind: 'competitor_momentum',+ payload: {+ entity: 'competitors',+ competitorName: 'Profound',+ positions: [+ {+ promptId: 'p1',+ promptText: 'Best AI rank tracker?',+ platform: 'chatgpt-web',+ competitor: { now: 1, before: 3 },+ you: { now: 3, before: 2 },+ },+ {+ promptId: 'p2',+ promptText: 'AI rank tracker comparison',+ platform: 'perplexity-web',+ competitor: { now: 2, before: null },+ you: { now: null, before: 4 },+ },+ ],+ winningSources: [{ domain: 'g2.example', answers: 2, answersRead: 3 }],+ },+ where: NO_WHERE,+ })}+ />,+ );+ const rows = [...container.querySelectorAll('dt')].map(+ (dt) => `${dt.textContent}: ${dt.nextElementSibling?.textContent}`,+ );+ expect(rows).toContain(+ 'Positions by prompt: Best AI rank tracker?ChatGPT · Profound #1 ↑2 · You #3 ↓1' ++ 'AI rank tracker comparisonPerplexity · Profound #2 new · You — lost',+ );+ expect(rows).toContain(+ 'Sources behind their wins: g2.examplecited in 2 of the 3 latest answers they win',+ );+ expect(rows).toContain('Platforms: ChatGPTPerplexity');+ // A competitor's climb and the brand's fall are both bad news.+ const tone = (text: string) =>+ [...container.querySelectorAll('span')].find((s) => s.textContent === text)?.className;+ expect(tone(' ↑2')).toContain('text-red-600');+ expect(tone(' ↓1')).toContain('text-red-600');+ });+});+describe('SignalEvidenceBlock', () => {it('links the answers and the action the signal is used by', async () => {getSignalActions.mockResolvedValue([diff --git a/web/src/components/action-center/signal-detail-blocks.tsx b/web/src/components/action-center/signal-detail-blocks.tsxindex 817f9abcb..bdea6b20c 100644--- a/web/src/components/action-center/signal-detail-blocks.tsx+++ b/web/src/components/action-center/signal-detail-blocks.tsx@@ -127,6 +127,43 @@ function WhereValueView({ value }: { value: WhereValue }) {);case 'all_platforms':return <span>{t('drawer.allPlatforms')}</span>;+ case 'positions':+ return (+ <ul className="space-y-1.5">+ {value.items.map((row) => (+ <li key={`${row.promptId}-${row.platform}`}>+ <Link+ href={`/dashboard/prompts/${row.promptId}`}+ className="break-words underline-offset-2 hover:underline"+ >+ {row.promptText || t('drawer.positions.untitled')}+ </Link>+ <span className="block text-xs text-muted-foreground">+ {platformName(row.platform)} ·{' '}+ {value.competitor || t('drawer.change.roles.unnamed')}{' '}+ <PositionMove position={row.competitor} side="competitor" /> ·{' '}+ {t('drawer.positions.you')} <PositionMove position={row.you} side="you" />+ </span>+ </li>+ ))}+ </ul>+ );+ case 'sources':+ return (+ <ul className="space-y-1">+ {value.items.map((source) => (+ <li key={source.domain}>+ <span className="break-all">{source.domain}</span>+ <span className="block text-xs text-muted-foreground">+ {t('drawer.positions.sourceAnswers', {+ count: source.answers,+ of: source.answersRead,+ })}+ </span>+ </li>+ ))}+ </ul>+ );case 'citations':return (<ul className="space-y-1">@@ -160,6 +197,53 @@ function WhereValueView({ value }: { value: WhereValue }) {}}+/**+ * "#1 ↑2": a position this week and how it moved since last week (1 is named+ * first, so a smaller number is up). "—" when not named this week. Coloured+ * as news for the brand: its own climb is good, a competitor's is not.+ */+function PositionMove({+ position,+ side,+}: {+ position: { now: number | null; before: number | null };+ side: 'competitor' | 'you';+}) {+ const t = useTranslations('actionCenter.signalsPage.drawer.positions');+ const format = useFormatter();+ const n = (value: number) => format.number(value, { maximumFractionDigits: 1 });+ if (position.now === null) {+ return (+ <span className="font-medium text-foreground">+ —+ {position.before !== null && (+ <span className="text-red-600 dark:text-red-400"> {t('lost')}</span>+ )}+ </span>+ );+ }+ const moved =+ position.before === null ? null : Math.round((position.before - position.now) * 10) / 10;+ const tone = (up: boolean) =>+ up !== (side === 'competitor')+ ? 'text-green-600 dark:text-green-400'+ : 'text-red-600 dark:text-red-400';+ return (+ <span className="font-medium text-foreground">+ #{n(position.now)}+ {moved === null ? (+ <span className="text-muted-foreground"> {t('new')}</span>+ ) : moved > 0 ? (+ <span className={tone(true)}> ↑{n(moved)}</span>+ ) : moved < 0 ? (+ <span className={tone(false)}> ↓{n(-moved)}</span>+ ) : (+ <span className="text-muted-foreground"> =</span>+ )}+ </span>+ );+}+export function SignalWhereBlock({ signal }: { signal: Signal }) {const t = useTranslations('actionCenter.signalsPage.drawer');const fields = signalWhereFields(signal);diff --git a/web/src/lib/signals/detail.test.ts b/web/src/lib/signals/detail.test.tsindex e33543e6f..ea8839e83 100644--- a/web/src/lib/signals/detail.test.ts+++ b/web/src/lib/signals/detail.test.ts@@ -331,3 +331,65 @@ describe('a lost citation with its evidence recorded', () => {});});});++describe('a competitor signal with its evidence recorded', () => {+ const recorded = signal({+ category: 'competitor',+ kind: 'competitor_momentum',+ payload: {+ entity: 'competitors',+ competitorName: 'Profound',+ competitorId: 'c1',+ targets: [{ id: 'c1', label: 'Profound' }],+ positions: [+ {+ promptId: 'p1',+ promptText: 'Best AI rank tracker?',+ platform: 'chatgpt-web',+ competitor: { now: 1, before: 3 },+ you: { now: 3, before: 2 },+ },+ ],+ winningSources: [{ domain: 'g2.example', answers: 2, answersRead: 3 }],+ },+ previousValue: 12,+ currentValue: 31,+ });++ it('shows its positions by prompt, the sources behind its wins, and where it leads', () => {+ const byKey = Object.fromEntries(signalWhereFields(recorded).map((f) => [f.key, f.value]));+ expect(byKey.competitor).toEqual({ type: 'text', text: 'Profound' });+ expect(byKey.platforms).toEqual({ type: 'platforms', slugs: ['chatgpt-web'] });+ expect(byKey.competitorPositions).toEqual({+ type: 'positions',+ competitor: 'Profound',+ items: [+ {+ promptId: 'p1',+ promptText: 'Best AI rank tracker?',+ platform: 'chatgpt-web',+ competitor: { now: 1, before: 3 },+ you: { now: 3, before: 2 },+ },+ ],+ });+ expect(byKey.winningSources).toEqual({+ type: 'sources',+ items: [{ domain: 'g2.example', answers: 2, answersRead: 3 }],+ });+ });++ it('returns the same over the API', () => {+ const { where } = signalDetailForApi(recorded, []);+ expect(where.competitor_positions).toEqual([+ {+ prompt_id: 'p1',+ prompt_text: 'Best AI rank tracker?',+ platform: { slug: 'chatgpt-web', name: 'ChatGPT' },+ competitor: { now: 1, before: 3 },+ you: { now: 3, before: 2 },+ },+ ]);+ expect(where.winning_sources).toEqual([{ domain: 'g2.example', answers: 2, answers_read: 3 }]);+ });+});diff --git a/web/src/lib/signals/detail.ts b/web/src/lib/signals/detail.tsindex 2991046b7..9e69007fc 100644--- a/web/src/lib/signals/detail.ts+++ b/web/src/lib/signals/detail.ts@@ -367,6 +367,10 @@ export type WhereValue =| { type: 'all_platforms' }/** Cited pages: the brand's lost ones, or those cited in their place. */| { type: 'citations'; items: CitedPage[] }+ /** A competitor's position against the brand's, per prompt and platform. */+ | { type: 'positions'; competitor: string; items: PromptPosition[] }+ /** Domains cited in the answers a competitor wins. */+ | { type: 'sources'; items: WinningSource[] }| { type: 'locations'; codes: readonly string[] }| { type: 'number'; value: number };@@ -393,6 +397,54 @@ function citedPages(value: unknown): CitedPage[] {}));}+/** Positions are averages over the week's answers (1 = named first); null when not named. */+export interface PromptPosition {+ promptId: string;+ promptText: string;+ platform: string;+ competitor: { now: number | null; before: number | null };+ you: { now: number | null; before: number | null };+}++export interface WinningSource {+ domain: string;+ /** Answers it is cited in, of the answers read that the competitor wins. */+ answers: number;+ answersRead: number;+}++function num(value: unknown): number | null {+ return typeof value === 'number' ? value : null;+}++function promptPositions(value: unknown): PromptPosition[] {+ if (!Array.isArray(value)) return [];+ return value+ .filter((v): v is Record<string, unknown> => typeof v?.promptId === 'string')+ .map((v) => {+ const competitor = (v.competitor ?? {}) as Record<string, unknown>;+ const you = (v.you ?? {}) as Record<string, unknown>;+ return {+ promptId: v.promptId as string,+ promptText: typeof v.promptText === 'string' ? v.promptText : '',+ platform: typeof v.platform === 'string' ? v.platform : '',+ competitor: { now: num(competitor.now), before: num(competitor.before) },+ you: { now: num(you.now), before: num(you.before) },+ };+ });+}++function winningSourcesOf(value: unknown): WinningSource[] {+ if (!Array.isArray(value)) return [];+ return value+ .filter((v): v is Record<string, unknown> => typeof v?.domain === 'string')+ .map((v) => ({+ domain: v.domain as string,+ answers: num(v.answers) ?? 0,+ answersRead: num(v.answersRead) ?? 0,+ }));+}+export interface WhereField {key: WhereFieldKey;/** Null when no detector records it yet: the panel says "Not available". */@@ -547,10 +599,13 @@ function fieldValue(signal: Signal, key: WhereFieldKey): WhereValue | null {if (topics.length > 1) return { type: 'list', items: [...topics], total: topics.length };return topics[0] ? { type: 'text', text: topics[0] } : null;}- case 'platforms':+ case 'platforms': {if (signal.where.platforms.length) {return { type: 'platforms', slugs: signal.where.platforms };}+ // A competitor's recorded positions say which platforms it leads on.+ const leading = [...new Set(promptPositions(p.positions).map((row) => row.platform))];+ if (leading.length) return { type: 'platforms', slugs: leading.filter(Boolean) };if (signal.kind === 'sharp_drop' ||signal.kind === 'visibility_slipping' ||@@ -559,6 +614,7 @@ function fieldValue(signal: Signal, key: WhereFieldKey): WhereValue | null {return { type: 'all_platforms' };}return null;+ }case 'locations':return signal.where.regions.length? { type: 'locations', codes: signal.where.regions }@@ -605,6 +661,16 @@ function fieldValue(signal: Signal, key: WhereFieldKey): WhereValue | null {const now = citedPages(p.citedNow);return now.length ? { type: 'citations', items: now } : null;}+ case 'competitorPositions': {+ const rows = promptPositions(p.positions);+ return rows.length+ ? { type: 'positions', competitor: str(p, 'competitorName'), items: rows }+ : null;+ }+ case 'winningSources': {+ const sources = winningSourcesOf(p.winningSources);+ return sources.length ? { type: 'sources', items: sources } : null;+ }case 'evidence': {const checks = targets.flatMap((t) =>Array.isArray(t.checks) ? t.checks.filter((c): c is string => typeof c === 'string') : [],@@ -629,7 +695,9 @@ function placeIsNamed(signal: Signal): boolean {return (typeof p.platform === 'string' ||typeof p.region === 'string' ||- (Array.isArray(p.platforms) && p.platforms.length > 0)+ (Array.isArray(p.platforms) && p.platforms.length > 0) ||+ // A competitor's recorded positions name the platforms it leads on.+ (Array.isArray(p.positions) && p.positions.length > 0));}@@ -730,6 +798,20 @@ function apiValue(value: WhereValue): unknown {return value.slugs.map((slug) => ({ slug, name: platformName(slug) }));case 'all_platforms':return 'all';+ case 'positions':+ return value.items.map((row) => ({+ prompt_id: row.promptId,+ prompt_text: row.promptText,+ platform: { slug: row.platform, name: platformName(row.platform) },+ competitor: row.competitor,+ you: row.you,+ }));+ case 'sources':+ return value.items.map((source) => ({+ domain: source.domain,+ answers: source.answers,+ answers_read: source.answersRead,+ }));case 'citations':return value.items.map((page) => ({url: page.url,