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(action-center): show where a signal happened, what changed and what it rests on (#1060)

Cihan69605901d90c
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdx
index ea2858a91..832b4587e 100644
--- a/docs/guides/mcp-server.mdx
+++ b/docs/guides/mcp-server.mdx
@@ -285,7 +285,7 @@ intent, not during exploratory queries.
| --- | --- | --- |
| `list_actions` | Recommended actions for a brand with status, impact, assignee, due date, and task progress. | |
| `get_action` | One action in full: payload, triggering signals, tasks (`mode`, `permission`), and event trail. | |
-| `list_signals` | Detected changes (visibility, citations, traffic) with before/after values and linked `action_id`. | |
+| `list_signals` | Detected changes (visibility, citations, traffic), each with `where` (prompt, topic, platforms, locations, domain, competitor), `change` (labelled figures with unit and period), `evidence` (detection dates, app links) and `used_by_actions`. | |
| `list_action_history` | Closed actions with measured outcomes and before/after validation results. | |
| `update_task_status` | Record progress on a task (`in_progress`, `completed`, `skipped`, `failed`); does not execute the task. | **yes** |
| `create_improve_action` | Send a prompt's Improve suggestions to Action Center as a `prompt_improve` action (needs a generated suggestion set for the range and a plan with Improve; idempotent on `idempotency_key`). | **yes** |
diff --git a/web/messages/en.json b/web/messages/en.json
index 8c6d44d23..9139ff024 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -339,14 +339,110 @@
"description": "Select a brand to view its signals."
},
"drawer": {
+ "where": "Where",
"whatChanged": "What changed",
- "affected": "Affected",
+ "evidence": "Evidence and links",
"relatedKpis": "Related KPIs",
- "detected": "Detected",
+ "detected": "First detected",
"lastDetected": "Last detected",
"source": "Source",
"status": "Status",
- "viewPrompt": "View prompt"
+ "viewPrompt": "View prompt",
+ "notAvailable": "Not available",
+ "allPlatforms": "All tracked platforms",
+ "loading": "Loading…",
+ "more": "+{count} more",
+ "usedBy": "Used by actions",
+ "usedByNone": "No action uses this signal yet.",
+ "usedByFailed": "Couldn’t load the actions.",
+ "actionLabel": "AC-{no} · {title}",
+ "fields": {
+ "scope": "Scope",
+ "prompt": "Prompt",
+ "prompts": "Prompts",
+ "topic": "Topic",
+ "platforms": "Platforms",
+ "locations": "Locations",
+ "trackedOn": "Tracked on",
+ "trackedIn": "Tracked in",
+ "domain": "Domain",
+ "competitor": "Competitor",
+ "url": "URL",
+ "pages": "Pages",
+ "queries": "Queries",
+ "engagementRank": "Engagement rank",
+ "lostUrl": "Your page cited before",
+ "citedNow": "Cited now",
+ "exampleUrls": "Example cited URLs",
+ "competitorsNamed": "Competitors it names",
+ "bestPage": "Your best matching page",
+ "position": "Mention position",
+ "sentiment": "Sentiment",
+ "excerpt": "Answer excerpt",
+ "aiReferrals": "AI referrals by platform",
+ "citablePrompts": "Prompts it could be cited on",
+ "issue": "Issue",
+ "crawlers": "Affected crawlers",
+ "evidence": "Failed checks",
+ "competitorPositions": "Positions by prompt",
+ "winningSources": "Sources behind their wins"
+ },
+ "scopes": {
+ "all_prompts": "All prompts",
+ "site": "Whole site",
+ "topic": "Topic",
+ "platform": "Platform",
+ "location": "Location",
+ "prompt": "Prompt"
+ },
+ "change": {
+ "points": "{value} pts",
+ "periods": {
+ "week_over_week": "Last 7 days against the 7 days before",
+ "last_7_days": "Last 7 days",
+ "latest": "Latest data"
+ },
+ "metrics": {
+ "visibility_rate": "Visibility rate",
+ "mention_rate": "Mention rate",
+ "coverage": "Coverage",
+ "mentions": "Mentions",
+ "citation_answers": "Answers citing",
+ "answers_citing": "Answers citing it",
+ "visibility_score": "Visibility score",
+ "ai_sessions": "AI referral sessions",
+ "search_clicks": "Search clicks",
+ "sessions": "Sessions",
+ "engagement_rank": "Engagement rank",
+ "prompts": "Prompts",
+ "pages": "Pages",
+ "queries": "Queries"
+ },
+ "roles": {
+ "before": "previous 7 days",
+ "after": "last 7 days",
+ "change": "change",
+ "you": "you",
+ "competitor": "{name}",
+ "best": "{name} (best)",
+ "this": "{name}",
+ "total": "all",
+ "naming_you": "naming you",
+ "competitors_only": "naming only competitors",
+ "now": "now",
+ "unnamed": "competitor"
+ }
+ },
+ "links": {
+ "prompt_answers": "View AI answers",
+ "prompts": "Open Prompts",
+ "topic": "Open topic",
+ "citations": "Open Citations",
+ "competitors": "Open Competitors",
+ "traffic": "Open Traffic",
+ "audit": "Open Site Audit",
+ "insights": "Open Insights"
+ }
}
},
"signalTexts": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx
index f4ea6ed93..41d2bebb6 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx
@@ -586,6 +586,7 @@ function SignalsContent({ brand }: { brand: Brand }) {
)}
<SignalDrawer
+ brandId={brand.id}
signal={selected}
onOpenChange={(open) => {
if (!open) selectSignal(null);
diff --git a/web/src/components/action-center/signal-detail-blocks.test.tsx b/web/src/components/action-center/signal-detail-blocks.test.tsx
new file mode 100644
index 000000000..45354ea84
--- /dev/null
+++ b/web/src/components/action-center/signal-detail-blocks.test.tsx
@@ -0,0 +1,201 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+import type { Signal } from '@/lib/signals/map';
+import { NO_WHERE } from '@/lib/signals/where';
+
+const getSignalActions = vi.fn();
+vi.mock('@/lib/actions/signals', () => ({
+ getSignalActions: (...args: unknown[]) => getSignalActions(...args),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ ),
+}));
+
+const { SignalChangeBlock, SignalEvidenceBlock, SignalWhereBlock } =
+ await import('./signal-detail-blocks');
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+function render(node: React.ReactNode) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ {node}
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ getSignalActions.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+const signal = (over: Partial<Signal>): Signal => ({
+ id: 's1',
+ category: 'visibility',
+ kind: 'platform_drop',
+ impact: 'high',
+ status: 'new',
+ source: ['ai_results'],
+ detectedAt: '2026-10-08T10:53:00+00:00',
+ lastDetectedAt: '2026-10-09T10:53:00+00:00',
+ resolvedAt: null,
+ previousValue: 34,
+ currentValue: 18,
+ changeValue: -16,
+ payload: {
+ entity: 'platforms',
+ platform: 'gemini-web',
+ targets: [{ id: 'gemini-web', label: 'gemini-web' }],
+ },
+ kpiKeys: [],
+ actionId: null,
+ where: { platforms: ['gemini-web'], regions: [], topics: [] },
+ ...over,
+});
+
+describe('SignalChangeBlock', () => {
+ it('labels every figure with its metric, window and unit', () => {
+ render(<SignalChangeBlock signal={signal({})} />);
+ const text = container.textContent ?? '';
+ expect(text).toContain('Last 7 days against the 7 days before');
+ expect(text).toContain('Mention rate · previous 7 days34%');
+ expect(text).toContain('Mention rate · last 7 days18%');
+ expect(text).toContain('−16 pts');
+ // A fall in the brand's own rate is bad news.
+ const delta = [...container.querySelectorAll('span')].find((s) => s.textContent === '−16 pts');
+ expect(delta?.className).toContain('text-red-600');
+ });
+
+ it("colours a competitor's rise as bad news", () => {
+ render(
+ <SignalChangeBlock
+ signal={signal({
+ category: 'competitor',
+ kind: 'competitor_momentum',
+ payload: { entity: 'competitors', competitorName: 'Profound' },
+ previousValue: 12,
+ currentValue: 31,
+ changeValue: 19,
+ })}
+ />,
+ );
+ const delta = [...container.querySelectorAll('span')].find((s) => s.textContent === '+19');
+ expect(delta?.className).toContain('text-red-600');
+ expect(container.textContent).toContain('Mentions · Profound · last 7 days31');
+ });
+
+ it("names a source's counts rather than showing 0 → 251 +167", () => {
+ render(
+ <SignalChangeBlock
+ signal={signal({
+ category: 'competitor',
+ kind: 'competitor_winning_source',
+ payload: { entity: 'sources', domain: 'yotpo.com', prompts: 6 },
+ previousValue: 0,
+ currentValue: 251,
+ changeValue: 167,
+ })}
+ />,
+ );
+ const text = container.textContent ?? '';
+ expect(text).toContain('Answers citing it · all251');
+ expect(text).toContain('Answers citing it · naming you0');
+ expect(text).toContain('Answers citing it · naming only competitors167');
+ });
+
+ it('says so when a signal records no figures', () => {
+ render(
+ <SignalChangeBlock
+ signal={signal({
+ category: 'citation',
+ kind: 'lost_citations',
+ payload: { promptId: 'p1', promptText: 'Best coffee subscription?' },
+ previousValue: null,
+ currentValue: null,
+ changeValue: null,
+ })}
+ />,
+ );
+ expect(container.textContent).toBe('What changedNot available');
+ });
+});
+
+describe('SignalWhereBlock', () => {
+ it('shows each field, with "Not available" where no detector records it', () => {
+ render(
+ <SignalWhereBlock
+ signal={signal({
+ category: 'citation',
+ kind: 'lost_citations',
+ payload: { promptId: 'p1', promptText: 'Best coffee subscription?' },
+ where: { platforms: ['chatgpt-web'], regions: ['US'], topics: ['Coffee'] },
+ })}
+ />,
+ );
+ const rows = [...container.querySelectorAll('dt')].map(
+ (dt) => `${dt.textContent}: ${dt.nextElementSibling?.textContent}`,
+ );
+ expect(rows).toEqual([
+ 'Prompt: Best coffee subscription?View prompt',
+ 'Topic: Coffee',
+ 'Tracked on: ChatGPT',
+ 'Tracked in: United States',
+ 'Your page cited before: Not available',
+ 'Cited now: Not available',
+ ]);
+ expect(container.querySelector('a')?.getAttribute('href')).toBe('/dashboard/prompts/p1');
+ });
+});
+
+describe('SignalEvidenceBlock', () => {
+ it('links the answers and the action the signal is used by', async () => {
+ getSignalActions.mockResolvedValue([
+ { id: 'a1', actionNo: 52, kind: 'unknown_kind_for_test', status: 'new', payload: {} },
+ ]);
+ await act(async () => {
+ render(
+ <SignalEvidenceBlock
+ brandId="b1"
+ signal={signal({ payload: { promptId: 'p1', promptText: 'x' }, actionId: 'a1' })}
+ />,
+ );
+ });
+ expect(getSignalActions).toHaveBeenCalledWith('b1', ['a1']);
+ const links = [...container.querySelectorAll('a')].map(
+ (a) => `${a.textContent} → ${a.getAttribute('href')}`,
+ );
+ expect(links).toEqual([
+ 'View AI answers → /dashboard/prompts/p1',
+ 'AC-52 · Unknown kind for test → /dashboard/action-center/actions?action=a1',
+ ]);
+ });
+
+ it('says when no action uses the signal, without asking', () => {
+ render(<SignalEvidenceBlock brandId="b1" signal={signal({ where: NO_WHERE })} />);
+ expect(getSignalActions).not.toHaveBeenCalled();
+ expect(container.textContent).toContain('No action uses this signal yet.');
+ });
+});
diff --git a/web/src/components/action-center/signal-detail-blocks.tsx b/web/src/components/action-center/signal-detail-blocks.tsx
new file mode 100644
index 000000000..a8a85f4c8
--- /dev/null
+++ b/web/src/components/action-center/signal-detail-blocks.tsx
@@ -0,0 +1,375 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useFormatter, useTranslations } from 'next-intl';
+import { ArrowRight, ArrowUpRight } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { AIProviderAvatar } from '@/components/ai-provider-avatar';
+import { getSignalActions, type Signal, type SignalAction } from '@/lib/actions/signals';
+import { actionTexts } from '@/lib/action-center/display';
+import { locationName, platformFamily, platformName } from '@/lib/signals/names';
+import {
+ METRIC_UNITS,
+ signalChange,
+ signalLinks,
+ signalWhereFields,
+ type SignalFigure,
+ type WhereValue,
+} from '@/lib/signals/detail';
+import { cn } from '@/lib/utils';
+
+/**
+ * The signal drawer's three blocks (AC-001): Where, What changed, and
+ * Evidence and links. lib/signals/detail.ts decides what each holds; these
+ * only render it.
+ */
+
+const LIST_LIMIT = 5;
+
+function BlockTitle({ children }: { children: React.ReactNode }) {
+ return <p className="text-xs font-medium text-muted-foreground">{children}</p>;
+}
+
+function NotAvailable() {
+ const t = useTranslations('actionCenter.signalsPage.drawer');
+ return <span className="text-xs text-muted-foreground">{t('notAvailable')}</span>;
+}
+
+function More({ shown, total }: { shown: number; total: number }) {
+ const t = useTranslations('actionCenter.signalsPage.drawer');
+ return total > shown ? (
+ <li className="text-xs text-muted-foreground">{t('more', { count: total - shown })}</li>
+ ) : null;
+}
+
+function WhereValueView({ value }: { value: WhereValue }) {
+ const t = useTranslations('actionCenter.signalsPage');
+ const format = useFormatter();
+ switch (value.type) {
+ case 'text':
+ return <span className="break-words">{value.text}</span>;
+ case 'number':
+ return <span className="tabular-nums">#{format.number(value.value)}</span>;
+ case 'scope':
+ return <span>{t(`drawer.scopes.${value.scope}`)}</span>;
+ case 'prompt':
+ return (
+ <span className="break-words">
+ {value.text}
+ {value.id && (
+ <Link
+ href={`/dashboard/prompts/${value.id}`}
+ className="ml-1.5 inline-flex items-center gap-0.5 text-xs font-medium underline-offset-2 hover:underline"
+ >
+ {t('drawer.viewPrompt')}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
+ )}
+ </span>
+ );
+ case 'prompts': {
+ if (value.items.length === 0)
+ return <span>{t('affected.prompts', { count: value.total })}</span>;
+ const shown = value.items.slice(0, LIST_LIMIT);
+ return (
+ <ul className="space-y-0.5">
+ {shown.map((item, i) => (
+ <li key={item.id ?? i} className="break-words">
+ {item.id ? (
+ <Link
+ href={`/dashboard/prompts/${item.id}`}
+ className="underline-offset-2 hover:underline"
+ >
+ {item.text}
+ </Link>
+ ) : (
+ item.text
+ )}
+ </li>
+ ))}
+ <More shown={shown.length} total={value.total} />
+ </ul>
+ );
+ }
+ case 'list': {
+ const shown = value.items.slice(0, LIST_LIMIT);
+ return (
+ <ul className="space-y-0.5">
+ {shown.map((item, i) => (
+ <li key={i} className="break-all">
+ {item}
+ </li>
+ ))}
+ <More shown={shown.length} total={value.total} />
+ </ul>
+ );
+ }
+ case 'platforms':
+ return (
+ <span className="flex flex-wrap gap-1">
+ {value.slugs.map((slug) => {
+ const family = platformFamily(slug);
+ return (
+ <span
+ key={slug}
+ className="inline-flex items-center gap-1 rounded border bg-muted/40 px-1.5 py-0.5 text-xs"
+ >
+ {family && (
+ <span aria-hidden="true" className="flex">
+ <AIProviderAvatar provider={family} className="h-3.5 w-3.5" />
+ </span>
+ )}
+ {platformName(slug)}
+ </span>
+ );
+ })}
+ </span>
+ );
+ case 'all_platforms':
+ return <span>{t('drawer.allPlatforms')}</span>;
+ case 'locations':
+ return <span>{value.codes.map(locationName).join(', ')}</span>;
+ }
+}
+
+export function SignalWhereBlock({ signal }: { signal: Signal }) {
+ const t = useTranslations('actionCenter.signalsPage.drawer');
+ const fields = signalWhereFields(signal);
+ if (fields.length === 0) return null;
+ return (
+ <div>
+ <BlockTitle>{t('where')}</BlockTitle>
+ <dl className="mt-2 grid grid-cols-[112px_1fr] gap-x-3 gap-y-2 rounded-lg border bg-muted/30 px-3 py-2.5 text-sm">
+ {fields.map(({ key, value }) => (
+ <div key={key} className="contents">
+ <dt className="text-xs text-muted-foreground">{t(`fields.${key}`)}</dt>
+ <dd className="min-w-0 text-sm">
+ {value ? <WhereValueView value={value} /> : <NotAvailable />}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </div>
+ );
+}
+
+function useFigureText() {
+ const t = useTranslations('actionCenter.signalsPage.drawer.change');
+ const format = useFormatter();
+
+ const value = (figure: Pick<SignalFigure, 'metric' | 'value'>, signed = false) => {
+ const unit = METRIC_UNITS[figure.metric];
+ const n = format.number(Math.abs(figure.value), { maximumFractionDigits: 1 });
+ const sign = signed ? (figure.value > 0 ? '+' : figure.value < 0 ? '−' : '') : '';
+ if (unit === 'percent') return signed ? t('points', { value: `${sign}${n}` }) : `${n}%`;
+ if (unit === 'points') return t('points', { value: `${sign}${n}` });
+ if (unit === 'rank') return `#${n}`;
+ return `${sign}${n}`;
+ };
+
+ // The subject is a stored slug or code; say it the way people do.
+ const subject = (figure: SignalFigure) => {
+ const raw = figure.subject ?? '';
+ if (!raw) return '';
+ if (figure.subjectType === 'location') return locationName(raw);
+ if (figure.subjectType === 'platform') return platformName(raw);
+ return raw;
+ };
+
+ // "Mention rate · last 7 days", "Mentions · Profound · last 7 days",
+ // "Mention rate · United States (best)": the metric, whose, and when.
+ const label = (figure: SignalFigure) => {
+ const name = subject(figure);
+ const overTime = ['before', 'after', 'change'].includes(figure.role);
+ return [
+ t(`metrics.${figure.metric}`),
+ overTime && name ? name : null,
+ t(`roles.${figure.role}`, { name: name || t('roles.unnamed') }),
+ ]
+ .filter(Boolean)
+ .join(' · ');
+ };
+
+ return { value, label };
+}
+
+export function SignalChangeBlock({ signal }: { signal: Signal }) {
+ const t = useTranslations('actionCenter.signalsPage.drawer');
+ const { value, label } = useFigureText();
+ const change = signalChange(signal);
+
+ return (
+ <div>
+ <BlockTitle>{t('whatChanged')}</BlockTitle>
+ {!change ? (
+ <p className="mt-1">
+ <NotAvailable />
+ </p>
+ ) : (
+ <>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {t(`change.periods.${change.period}`)}
+ </p>
+ <div className="mt-2 space-y-2">
+ {groupByMetric(change.figures).map((figures) => {
+ const before = figures.find((f) => f.role === 'before');
+ const after = figures.find((f) => f.role === 'after');
+ if (before && after) {
+ const delta = { metric: after.metric, value: after.value - before.value };
+ // A rise is good news for the brand's own numbers and bad news
+ // for a competitor's.
+ const good = delta.value >= 0 !== (after.subjectType === 'competitor');
+ return (
+ <div key={after.metric} className="flex flex-wrap items-center gap-2">
+ <FigureBox label={label(before)} value={value(before)} />
+ <ArrowRight className="h-3.5 w-3.5 text-muted-foreground" aria-hidden="true" />
+ <FigureBox label={label(after)} value={value(after)} />
+ {delta.value !== 0 && (
+ <span
+ className={cn(
+ 'text-xs font-medium',
+ good
+ ? 'text-green-600 dark:text-green-400'
+ : 'text-red-600 dark:text-red-400',
+ )}
+ >
+ {value(delta, true)}
+ </span>
+ )}
+ </div>
+ );
+ }
+ return (
+ <div key={figures[0].metric + figures[0].role} className="flex flex-wrap gap-2">
+ {figures.map((figure) => (
+ <FigureBox
+ key={figure.role + (figure.subject ?? '')}
+ label={label(figure)}
+ value={value(figure, figure.role === 'change')}
+ />
+ ))}
+ </div>
+ );
+ })}
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
+/** Figures of one metric together, in their order: one comparison per row. */
+function groupByMetric(figures: SignalFigure[]): SignalFigure[][] {
+ const groups = new Map<string, SignalFigure[]>();
+ for (const figure of figures) {
+ groups.set(figure.metric, [...(groups.get(figure.metric) ?? []), figure]);
+ }
+ return [...groups.values()];
+}
+
+function FigureBox({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="min-w-[120px] rounded-lg border px-3 py-1.5">
+ <p className="text-[11px] text-muted-foreground">{label}</p>
+ <p className="text-base font-semibold tabular-nums">{value}</p>
+ </div>
+ );
+}
+
+export function SignalEvidenceBlock({ signal, brandId }: { signal: Signal; brandId: string }) {
+ const t = useTranslations('actionCenter.signalsPage.drawer');
+ const tActions = useTranslations('actionCenter.actionTexts');
+ // Loaded per action id; until the answer for this id arrives it is loading.
+ const [loaded, setLoaded] = useState<{
+ id: string;
+ actions: SignalAction[] | null;
+ } | null>(null);
+ const actionId = signal.actionId;
+
+ useEffect(() => {
+ if (!actionId) return;
+ let cancelled = false;
+ getSignalActions(brandId, [actionId])
+ .then((rows) => {
+ if (!cancelled) setLoaded({ id: actionId, actions: rows });
+ })
+ .catch(() => {
+ if (!cancelled) setLoaded({ id: actionId, actions: null });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, actionId]);
+
+ const current = actionId && loaded?.id === actionId ? loaded : null;
+ const actions: SignalAction[] | 'loading' | 'failed' = !actionId
+ ? []
+ : !current
+ ? 'loading'
+ : (current.actions ?? 'failed');
+
+ const stamp = (iso: string) =>
+ new Date(iso).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ });
+
+ return (
+ <div className="space-y-3">
+ <BlockTitle>{t('evidence')}</BlockTitle>
+ <div className="flex flex-wrap gap-x-4 gap-y-1">
+ {signalLinks(signal).map((link) => (
+ <Link
+ key={link.href}
+ href={link.href}
+ className="inline-flex items-center gap-1 text-xs font-medium underline-offset-2 hover:underline"
+ >
+ {t(`links.${link.kind}`)}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
+ ))}
+ </div>
+ <div className="grid grid-cols-2 gap-x-4 text-xs">
+ <div>
+ <p className="text-muted-foreground">{t('detected')}</p>
+ <p className="mt-0.5 tabular-nums">{stamp(signal.detectedAt)}</p>
+ </div>
+ <div>
+ <p className="text-muted-foreground">{t('lastDetected')}</p>
+ <p className="mt-0.5 tabular-nums">{stamp(signal.lastDetectedAt)}</p>
+ </div>
+ </div>
+ <div>
+ <p className="text-xs text-muted-foreground">{t('usedBy')}</p>
+ <div className="mt-1 text-xs">
+ {actions === 'failed' ? (
+ <span className="text-muted-foreground">{t('usedByFailed')}</span>
+ ) : actions === 'loading' ? (
+ <span className="text-muted-foreground">{t('loading')}</span>
+ ) : actions.length === 0 ? (
+ <span className="text-muted-foreground">{t('usedByNone')}</span>
+ ) : (
+ <ul className="space-y-1">
+ {actions.map((action) => (
+ <li key={action.id}>
+ <Link
+ href={`/dashboard/action-center/actions?action=${action.id}`}
+ className="inline-flex items-start gap-1 rounded-md border px-2.5 py-1 font-medium hover:bg-muted"
+ >
+ {t('actionLabel', {
+ no: action.actionNo,
+ title: actionTexts(action, tActions).title,
+ })}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/components/action-center/signal-drawer.tsx b/web/src/components/action-center/signal-drawer.tsx
index 208ca7e31..f0eca5f00 100644
--- a/web/src/components/action-center/signal-drawer.tsx
+++ b/web/src/components/action-center/signal-drawer.tsx
@@ -1,8 +1,7 @@
'use client';
import { useTranslations } from 'next-intl';
-import { ArrowUpRight, Check, Eye, RotateCcw, X } from 'lucide-react';
-import { Link } from '@/i18n/navigation';
+import { Check, Eye, RotateCcw, X } from 'lucide-react';
import {
Sheet,
SheetContent,
@@ -15,7 +14,7 @@ import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import type { Signal } from '@/lib/actions/signals';
import { SIGNAL_KINDS, type SignalStatus } from '@/lib/signals/registry';
-import { signalAffected, signalTexts } from '@/lib/signals/display';
+import { signalTexts } from '@/lib/signals/display';
import { isKpiKey } from '@/lib/kpis/registry';
import {
ImpactDots,
@@ -24,19 +23,21 @@ import {
SignalStatusBadge,
SourceList,
} from './signal-table';
+import { SignalChangeBlock, SignalEvidenceBlock, SignalWhereBlock } from './signal-detail-blocks';
/**
- * Signal detail: the evidence view. Deliberately light in v1 — identity,
- * the measured change, affected entities, related KPIs, and triage. The
- * "Create Action" CTA belongs to the Actions iteration and is absent rather
- * than dead.
+ * Signal detail: where it happened, what changed, and what it rests on
+ * (AC-001), then the related KPIs and triage. The "Create Action" CTA
+ * belongs to the Actions iteration and is absent rather than dead.
*/
export function SignalDrawer({
+ brandId,
signal,
onOpenChange,
onStatusChange,
isBusy,
}: {
+ brandId: string;
signal: Signal | null;
onOpenChange: (open: boolean) => void;
onStatusChange: (signal: Signal, status: SignalStatus) => void;
@@ -49,18 +50,9 @@ export function SignalDrawer({
if (!signal) return null;
const texts = signalTexts(signal, tTexts);
- const affected = signalAffected(signal, t);
const stateKey = SIGNAL_KINDS[signal.kind].stateKey;
const relatedKpis = signal.kpiKeys.filter(isKpiKey);
- const formatStamp = (iso: string) =>
- new Date(iso).toLocaleDateString('en-US', {
- month: 'short',
- day: 'numeric',
- hour: 'numeric',
- minute: '2-digit',
- });
-
return (
<Sheet open={Boolean(signal)} onOpenChange={onOpenChange}>
<SheetContent className="flex flex-col gap-0 p-0 data-[side=right]:w-full data-[side=right]:sm:max-w-md">
@@ -93,64 +85,14 @@ export function SignalDrawer({
<DetailItem label={t('drawer.source')}>
<SourceList sources={signal.source} />
</DetailItem>
- <DetailItem label={t('drawer.detected')}>
- <span className="text-xs tabular-nums">{formatStamp(signal.detectedAt)}</span>
- </DetailItem>
- <DetailItem label={t('drawer.lastDetected')}>
- <span className="text-xs tabular-nums">{formatStamp(signal.lastDetectedAt)}</span>
- </DetailItem>
</div>
- {(signal.previousValue !== null || signal.changeValue !== null) && (
- <>
- <Separator />
- <div>
- <p className="text-xs font-medium text-muted-foreground">
- {t('drawer.whatChanged')}
- </p>
- <div className="mt-2 flex items-baseline gap-3 tabular-nums">
- {signal.previousValue !== null && (
- <span className="text-sm text-muted-foreground line-through">
- {signal.previousValue}
- </span>
- )}
- {signal.currentValue !== null && (
- <span className="text-lg font-semibold">{signal.currentValue}</span>
- )}
- {signal.changeValue !== null && (
- <span
- className={
- signal.changeValue >= 0 === SIGNAL_KINDS[signal.kind].positive
- ? 'text-xs font-medium text-green-600 dark:text-green-400'
- : 'text-xs font-medium text-red-500'
- }
- >
- {signal.changeValue > 0 ? '+' : ''}
- {signal.changeValue}
- </span>
- )}
- </div>
- </div>
- </>
- )}
-
<Separator />
- <div>
- <p className="text-xs font-medium text-muted-foreground">{t('drawer.affected')}</p>
- <p className="mt-1 text-sm">{affected.label}</p>
- {affected.detail && (
- <p className="break-all text-xs text-muted-foreground">{affected.detail}</p>
- )}
- {typeof signal.payload.promptId === 'string' && (
- <Link
- href={`/dashboard/prompts/${signal.payload.promptId}`}
- className="mt-2 inline-flex items-center gap-1 text-xs font-medium text-foreground underline-offset-2 hover:underline"
- >
- {t('drawer.viewPrompt')}
- <ArrowUpRight className="h-3 w-3" />
- </Link>
- )}
- </div>
+ <SignalWhereBlock signal={signal} />
+ <Separator />
+ <SignalChangeBlock signal={signal} />
+ <Separator />
+ <SignalEvidenceBlock signal={signal} brandId={brandId} />
{relatedKpis.length > 0 && (
<>
diff --git a/web/src/lib/actions/signals.ts b/web/src/lib/actions/signals.ts
index 2cb515cbb..e8780f27c 100644
--- a/web/src/lib/actions/signals.ts
+++ b/web/src/lib/actions/signals.ts
@@ -18,7 +18,7 @@ import type {
SignalStatus,
} from '@/lib/signals/registry';
import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';
-import type { PromptPlace } from '@/lib/signals/where';
+import { readPromptPlaces } from '@/lib/signals/prompt-places';
export type { Signal } from '@/lib/signals/map';
@@ -58,49 +58,48 @@ export async function getSignals(brandId: string, filters: SignalFilters): Promi
if (filters.status) query = query.eq('status', filters.status);
if (filters.source) query = query.contains('source', [filters.source]);
- const [{ data, error }, prompts] = await Promise.all([query, getPromptPlaces(supabase, brandId)]);
+ const [{ data, error }, prompts] = await Promise.all([
+ query,
+ readPromptPlaces(supabase, brandId),
+ ]);
if (error) throw new Error(error.message);
return mapSignalRows((data ?? []) as SignalRow[], prompts);
}
+/** An action a signal feeds, as its drawer lists it under "Used by actions". */
+export interface SignalAction {
+ id: string;
+ actionNo: number;
+ kind: string;
+ status: string;
+ payload: Record<string, unknown>;
+}
+
/**
- * Where each of the brand's prompts is tracked, by id. Paged, because a
- * brand can hold more prompts than one PostgREST response carries. A failed
- * read costs the Where line, not the page, so it is logged and the page
- * shows signals without it.
+ * The actions behind a signal's `action_id` (spec §10: signal → action
+ * traceability). Read when a drawer opens rather than with the list, so the
+ * list stays one query of signals.
*/
-async function getPromptPlaces(
- supabase: Awaited<ReturnType<typeof createClient>>,
+export async function getSignalActions(
brandId: string,
-): Promise<Map<string, PromptPlace>> {
- const places = new Map<string, PromptPlace>();
- for (let from = 0; ; from += 1000) {
- const { data, error } = await supabase
- .from('prompts')
- .select(
- 'id, platforms, regions, topic_id, is_active, prompt_sets!inner(brand_id), topics(name)',
- )
- .eq('prompt_sets.brand_id', brandId)
- .order('id')
- .range(from, from + 999);
- if (error) {
- console.error('[signals] prompt places read failed:', error.message);
- return new Map();
- }
- for (const row of data ?? []) {
- // The generated types read the topic join as a list; it is one topic.
- const topic = row.topics as { name: string } | { name: string }[] | null;
- places.set(row.id, {
- platforms: row.platforms ?? [],
- regions: row.regions ?? [],
- topicId: row.topic_id,
- topic: (Array.isArray(topic) ? topic[0]?.name : topic?.name) ?? null,
- isActive: row.is_active,
- });
- }
- if ((data ?? []).length < 1000) return places;
- }
+ actionIds: string[],
+): Promise<SignalAction[]> {
+ if (actionIds.length === 0) return [];
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('actions')
+ .select('id, action_no, kind, status, payload')
+ .eq('brand_id', brandId)
+ .in('id', actionIds);
+ if (error) throw new Error(error.message);
+ return (data ?? []).map((row) => ({
+ id: row.id,
+ actionNo: Number(row.action_no),
+ kind: row.kind,
+ status: row.status,
+ payload: (row.payload ?? {}) as Record<string, unknown>,
+ }));
}
export interface SignalsSummary {
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 93d246a84..5d6362b68 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -18,6 +18,9 @@ import {
toPromptUsageSummary,
type PromptUsageSummary,
} from '@/lib/prompt-usage-summary';
+import { mapSignalRows, type SignalRow } from '@/lib/signals/map';
+import { readPromptPlaces } from '@/lib/signals/prompt-places';
+import { signalDetailForApi, type SignalActionRef } from '@/lib/signals/detail';
/**
* Pure data-fetch functions shared by the MCP route and the parallel REST
@@ -2728,7 +2731,42 @@ export async function listSignalsFor(
const { data, error } = await query;
if (error) throw new Error(error.message);
- return (data ?? []) as Record<string, unknown>[];
+ const rows = (data ?? []) as SignalRow[];
+
+ // Each signal also says where it happened, what changed with units and
+ // period, what it rests on, and which actions use it (AC-001), the same
+ // way the dashboard's signal drawer does.
+ const actionIds = [...new Set(rows.map((row) => row.action_id).filter(Boolean))] as string[];
+ const [prompts, actionsRes] = await Promise.all([
+ readPromptPlaces(supabaseAdmin, params.brandId),
+ actionIds.length
+ ? supabaseAdmin
+ .from('actions')
+ .select('id, action_no, kind, status')
+ .eq('brand_id', params.brandId)
+ .in('id', actionIds)
+ : Promise.resolve({ data: [], error: null }),
+ ]);
+ // The actions only add used_by_actions; a failed read leaves it empty
+ // rather than taking the signals down with it.
+ if (actionsRes.error)
+ console.error('[mcp] signal actions read failed:', actionsRes.error.message);
+ const actions = new Map<string, SignalActionRef>(
+ (actionsRes.error ? [] : (actionsRes.data ?? [])).map((a) => [
+ a.id,
+ { id: a.id, action_no: Number(a.action_no), kind: a.kind, status: a.status },
+ ]),
+ );
+ const known = new Map(mapSignalRows(rows, prompts).map((signal) => [signal.id, signal]));
+
+ return rows.map((row) => {
+ const used = row.action_id && actions.has(row.action_id) ? [actions.get(row.action_id)!] : [];
+ const signal = known.get(row.id);
+ // A kind this build has no detail for still comes back, as it always did.
+ return signal
+ ? { ...row, ...signalDetailForApi(signal, used) }
+ : { ...row, used_by_actions: used };
+ });
}
export interface ActionHistoryRow {
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 2542f0fee..98711641f 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -954,7 +954,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'list_signals',
{
description:
- 'List the signals the Action Center detected for a brand: measured changes such as a visibility drop, a competitor gaining citations or a page losing AI traffic. Each signal carries previous_value, current_value and change_value, its payload, and the action_id it was consolidated into (null when no action covers it yet). Newest first. Use this to explain why an action exists or what has changed recently.',
+ "List the signals the Action Center detected for a brand: measured changes such as a visibility drop, a competitor gaining citations or a page losing AI traffic. Newest first. Each signal carries its raw row (previous_value, current_value, change_value, payload, action_id) and, read from it: `where` (the prompt, topic, platforms with names, locations, domain, competitor or pages it is about; a field is null when no detector records it yet), `change` (labelled figures: metric, role such as before/after or you/competitor, value, unit and the period, e.g. 'week_over_week'; null when the signal records no figures), `evidence` (first and last detection, and app paths that show the underlying answers) and `used_by_actions` (the actions built on it). Prefer `change` over the raw value columns: their meaning differs per signal kind. Use this to explain why an action exists or what has changed recently.",
inputSchema: {
brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),
status: z
diff --git a/web/src/lib/mcp/signals.test.ts b/web/src/lib/mcp/signals.test.ts
new file mode 100644
index 000000000..da5e478e4
--- /dev/null
+++ b/web/src/lib/mcp/signals.test.ts
@@ -0,0 +1,108 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+
+/**
+ * list_signals returns each signal's raw row plus the detail the dashboard's
+ * drawer shows (AC-001): where, change, evidence and used_by_actions. These
+ * pin that a kind this build doesn't know still comes back as it always did,
+ * and that a failed actions read costs used_by_actions, not the signals.
+ */
+
+let rows: Record<string, unknown[]> = {};
+let errors: Record<string, { message: string } | null> = {};
+
+function builder(table: string) {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ order: () => chain,
+ limit: () => chain,
+ in: () => chain,
+ range: () => chain,
+ maybeSingle: async () => ({ data: table === 'brands' ? { id: 'b1' } : null, error: null }),
+ then: (resolve: (v: { data: unknown[]; error: { message: string } | null }) => void) =>
+ resolve({ data: rows[table] ?? [], error: errors[table] ?? null }),
+ };
+ return chain;
+}
+
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: { from: (table: string) => builder(table) },
+}));
+
+const { listSignalsFor } = await import('./data');
+
+const auth: McpAuthContext = {
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+};
+
+const row = (over: Record<string, unknown>) => ({
+ id: 's1',
+ category: 'citation',
+ kind: 'lost_citations',
+ impact: 'high',
+ status: 'new',
+ source: ['ai_results'],
+ detected_at: '2026-10-08T10:53:00+00:00',
+ last_detected_at: '2026-10-09T10:53:00+00:00',
+ resolved_at: null,
+ previous_value: null,
+ current_value: null,
+ change_value: null,
+ payload: { promptId: 'p1', promptText: 'Best coffee subscription?' },
+ kpi_keys: [],
+ action_id: 'a1',
+ ...over,
+});
+
+beforeEach(() => {
+ errors = {};
+ rows = {
+ signals: [row({}), row({ id: 's2', kind: 'retired_kind', action_id: null, payload: {} })],
+ prompts: [
+ {
+ id: 'p1',
+ platforms: ['chatgpt-web'],
+ regions: ['US'],
+ topic_id: 't1',
+ is_active: true,
+ topics: { name: 'Coffee' },
+ },
+ ],
+ actions: [{ id: 'a1', action_no: 52, kind: 'recover_lost_citations', status: 'new' }],
+ };
+});
+
+describe('listSignalsFor', () => {
+ it('adds where, change, evidence and the actions using each signal', async () => {
+ const [known, unknown] = (await listSignalsFor(auth, { brandId: 'b1' }))!;
+ expect(known).toMatchObject({
+ id: 's1',
+ action_id: 'a1',
+ where: {
+ prompt: { id: 'p1', text: 'Best coffee subscription?' },
+ topic: 'Coffee',
+ tracked_on: [{ slug: 'chatgpt-web', name: 'ChatGPT' }],
+ tracked_in: [{ code: 'US', name: 'United States' }],
+ lost_url: null,
+ cited_now: null,
+ },
+ change: null,
+ evidence: { links: [{ kind: 'prompt_answers', path: '/dashboard/prompts/p1' }] },
+ used_by_actions: [{ id: 'a1', action_no: 52, kind: 'recover_lost_citations', status: 'new' }],
+ });
+ // A kind this build has no copy for keeps its raw row.
+ expect(unknown).toMatchObject({ id: 's2', kind: 'retired_kind', used_by_actions: [] });
+ expect(unknown).not.toHaveProperty('where');
+ });
+
+ it('still returns the signals when the actions read fails', async () => {
+ errors.actions = { message: 'timeout' };
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const [known] = (await listSignalsFor(auth, { brandId: 'b1' }))!;
+ expect(known).toMatchObject({ id: 's1', used_by_actions: [] });
+ });
+});
diff --git a/web/src/lib/signals/detail.test.ts b/web/src/lib/signals/detail.test.ts
new file mode 100644
index 000000000..1426d0d97
--- /dev/null
+++ b/web/src/lib/signals/detail.test.ts
@@ -0,0 +1,277 @@
+import { describe, expect, it } from 'vitest';
+import type { Signal } from './map';
+import { NO_WHERE } from './where';
+import { signalChange, signalDetailForApi, signalLinks, signalWhereFields } from './detail';
+
+const signal = (over: Partial<Signal>): Signal => ({
+ id: 's1',
+ category: 'visibility',
+ kind: 'platform_drop',
+ impact: 'high',
+ status: 'new',
+ source: ['ai_results'],
+ detectedAt: '2026-10-08T10:53:00+00:00',
+ lastDetectedAt: '2026-10-09T10:53:00+00:00',
+ resolvedAt: null,
+ previousValue: null,
+ currentValue: null,
+ changeValue: null,
+ payload: {},
+ kpiKeys: [],
+ actionId: null,
+ where: NO_WHERE,
+ ...over,
+});
+
+const platformDrop = signal({
+ payload: {
+ entity: 'platforms',
+ platform: 'gemini-web',
+ targets: [{ id: 'gemini-web', label: 'gemini-web' }],
+ },
+ previousValue: 34,
+ currentValue: 18,
+ changeValue: -16,
+ where: { platforms: ['gemini-web'], regions: [], topics: [] },
+});
+
+const lostCitation = signal({
+ category: 'citation',
+ kind: 'lost_citations',
+ payload: { promptId: 'p1', promptText: 'Best coffee subscription?' },
+ where: { platforms: ['chatgpt-web', 'gemini-web'], regions: ['US'], topics: ['Coffee'] },
+});
+
+const source = signal({
+ category: 'competitor',
+ kind: 'competitor_winning_source',
+ payload: {
+ entity: 'sources',
+ domain: 'yotpo.com',
+ prompts: 6,
+ results: 251,
+ targets: [{ id: 'yotpo.com', label: 'yotpo.com' }],
+ },
+ previousValue: 0,
+ currentValue: 251,
+ changeValue: 167,
+});
+
+describe('signalChange', () => {
+ it('gives a week-over-week change its two windows', () => {
+ expect(signalChange(platformDrop)).toEqual({
+ period: 'week_over_week',
+ figures: [
+ { metric: 'mention_rate', role: 'before', value: 34 },
+ { metric: 'mention_rate', role: 'after', value: 18 },
+ ],
+ });
+ });
+
+ it("names a source's three counts instead of a before and an after", () => {
+ expect(signalChange(source)).toEqual({
+ period: 'last_7_days',
+ figures: [
+ { metric: 'answers_citing', role: 'total', value: 251 },
+ { metric: 'answers_citing', role: 'naming_you', value: 0 },
+ { metric: 'answers_citing', role: 'competitors_only', value: 167 },
+ ],
+ });
+ });
+
+ it('compares inside one window, naming what is compared', () => {
+ expect(
+ signalChange(
+ signal({
+ kind: 'country_gap',
+ payload: { entity: 'regions', region: 'TR', bestRegion: 'US' },
+ previousValue: 22.5,
+ currentValue: 3.1,
+ }),
+ )?.figures,
+ ).toEqual([
+ { metric: 'mention_rate', role: 'best', value: 22.5, subject: 'US', subjectType: 'location' },
+ { metric: 'mention_rate', role: 'this', value: 3.1, subject: 'TR', subjectType: 'location' },
+ ]);
+ expect(
+ signalChange(
+ signal({
+ category: 'competitor',
+ kind: 'competitor_leads',
+ payload: { competitorName: 'Profound' },
+ previousValue: 40,
+ currentValue: 160,
+ }),
+ )?.figures,
+ ).toEqual([
+ {
+ metric: 'mentions',
+ role: 'competitor',
+ value: 160,
+ subject: 'Profound',
+ subjectType: 'competitor',
+ },
+ { metric: 'mentions', role: 'you', value: 40 },
+ ]);
+ });
+
+ it('adds what fell beside AI sessions on a cross-channel finding', () => {
+ const figures = signalChange(
+ signal({
+ category: 'traffic',
+ kind: 'cross_channel_risk',
+ payload: { entity: 'pages', targets: [{ id: 'site' }], clicksBefore: 900, clicksNow: 600 },
+ previousValue: 120,
+ currentValue: 80,
+ }),
+ )?.figures;
+ expect(figures?.map((f) => `${f.metric}:${f.role}:${f.value}`)).toEqual([
+ 'ai_sessions:before:120',
+ 'ai_sessions:after:80',
+ 'search_clicks:before:900',
+ 'search_clicks:after:600',
+ ]);
+ });
+
+ it("counts a competitor topic finding's prompts", () => {
+ expect(
+ signalChange(
+ signal({
+ category: 'competitor',
+ kind: 'competitor_topic_lead',
+ payload: { entity: 'topics', topicName: 'AEO', targets: [{ id: 't1', label: 'AEO' }] },
+ currentValue: 12,
+ }),
+ ),
+ ).toEqual({
+ period: 'last_7_days',
+ figures: [{ metric: 'prompts', role: 'total', value: 12 }],
+ });
+ });
+
+ it('has nothing to say when the row records no figures', () => {
+ expect(signalChange(lostCitation)).toBeNull();
+ });
+});
+
+describe('signalWhereFields', () => {
+ const keys = (s: Signal) => signalWhereFields(s).map((f) => `${f.key}${f.value ? '' : ' (n/a)'}`);
+
+ it('asks a lost citation which page was cited and who is cited now', () => {
+ expect(keys(lostCitation)).toEqual([
+ 'prompt',
+ 'topic',
+ 'trackedOn',
+ 'trackedIn',
+ 'lostUrl (n/a)',
+ 'citedNow (n/a)',
+ ]);
+ expect(signalWhereFields(lostCitation)[0].value).toEqual({
+ type: 'prompt',
+ id: 'p1',
+ text: 'Best coffee subscription?',
+ });
+ });
+
+ it("lists a competitor source's open questions as not available", () => {
+ expect(keys(source)).toEqual([
+ 'competitor (n/a)',
+ 'domain',
+ 'platforms (n/a)',
+ 'competitorPositions (n/a)',
+ 'winningSources (n/a)',
+ ]);
+ });
+
+ it("names a platform signal's scope and platform", () => {
+ expect(keys(platformDrop)).toEqual(['scope', 'platforms']);
+ });
+
+ it('says a brand-wide finding covers every platform rather than none', () => {
+ expect(
+ signalWhereFields(
+ signal({ kind: 'sharp_drop', previousValue: 24, currentValue: 15, payload: {} }),
+ ),
+ ).toEqual([
+ { key: 'scope', value: { type: 'scope', scope: 'all_prompts' } },
+ { key: 'platforms', value: { type: 'all_platforms' } },
+ ]);
+ });
+
+ it("reads a technical finding's failed checks as its evidence", () => {
+ const audit = signal({
+ category: 'technical',
+ kind: 'outdated_content',
+ payload: {
+ entity: 'pages',
+ targets: [{ id: '/pricing', page: '/pricing', checks: ['dateModified', 'freshness'] }],
+ },
+ currentValue: 1,
+ });
+ expect(signalWhereFields(audit)).toEqual([
+ { key: 'pages', value: { type: 'list', items: ['/pricing'], total: 1 } },
+ { key: 'crawlers', value: null },
+ {
+ key: 'evidence',
+ value: { type: 'list', items: ['dateModified', 'freshness'], total: 2 },
+ },
+ ]);
+ });
+});
+
+describe('signalLinks', () => {
+ it('points at the answers behind a signal, or the page that shows its source', () => {
+ expect(signalLinks(lostCitation)).toEqual([
+ { kind: 'prompt_answers', href: '/dashboard/prompts/p1' },
+ ]);
+ expect(signalLinks(source)).toEqual([{ kind: 'citations', href: '/dashboard/citations' }]);
+ expect(
+ signalLinks(
+ signal({ kind: 'topic_drop', payload: { entity: 'topics', targets: [{ id: 't1' }] } }),
+ ),
+ ).toEqual([{ kind: 'topic', href: '/dashboard/topics/t1' }]);
+ // Several prompts are each linked in Where; the evidence link is the list.
+ expect(
+ signalLinks(
+ signal({
+ kind: 'high_demand_gap',
+ payload: { entity: 'prompts', targets: [{ id: 'p1' }, { id: 'p2' }] },
+ }),
+ ),
+ ).toEqual([{ kind: 'prompts', href: '/dashboard/prompts' }]);
+ });
+});
+
+describe('signalDetailForApi', () => {
+ it('returns the same detail with snake_case keys, units and named platforms', () => {
+ const detail = signalDetailForApi({ ...lostCitation, actionId: 'a1' }, [
+ { id: 'a1', action_no: 52, kind: 'recover_lost_citations', status: 'new' },
+ ]);
+ expect(detail.where).toEqual({
+ prompt: { id: 'p1', text: 'Best coffee subscription?' },
+ topic: 'Coffee',
+ tracked_on: [
+ { slug: 'chatgpt-web', name: 'ChatGPT' },
+ { slug: 'gemini-web', name: 'Gemini' },
+ ],
+ tracked_in: [{ code: 'US', name: 'United States' }],
+ lost_url: null,
+ cited_now: null,
+ });
+ expect(detail.change).toBeNull();
+ expect(detail.evidence).toEqual({
+ first_detected_at: '2026-10-08T10:53:00+00:00',
+ last_detected_at: '2026-10-09T10:53:00+00:00',
+ links: [{ kind: 'prompt_answers', path: '/dashboard/prompts/p1' }],
+ });
+ expect(detail.used_by_actions).toHaveLength(1);
+ expect(signalDetailForApi(platformDrop, []).change?.figures[0]).toEqual({
+ metric: 'mention_rate',
+ role: 'before',
+ value: 34,
+ unit: 'percent',
+ subject: null,
+ subject_type: null,
+ });
+ });
+});
diff --git a/web/src/lib/signals/detail.ts b/web/src/lib/signals/detail.ts
new file mode 100644
index 000000000..652cb8d0b
--- /dev/null
+++ b/web/src/lib/signals/detail.ts
@@ -0,0 +1,714 @@
+import type { Signal } from './map';
+import { locationName, platformName } from './names';
+import { isLibrarySignalKind, type SignalCategory, type SignalKind } from './registry';
+
+/**
+ * What a signal's detail says, as data (AC-001): where it happened, what
+ * changed, and what it rests on. The drawer renders it and the MCP
+ * list_signals tool returns it, so both describe a signal the same way.
+ *
+ * Every number gets a metric, a role and a period, because the row's three
+ * value columns mean different things per detector: for a source domain
+ * "0 → 251 +167" is answers naming you, answers citing it and answers naming
+ * only competitors, not a before and an after. A field the spec asks for
+ * but no detector records yet is listed with no value, so the panel says
+ * "Not available" rather than hiding the question.
+ */
+
+// ─── What changed ───────────────────────────────────────────────────────────
+
+export type SignalMetric =
+ /** Share of tracked prompts where the brand appears. */
+ | 'visibility_rate'
+ /** Share of answers naming the brand (or the competitor in `subject`). */
+ | 'mention_rate'
+ /** Share of a topic's prompts where the brand appears. */
+ | 'coverage'
+ /** Answers naming the brand, or the competitor in `subject`. */
+ | 'mentions'
+ /** Answers citing the brand, or the competitor in `subject`. */
+ | 'citation_answers'
+ /** Answers citing a source domain. */
+ | 'answers_citing'
+ | 'visibility_score'
+ | 'ai_sessions'
+ | 'search_clicks'
+ | 'sessions'
+ | 'engagement_rank'
+ /** How many things a grouped finding covers. */
+ | 'prompts'
+ | 'pages'
+ | 'queries';
+
+export type SignalUnit = 'percent' | 'points' | 'count' | 'rank';
+
+export const METRIC_UNITS: Record<SignalMetric, SignalUnit> = {
+ visibility_rate: 'percent',
+ mention_rate: 'percent',
+ coverage: 'percent',
+ mentions: 'count',
+ citation_answers: 'count',
+ answers_citing: 'count',
+ visibility_score: 'points',
+ ai_sessions: 'count',
+ search_clicks: 'count',
+ sessions: 'count',
+ engagement_rank: 'rank',
+ prompts: 'count',
+ pages: 'count',
+ queries: 'count',
+};
+
+/**
+ * Whose or when a figure is. `before`/`after` are the two windows of a
+ * week-over-week change; the others compare things inside one window, with
+ * `subject` naming the competitor, platform or location.
+ */
+export type FigureRole =
+ | 'before'
+ | 'after'
+ | 'change'
+ | 'you'
+ | 'competitor'
+ | 'best'
+ | 'this'
+ | 'total'
+ | 'naming_you'
+ | 'competitors_only'
+ | 'now';
+
+export interface SignalFigure {
+ metric: SignalMetric;
+ role: FigureRole;
+ value: number;
+ /** The competitor's name, or the platform slug or location code compared. */
+ subject?: string;
+ subjectType?: 'competitor' | 'platform' | 'location';
+}
+
+/** The window the figures cover. The detectors all read 7-day windows. */
+export type ChangePeriod = 'week_over_week' | 'last_7_days' | 'latest';
+
+export interface SignalChange {
+ period: ChangePeriod;
+ figures: SignalFigure[];
+}
+
+function str(payload: Record<string, unknown>, key: string): string {
+ const value = payload[key];
+ return typeof value === 'string' ? value : '';
+}
+
+/** Kinds whose two values are the previous and the last 7 days of one metric. */
+const WEEK_OVER_WEEK: Partial<Record<SignalKind, SignalMetric>> = {
+ sharp_drop: 'visibility_rate',
+ visibility_slipping: 'visibility_rate',
+ platform_slipping: 'mention_rate',
+ platform_drop: 'mention_rate',
+ topic_gap: 'coverage',
+ topic_uncovered: 'coverage',
+ topic_slipping: 'coverage',
+ topic_drop: 'coverage',
+ competitor_momentum: 'mentions',
+ competitor_surge: 'mention_rate',
+ ai_traffic_drop: 'ai_sessions',
+ visibility_traffic_loss: 'ai_sessions',
+ cross_channel_risk: 'ai_sessions',
+};
+
+const COUNTED: Record<string, SignalMetric> = {
+ prompts: 'prompts',
+ pages: 'pages',
+ queries: 'queries',
+};
+
+/** The figures behind a signal, or null when its row records none. */
+export function signalChange(signal: Signal): SignalChange | null {
+ const p = signal.payload ?? {};
+ const prev = signal.previousValue;
+ const cur = signal.currentValue;
+ const change = signal.changeValue;
+ const competitor = str(p, 'competitorName') || undefined;
+
+ const overTime = WEEK_OVER_WEEK[signal.kind];
+ if (overTime && prev !== null && cur !== null) {
+ // A competitor's own trend names the competitor; the brand's doesn't.
+ const competitorOnly = overTime === 'mentions' || overTime === 'mention_rate';
+ const about =
+ competitor && competitorOnly
+ ? { subject: competitor, subjectType: 'competitor' as const }
+ : {};
+ const figures: SignalFigure[] = [
+ { metric: overTime, role: 'before', value: prev, ...about },
+ { metric: overTime, role: 'after', value: cur, ...about },
+ ];
+ // The cross-channel findings say what fell beside the AI sessions.
+ if (signal.kind === 'cross_channel_risk') {
+ figures.push(
+ { metric: 'search_clicks', role: 'before', value: Number(p.clicksBefore ?? 0) },
+ { metric: 'search_clicks', role: 'after', value: Number(p.clicksNow ?? 0) },
+ );
+ }
+ if (signal.kind === 'visibility_traffic_loss') {
+ figures.push(
+ { metric: 'mentions', role: 'before', value: Number(p.mentionsBefore ?? 0) },
+ { metric: 'mentions', role: 'after', value: Number(p.mentionsNow ?? 0) },
+ );
+ }
+ return { period: 'week_over_week', figures };
+ }
+
+ switch (signal.kind) {
+ case 'platform_gap':
+ if (prev === null || cur === null) return null;
+ return {
+ period: 'last_7_days',
+ figures: [
+ {
+ metric: 'visibility_rate',
+ role: 'best',
+ value: prev,
+ subject: str(p, 'bestPlatform'),
+ subjectType: 'platform',
+ },
+ {
+ metric: 'visibility_rate',
+ role: 'this',
+ value: cur,
+ subject: str(p, 'platform'),
+ subjectType: 'platform',
+ },
+ ],
+ };
+ case 'country_gap':
+ if (prev === null || cur === null) return null;
+ return {
+ period: 'last_7_days',
+ figures: [
+ {
+ metric: 'mention_rate',
+ role: 'best',
+ value: prev,
+ subject: str(p, 'bestRegion'),
+ subjectType: 'location',
+ },
+ {
+ metric: 'mention_rate',
+ role: 'this',
+ value: cur,
+ subject: str(p, 'region'),
+ subjectType: 'location',
+ },
+ ],
+ };
+ case 'competitor_leads':
+ if (prev === null || cur === null) return null;
+ return {
+ period: 'last_7_days',
+ figures: [
+ {
+ metric: 'mentions',
+ role: 'competitor',
+ value: cur,
+ subject: competitor,
+ subjectType: 'competitor',
+ },
+ { metric: 'mentions', role: 'you', value: prev },
+ ],
+ };
+ case 'competitor_citation_gap':
+ if (prev === null || cur === null) return null;
+ return {
+ period: 'last_7_days',
+ figures: [
+ {
+ metric: 'citation_answers',
+ role: 'competitor',
+ value: prev,
+ subject: competitor,
+ subjectType: 'competitor',
+ },
+ { metric: 'citation_answers', role: 'you', value: cur },
+ ],
+ };
+ case 'competitor_crossed':
+ case 'competitor_overtaken':
+ return {
+ period: 'last_7_days',
+ figures: [
+ {
+ metric: 'mention_rate',
+ role: 'competitor',
+ value: Number(p.competitorRate ?? 0),
+ subject: competitor,
+ subjectType: 'competitor',
+ },
+ { metric: 'mention_rate', role: 'you', value: Number(p.brandRate ?? 0) },
+ ],
+ };
+ case 'prompt_gain':
+ if (change === null) return null;
+ return {
+ period: 'week_over_week',
+ figures: [{ metric: 'visibility_score', role: 'change', value: change }],
+ };
+ case 'page_opportunity': {
+ const figures: SignalFigure[] = [];
+ if (typeof p.valueRank === 'number') {
+ figures.push({ metric: 'engagement_rank', role: 'now', value: p.valueRank });
+ }
+ if (cur !== null) figures.push({ metric: 'sessions', role: 'now', value: cur });
+ return figures.length ? { period: 'latest', figures } : null;
+ }
+ case 'uncited_mentions':
+ return cur === null
+ ? null
+ : { period: 'last_7_days', figures: [{ metric: 'prompts', role: 'total', value: cur }] };
+ case 'audit_low_score':
+ return cur === null
+ ? null
+ : { period: 'latest', figures: [{ metric: 'pages', role: 'total', value: cur }] };
+ }
+
+ if (!isLibrarySignalKind(signal.kind)) return null;
+ const entity = str(p, 'entity');
+ // Answers citing a source domain: all of them, those naming the brand, and
+ // those naming only competitors (ae_citation_sources).
+ if (entity === 'sources' && cur !== null) {
+ return {
+ period: 'last_7_days',
+ figures: [
+ { metric: 'answers_citing', role: 'total', value: cur },
+ { metric: 'answers_citing', role: 'naming_you', value: prev ?? 0 },
+ { metric: 'answers_citing', role: 'competitors_only', value: change ?? 0 },
+ ],
+ };
+ }
+ // A competitor's topic finding counts the topic's tracked prompts.
+ if (entity === 'topics' && prev === null && cur !== null) {
+ return { period: 'last_7_days', figures: [{ metric: 'prompts', role: 'total', value: cur }] };
+ }
+ const counted = COUNTED[entity];
+ if (counted && cur !== null) {
+ return { period: 'last_7_days', figures: [{ metric: counted, role: 'total', value: cur }] };
+ }
+ return null;
+}
+
+// ─── Where ──────────────────────────────────────────────────────────────────
+
+export type WhereFieldKey =
+ | 'scope'
+ | 'prompt'
+ | 'prompts'
+ | 'topic'
+ | 'platforms'
+ | 'locations'
+ /** Where the signal's prompts are tracked, which can be wider than where it happened. */
+ | 'trackedOn'
+ | 'trackedIn'
+ | 'domain'
+ | 'competitor'
+ | 'url'
+ | 'pages'
+ | 'queries'
+ | 'engagementRank'
+ | 'lostUrl'
+ | 'citedNow'
+ | 'exampleUrls'
+ | 'competitorsNamed'
+ | 'bestPage'
+ | 'position'
+ | 'sentiment'
+ | 'excerpt'
+ | 'aiReferrals'
+ | 'citablePrompts'
+ | 'issue'
+ | 'crawlers'
+ | 'evidence'
+ | 'competitorPositions'
+ | 'winningSources';
+
+export type WhereValue =
+ | { type: 'text'; text: string }
+ | { type: 'scope'; scope: 'all_prompts' | 'site' | 'topic' | 'platform' | 'location' | 'prompt' }
+ | { type: 'prompt'; id: string | null; text: string }
+ | { type: 'prompts'; items: { id: string | null; text: string }[]; total: number }
+ | { type: 'list'; items: string[]; total: number }
+ | { type: 'platforms'; slugs: readonly string[] }
+ /** Every tracked platform: a finding about the whole brand or a location. */
+ | { type: 'all_platforms' }
+ | { type: 'locations'; codes: readonly string[] }
+ | { type: 'number'; value: number };
+
+export interface WhereField {
+ key: WhereFieldKey;
+ /** Null when no detector records it yet: the panel says "Not available". */
+ value: WhereValue | null;
+}
+
+// Signals about one of the brand's own citations going away.
+const CITATION_LOSS: readonly SignalKind[] = [
+ 'lost_citations',
+ 'citation_at_risk',
+ 'page_citation_slipping',
+ 'owned_page_citation_lost',
+];
+
+// What the spec asks each panel to answer, per category (AC-001's table).
+// The fields a signal's data can fill come first in each list.
+const LAYOUT: Record<SignalCategory, WhereFieldKey[]> = {
+ visibility: ['scope', 'prompt', 'prompts', 'topic', 'platforms', 'locations', 'queries'],
+ citation: [
+ 'domain',
+ 'prompt',
+ 'prompts',
+ 'topic',
+ 'platforms',
+ 'locations',
+ 'url',
+ 'exampleUrls',
+ 'competitorsNamed',
+ 'bestPage',
+ ],
+ mention: ['prompt', 'prompts', 'platforms', 'locations', 'position', 'sentiment', 'excerpt'],
+ traffic: ['scope', 'url', 'pages', 'queries', 'engagementRank', 'aiReferrals', 'citablePrompts'],
+ technical: ['url', 'pages', 'issue', 'crawlers', 'evidence'],
+ competitor: [
+ 'competitor',
+ 'domain',
+ 'topic',
+ 'prompts',
+ 'queries',
+ 'platforms',
+ 'competitorPositions',
+ 'winningSources',
+ ],
+};
+
+// A first citation is a gain: the page and the prompt, not who replaced it.
+const FIRST_CITATION_LAYOUT: WhereFieldKey[] = ['url', 'prompt', 'platforms', 'locations'];
+
+const CITATION_LOSS_LAYOUT: WhereFieldKey[] = [
+ 'prompt',
+ 'prompts',
+ 'topic',
+ 'pages',
+ 'platforms',
+ 'locations',
+ 'lostUrl',
+ 'citedNow',
+];
+
+// 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([
+ 'scope',
+ 'prompt',
+ 'prompts',
+ 'topic',
+ 'domain',
+ 'url',
+ 'pages',
+ 'queries',
+ 'locations',
+ 'engagementRank',
+ 'issue',
+]);
+
+interface Target {
+ id?: unknown;
+ label?: unknown;
+ competitor?: unknown;
+ checks?: unknown;
+ page?: unknown;
+}
+
+function targetsOf(signal: Signal): Target[] {
+ const targets = signal.payload?.targets;
+ return Array.isArray(targets) ? (targets as Target[]) : [];
+}
+
+function label(target: Target): string {
+ if (typeof target.label === 'string' && target.label) return target.label;
+ if (typeof target.page === 'string') return target.page;
+ return typeof target.id === 'string' ? target.id : '';
+}
+
+function fieldValue(signal: Signal, key: WhereFieldKey): WhereValue | null {
+ const p = signal.payload ?? {};
+ const entity = str(p, 'entity');
+ const targets = targetsOf(signal);
+ // A grouped finding names the first 50 of its targets; the count is all.
+ const total = Math.max(targets.length, Number(signal.currentValue ?? 0));
+
+ switch (key) {
+ case 'scope': {
+ if (signal.kind === 'sharp_drop' || signal.kind === 'visibility_slipping') {
+ return { type: 'scope', scope: 'all_prompts' };
+ }
+ if (str(p, 'entity') === 'pages' && targets[0]?.id === 'site') {
+ return { type: 'scope', scope: 'site' };
+ }
+ if (entity === 'topics') return { type: 'scope', scope: 'topic' };
+ if (
+ entity === 'platforms' ||
+ signal.kind === 'platform_gap' ||
+ signal.kind === 'new_engine'
+ ) {
+ return { type: 'scope', scope: 'platform' };
+ }
+ if (entity === 'regions') return { type: 'scope', scope: 'location' };
+ if (str(p, 'promptId') || entity === 'prompts') return { type: 'scope', scope: 'prompt' };
+ return null;
+ }
+ case 'prompt': {
+ const text = str(p, 'promptText');
+ if (!text) return null;
+ return { type: 'prompt', id: str(p, 'promptId') || null, text };
+ }
+ case 'prompts': {
+ if (entity === 'topics' && typeof p.prompts === 'number') {
+ return { type: 'prompts', items: [], total: p.prompts };
+ }
+ if (entity !== 'prompts' || targets.length === 0) {
+ const ids = Array.isArray(p.promptIds) ? p.promptIds : [];
+ return ids.length > 0
+ ? { type: 'prompts', items: [], total: Number(signal.currentValue ?? ids.length) }
+ : null;
+ }
+ return {
+ type: 'prompts',
+ items: targets.map((t) => ({
+ id: typeof t.id === 'string' ? t.id : null,
+ text: label(t),
+ })),
+ total,
+ };
+ }
+ case 'topic': {
+ if (entity === 'topics') {
+ const name = label(targets[0] ?? {});
+ return name ? { type: 'text', text: name } : null;
+ }
+ const topics = signal.where.topics;
+ if (topics.length > 1) return { type: 'list', items: [...topics], total: topics.length };
+ return topics[0] ? { type: 'text', text: topics[0] } : null;
+ }
+ case 'platforms':
+ if (signal.where.platforms.length) {
+ return { type: 'platforms', slugs: signal.where.platforms };
+ }
+ if (
+ signal.kind === 'sharp_drop' ||
+ signal.kind === 'visibility_slipping' ||
+ entity === 'regions'
+ ) {
+ return { type: 'all_platforms' };
+ }
+ return null;
+ case 'locations':
+ return signal.where.regions.length
+ ? { type: 'locations', codes: signal.where.regions }
+ : null;
+ case 'domain': {
+ const domain = str(p, 'domain');
+ return domain ? { type: 'text', text: domain } : null;
+ }
+ case 'competitor': {
+ const named = str(p, 'competitorName');
+ if (named) return { type: 'text', text: named };
+ const leaders = [
+ ...new Set(targets.map((t) => (typeof t.competitor === 'string' ? t.competitor : ''))),
+ ].filter(Boolean);
+ return leaders.length ? { type: 'list', items: leaders, total: leaders.length } : null;
+ }
+ case 'url': {
+ const url = str(p, 'landingPage') || str(p, 'url');
+ return url ? { type: 'text', text: url } : null;
+ }
+ case 'pages': {
+ if (entity === 'pages' && targets.length && targets[0]?.id !== 'site') {
+ return { type: 'list', items: targets.map(label), total };
+ }
+ const urls = Array.isArray(p.urls) ? (p.urls as { url?: unknown }[]) : [];
+ const items = urls.map((u) => (typeof u.url === 'string' ? u.url : '')).filter(Boolean);
+ return items.length ? { type: 'list', items, total: Math.max(items.length, total) } : null;
+ }
+ case 'queries':
+ return entity === 'queries' && targets.length
+ ? { type: 'list', items: targets.map(label), total }
+ : null;
+ case 'engagementRank':
+ return typeof p.valueRank === 'number' ? { type: 'number', value: p.valueRank } : null;
+ case 'lostUrl':
+ // An owned page that stopped being cited is the lost URL itself.
+ return signal.kind === 'owned_page_citation_lost' && targets.length
+ ? { type: 'list', items: targets.map(label), total }
+ : null;
+ case 'evidence': {
+ const checks = targets.flatMap((t) =>
+ Array.isArray(t.checks) ? t.checks.filter((c): c is string => typeof c === 'string') : [],
+ );
+ const unique = [...new Set(checks)];
+ return unique.length ? { type: 'list', items: unique, total: unique.length } : null;
+ }
+ default:
+ return null;
+ }
+}
+
+// A place the payload names is where the signal happened; one read from its
+// prompts is where those are tracked, and is labelled so.
+const TRACKED: Partial<Record<WhereFieldKey, WhereFieldKey>> = {
+ platforms: 'trackedOn',
+ locations: 'trackedIn',
+};
+
+function placeIsNamed(signal: Signal): boolean {
+ const p = signal.payload ?? {};
+ return typeof p.platform === 'string' || typeof p.region === 'string';
+}
+
+/** The Where block: the spec's fields for this signal, each with its value or none. */
+export function signalWhereFields(signal: Signal): WhereField[] {
+ const layout =
+ signal.kind === 'first_citation'
+ ? FIRST_CITATION_LAYOUT
+ : CITATION_LOSS.includes(signal.kind)
+ ? CITATION_LOSS_LAYOUT
+ : LAYOUT[signal.category];
+ const named = placeIsNamed(signal);
+ return layout
+ .map((key) => {
+ const value = fieldValue(signal, key);
+ const tracked = TRACKED[key];
+ return {
+ // 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
+ : key,
+ value,
+ };
+ })
+ .filter((field) => field.value !== null || !OPTIONAL.has(field.key));
+}
+
+// ─── Evidence ───────────────────────────────────────────────────────────────
+
+/** A page that shows what the signal rests on, by app path. */
+export interface SignalLink {
+ kind:
+ | 'prompt_answers'
+ | 'prompts'
+ | 'topic'
+ | 'citations'
+ | 'competitors'
+ | 'traffic'
+ | 'audit'
+ | 'insights';
+ href: string;
+}
+
+export function signalLinks(signal: Signal): SignalLink[] {
+ const p = signal.payload ?? {};
+ const promptId = str(p, 'promptId');
+ if (promptId) {
+ return [{ kind: 'prompt_answers', href: `/dashboard/prompts/${promptId}` }];
+ }
+ const entity = str(p, 'entity');
+ const first = targetsOf(signal)[0];
+ if (entity === 'topics' && typeof first?.id === 'string') {
+ return [{ kind: 'topic', href: `/dashboard/topics/${first.id}` }];
+ }
+ // One prompt's answers for a one-prompt finding; a larger one lists its
+ // prompts in Where, each linked, and points at the prompts list here.
+ if (entity === 'prompts' && typeof first?.id === 'string') {
+ return targetsOf(signal).length === 1
+ ? [{ kind: 'prompt_answers', href: `/dashboard/prompts/${first.id}` }]
+ : [{ kind: 'prompts', href: '/dashboard/prompts' }];
+ }
+ if (entity === 'sources' || signal.category === 'citation') {
+ return [{ kind: 'citations', href: '/dashboard/citations' }];
+ }
+ switch (signal.category) {
+ case 'competitor':
+ return [{ kind: 'competitors', href: '/dashboard/competitors' }];
+ case 'traffic':
+ return [{ kind: 'traffic', href: '/dashboard/traffic' }];
+ case 'technical':
+ return [{ kind: 'audit', href: '/dashboard/audit' }];
+ default:
+ return [{ kind: 'insights', href: '/dashboard/insights' }];
+ }
+}
+
+// ─── For the API ────────────────────────────────────────────────────────────
+
+const snake = (key: string) => key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
+
+function apiValue(value: WhereValue): unknown {
+ switch (value.type) {
+ case 'text':
+ return value.text;
+ case 'scope':
+ return value.scope;
+ case 'number':
+ return value.value;
+ case 'prompt':
+ return { id: value.id, text: value.text };
+ case 'prompts':
+ return { total: value.total, items: value.items };
+ case 'list':
+ return { total: value.total, items: value.items };
+ case 'platforms':
+ return value.slugs.map((slug) => ({ slug, name: platformName(slug) }));
+ case 'all_platforms':
+ return 'all';
+ case 'locations':
+ return value.codes.map((code) => ({ code, name: locationName(code) }));
+ }
+}
+
+export interface SignalActionRef {
+ id: string;
+ action_no: number;
+ kind: string;
+ status: string;
+}
+
+/**
+ * A signal's detail in the shape the MCP tools return (AC-001: "the signal
+ * API/MCP returns the same structured fields"): snake_case keys, a null for
+ * every field no detector records yet, and every figure with its unit.
+ */
+export function signalDetailForApi(signal: Signal, actions: SignalActionRef[]) {
+ const change = signalChange(signal);
+ return {
+ where: Object.fromEntries(
+ signalWhereFields(signal).map(({ key, value }) => [
+ snake(key),
+ value ? apiValue(value) : null,
+ ]),
+ ),
+ change: change && {
+ period: change.period,
+ figures: change.figures.map((f) => ({
+ metric: f.metric,
+ role: f.role,
+ value: f.value,
+ unit: METRIC_UNITS[f.metric],
+ subject: f.subject ?? null,
+ subject_type: f.subjectType ?? null,
+ })),
+ },
+ evidence: {
+ first_detected_at: signal.detectedAt,
+ last_detected_at: signal.lastDetectedAt,
+ links: signalLinks(signal).map((link) => ({ kind: link.kind, path: link.href })),
+ },
+ used_by_actions: actions,
+ };
+}
diff --git a/web/src/lib/signals/prompt-places.ts b/web/src/lib/signals/prompt-places.ts
new file mode 100644
index 000000000..6d007ede5
--- /dev/null
+++ b/web/src/lib/signals/prompt-places.ts
@@ -0,0 +1,52 @@
+import type { SupabaseClient } from '@supabase/supabase-js';
+import type { PromptPlace } from './where';
+
+/**
+ * Where each of a brand's prompts is tracked, by id: the read behind every
+ * signal's Where (AC-002), shared by the Signals page (as the signed-in user)
+ * and the MCP tools (through the API key's admin client). Paged, because a
+ * brand can hold more prompts than one PostgREST response carries. A failed
+ * read costs the Where details, not the caller, so it is logged and empty.
+ */
+export async function readPromptPlaces(
+ client: SupabaseClient,
+ brandId: string,
+): Promise<Map<string, PromptPlace>> {
+ const places = new Map<string, PromptPlace>();
+ for (let from = 0; ; from += 1000) {
+ const { data, error } = await client
+ .from('prompts')
+ .select(
+ 'id, platforms, regions, topic_id, is_active, prompt_sets!inner(brand_id), topics(name)',
+ )
+ .eq('prompt_sets.brand_id', brandId)
+ .order('id')
+ .range(from, from + 999);
+ if (error) {
+ console.error('[signals] prompt places read failed:', error.message);
+ return new Map();
+ }
+ const rows = (data ?? []) as PromptPlaceRow[];
+ for (const row of rows) {
+ // The join is to one topic, though it can come back as a list.
+ const topic = Array.isArray(row.topics) ? row.topics[0] : row.topics;
+ places.set(row.id, {
+ platforms: row.platforms ?? [],
+ regions: row.regions ?? [],
+ topicId: row.topic_id,
+ topic: topic?.name ?? null,
+ isActive: row.is_active,
+ });
+ }
+ if (rows.length < 1000) return places;
+ }
+}
+
+interface PromptPlaceRow {
+ id: string;
+ platforms: string[] | null;
+ regions: string[] | null;
+ topic_id: string | null;
+ is_active: boolean;
+ topics: { name: string } | { name: string }[] | null;
+}