Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(action-center): write an action's why and goal from its own data (#1077)
Cihand566658ae65d
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 67e66634a..6dd4f5c26 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1022,6 +1022,106 @@"more": "Showing {shown} of {total}","empty": "Nothing recorded to list for this action."},+ "story": {+ "subject": {+ "prompts": "{count, plural, one {# prompt} other {# prompts}}",+ "pages": "{count, plural, one {# page} other {# pages}}",+ "topics": "prompts in {count, plural, one {# topic} other {# topics}}",+ "prompt": "“{label}”",+ "page": "{label}",+ "topic": "prompts in {label}",+ "inTopic": " in {topic}",+ "volume": " (~{volume} AI searches a month)"+ },+ "noun": {+ "prompts": "{count, plural, one {prompt} other {prompts}}",+ "pages": "{count, plural, one {page} other {pages}}",+ "topics": "{count, plural, one {topic} other {topics}}"+ },+ "scope": {+ "all": "{count, plural, =2 {both {noun}} other {all # {noun}}}",+ "some": "≥{target} of {count} {noun}"+ },+ "domain": " to {domain}",+ "platforms": " on {list}",+ "more": "{count} more",+ "when": {+ "day": " on {day}",+ "range": " between {from} and {to}"+ },+ "fromToRate": " from {from}% to {to}%",+ "fromToVisits": " from {before} to {now}",+ "issues": ": {list}",+ "competitorUnnamed": "a competitor",+ "why": {+ "citationLoss": "{count, plural, one {{subject} lost its citations} other {{subject} lost their citations}}{domain}{platforms}{when}.",+ "citationLossAll": "Your pages lost citations{domain}{platforms}{when}.",+ "citationGap": "{entity, select, pages {{subject} {count, plural, one {doesn't} other {don't}} cite you} other {AI answers to {subject} cite other sites, not yours}}{platforms}{when}.",+ "citationGapAll": "AI answers cite other sites, not yours{platforms}{when}.",+ "citationGain": "{entity, select, pages {{subject} started earning citations} other {AI answers to {subject} started citing you}}{platforms}{when}.",+ "citationGainAll": "AI answers started citing you{platforms}{when}.",+ "visibilityLoss": "Your brand dropped out of AI answers to {subject}{platforms}{when}.",+ "visibilityLossAll": "Your AI visibility fell{fromTo}{platforms}{when}.",+ "visibilityGap": "{entity, select, pages {{subject} {count, plural, one {isn't} other {aren't}} showing up in AI answers} other {Your brand is missing from AI answers to {subject}}}{platforms}{when}.",+ "visibilityGapAll": "Your brand is missing from AI answers{platforms}{when}.",+ "visibilityGain": "{entity, select, pages {{subject} started showing up in AI answers} other {Your brand started appearing in AI answers to {subject}}}{platforms}{when}.",+ "visibilityGainAll": "Your AI visibility rose{fromTo}{platforms}{when}.",+ "mentionLoss": "AI answers to {subject} stopped naming your brand{platforms}{when}.",+ "mentionLossAll": "AI answers stopped naming your brand{platforms}{when}.",+ "mentionGap": "AI answers to {subject} name your brand without citing you{platforms}{when}.",+ "mentionGapAll": "AI answers name your brand without citing you{platforms}{when}.",+ "competitorBehind": "{named, select, yes {{competitor} {competitors, plural, one {is} other {are}}} other {A competitor is}} ahead of you on {subject}{platforms}{when}.",+ "competitorBehindAll": "{named, select, yes {{competitor} {competitors, plural, one {is} other {are}}} other {A competitor is}} ahead of you{platforms}{when}.",+ "competitorAhead": "You moved ahead of {competitor} on {subject}{platforms}{when}.",+ "competitorAheadAll": "You moved ahead of {competitor}{platforms}{when}.",+ "trafficLoss": "AI visits to {subject} fell{fromTo}{when}.",+ "trafficLossAll": "AI visits to your site fell{fromTo}{when}.",+ "trafficGap": "{subject} {count, plural, one {draws} other {draw}} fewer AI visits than {count, plural, one {it} other {they}} could{when}.",+ "trafficGapAll": "Your pages draw fewer AI visits than they could{when}.",+ "trafficGain": "AI visits to {subject} rose{fromTo}{when}.",+ "trafficGainAll": "AI visits to your site rose{fromTo}{when}.",+ "searchLoss": "Google search clicks to {subject} fell{when}.",+ "searchLossAll": "Google search clicks to your site fell{when}.",+ "searchGap": "{subject} {count, plural, one {underperforms} other {underperform}} in Google search{when}.",+ "searchGapAll": "Your pages underperform in Google search{when}.",+ "technicalIssue": "Site Audit flagged {subject}{issues}{when}.",+ "technicalIssueAll": "Site Audit flagged your site{issues}{when}."+ },+ "goal": {+ "citationLoss": "Citations back on {scope} by {date}.",+ "citationLossAll": "Your citations back{platforms} by {date}.",+ "citationGap": "Cited on {scope} by {date}.",+ "citationGapAll": "Cited in AI answers{platforms} by {date}.",+ "citationGain": "Citations kept on {scope} through {date}.",+ "citationGainAll": "Citations kept{platforms} through {date}.",+ "visibilityLoss": "Back in AI answers to {scope} by {date}.",+ "visibilityLossAll": "{hasFrom, select, yes {AI visibility back to {from}%} other {AI visibility back}}{platforms} by {date}.",+ "visibilityGap": "{entity, select, pages {Showing up in AI answers on {scope}} other {In AI answers to {scope}}} by {date}.",+ "visibilityGapAll": "In AI answers{platforms} by {date}.",+ "visibilityGain": "Still in AI answers to {scope} through {date}.",+ "visibilityGainAll": "AI visibility kept{platforms} through {date}.",+ "mentionLoss": "Named again in AI answers to {scope} by {date}.",+ "mentionLossAll": "Named again in AI answers{platforms} by {date}.",+ "mentionGap": "Cited, not just named, on {scope} by {date}.",+ "mentionGapAll": "Cited, not just named, in AI answers{platforms} by {date}.",+ "competitorBehind": "Ahead of {competitor} on {scope} by {date}.",+ "competitorBehindAll": "Back ahead of {competitor}{platforms} by {date}.",+ "competitorAhead": "Still ahead of {competitor} on {scope} through {date}.",+ "competitorAheadAll": "Still ahead of {competitor}{platforms} through {date}.",+ "trafficLoss": "{hasVisits, select, yes {AI visits to {subject} back to {before}} other {AI visits back on {scope}}} by {date}.",+ "trafficLossAll": "{hasVisits, select, yes {AI visits back to {before}} other {AI visits back}} by {date}.",+ "trafficGap": "More AI visits to {scope} by {date}.",+ "trafficGapAll": "More AI visits to your pages by {date}.",+ "trafficGain": "{hasVisits, select, yes {AI visits to {subject} at {now} or more} other {AI visits kept on {scope}}} through {date}.",+ "trafficGainAll": "{hasVisits, select, yes {AI visits at {now} or more} other {AI visits kept}} through {date}.",+ "searchLoss": "Search clicks back on {scope} by {date}.",+ "searchLossAll": "Search clicks back by {date}.",+ "searchGap": "Better Google search results for {scope} by {date}.",+ "searchGapAll": "Better Google search results by {date}.",+ "technicalIssue": "Issues fixed on {scope} by {date}.",+ "technicalIssueAll": "Issues fixed by {date}."+ }+ },"tasksProgress": "{completed} / {total} tasks completed","noSignals": "No linked signals.","assignee": "Assignee",diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex 15b31dd4f..2818a87d6 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -1,7 +1,7 @@'use client';import { useCallback, useEffect, useMemo, useState } from 'react';-import { useTranslations } from 'next-intl';+import { useFormatter, useTranslations } from 'next-intl';import { useRouter } from '@/i18n/navigation';import { toast } from 'sonner';import { Plus, Trash2 } from 'lucide-react';@@ -70,6 +70,7 @@ import {affectedSignals,affectedTotal,} from '@/lib/action-center/affected';+import { actionStory } from '@/lib/action-center/story';import { ImproveContext } from './improve-context';import { TopicGapContext } from './topic-gap-context';import { TopicOpportunityContext } from './topic-opportunity-context';@@ -110,6 +111,8 @@ export function ActionDrawer({const tTasks = useTranslations('actionCenter.actionTasks');const tTaskStatus = useTranslations('actionCenter.taskStatus');const tPriority = useTranslations('actionCenter.actionsPage.priority');+ const tStory = useTranslations('actionCenter.actionsPage.drawer.story');+ const format = useFormatter();const router = useRouter();const [tab, setTab] = useState<DrawerTab>('overview');@@ -142,35 +145,71 @@ export function ActionDrawer({// eslint-disable-next-line react-hooks/exhaustive-deps}, [action?.id]);- // What the action is about, item by item (AC-003), from the signals it rests on.- const affected = useMemo(- () =>- action && detail- ? affectedOf(affectedSignals(detail.signals, action.id), action.payload ?? {})- : null,+ // The signals the action rests on, and what they affect, item by item (AC-003).+ const evidence = useMemo(+ () => (action && detail ? affectedSignals(detail.signals, action.id) : null),[action, detail],);+ const affected = useMemo(+ () => (action && evidence ? affectedOf(evidence, action.payload ?? {}) : null),+ [action, evidence],+ );- // Each affected prompt's demand. Best effort: without it the column is left out.- const [volumes, setVolumes] = useState<Map<string, number> | null>(null);+ // Each affected prompt's demand. Best effort: without it the column is left+ // out. Kept with the prompts it was read for, so a read still under way is+ // told apart from one that failed.const promptIdsKey = (affected?.prompts ?? []).map((row) => row.id).filter(Boolean).join(',');+ const demandKey = `${brandId}:${promptIdsKey}`;+ const [demand, setDemand] = useState<{+ key: string;+ volumes: Map<string, number> | null;+ } | null>(null);useEffect(() => {- setVolumes(null);if (!promptIdsKey) return;let cancelled = false;+ const key = `${brandId}:${promptIdsKey}`;getPromptDemand(brandId, promptIdsKey.split(',')).then(- (demand) => {- if (!cancelled) setVolumes(new Map(Object.entries(demand)));+ (read) => {+ if (!cancelled) setDemand({ key, volumes: new Map(Object.entries(read)) });+ },+ () => {+ if (!cancelled) setDemand({ key, volumes: null });},- () => undefined,);return () => {cancelled = true;};}, [brandId, promptIdsKey]);+ const demandRead = !promptIdsKey || demand?.key === demandKey;+ const volumes = promptIdsKey && demand?.key === demandKey ? demand.volumes : null;+ // The detail and its demand are both in: the Why names the prompts' demand,+ // so it waits for it rather than reading one way and then another.+ const ready = detail !== null && demandRead;++ // Why and Goal in the action's own terms (AC-003); null for an action a+ // person sent, which carries its own.+ const story = useMemo(+ () =>+ action && evidence+ ? actionStory(+ {+ signals: evidence,+ volumes,+ createdAt: action.createdAt,+ dueDate: action.dueDate,+ },+ tStory,+ {+ day: (date) => format.dateTime(date, { month: 'short', day: 'numeric' }),+ list: (items) => format.list(items, { type: 'conjunction' }),+ },+ )+ : null,+ [action, evidence, volumes, tStory, format],+ );if (!action) return null;const texts = actionTexts(action, tTexts);@@ -234,7 +273,9 @@ export function ActionDrawer({</div><div className="min-w-0"><SheetTitle>{texts.title}</SheetTitle>- <SheetDescription>{texts.description}</SheetDescription>+ <SheetDescription>+ {ready ? (story?.why ?? texts.description) : null}+ </SheetDescription></div></div><div className="flex flex-wrap gap-1">@@ -257,9 +298,10 @@ export function ActionDrawer({</div><ActionExportButtonsaction={action}- detail={detail}+ detail={ready ? detail : null}affected={affected}volumes={volumes}+ story={story}/></SheetHeader>@@ -365,7 +407,7 @@ export function ActionDrawer({</nav><div className="flex-1 space-y-5 overflow-y-auto px-6 py-4 text-sm">- {isLoading || !detail ? (+ {isLoading || !detail || !ready ? (<div className="space-y-3">{[0, 1, 2].map((i) => (<Skeleton key={i} className="h-16 w-full" />@@ -384,7 +426,7 @@ export function ActionDrawer({)}<section><p className="text-xs font-medium text-muted-foreground">{t('drawer.why')}</p>- <p className="mt-1">{texts.description}</p>+ <p className="mt-1">{story?.why ?? texts.description}</p>{detail.signals.length > 0 && (<SupportingSignalsactionId={action.id}@@ -397,7 +439,9 @@ export function ActionDrawer({<Separator /><section><p className="text-xs font-medium text-muted-foreground">{t('drawer.goal')}</p>- <p className="mt-1">{actionGoal(action.kind, tTexts, action.payload)}</p>+ <p className="mt-1">+ {story?.goal ?? actionGoal(action.kind, tTexts, action.payload)}+ </p></section><Separator /><section>diff --git a/web/src/components/action-center/action-export-buttons.test.tsx b/web/src/components/action-center/action-export-buttons.test.tsxindex bcb902b6a..450a3508b 100644--- a/web/src/components/action-center/action-export-buttons.test.tsx+++ b/web/src/components/action-center/action-export-buttons.test.tsx@@ -182,6 +182,24 @@ describe('ActionExportButtons', () => {expect(document.querySelector('button[aria-label="Copied"]')).not.toBeNull();});+ it('uses the Why and Goal the drawer wrote from the action’s data (AC-003)', async () => {+ render(+ <ActionExportButtons+ action={action}+ detail={detail}+ story={{+ family: 'visibilityLoss',+ why: 'Your AI visibility fell from 40% to 20% on Gemini on Oct 8.',+ goal: 'AI visibility back to 40% on Gemini by Nov 7.',+ }}+ />,+ );+ await act(async () => button('Copy Data').click());+ const shown = document.querySelector('textarea')?.value ?? '';+ expect(shown).toContain('Why: Your AI visibility fell from 40% to 20% on Gemini on Oct 8.');+ expect(shown).toContain('Goal: AI visibility back to 40% on Gemini by Nov 7.');+ });+it("copies with the browser's command where the clipboard is blocked", async () => {Object.defineProperty(navigator, 'clipboard', {configurable: true,diff --git a/web/src/components/action-center/action-export-buttons.tsx b/web/src/components/action-center/action-export-buttons.tsxindex 1253ca18a..f05f9d18d 100644--- a/web/src/components/action-center/action-export-buttons.tsx+++ b/web/src/components/action-center/action-export-buttons.tsx@@ -32,6 +32,7 @@ import { signalAffected, signalTexts, signalTypeLabel } from '@/lib/signals/dispimport { viewerTimeZone } from '@/lib/time-zone';import { isSuperseded } from './signal-table';import { leaderText, type Affected } from '@/lib/action-center/affected';+import type { ActionStory } from '@/lib/action-center/story';import { platformName } from '@/lib/signals/names';import { getPlatformName } from '@/lib/traffic-platforms';import { formatCompactNumber } from '@/lib/format';@@ -64,12 +65,15 @@ export function ActionExportButtons({detail,affected = null,volumes = null,+ story = null,}: {action: ActionItem;detail: ActionDetail | null;/** The Affected tab's list and its prompts' demand, as the drawer shows them (AC-003). */affected?: Affected | null;volumes?: Map<string, number> | null;+ /** Why and Goal as the drawer words them, from the action's data (AC-003). */+ story?: ActionStory | null;}) {const t = useTranslations('actionCenter.actionsPage');const tExport = useTranslations('actionCenter.actionsPage.export');@@ -201,8 +205,8 @@ export function ActionExportButtons({: '',}: null,- why: texts.description,- goal: actionGoal(action.kind, tTexts, action.payload),+ why: story?.why ?? texts.description,+ goal: story?.goal ?? actionGoal(action.kind, tTexts, action.payload),category: tCategories(action.category),status: t(`status.${action.status}`),tags: actionContextTags(action, t),diff --git a/web/src/components/action-center/affected-tab.tsx b/web/src/components/action-center/affected-tab.tsxindex d2f5cbe4f..aadfecbfb 100644--- a/web/src/components/action-center/affected-tab.tsx+++ b/web/src/components/action-center/affected-tab.tsx@@ -13,7 +13,10 @@ import {TableRow,} from '@/components/ui/table';import {+ bareUrl,+ hostOf,leaderText,+ pathOf,type Affected,type AffectedPage,type AffectedPrompt,@@ -278,11 +281,7 @@ function Urls({return (<div className="space-y-0.5">{urls.map((url) => {- const text = short- ? domainOf(url)- : path- ? pathOf(url)- : url.replace(/^https?:\/\/(www\.)?/, '');+ const text = short ? (hostOf(url) ?? url) : path ? pathOf(url) : bareUrl(url);return /^https?:\/\//.test(url) ? (<akey={url}@@ -304,20 +303,3 @@ function Urls({</div>);}--function pathOf(url: string): string {- try {- const { pathname, search } = new URL(url);- return `${pathname}${search}`;- } catch {- return url;- }-}--function domainOf(url: string): string {- try {- return new URL(url).hostname.replace(/^www\./, '');- } catch {- return url;- }-}diff --git a/web/src/lib/action-center/affected.ts b/web/src/lib/action-center/affected.tsindex 719fc2e7b..a04eec549 100644--- a/web/src/lib/action-center/affected.ts+++ b/web/src/lib/action-center/affected.ts@@ -235,6 +235,30 @@ export function affectedOf(signals: Signal[], payload: Record<string, unknown> =const str = (value: unknown) => (typeof value === 'string' ? value : '');+/** A URL without its scheme and "www.": "acme.example/pricing". */+export function bareUrl(url: string): string {+ return url.replace(/^https?:\/\/(www\.)?/, '');+}++/** "/blog/best-tools?ref=a" for an absolute URL; the value itself otherwise. */+export function pathOf(url: string): string {+ try {+ const { pathname, search } = new URL(url);+ return `${pathname}${search}`;+ } catch {+ return url;+ }+}++/** "acme.example" for an absolute URL; null otherwise. */+export function hostOf(url: string): string | null {+ try {+ return new URL(url).hostname.replace(/^www\./, '');+ } catch {+ return null;+ }+}+/** An action a person sent: what it was sent about, from its payload. */function affectedFromPayload(payload: Record<string, unknown>): Affected {const out: Affected = empty();diff --git a/web/src/lib/action-center/story.test.ts b/web/src/lib/action-center/story.test.tsnew file mode 100644index 000000000..a3b4e287a--- /dev/null+++ b/web/src/lib/action-center/story.test.ts@@ -0,0 +1,377 @@+import { createTranslator } from 'next-intl';+import { describe, expect, it } from 'vitest';+import messages from '../../../messages/en.json';+import type { Signal } from '@/lib/signals/map';+import { actionStory, storyFamily, type StoryFamily } from './story';++// Days are read where the reader is; pin it so the fixtures' days hold anywhere.+process.env.TZ = 'UTC';++// The real English copy, behind the plain (key, values) shape the helpers take.+const story = createTranslator({+ locale: 'en',+ messages,+ namespace: 'actionCenter.actionsPage.drawer.story',+});+const t = (key: string, values?: Record<string, string | number>) =>+ story(key as Parameters<typeof story>[0], values);+const format = {+ day: (date: Date) => date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),+ list: (items: string[]) =>+ new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }).format(items),+};++const signal = (over: Partial<Signal> = {}): Signal =>+ ({+ id: 's1',+ category: 'citation',+ kind: 'lost_citations',+ impact: 'high',+ status: 'new',+ source: ['ai_results'],+ detectedAt: '2026-10-09T12:00:00Z',+ lastDetectedAt: '2026-10-09T12:00:00Z',+ resolvedAt: null,+ previousValue: null,+ currentValue: null,+ changeValue: null,+ payload: {},+ kpiKeys: [],+ actionId: 'a1',+ where: { platforms: [], regions: [], topics: [] },+ ...over,+ }) as Signal;++const tell = (+ signals: Signal[],+ opts: { volumes?: Map<string, number>; dueDate?: string | null } = {},+) =>+ actionStory(+ {+ signals,+ volumes: opts.volumes ?? null,+ createdAt: '2026-10-09T12:00:00Z',+ dueDate: opts.dueDate ?? null,+ },+ t,+ format,+ );++/** Seven prompts in one topic losing their citations, as in the spec. */+const lostSeven = Array.from({ length: 7 }, (_, i) =>+ signal({+ id: `s${i}`,+ detectedAt:+ i === 0 ? '2026-10-02T12:00:00Z' : i === 6 ? '2026-10-09T12:00:00Z' : '2026-10-05T12:00:00Z',+ // Seen again every night since: not when they were lost.+ lastDetectedAt: '2026-10-15T12:00:00Z',+ payload: {+ promptId: `p${i}`,+ promptText: `Prompt ${i}`,+ lostUrls: [{ url: 'https://www.acme.example/blog/best-tools', position: 2 }],+ },+ where: {+ platforms: i % 2 ? ['chatgpt-web'] : ['gemini-web', 'google-aio'],+ regions: ['US'],+ topics: ['AI Rank Tracker'],+ },+ }),+);++describe('actionStory', () => {+ it('names the prompts, their topic and demand, the domain, the platforms and the days', () => {+ const volumes = new Map(lostSeven.map((_, i) => [`p${i}`, 5_000]));+ const told = tell(lostSeven, { volumes })!;++ expect(told.family).toBe('citationLoss');+ expect(told.why).toBe(+ '7 prompts in AI Rank Tracker (~35k AI searches a month) lost their citations to acme.example on Gemini, Google AI Overview, and ChatGPT between Oct 2 and Oct 9.',+ );+ // 70% of 7, rounded up; 30 days after the action was raised.+ expect(told.goal).toBe('Citations back on ≥5 of 7 prompts by Nov 8.');+ });++ it('dates the goal by the due date when the action has one', () => {+ expect(tell(lostSeven, { dueDate: '2026-11-20' })!.goal).toBe(+ 'Citations back on ≥5 of 7 prompts by Nov 20.',+ );+ });++ it('leaves the demand out when it covers only some of the prompts', () => {+ const grouped = signal({+ category: 'visibility',+ kind: 'prompt_visibility_gap',+ payload: {+ entity: 'prompts',+ targets: [{ id: 'p1', label: 'One' }],+ },+ currentValue: 60,+ });+ const told = tell([grouped], { volumes: new Map([['p1', 9_000]]) })!;+ expect(told.why).toBe('Your brand is missing from AI answers to 60 prompts on Oct 9.');+ expect(told.goal).toBe('In AI answers to ≥42 of 60 prompts by Nov 8.');+ });++ it('quotes a single prompt and agrees with it', () => {+ const told = tell([lostSeven[6]])!;+ expect(told.why).toBe(+ '“Prompt 6” in AI Rank Tracker lost its citations to acme.example on Gemini and Google AI Overview on Oct 9.',+ );+ expect(told.goal).toBe('Citations back on “Prompt 6” in AI Rank Tracker by Nov 8.');+ });++ it('names the competitor ahead and the prompts it leads on', () => {+ const told = tell([+ signal({+ category: 'competitor',+ kind: 'competitor_leads',+ payload: {+ competitorName: 'Profound',+ positions: [+ {+ promptId: 'p1',+ promptText: 'One',+ platform: 'chatgpt-web',+ competitor: { now: 1, before: 2 },+ you: { now: 4, before: 3 },+ },+ {+ promptId: 'p2',+ promptText: 'Two',+ platform: 'chatgpt-web',+ competitor: { now: 1, before: 1 },+ you: { now: null, before: null },+ },+ ],+ },+ }),+ ])!;+ expect(told.why).toBe('Profound is ahead of you on 2 prompts on ChatGPT on Oct 9.');+ expect(told.goal).toBe('Ahead of Profound on both prompts by Nov 8.');+ });++ it("quotes the pages' AI visits before and after, and asks them back", () => {+ const told = tell(+ [+ signal({+ category: 'traffic',+ kind: 'ai_traffic_drop',+ detectedAt: '2026-10-02T12:00:00Z',+ payload: {+ entity: 'pages',+ targets: [+ { id: '/subscriptions', label: '/subscriptions', before: 40, now: 32 },+ { id: '/gifts', label: '/gifts', before: 30, now: 18 },+ ],+ },+ }),+ ],+ { dueDate: '2026-11-20' },+ )!;+ expect(told.why).toBe('AI visits to 2 pages fell from 70 to 50 on Oct 2.');+ expect(told.goal).toBe('AI visits to 2 pages back to 70 by Nov 20.');+ });++ it('names an audit finding and asks every page fixed', () => {+ const told = tell([+ signal({+ category: 'technical',+ kind: 'crawler_blocked',+ payload: {+ entity: 'pages',+ targets: [+ {+ id: 'https://acme.example/pricing',+ label: 'https://acme.example/pricing',+ issues: [{ check: 'robots_ai_bots', label: 'robots.txt blocks AI bots' }],+ },+ ],+ },+ }),+ ])!;+ // By its address: a page elsewhere keeps its site.+ expect(told.why).toBe(+ 'Site Audit flagged acme.example/pricing: robots.txt blocks AI bots on Oct 9.',+ );+ expect(told.goal).toBe('Issues fixed on acme.example/pricing by Nov 8.');+ });++ it('quotes a brand-wide rate when nothing narrower is affected', () => {+ const told = tell([+ signal({+ category: 'visibility',+ kind: 'sharp_drop',+ previousValue: 34,+ currentValue: 18,+ where: { platforms: ['gemini-web'], regions: [], topics: [] },+ }),+ ])!;+ expect(told.why).toBe('Your AI visibility fell from 34% to 18% on Gemini on Oct 9.');+ expect(told.goal).toBe('AI visibility back to 34% on Gemini by Nov 8.');+ });++ it('tells the story most of the signals share', () => {+ const competitor = signal({+ id: 'c1',+ category: 'competitor',+ kind: 'competitor_momentum',+ payload: { competitorName: 'Profound' },+ });+ expect(tell([competitor, ...lostSeven.slice(0, 2)])!.family).toBe('citationLoss');+ });++ it('is null for an action no signal supports', () => {+ expect(tell([])).toBeNull();+ });+});++describe('what the review found', () => {+ const leads = (over: Partial<Signal> = {}) =>+ signal({+ id: 'c1',+ category: 'competitor',+ kind: 'competitor_leads',+ payload: {+ positions: ['p8', 'p9'].map((id) => ({+ promptId: id,+ promptText: id,+ platform: 'chatgpt-web',+ competitor: { now: 1, before: 1 },+ you: { now: 3, before: 3 },+ })),+ },+ ...over,+ });++ it("counts only the lead family's prompts", () => {+ const told = tell([...lostSeven.slice(0, 3), leads()])!;+ expect(told.family).toBe('citationLoss');+ expect(told.why).toMatch(/^3 prompts in AI Rank Tracker lost their citations/);+ expect(told.goal).toBe('Citations back on all 3 prompts by Nov 8.');+ });++ it('writes an unnamed competitor in lower case mid-sentence', () => {+ expect(tell([leads()])!.why).toBe(+ 'A competitor is ahead of you on 2 prompts on ChatGPT on Oct 9.',+ );+ const ahead = tell([leads({ kind: 'competitor_overtaken' })])!;+ expect(ahead.why).toBe('You moved ahead of a competitor on 2 prompts on ChatGPT on Oct 9.');+ expect(ahead.goal).toBe('Still ahead of a competitor on both prompts through Nov 8.');+ });++ it('does not put the prompts in a topic only some of them are in', () => {+ const other = signal({+ ...lostSeven[1],+ id: 'x',+ payload: { promptId: 'px', promptText: 'Elsewhere' },+ where: { platforms: ['chatgpt-web'], regions: [], topics: [] },+ });+ expect(tell([lostSeven[0], other])!.why).toMatch(/^2 prompts lost their citations/);+ });++ it("counts a topic's prompts it names none of", () => {+ const told = tell([+ signal({+ category: 'visibility',+ kind: 'topic_gap',+ currentValue: 30,+ payload: { entity: 'topics', prompts: 12, targets: [{ id: 't1', label: 'Office coffee' }] },+ }),+ ])!;+ expect(told.why).toBe(+ 'Your brand is missing from AI answers to 12 prompts in Office coffee on Oct 9.',+ );+ expect(told.goal).toBe('In AI answers to ≥9 of 12 prompts by Nov 8.');+ });++ it('formats every sentence, for each kind of subject', () => {+ const errors: string[] = [];+ const strict = createTranslator({+ locale: 'en',+ messages,+ namespace: 'actionCenter.actionsPage.drawer.story',+ onError: (error) => errors.push(error.message),+ });+ const copy = messages.actionCenter.actionsPage.drawer.story;+ for (const group of ['why', 'goal'] as const) {+ for (const key of Object.keys(copy[group])) {+ for (const entity of ['prompts', 'pages', 'topics']) {+ for (const count of [1, 2]) {+ const text = strict(`${group}.${key}` as Parameters<typeof strict>[0], {+ subject: 'S',+ count,+ entity,+ domain: '',+ platforms: '',+ when: '',+ fromTo: '',+ competitor: 'C',+ named: count === 1 ? 'yes' : 'no',+ competitors: count,+ issues: '',+ scope: 'SC',+ date: 'D',+ hasFrom: 'yes',+ from: '3',+ hasVisits: count === 1 ? 'yes' : 'no',+ before: 1,+ now: 2,+ });+ expect(text).not.toContain(`${group}.${key}`);+ }+ }+ }+ }+ expect(errors).toEqual([]);+ });+});++describe('storyFamily', () => {+ it.each<[Signal['category'], string, StoryFamily]>([+ ['citation', 'owned_page_citation_lost', 'citationLoss'],+ ['citation', 'third_party_citation_gap', 'citationGap'],+ ['citation', 'first_citation', 'citationGain'],+ ['visibility', 'lost_mentions', 'visibilityLoss'],+ ['visibility', 'topic_gap', 'visibilityGap'],+ ['visibility', 'prompt_gain', 'visibilityGain'],+ ['mention', 'uncited_mentions', 'mentionGap'],+ ['competitor', 'competitor_surge', 'competitorBehind'],+ ['competitor', 'competitor_overtaken', 'competitorAhead'],+ ['traffic', 'ai_traffic_slipping', 'trafficLoss'],+ ['traffic', 'ai_landing_underperforming', 'trafficGap'],+ ['traffic', 'ai_landing_page_winner', 'trafficGain'],+ ['traffic', 'gsc_decline', 'searchLoss'],+ ['traffic', 'gsc_low_ctr', 'searchGap'],+ ['technical', 'weak_entity', 'technicalIssue'],+ ])('reads %s/%s as %s', (category, kind, family) => {+ expect(storyFamily({ category, kind } as Signal)).toBe(family);+ });++ it('has a Why and a Goal for every family, with and without a subject', () => {+ const families: StoryFamily[] = [+ 'citationLoss',+ 'citationGap',+ 'citationGain',+ 'visibilityLoss',+ 'visibilityGap',+ 'visibilityGain',+ 'mentionLoss',+ 'mentionGap',+ 'competitorBehind',+ 'competitorAhead',+ 'trafficLoss',+ 'trafficGap',+ 'trafficGain',+ 'searchLoss',+ 'searchGap',+ 'technicalIssue',+ ];+ const copy = messages.actionCenter.actionsPage.drawer.story;+ for (const family of families) {+ for (const key of [family, `${family}All`]) {+ expect(copy.why).toHaveProperty(key);+ expect(copy.goal).toHaveProperty(key);+ }+ }+ });+});diff --git a/web/src/lib/action-center/story.ts b/web/src/lib/action-center/story.tsnew file mode 100644index 000000000..6356873c0--- /dev/null+++ b/web/src/lib/action-center/story.ts@@ -0,0 +1,345 @@+import type { Signal } from '@/lib/signals/map';+import { signalWhereValue } from '@/lib/signals/detail';+import { SIGNAL_KINDS, isSignalKind } from '@/lib/signals/registry';+import { platformName } from '@/lib/signals/names';+import { formatCompactNumber } from '@/lib/format';+import { affectedOf, bareUrl, hostOf, type Affected } from './affected';++/**+ * "Why this action?" and "Goal" written from the action's own data (AC-003):+ * which prompts or pages, on which platforms, between which days, and what+ * counts as done by when. "Citations you held consistently are gone." names+ * nothing; "7 prompts in AI Rank Tracker lost their citations to acme.com on+ * ChatGPT and Gemini between Oct 2 and Oct 9." does.+ *+ * Sentences follow the evidence rather than the action's kind: sixty-six+ * kinds rest on a handful of situations (a citation lost, a gap, a+ * competitor ahead, traffic falling, an audit finding), each told by a+ * family of sentences in actionsPage.drawer.story.+ */++export type StoryFamily =+ | 'citationLoss'+ | 'citationGap'+ | 'citationGain'+ | 'visibilityLoss'+ | 'visibilityGap'+ | 'visibilityGain'+ | 'mentionLoss'+ | 'mentionGap'+ | 'competitorBehind'+ | 'competitorAhead'+ | 'trafficLoss'+ | 'trafficGap'+ | 'trafficGain'+ | 'searchLoss'+ | 'searchGap'+ | 'technicalIssue';++type Translator = (key: string, values?: Record<string, string | number>) => string;++export interface StoryFormat {+ /** "Oct 9", in the reader's language. */+ day: (date: Date) => string;+ /** "ChatGPT, Gemini, and AIO", in the reader's language. */+ list: (items: string[]) => string;+}++/** Share of the affected items the goal asks back (5 of 7). */+export const GOAL_SHARE = 0.7;+/** Days to the goal when the action has no due date. */+export const GOAL_DAYS = 30;+/** Names listed before "and n more". */+const LIST_MAX = 3;++/** Families whose goal is to keep what is there, or to fix every finding. */+const ALL_OF_THEM: readonly StoryFamily[] = [+ 'citationGain',+ 'visibilityGain',+ 'competitorAhead',+ 'trafficGain',+ 'technicalIssue',+];++/** Families told about pages first; the rest about prompts first. */+const PAGE_FIRST: readonly StoryFamily[] = [+ 'trafficLoss',+ 'trafficGap',+ 'trafficGain',+ 'searchLoss',+ 'searchGap',+ 'technicalIssue',+];++/** Brand-wide rates, in percent, whose before and after the sentence can quote. */+const RATE_KINDS = ['sharp_drop', 'visibility_slipping'];++/** The situation one signal describes. */+export function storyFamily(signal: Pick<Signal, 'category' | 'kind'>): StoryFamily {+ const meta = isSignalKind(signal.kind) ? SIGNAL_KINDS[signal.kind] : null;+ const state = meta?.stateKey ?? 'gap';+ const group = meta?.positive+ ? 'gain'+ : state === 'issue'+ ? 'issue'+ : state === 'lost' || state === 'dropped' || state === 'slipping'+ ? 'loss'+ : 'gap';++ switch (signal.category) {+ case 'citation':+ return group === 'gain' ? 'citationGain' : group === 'loss' ? 'citationLoss' : 'citationGap';+ case 'mention':+ return group === 'gain' ? 'visibilityGain' : group === 'loss' ? 'mentionLoss' : 'mentionGap';+ case 'competitor':+ return group === 'gain' ? 'competitorAhead' : 'competitorBehind';+ case 'traffic':+ // Search Console findings are about Google search, not AI visits.+ if (signal.kind.startsWith('gsc_')) return group === 'loss' ? 'searchLoss' : 'searchGap';+ return group === 'gain' ? 'trafficGain' : group === 'loss' ? 'trafficLoss' : 'trafficGap';+ case 'technical':+ return 'technicalIssue';+ default:+ return group === 'gain'+ ? 'visibilityGain'+ : group === 'loss'+ ? 'visibilityLoss'+ : 'visibilityGap';+ }+}++/** The family most of the signals share; on a tie, the first signal's. */+function leadFamily(signals: Signal[]): StoryFamily {+ const counts = new Map<StoryFamily, number>();+ for (const signal of signals) {+ const family = storyFamily(signal);+ counts.set(family, (counts.get(family) ?? 0) + 1);+ }+ let lead = storyFamily(signals[0]);+ for (const [family, count] of counts) if (count > counts.get(lead)!) lead = family;+ return lead;+}++interface Subject {+ entity: 'prompts' | 'pages' | 'topics';+ count: number;+ /** The one item's name, when there is only one. */+ label: string | null;+}++/**+ * What the sentence is about: the prompts, the pages or the topics. A group+ * that counts its prompts without naming them still gives the sentence its+ * number, though the Affected list has no rows for it.+ */+function subjectOf(affected: Affected, family: StoryFamily, signals: Signal[]): Subject | null {+ const unnamed = Math.max(+ 0,+ ...signals.map((signal) => {+ const value = signalWhereValue(signal, 'prompts');+ return value?.type === 'prompts' && value.items.length === 0 ? value.total : 0;+ }),+ );+ const prompts: Subject | null =+ affected.promptTotal > 0+ ? {+ entity: 'prompts',+ count: affected.promptTotal,+ label: affected.promptTotal === 1 ? (affected.prompts[0]?.text ?? null) : null,+ }+ : unnamed > 0+ ? { entity: 'prompts', count: unnamed, label: null }+ : null;+ // A page by its address without the scheme: a third-party page keeps its site.+ const pages: Subject | null =+ affected.pageTotal > 0+ ? {+ entity: 'pages',+ count: affected.pageTotal,+ label: affected.pageTotal === 1 ? bareUrl(affected.pages[0]?.url ?? '') || null : null,+ }+ : null;+ const topics: Subject | null =+ affected.topics.length > 0+ ? {+ entity: 'topics',+ count: affected.topics.length,+ label: affected.topics.length === 1 ? affected.topics[0] : null,+ }+ : null;+ return PAGE_FIRST.includes(family) ? (pages ?? prompts ?? topics) : (prompts ?? pages ?? topics);+}++/** "a, b, c and 2 more". */+function listOf(items: string[], t: Translator, format: StoryFormat): string {+ const shown = items.slice(0, LIST_MAX);+ const rest = items.length - shown.length;+ return format.list(rest > 0 ? [...shown, t('more', { count: rest })] : shown);+}++/** A calendar date ("2026-11-09") as that day where the reader is. */+function calendarDay(value: string): Date {+ const [year, month, day] = value.slice(0, 10).split('-').map(Number);+ return new Date(year, month - 1, day);+}++export interface ActionStory {+ family: StoryFamily;+ why: string;+ goal: string;+}++/**+ * The action's Why and Goal from its signals and what they affect. Null for+ * an action no signal supports (one a person sent): it carries its own.+ */+export function actionStory(+ {+ signals,+ volumes,+ createdAt,+ dueDate,+ }: {+ /** The signals the Affected list was built from. */+ signals: Signal[];+ /** Estimated monthly AI searches per prompt id, when read. */+ volumes: Map<string, number> | null;+ createdAt: string;+ dueDate: string | null;+ },+ t: Translator,+ format: StoryFormat,+): ActionStory | null {+ if (signals.length === 0) return null;+ const family = leadFamily(signals);+ // Told from the lead family's signals alone, so the counts match the verb:+ // a competitor's prompts are not "lost citations".+ const mine = signals.filter((signal) => storyFamily(signal) === family);+ const affected = affectedOf(mine);+ const subject = subjectOf(affected, family, mine);++ // The subject: "7 prompts in AI Rank Tracker (~41k AI searches a month)".+ // The goal names the same items without their demand.+ let named = '';+ let demand = '';+ if (subject?.entity === 'topics') {+ named = subject.label+ ? t('subject.topic', { label: subject.label })+ : t('subject.topics', { count: subject.count });+ } else if (subject) {+ named = subject.label+ ? t(subject.entity === 'prompts' ? 'subject.prompt' : 'subject.page', {+ label: subject.label,+ })+ : t(`subject.${subject.entity}`, { count: subject.count });+ }+ if (subject?.entity === 'prompts') {+ // "in AI Rank Tracker" only when every signal is about that one topic, or+ // when the prompts are a topic's, counted rather than named.+ const first = mine[0].where.topics;+ const shared =+ first.length === 1 &&+ mine.every(+ (signal) => signal.where.topics.length === 1 && signal.where.topics[0] === first[0],+ )+ ? first[0]+ : null;+ const topic =+ shared ??+ (affected.prompts.length === 0 && affected.topics.length === 1 ? affected.topics[0] : null);+ if (topic) named += t('subject.inTopic', { topic });+ // Only when every prompt is listed: a sum over the first 50 would undercount.+ if (volumes && affected.prompts.length === affected.promptTotal) {+ const volume = affected.prompts.reduce(+ (sum, row) => sum + (row.id ? (volumes.get(row.id) ?? 0) : 0),+ 0,+ );+ if (volume > 0) demand = t('subject.volume', { volume: formatCompactNumber(volume) });+ }+ }++ // Where: the engines, and the brand's domain for a lost citation.+ const platforms = [...new Set(affected.platforms.map(platformName))];+ const platformsText =+ platforms.length > 0 ? t('platforms', { list: listOf(platforms, t, format) }) : '';+ const domains = [+ ...new Set(affected.lostPages.map(hostOf).filter((host): host is string => !!host)),+ ];+ const domainText = domains.length === 1 ? t('domain', { domain: domains[0] }) : '';++ // When: the days these signals were raised. Not when they were last seen:+ // a lasting finding is seen again every night.+ const times = mine.map((signal) => new Date(signal.detectedAt).getTime()).filter(Number.isFinite);+ let whenText = '';+ if (times.length > 0) {+ const from = format.day(new Date(Math.min(...times)));+ const to = format.day(new Date(Math.max(...times)));+ whenText = from === to ? t('when.day', { day: from }) : t('when.range', { from, to });+ }++ // How much: a brand-wide rate, or the pages' AI visits.+ let fromText = '';+ let rateFrom = '';+ const rate = mine.length === 1 && RATE_KINDS.includes(mine[0].kind) ? mine[0] : null;+ if (rate && rate.previousValue !== null && rate.currentValue !== null) {+ rateFrom = String(rate.previousValue);+ fromText = t('fromToRate', { from: rate.previousValue, to: rate.currentValue });+ }+ const visits = affected.pages.length > 0 && affected.pages.length === affected.pageTotal;+ const counted = visits && affected.pages.every((p) => p.sessions !== null && p.before !== null);+ const before = counted ? affected.pages.reduce((sum, p) => sum + (p.before ?? 0), 0) : null;+ const now = counted ? affected.pages.reduce((sum, p) => sum + (p.sessions ?? 0), 0) : null;+ if (!rate && before !== null && now !== null && family.startsWith('traffic')) {+ fromText = t('fromToVisits', { before, now });+ }++ const competitors = affected.competitors;+ const competitorText =+ competitors.length > 0 ? listOf(competitors, t, format) : t('competitorUnnamed');+ const issues = [...new Set(affected.pages.flatMap((page) => page.issues))];+ const issuesText = issues.length > 0 ? t('issues', { list: listOf(issues, t, format) }) : '';++ // The goal: how many back, by when.+ const target = ALL_OF_THEM.includes(family)+ ? (subject?.count ?? 0)+ : Math.ceil((subject?.count ?? 0) * GOAL_SHARE);+ let scopeText = '';+ if (subject) {+ if (subject.count === 1 || subject.entity === 'topics') {+ scopeText = named;+ } else {+ const noun = t(`noun.${subject.entity}`, { count: subject.count });+ scopeText =+ target >= subject.count+ ? t('scope.all', { count: subject.count, noun })+ : t('scope.some', { target, count: subject.count, noun });+ }+ }+ const goalDate = dueDate+ ? calendarDay(dueDate)+ : new Date(new Date(createdAt).getTime() + GOAL_DAYS * 86_400_000);++ const values = {+ subject: named + demand,+ // Verb agreement: topics read as "prompts in …", plural.+ count: subject ? (subject.entity === 'topics' ? 2 : subject.count) : 0,+ entity: subject?.entity ?? 'prompts',+ domain: domainText,+ platforms: platformsText,+ when: whenText,+ fromTo: fromText,+ competitor: competitorText,+ named: competitors.length > 0 ? 'yes' : 'no',+ competitors: Math.max(1, competitors.length),+ issues: issuesText,+ scope: scopeText,+ date: format.day(goalDate),+ hasFrom: rateFrom ? 'yes' : 'no',+ from: rateFrom,+ hasVisits: before !== null && now !== null ? 'yes' : 'no',+ before: before ?? 0,+ now: now ?? 0,+ };+ const key = subject ? family : `${family}All`;+ return { family, why: t(`why.${key}`, values), goal: t(`goal.${key}`, values) };+}