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(signals): show where the brand is mentioned without a citation (#1064)

Cihandfb4513f53b6
diff --git a/server/src/lib/response-parser.js b/server/src/lib/response-parser.js
index 59ac6965a..25c0c2d70 100644
--- a/server/src/lib/response-parser.js
+++ b/server/src/lib/response-parser.js
@@ -57,6 +57,47 @@ function countOccurrences(text, term) {
return (text.match(nameRegex(term, 'gi')) || []).length;
}
+/**
+ * A short quote of the answer around the brand's first mention, for the
+ * Action Center's mention evidence (AC-001): the same name and domain
+ * matching as the mention count, on the answer stripped of links and
+ * markdown marks, cut to about `radius` characters on each side. Null when
+ * the answer does not name the brand.
+ */
+export function mentionExcerpt(text, brand, radius = 110) {
+ // Markdown's marks only: headings, quotes and list bullets at the start of
+ // a line, bold and code anywhere. A "#1" or "A > B" in a sentence stays.
+ const clean = stripUrls(String(text ?? ''))
+ .replace(/^[ \t]{0,3}#{1,6}[ \t]+/gm, '')
+ .replace(/^[ \t]*>[ \t]?/gm, '')
+ .replace(/^[ \t]*[*+-][ \t]+/gm, '')
+ .replace(/\*\*|__|`/g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+ let at = -1;
+ let length = 0;
+ for (const term of [brand?.brandName, ...(brand?.domains ?? [])].filter(Boolean)) {
+ const index = firstOccurrenceIndex(clean, term);
+ if (index >= 0 && (at < 0 || index < at)) {
+ at = index;
+ length = term.length;
+ }
+ }
+ if (at < 0) return null;
+ // Cut on spaces, so the quote starts and ends on whole words.
+ let start = Math.max(0, at - radius);
+ if (start > 0) {
+ const space = clean.indexOf(' ', start);
+ start = space >= 0 && space < at ? space + 1 : start;
+ }
+ let end = Math.min(clean.length, at + length + radius);
+ if (end < clean.length) {
+ const space = clean.lastIndexOf(' ', end);
+ end = space > at + length ? space : end;
+ }
+ return `${start > 0 ? '…' : ''}${clean.slice(start, end).trim()}${end < clean.length ? '…' : ''}`;
+}
+
/**
* Normalized hostname of a URL ("https://www.FOO.com/bar" → "foo.com").
* Mirrors extractHostname in web/src/lib/citations/classify.ts — keep the two
diff --git a/server/src/lib/response-parser.test.js b/server/src/lib/response-parser.test.js
index 43599bdee..bf50267f3 100644
--- a/server/src/lib/response-parser.test.js
+++ b/server/src/lib/response-parser.test.js
@@ -4,6 +4,7 @@ import {
computeMentionPosition,
countBrandMentions,
parseResponse,
+ mentionExcerpt,
} from './response-parser.js';
describe('response-parser', () => {
@@ -475,3 +476,35 @@ describe('brandMentionRanges', () => {
]);
});
});
+
+describe('mentionExcerpt', () => {
+ const brand = { brandName: 'Acme Coffee', domains: ['acme-coffee.example.com'] };
+
+ it('quotes the answer around the first mention, without links or markdown marks', () => {
+ const text = `${'Intro words. '.repeat(20)}Our pick is **Acme Coffee** ([site](https://x.example)) for offices.`;
+ expect(mentionExcerpt(text, brand, 20)).toBe(
+ '…words. Our pick is Acme Coffee (site) for offices.',
+ );
+ // A cut inside a word moves to the next whole word.
+ expect(mentionExcerpt(text, brand, 22)).toBe(
+ '…words. Our pick is Acme Coffee (site) for offices.',
+ );
+ expect(mentionExcerpt(`Acme Coffee is a pick for remote offices`, brand, 5)).toBe(
+ 'Acme Coffee is a…',
+ );
+ });
+
+ it('drops markdown marks but keeps a # or > inside a sentence', () => {
+ expect(mentionExcerpt('## Picks\n> Acme Coffee is the #1 pick, and A > B.', brand)).toBe(
+ 'Picks Acme Coffee is the #1 pick, and A > B.',
+ );
+ });
+
+ it('finds the brand by its domain, and says nothing when it is not named', () => {
+ expect(mentionExcerpt('See acme-coffee.example.com today.', brand)).toBe(
+ 'See acme-coffee.example.com today.',
+ );
+ expect(mentionExcerpt('No brand here.', brand)).toBeNull();
+ expect(mentionExcerpt(null, brand)).toBeNull();
+ });
+});
diff --git a/server/src/lib/signals/mention-evidence.js b/server/src/lib/signals/mention-evidence.js
new file mode 100644
index 000000000..47e3e4ad6
--- /dev/null
+++ b/server/src/lib/signals/mention-evidence.js
@@ -0,0 +1,147 @@
+/**
+ * Where the brand is mentioned without being cited (AC-001): per prompt, the
+ * platforms, the brand's position in the answers, their sentiment, and a
+ * quote of the newest answer around the mention.
+ *
+ * The uncited-mentions signal names up to fifty prompts and nothing about
+ * them. The panel asks, per mention, for the prompt, platform, position,
+ * sentiment and an answer excerpt; this reads those for the prompts it lists
+ * first (the most mentioned), from the window's answers that name the brand
+ * and cite none of its pages, and the text of one answer per prompt.
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+import { mentionExcerpt } from '../response-parser.js';
+
+const DAY_MS = 86_400_000;
+
+/** Prompts the panel describes: the signal's first, the most mentioned. */
+const MAX_PROMPTS = 5;
+
+/** Answers tried per prompt for a quote, newest first. */
+const QUOTE_TRIES = 3;
+
+/** Pages of answers read per signal, so a busy week is summarised whole. */
+const MAX_PAGES = 5;
+
+/** The middle value, or null for none. */
+function median(values) {
+ const sorted = values.filter((v) => typeof v === 'number').sort((a, b) => a - b);
+ if (sorted.length === 0) return null;
+ const mid = Math.floor(sorted.length / 2);
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
+}
+
+/** The sentiment most answers carry; a tie reads neutral. */
+function mostCommonSentiment(values) {
+ const counts = new Map();
+ for (const v of values) if (v) counts.set(v, (counts.get(v) ?? 0) + 1);
+ const ranked = [...counts.entries()].sort(([, a], [, b]) => b - a);
+ if (ranked.length === 0) return null;
+ if (ranked.length > 1 && ranked[0][1] === ranked[1][1]) return 'neutral';
+ return ranked[0][0];
+}
+
+/**
+ * One prompt's mentions summarised. `rows` are its answers that name the
+ * brand and cite none of its pages, newest first.
+ */
+export function summarizeMentions(rows) {
+ return {
+ platforms: [...new Set(rows.map((r) => r.platform))].sort(),
+ answers: rows.length,
+ position: median(rows.map((r) => r.mention_position)),
+ sentiment: mostCommonSentiment(rows.map((r) => r.sentiment)),
+ };
+}
+
+/**
+ * The mention evidence for the first prompts of an uncited-mentions signal,
+ * in their order. Four reads: the brand's name and domains, the prompts'
+ * texts, their uncited answers over the window (columns only), and the text
+ * of the newest such answer per prompt.
+ */
+export async function mentionEvidence(brandId, promptIds, { now, windowDays }) {
+ const ids = promptIds.slice(0, MAX_PROMPTS);
+ if (ids.length === 0) return [];
+ const since = new Date(now.getTime() - windowDays * DAY_MS).toISOString();
+
+ const [brandRes, domainsRes, promptsRes, answers] = await Promise.all([
+ supabaseAdmin.from('brands').select('name').eq('id', brandId).maybeSingle(),
+ supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brandId),
+ supabaseAdmin.from('prompts').select('id, text').in('id', ids),
+ uncitedAnswers(brandId, ids, since),
+ ]);
+ for (const res of [brandRes, domainsRes, promptsRes]) {
+ if (res.error) throw new Error(`mention evidence read failed: ${res.error.message}`);
+ }
+
+ const brand = {
+ brandName: brandRes.data?.name ?? '',
+ domains: (domainsRes.data ?? []).map((r) => r.domain),
+ };
+ const texts = new Map(
+ (promptsRes.data ?? []).map((p) => [p.id, String(p.text ?? '').slice(0, 160)]),
+ );
+ const byPrompt = new Map();
+ for (const row of answers) {
+ const list = byPrompt.get(row.prompt_id);
+ if (list) list.push(row);
+ else byPrompt.set(row.prompt_id, [row]);
+ }
+
+ // The newest answers per prompt are tried for a quote, in order. Their
+ // text is the heaviest read here, so a failure costs the quotes only.
+ const tried = ids.flatMap((id) => (byPrompt.get(id) ?? []).slice(0, QUOTE_TRIES));
+ const responses = new Map();
+ if (tried.length) {
+ const { data, error } = await supabaseAdmin
+ .from('prompt_results')
+ .select('id, response')
+ .in(
+ 'id',
+ tried.map((row) => row.id),
+ );
+ if (!error) for (const row of data ?? []) responses.set(row.id, row.response);
+ }
+
+ return ids
+ .filter((id) => byPrompt.has(id))
+ .map((id) => {
+ const rows = byPrompt.get(id);
+ const quote = rows
+ .slice(0, QUOTE_TRIES)
+ .map((row) => ({ row, excerpt: mentionExcerpt(responses.get(row.id), brand) }))
+ .find(({ excerpt }) => excerpt);
+ return {
+ promptId: id,
+ promptText: texts.get(id) ?? '',
+ ...summarizeMentions(rows),
+ excerpt: quote?.excerpt ?? null,
+ excerptPlatform: quote?.row.platform ?? null,
+ excerptAt: quote?.row.created_at ?? null,
+ };
+ });
+}
+
+/** The prompts' answers that name the brand and cite none of its pages, newest first. */
+async function uncitedAnswers(brandId, ids, since) {
+ const rows = [];
+ for (let page = 0; page < MAX_PAGES; page += 1) {
+ const { data, error } = await supabaseAdmin
+ .from('prompt_results')
+ .select('id, prompt_id, platform, mention_position, sentiment, created_at')
+ .eq('brand_id', brandId)
+ .neq('platform', 'chatgpt-shopping')
+ .in('prompt_id', ids)
+ .gt('mention_count', 0)
+ .eq('citation_count', 0)
+ .gte('created_at', since)
+ .order('created_at', { ascending: false })
+ .range(page * 1000, page * 1000 + 999);
+ if (error) throw new Error(`mention evidence read failed: ${error.message}`);
+ rows.push(...(data ?? []));
+ if ((data ?? []).length < 1000) break;
+ }
+ return rows;
+}
diff --git a/server/src/lib/signals/mention-evidence.test.js b/server/src/lib/signals/mention-evidence.test.js
new file mode 100644
index 000000000..89d6d6c35
--- /dev/null
+++ b/server/src/lib/signals/mention-evidence.test.js
@@ -0,0 +1,176 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The evidence of an uncited-mentions signal (AC-001): per prompt, the
+ * platforms, the brand's position, the sentiment, and a quote of the newest
+ * answer around the mention.
+ */
+
+let tables = {};
+let reads = [];
+let failResponses = false;
+
+function builder(table) {
+ let columns = '';
+ const chain = {
+ select: (cols) => {
+ columns = cols;
+ return chain;
+ },
+ eq: () => chain,
+ neq: () => chain,
+ gt: () => chain,
+ gte: () => chain,
+ order: () => chain,
+ limit: () => chain,
+ range: () => chain,
+ in: (column, values) => {
+ reads.push({ table, column, values, columns });
+ return chain;
+ },
+ maybeSingle: async () => ({ data: tables[table]?.[0] ?? null, error: null }),
+ then: (resolve) => {
+ const rows = tables[table] ?? [];
+ if (table === 'prompt_results' && columns.includes('response')) {
+ resolve(
+ failResponses
+ ? { data: null, error: { message: 'timeout' } }
+ : { data: tables.responses, error: null },
+ );
+ return;
+ }
+ resolve({ data: rows, error: null });
+ },
+ };
+ return chain;
+}
+
+vi.mock('../../config/supabase.js', () => ({ default: { from: (t) => builder(t) } }));
+
+const { mentionEvidence, summarizeMentions } = await import('./mention-evidence.js');
+
+const answer = (over) => ({
+ id: 'r1',
+ prompt_id: 'p1',
+ platform: 'chatgpt-web',
+ mention_position: 2,
+ sentiment: 'neutral',
+ created_at: '2026-10-14T05:00:00Z',
+ ...over,
+});
+
+describe('summarizeMentions', () => {
+ it('gives the platforms, the median position and the most common sentiment', () => {
+ expect(
+ summarizeMentions([
+ answer({ platform: 'gemini-web', mention_position: 1, sentiment: 'positive' }),
+ answer({ mention_position: 3, sentiment: 'positive' }),
+ answer({ mention_position: null, sentiment: 'neutral' }),
+ ]),
+ ).toEqual({
+ platforms: ['chatgpt-web', 'gemini-web'],
+ answers: 3,
+ position: 2,
+ sentiment: 'positive',
+ });
+ });
+
+ it('calls a tie neutral rather than picking a side', () => {
+ expect(
+ summarizeMentions([answer({ sentiment: 'positive' }), answer({ sentiment: 'negative' })])
+ .sentiment,
+ ).toBe('neutral');
+ });
+});
+
+describe('mentionEvidence', () => {
+ beforeEach(() => {
+ reads = [];
+ failResponses = false;
+ tables = {
+ brands: [{ name: 'Acme Coffee' }],
+ brand_domains: [{ domain: 'acme-coffee.example.com' }],
+ prompts: [
+ { id: 'p1', text: 'Best coffee subscription?' },
+ { id: 'p2', text: 'Coffee gifts' },
+ ],
+ prompt_results: [
+ answer({ id: 'r3', created_at: '2026-10-14T05:00:00Z' }),
+ answer({ id: 'r2', platform: 'gemini-web', created_at: '2026-10-13T05:00:00Z' }),
+ answer({ id: 'r9', prompt_id: 'p2', mention_position: 1 }),
+ ],
+ responses: [
+ { id: 'r3', response: 'For offices, **Acme Coffee** ships beans weekly.' },
+ { id: 'r9', response: 'Try [acme-coffee.example.com](https://acme-coffee.example.com).' },
+ ],
+ };
+ });
+
+ it("describes each prompt in the signal's order and quotes its newest answer", async () => {
+ const evidence = await mentionEvidence('b1', ['p1', 'p2', 'p3'], {
+ now: new Date('2026-10-15T00:00:00Z'),
+ windowDays: 7,
+ });
+ expect(evidence).toEqual([
+ {
+ promptId: 'p1',
+ promptText: 'Best coffee subscription?',
+ platforms: ['chatgpt-web', 'gemini-web'],
+ answers: 2,
+ position: 2,
+ sentiment: 'neutral',
+ excerpt: 'For offices, Acme Coffee ships beans weekly.',
+ excerptPlatform: 'chatgpt-web',
+ excerptAt: '2026-10-14T05:00:00Z',
+ },
+ {
+ promptId: 'p2',
+ promptText: 'Coffee gifts',
+ platforms: ['chatgpt-web'],
+ answers: 1,
+ position: 1,
+ sentiment: 'neutral',
+ excerpt: 'Try acme-coffee.example.com.',
+ excerptPlatform: 'chatgpt-web',
+ excerptAt: '2026-10-14T05:00:00Z',
+ },
+ ]);
+ // Only the newest answers' text is read back, a few per prompt.
+ expect(reads.find((r) => r.columns.includes('response'))?.values).toEqual(['r3', 'r2', 'r9']);
+ });
+
+ it('quotes an older answer when the newest does not name the brand', async () => {
+ tables.responses = [
+ { id: 'r3', response: 'A list with no brand in it.' },
+ { id: 'r2', response: 'Acme Coffee ships weekly.' },
+ ];
+ const [first] = await mentionEvidence('b1', ['p1'], {
+ now: new Date('2026-10-15T00:00:00Z'),
+ windowDays: 7,
+ });
+ expect(first).toMatchObject({
+ excerpt: 'Acme Coffee ships weekly.',
+ excerptPlatform: 'gemini-web',
+ excerptAt: '2026-10-13T05:00:00Z',
+ });
+ });
+
+ it("keeps the summary when the answers' text cannot be read", async () => {
+ failResponses = true;
+ const [first] = await mentionEvidence('b1', ['p1'], {
+ now: new Date('2026-10-15T00:00:00Z'),
+ windowDays: 7,
+ });
+ expect(first).toMatchObject({
+ platforms: ['chatgpt-web', 'gemini-web'],
+ answers: 2,
+ excerpt: null,
+ excerptPlatform: null,
+ });
+ });
+
+ it('reads nothing for a signal without prompts', async () => {
+ expect(await mentionEvidence('b1', [], { now: new Date(), windowDays: 7 })).toEqual([]);
+ expect(reads).toEqual([]);
+ });
+});
diff --git a/server/src/lib/signals/nightly-reads.test.js b/server/src/lib/signals/nightly-reads.test.js
index 9d1249c1b..910e8431b 100644
--- a/server/src/lib/signals/nightly-reads.test.js
+++ b/server/src/lib/signals/nightly-reads.test.js
@@ -21,6 +21,7 @@ const NIGHTLY_MODULES = [
'src/lib/signals/record.js',
'src/lib/signals/lost-citation-evidence.js',
'src/lib/signals/competitor-evidence.js',
+ 'src/lib/signals/mention-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.js
index ac95ef5d6..d867d67c7 100644
--- a/server/src/lib/signals/record-evidence.test.js
+++ b/server/src/lib/signals/record-evidence.test.js
@@ -34,8 +34,21 @@ vi.mock('./competitor-evidence.js', () => ({
},
}));
-const { attachCompetitorEvidence, attachLostCitationEvidence, keepRecordedEvidence } =
- await import('./record.js');
+let mentionRead = { calls: [], result: [], fail: false };
+vi.mock('./mention-evidence.js', () => ({
+ mentionEvidence: async (...args) => {
+ mentionRead.calls.push(args);
+ if (mentionRead.fail) throw new Error('timeout');
+ return mentionRead.result;
+ },
+}));
+
+const {
+ attachCompetitorEvidence,
+ attachLostCitationEvidence,
+ attachMentionEvidence,
+ keepRecordedEvidence,
+} = await import('./record.js');
const lost = (promptId) => ({
kind: 'lost_citations',
@@ -56,6 +69,7 @@ const evidence = {
beforeEach(() => {
read = { calls: [], result: new Map(), fail: false };
competitorRead = { calls: [], result: new Map(), fail: false };
+ mentionRead = { calls: [], result: [], fail: false };
});
describe('attachLostCitationEvidence', () => {
@@ -191,3 +205,35 @@ describe('attachCompetitorEvidence', () => {
expect(candidates[0].payload).toEqual({ competitorId: 'c1', ...found });
});
});
+
+describe('attachMentionEvidence', () => {
+ const mentions = [{ promptId: 'p1', platforms: ['chatgpt-web'], position: 2, excerpt: '…Acme…' }];
+ const uncited = () => ({
+ kind: 'uncited_mentions',
+ dedupKey: 'uncited_mentions',
+ payload: { promptIds: ['p1', 'p2'] },
+ });
+
+ it("describes the signal's prompts, and leaves other kinds alone", async () => {
+ mentionRead.result = mentions;
+ const candidates = [uncited(), { kind: 'prompt_gain', payload: { promptIds: ['p1'] } }];
+ await attachMentionEvidence('b1', candidates, new Date('2026-10-15T00:00:00Z'));
+ expect(mentionRead.calls).toEqual([
+ ['b1', ['p1', 'p2'], { now: new Date('2026-10-15T00:00:00Z'), windowDays: 7 }],
+ ]);
+ expect(candidates[0].payload).toEqual({ promptIds: ['p1', 'p2'], mentions });
+ expect(candidates[1].payload).toEqual({ promptIds: ['p1'] });
+ });
+
+ it("records it without evidence when the read fails, keeping an earlier night's", async () => {
+ mentionRead.fail = true;
+ const candidates = [uncited()];
+ await expect(attachMentionEvidence('b1', candidates, new Date())).resolves.toBeUndefined();
+ expect(candidates[0].payload).toEqual({ promptIds: ['p1', 'p2'] });
+ keepRecordedEvidence(
+ candidates,
+ new Map([['uncited_mentions', { payload: { promptIds: ['p1'], mentions } }]]),
+ );
+ expect(candidates[0].payload).toEqual({ promptIds: ['p1', 'p2'], mentions });
+ });
+});
diff --git a/server/src/lib/signals/record.js b/server/src/lib/signals/record.js
index affbcd8a8..00030c3c8 100644
--- a/server/src/lib/signals/record.js
+++ b/server/src/lib/signals/record.js
@@ -30,6 +30,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 { mentionEvidence } from './mention-evidence.js';
import { logger } from '../logger.js';
import { readAllRpcRows } from '../rpc-pages.js';
import { resolve } from '../../config/action-engine.js';
@@ -249,18 +250,22 @@ export async function uncitedMentionCandidates(brandId, now) {
if (error) throw new Error(error.message);
// By id, not by row: a prompt repeated at a page boundary is still one prompt.
- const uncited = [
- ...new Set(
- (data ?? [])
- .filter(
- (row) =>
- Number(row.runs) > 0 &&
- Number(row.total_mentions) > 0 &&
- Number(row.total_citations) === 0,
- )
- .map((row) => row.prompt_id),
- ),
- ];
+ const byPrompt = new Map();
+ for (const row of data ?? []) {
+ if (
+ Number(row.runs) > 0 &&
+ Number(row.total_mentions) > 0 &&
+ Number(row.total_citations) === 0
+ ) {
+ byPrompt.set(row.prompt_id, row);
+ }
+ }
+ // Most mentioned first: the prompts the panel describes are the first few.
+ const uncited = [...byPrompt.values()].sort(
+ (a, b) =>
+ Number(b.total_mentions) - Number(a.total_mentions) ||
+ String(a.prompt_id).localeCompare(String(b.prompt_id)),
+ );
if (uncited.length < detection.uncitedMinPrompts) return [];
return [
@@ -268,7 +273,7 @@ export async function uncitedMentionCandidates(brandId, now) {
kind: 'uncited_mentions',
dedupKey: 'uncited_mentions',
source: ['ai_results'],
- payload: { promptIds: uncited.slice(0, 50) },
+ payload: { promptIds: uncited.map((row) => row.prompt_id).slice(0, 50) },
previousValue: null,
currentValue: uncited.length,
changeValue: null,
@@ -596,6 +601,7 @@ const COMPETITOR_KINDS = new Set([
for (const kind of COMPETITOR_KINDS) {
EVIDENCE[kind] = { marker: 'positions', fields: ['positions', 'winningSources'] };
}
+EVIDENCE.uncited_mentions = { marker: 'mentions', fields: ['mentions'] };
/**
* A night whose evidence read failed refreshes a signal with its bare
@@ -615,6 +621,29 @@ export function keepRecordedEvidence(candidates, existing) {
}
}
+/**
+ * An uncited-mentions signal names its prompts and nothing about them. Before
+ * it is written, its first prompts get what the drawer shows (AC-001): the
+ * platforms, the brand's position, the answers' sentiment, and a quote of
+ * the newest one. Best effort, like the other evidence.
+ */
+export async function attachMentionEvidence(brandId, candidates, now) {
+ const uncited = candidates.filter(
+ (c) => c.kind === 'uncited_mentions' && Array.isArray(c.payload?.promptIds),
+ );
+ for (const candidate of uncited) {
+ try {
+ const mentions = await mentionEvidence(brandId, candidate.payload.promptIds, {
+ now,
+ windowDays: detection.windowDays,
+ });
+ candidate.payload = { ...candidate.payload, mentions };
+ } catch (err) {
+ logger.warn({ brandId, err: err.message }, '[signals] mention evidence unavailable');
+ }
+ }
+}
+
/** The competitor a signal is about: the library names it, the others key on it. */
function competitorOf(candidate) {
const named = candidate.payload?.competitorId;
@@ -737,6 +766,7 @@ export async function recordSignalsForBrand(brandId, { now = new Date() } = {})
(candidate) => !(outage && DECLINE_KINDS.has(candidate.kind)),
);
await attachCompetitorEvidence(brandId, [...candidates, ...overflow], now);
+ await attachMentionEvidence(brandId, candidates, 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.
diff --git a/web/messages/en.json b/web/messages/en.json
index bf32e53c8..01cda6df1 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -350,6 +350,14 @@
"viewPrompt": "View prompt",
"notAvailable": "Not available",
"allPlatforms": "All tracked platforms",
+ "mentions": {
+ "sentiment": {
+ "positive": "Positive",
+ "neutral": "Neutral",
+ "negative": "Negative"
+ },
+ "quotedFrom": "{platform}, {date}"
+ },
"positions": {
"you": "You",
"new": "new",
@@ -398,7 +406,8 @@
"crawlers": "Affected crawlers",
"evidence": "Failed checks",
"competitorPositions": "Positions by prompt",
- "winningSources": "Sources behind their wins"
+ "winningSources": "Sources behind their wins",
+ "mentionDetails": "Mentions by prompt"
},
"scopes": {
"all_prompts": "All prompts",
diff --git a/web/src/components/action-center/signal-detail-blocks.test.tsx b/web/src/components/action-center/signal-detail-blocks.test.tsx
index ebffd1d20..1742ffad6 100644
--- a/web/src/components/action-center/signal-detail-blocks.test.tsx
+++ b/web/src/components/action-center/signal-detail-blocks.test.tsx
@@ -260,6 +260,45 @@ describe('a competitor signal with its evidence', () => {
});
});
+describe('an uncited-mentions signal with its evidence', () => {
+ it('lists each prompt with its platforms, position, sentiment and a quote', () => {
+ render(
+ <SignalWhereBlock
+ signal={signal({
+ category: 'mention',
+ kind: 'uncited_mentions',
+ currentValue: 4,
+ payload: {
+ promptIds: ['p1'],
+ mentions: [
+ {
+ promptId: 'p1',
+ promptText: 'Best coffee subscription?',
+ platforms: ['gemini-web', 'chatgpt-web'],
+ answers: 3,
+ position: 2,
+ sentiment: 'positive',
+ excerpt: '…Acme Coffee ships beans weekly.',
+ excerptPlatform: 'gemini-web',
+ excerptAt: '2026-10-14T05:00:00Z',
+ },
+ ],
+ },
+ where: NO_WHERE,
+ })}
+ />,
+ );
+ const rows = [...container.querySelectorAll('dt')].map(
+ (dt) => `${dt.textContent}: ${dt.nextElementSibling?.textContent}`,
+ );
+ expect(rows).toContain(
+ 'Mentions by prompt: Best coffee subscription?Gemini, ChatGPT · #2 · Positive · in 3 answers' +
+ '“…Acme Coffee ships beans weekly.”Gemini, Oct 14',
+ );
+ expect(rows.some((r) => r.startsWith('Sentiment'))).toBe(false);
+ });
+});
+
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.tsx
index bdea6b20c..7336acf47 100644
--- a/web/src/components/action-center/signal-detail-blocks.tsx
+++ b/web/src/components/action-center/signal-detail-blocks.tsx
@@ -148,6 +148,50 @@ function WhereValueView({ value }: { value: WhereValue }) {
))}
</ul>
);
+ case 'mentions':
+ return (
+ <ul className="space-y-2.5">
+ {value.items.map((m) => (
+ <li key={m.promptId}>
+ <Link
+ href={`/dashboard/prompts/${m.promptId}`}
+ className="break-words underline-offset-2 hover:underline"
+ >
+ {m.promptText || t('drawer.positions.untitled')}
+ </Link>
+ <span className="block text-xs text-muted-foreground">
+ {[
+ m.platforms.map(platformName).join(', '),
+ m.position !== null &&
+ t('drawer.cited.position', {
+ position: format.number(m.position, { maximumFractionDigits: 1 }),
+ }),
+ m.sentiment && t(`drawer.mentions.sentiment.${m.sentiment}`),
+ t('drawer.cited.answers', { count: m.answers }),
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </span>
+ {m.excerpt && (
+ <blockquote className="mt-1 border-l-2 pl-2 text-xs text-muted-foreground italic">
+ “{m.excerpt}”
+ {m.excerptPlatform && m.excerptAt && (
+ <span className="mt-0.5 block not-italic">
+ {t('drawer.mentions.quotedFrom', {
+ platform: platformName(m.excerptPlatform),
+ date: format.dateTime(new Date(m.excerptAt), {
+ month: 'short',
+ day: 'numeric',
+ }),
+ })}
+ </span>
+ )}
+ </blockquote>
+ )}
+ </li>
+ ))}
+ </ul>
+ );
case 'sources':
return (
<ul className="space-y-1">
diff --git a/web/src/lib/signals/detail.test.ts b/web/src/lib/signals/detail.test.ts
index ea8839e83..5ac7374bc 100644
--- a/web/src/lib/signals/detail.test.ts
+++ b/web/src/lib/signals/detail.test.ts
@@ -393,3 +393,67 @@ describe('a competitor signal with its evidence recorded', () => {
expect(where.winning_sources).toEqual([{ domain: 'g2.example', answers: 2, answers_read: 3 }]);
});
});
+
+describe('an uncited-mentions signal', () => {
+ const base = {
+ category: 'mention' as const,
+ kind: 'uncited_mentions' as const,
+ currentValue: 4,
+ where: { platforms: ['chatgpt-web', 'claude'], regions: ['US'], topics: [] },
+ };
+ const mention = {
+ promptId: 'p1',
+ promptText: 'Best coffee subscription?',
+ platforms: ['gemini-web'],
+ answers: 3,
+ position: 2,
+ sentiment: 'positive',
+ excerpt: '…Acme Coffee ships beans weekly.',
+ excerptPlatform: 'gemini-web',
+ excerptAt: '2026-10-14T05:00:00Z',
+ };
+
+ it('asks for position, sentiment and an excerpt until its evidence is recorded', () => {
+ const keys = signalWhereFields(signal({ ...base, payload: { promptIds: ['p1', 'p2'] } })).map(
+ (f) => `${f.key}${f.value ? '' : ' (n/a)'}`,
+ );
+ expect(keys).toEqual([
+ 'prompts',
+ 'trackedOn',
+ 'trackedIn',
+ 'position (n/a)',
+ 'sentiment (n/a)',
+ 'excerpt (n/a)',
+ ]);
+ });
+
+ it('gives them per prompt once recorded, on the platforms that mention it', () => {
+ const recorded = signal({ ...base, payload: { promptIds: ['p1', 'p2'], mentions: [mention] } });
+ const fields = signalWhereFields(recorded);
+ // The evidence names the platforms; the locations are still where the
+ // prompts are tracked.
+ expect(fields.map((f) => f.key)).toEqual([
+ 'prompts',
+ 'platforms',
+ 'trackedIn',
+ 'mentionDetails',
+ ]);
+ expect(fields.find((f) => f.key === 'platforms')?.value).toEqual({
+ type: 'platforms',
+ slugs: ['gemini-web'],
+ });
+ expect(signalDetailForApi(recorded, []).where.mention_details).toEqual([
+ {
+ prompt_id: 'p1',
+ prompt_text: 'Best coffee subscription?',
+ platforms: [{ slug: 'gemini-web', name: 'Gemini' }],
+ answers: 3,
+ position: 2,
+ sentiment: 'positive',
+ excerpt: '…Acme Coffee ships beans weekly.',
+ excerpt_platform: 'gemini-web',
+ excerpt_at: '2026-10-14T05:00:00Z',
+ },
+ ]);
+ });
+});
diff --git a/web/src/lib/signals/detail.ts b/web/src/lib/signals/detail.ts
index 9e69007fc..54dea14f6 100644
--- a/web/src/lib/signals/detail.ts
+++ b/web/src/lib/signals/detail.ts
@@ -354,7 +354,9 @@ export type WhereFieldKey =
| 'crawlers'
| 'evidence'
| 'competitorPositions'
- | 'winningSources';
+ | 'winningSources'
+ /** Per prompt: platforms, position, sentiment and a quote, for mentions. */
+ | 'mentionDetails';
export type WhereValue =
| { type: 'text'; text: string }
@@ -371,6 +373,8 @@ export type WhereValue =
| { type: 'positions'; competitor: string; items: PromptPosition[] }
/** Domains cited in the answers a competitor wins. */
| { type: 'sources'; items: WinningSource[] }
+ /** The brand's mentions on each prompt: where, how high, in what tone. */
+ | { type: 'mentions'; items: PromptMention[] }
| { type: 'locations'; codes: readonly string[] }
| { type: 'number'; value: number };
@@ -406,6 +410,43 @@ export interface PromptPosition {
you: { now: number | null; before: number | null };
}
+export interface PromptMention {
+ promptId: string;
+ promptText: string;
+ platforms: string[];
+ answers: number;
+ /** Median position among the brands named, 1 first; null when not ranked. */
+ position: number | null;
+ sentiment: 'positive' | 'neutral' | 'negative' | null;
+ /** A quote of the newest answer around the mention, and where it came from. */
+ excerpt: string | null;
+ excerptPlatform: string | null;
+ excerptAt: string | null;
+}
+
+const SENTIMENTS = new Set(['positive', 'neutral', 'negative']);
+
+function promptMentions(value: unknown): PromptMention[] {
+ if (!Array.isArray(value)) return [];
+ return value
+ .filter((v): v is Record<string, unknown> => typeof v?.promptId === 'string')
+ .map((v) => ({
+ promptId: v.promptId as string,
+ promptText: typeof v.promptText === 'string' ? v.promptText : '',
+ platforms: Array.isArray(v.platforms)
+ ? v.platforms.filter((x): x is string => typeof x === 'string')
+ : [],
+ answers: num(v.answers) ?? 0,
+ position: num(v.position),
+ sentiment: SENTIMENTS.has(v.sentiment as string)
+ ? (v.sentiment as PromptMention['sentiment'])
+ : null,
+ excerpt: typeof v.excerpt === 'string' && v.excerpt ? v.excerpt : null,
+ excerptPlatform: typeof v.excerptPlatform === 'string' ? v.excerptPlatform : null,
+ excerptAt: typeof v.excerptAt === 'string' ? v.excerptAt : null,
+ }));
+}
+
export interface WinningSource {
domain: string;
/** Answers it is cited in, of the answers read that the competitor wins. */
@@ -475,7 +516,16 @@ const LAYOUT: Record<SignalCategory, WhereFieldKey[]> = {
'competitorsNamed',
'bestPage',
],
- mention: ['prompt', 'prompts', 'platforms', 'locations', 'position', 'sentiment', 'excerpt'],
+ mention: [
+ 'prompt',
+ 'prompts',
+ 'platforms',
+ 'locations',
+ 'mentionDetails',
+ 'position',
+ 'sentiment',
+ 'excerpt',
+ ],
traffic: ['scope', 'url', 'pages', 'queries', 'engagementRank', 'aiReferrals', 'citablePrompts'],
technical: ['url', 'pages', 'issue', 'crawlers', 'evidence'],
competitor: [
@@ -507,6 +557,7 @@ const CITATION_LOSS_LAYOUT: WhereFieldKey[] = [
// A field that only some signals of a category have is shown when it has a
// value; the spec's required fields are shown either way.
const OPTIONAL: ReadonlySet<WhereFieldKey> = new Set([
+ 'mentionDetails',
'scope',
'prompt',
'prompts',
@@ -600,12 +651,18 @@ function fieldValue(signal: Signal, key: WhereFieldKey): WhereValue | null {
return topics[0] ? { type: 'text', text: topics[0] } : null;
}
case 'platforms': {
+ // Recorded evidence says where it happened: the platforms a competitor
+ // leads on, or those whose answers name the brand without citing it.
+ const recorded = [
+ ...new Set([
+ ...promptPositions(p.positions).map((row) => row.platform),
+ ...promptMentions(p.mentions).flatMap((m) => m.platforms),
+ ]),
+ ].filter(Boolean);
+ if (recorded.length) return { type: 'platforms', slugs: recorded };
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' ||
@@ -667,6 +724,10 @@ function fieldValue(signal: Signal, key: WhereFieldKey): WhereValue | null {
? { type: 'positions', competitor: str(p, 'competitorName'), items: rows }
: null;
}
+ case 'mentionDetails': {
+ const mentions = promptMentions(p.mentions);
+ return mentions.length ? { type: 'mentions', items: mentions } : null;
+ }
case 'winningSources': {
const sources = winningSourcesOf(p.winningSources);
return sources.length ? { type: 'sources', items: sources } : null;
@@ -690,15 +751,25 @@ const TRACKED: Partial<Record<WhereFieldKey, WhereFieldKey>> = {
locations: 'trackedIn',
};
-function placeIsNamed(signal: Signal): boolean {
+/**
+ * Whether a signal's platforms and its locations say where it happened, each
+ * on its own: a lost citation records both, a competitor's positions and a
+ * mention's evidence record platforms only, so their locations are still
+ * where the prompts are tracked.
+ */
+function namedPlaces(signal: Signal): { platforms: boolean; locations: boolean } {
const p = signal.payload ?? {};
- return (
- typeof p.platform === 'string' ||
- typeof p.region === 'string' ||
- (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)
- );
+ const some = (value: unknown) => Array.isArray(value) && value.length > 0;
+ const lost = some(p.platforms);
+ return {
+ platforms:
+ typeof p.platform === 'string' ||
+ typeof p.region === 'string' ||
+ lost ||
+ some(p.positions) ||
+ some(p.mentions),
+ locations: typeof p.platform === 'string' || typeof p.region === 'string' || lost,
+ };
}
/** The Where block: the spec's fields for this signal, each with its value or none. */
@@ -709,8 +780,13 @@ export function signalWhereFields(signal: Signal): WhereField[] {
: CITATION_LOSS.includes(signal.kind)
? CITATION_LOSS_LAYOUT
: LAYOUT[signal.category];
- const named = placeIsNamed(signal);
+ const named = namedPlaces(signal);
+ // A mention's position, sentiment and quote are given per prompt when the
+ // evidence is recorded; asked for on their own only when it is not.
+ const perPrompt = promptMentions(signal.payload?.mentions).length > 0;
+ const covered = new Set<WhereFieldKey>(perPrompt ? ['position', 'sentiment', 'excerpt'] : []);
return layout
+ .filter((key) => !covered.has(key))
.map((key) => {
const value = fieldValue(signal, key);
const tracked = TRACKED[key];
@@ -718,8 +794,9 @@ export function signalWhereFields(signal: Signal): WhereField[] {
// Only a value read from the prompts is renamed; a missing one keeps
// the spec's question ("which platforms?").
key:
- tracked && !named && (value?.type === 'platforms' || value?.type === 'locations')
- ? tracked
+ (value?.type === 'platforms' && !named.platforms) ||
+ (value?.type === 'locations' && !named.locations)
+ ? (tracked ?? key)
: key,
value,
};
@@ -806,6 +883,18 @@ function apiValue(value: WhereValue): unknown {
competitor: row.competitor,
you: row.you,
}));
+ case 'mentions':
+ return value.items.map((m) => ({
+ prompt_id: m.promptId,
+ prompt_text: m.promptText,
+ platforms: m.platforms.map((slug) => ({ slug, name: platformName(slug) })),
+ answers: m.answers,
+ position: m.position,
+ sentiment: m.sentiment,
+ excerpt: m.excerpt,
+ excerpt_platform: m.excerptPlatform,
+ excerpt_at: m.excerptAt,
+ }));
case 'sources':
return value.items.map((source) => ({
domain: source.domain,