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): raise AI Traffic alerts as signals: weekly drop, new platform, broken links, unread cited pages (#1195)
Cihanefcb3c7835dc
diff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.jsindex fad98cf7d..f69df0662 100644--- a/server/src/config/action-engine.js+++ b/server/src/config/action-engine.js@@ -239,6 +239,10 @@ export const ENGINE_THRESHOLDS = Object.freeze({aiTrafficMinSessions: 10,aiTrafficSlipRatio: 0.1,aiTrafficDropRatio: 0.3,+ /** AI visits down this much week over week, from at least this many the+ * week before (AT-013, spec §3.8; 30 is the page's Low sample floor). */+ aiVisitsWeeklyDropRatio: 0.4,+ aiVisitsWeeklyMinVisits: 30,/** Key events per session above this multiple of the site's rate is a* winning page; engagement below `underperform` of it is a weak one. */landingWinnerMultiple: 1.5,diff --git a/server/src/lib/action-center/definitions/f02-fix-crawler-access.js b/server/src/lib/action-center/definitions/f02-fix-crawler-access.jsindex dbe6d21f4..cc05bd39f 100644--- a/server/src/lib/action-center/definitions/f02-fix-crawler-access.js+++ b/server/src/lib/action-center/definitions/f02-fix-crawler-access.js@@ -1,7 +1,14 @@/*** F02 — Fix AI Crawler Accessibility.*- * Signal: Pages AI crawlers are blocked from.+ * Signal: Pages AI crawlers are blocked from, as Site Audit finds them, and+ * cited pages no AI search bot read in 30 days, as the brand's own+ * Cloudflare or Vercel reports it (AT-013, spec §3.8).+ *+ * Only tracking, which every brand has, is required: the second signal+ * needs no Site Audit, and the tasks that read the audit+ * (analyze_site_audit, validate_technical_fix) require it themselves, so the+ * planner leaves them out for a brand without one.*/import { targetPayload } from './_helpers.js';@@ -12,8 +19,8 @@ export default {version: 1,category: 'fix',name: 'Fix AI Crawler Accessibility',- signalKinds: ['crawler_blocked'],- requires: ['site_audits'],+ signalKinds: ['crawler_blocked', 'cited_page_uncrawled'],+ requires: ['tracking'],optional: [],enabled: true,tasks: [diff --git a/server/src/lib/action-center/definitions/f07-fix-broken-citation-targets.js b/server/src/lib/action-center/definitions/f07-fix-broken-citation-targets.jsindex 70102423f..0cceefa15 100644--- a/server/src/lib/action-center/definitions/f07-fix-broken-citation-targets.js+++ b/server/src/lib/action-center/definitions/f07-fix-broken-citation-targets.js@@ -3,8 +3,9 @@** Signal: Owned URLs AI answers cite that are unavailable.*- * Disabled. Cited owned URLs are not health-checked yet, so there is nothing- * to detect a broken one from. Registered; enabled once URL checks exist.+ * Detected from the AI visitors themselves (AT-012, AT-013): a page an AI+ * answer sent someone to that answered 404 or 410, as the tracking snippet+ * reports it. Each target carries the working page to redirect it to.*/import { targetPayload } from './_helpers.js';@@ -16,11 +17,9 @@ export default {category: 'fix',name: 'Fix Broken Citation Targets',signalKinds: ['broken_citation_target'],- requires: ['tracking'],+ requires: ['ai_traffic'],optional: [],- enabled: false,- disabledReason:- 'Cited owned URLs are not health-checked yet, so there is nothing to detect a broken one from. Registered; enabled once URL checks exist.',+ enabled: true,tasks: ['analyze_citations','identify_target_pages',diff --git a/server/src/lib/action-center/definitions/r03-recover-ai-traffic.js b/server/src/lib/action-center/definitions/r03-recover-ai-traffic.jsindex 9785b642d..fd5e129e5 100644--- a/server/src/lib/action-center/definitions/r03-recover-ai-traffic.js+++ b/server/src/lib/action-center/definitions/r03-recover-ai-traffic.js@@ -1,7 +1,8 @@/*** R03 — Recover AI Traffic.*- * Signal: AI referral traffic falling significantly.+ * Signal: AI referral traffic falling significantly: over two weeks against+ * the two before, or by 40% week over week (AT-013, spec §3.8).*/import { targetPayload } from './_helpers.js';@@ -12,7 +13,7 @@ export default {version: 1,category: 'recover',name: 'Recover AI Traffic',- signalKinds: ['ai_traffic_drop'],+ signalKinds: ['ai_traffic_drop', 'ai_visits_weekly_drop'],requires: ['ai_traffic'],optional: ['analytics'],enabled: true,diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.jsindex 96b75ae69..23ec66d0c 100644--- a/server/src/lib/action-center/priority.js+++ b/server/src/lib/action-center/priority.js@@ -49,6 +49,7 @@ const SEVERITY = {const KIND_CHANGE = {// Something held is gone.lost_citations: 'lost',+ broken_citation_target: 'lost',owned_page_citation_lost: 'lost',high_value_prompt_lost: 'lost',lost_mentions: 'lost',@@ -57,6 +58,7 @@ const KIND_CHANGE = {platform_drop: 'dropped',topic_drop: 'dropped',ai_traffic_drop: 'dropped',+ ai_visits_weekly_drop: 'dropped',gsc_decline: 'dropped',visibility_traffic_loss: 'dropped',cross_channel_risk: 'dropped',@@ -81,10 +83,12 @@ const KIND_CHANGE = {weak_internal_links: 'issue',content_gap: 'issue',audit_low_score: 'issue',+ cited_page_uncrawled: 'issue',// Ground to win.page_opportunity: 'opportunity',ai_landing_page_winner: 'opportunity',new_engine: 'opportunity',+ ai_platform_new: 'opportunity',gsc_low_ctr: 'opportunity',// Ground never held: a gap to close or a lead to answer.prompt_visibility_gap: 'gap',@@ -121,6 +125,7 @@ const KIND_CHANGE = {const SESSION_KINDS = new Set(['ai_traffic_slipping','ai_traffic_drop',+ 'ai_visits_weekly_drop','ai_landing_page_winner','ai_landing_underperforming','converting_page_slipping',@@ -144,8 +149,10 @@ const HELD_BEFORE = new Set(['page_citation_slipping','citation_at_risk','ai_traffic_drop',+ 'ai_visits_weekly_drop','ai_traffic_slipping','converting_page_slipping',+ 'broken_citation_target','gsc_decline','gsc_risk','visibility_traffic_loss',@@ -155,6 +162,8 @@ const HELD_BEFORE = new Set([/** Kinds whose cure is a fix on the brand's own site. */const SITE_FIX = new Set(['crawler_blocked',+ 'cited_page_uncrawled',+ 'broken_citation_target','structured_data_issue','outdated_content','weak_internal_links',diff --git a/server/src/lib/action-center/tasks/plan.test.js b/server/src/lib/action-center/tasks/plan.test.jsindex b604d6cb2..579ce4940 100644--- a/server/src/lib/action-center/tasks/plan.test.js+++ b/server/src/lib/action-center/tasks/plan.test.js@@ -7,7 +7,7 @@ vi.mock('../../../config/supabase.js', () => ({ default: { from: vi.fn(), rpc: vimport { planTasks } from './plan.js';import { AUTOMATABLE_MODES, TASKS, libraryTasks, listTasks, validateTask } from './registry.js';-import { loadDefinitions } from '../definitions/index.js';+import { isEligible, loadDefinitions } from '../definitions/index.js';import { TOOLS } from '../execution/tools.js';const ALL = new Set(['tracking', 'competitors', 'site_audits', 'analytics']);@@ -311,3 +311,18 @@ describe('the task registry', () => {}});});++describe('F02 for a brand without Site Audit (AT-013)', () => {+ it('is raised from the AI bot report alone, without the tasks that read an audit', async () => {+ const definitions = await loadDefinitions();+ const f02 = definitions.find((d) => d.code === 'F02');+ // cited_page_uncrawled comes from the brand's Cloudflare or Vercel, not an audit.+ expect(isEligible(f02, BARE)).toBe(true);+ const plan = keys(planTasks(f02, { sources: BARE }));+ expect(plan).not.toContain('analyze_site_audit');+ expect(plan).not.toContain('validate_technical_fix');+ expect(plan).toContain('fix_crawler_access');+ // With an audit, the plan reads it first.+ expect(keys(planTasks(f02, { sources: ALL }))[0]).toBe('analyze_site_audit');+ });+});diff --git a/server/src/lib/signals/library/ai-traffic-alerts-family.test.js b/server/src/lib/signals/library/ai-traffic-alerts-family.test.jsnew file mode 100644index 000000000..2e63a626a--- /dev/null+++ b/server/src/lib/signals/library/ai-traffic-alerts-family.test.js@@ -0,0 +1,261 @@+import { describe, expect, it, vi } from 'vitest';++/**+ * AI Traffic Analytics' alerts (AT-013, spec §3.8): AI visits down 40% week+ * over week from at least 30, the pages AI visitors landed on that don't+ * exist (AT-012), and the cited pages no AI search bot read in 30 days+ * (AT-011).+ */++const rpc = vi.fn();+vi.mock('../../../config/supabase.js', () => ({+ default: { from: vi.fn(), rpc: (...args) => rpc(...args) },+}));+const logger = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }));+vi.mock('../../logger.js', () => ({ logger }));++const { DataNotWhole, LIBRARY_FAMILIES, LIBRARY_EMITTED_KINDS, libraryCandidates, weeklyWindows } =+ await import('./detect.js');++const family = (name) => LIBRARY_FAMILIES.find((f) => f.name === name);++const week = (visits, pages = [], over = {}) => ({ visits, pages, analytics_days: 0, ...over });++const alerts = ({ cur, prev, broken = { count: 0, rows: [] } }) =>+ family('aiTrafficAlerts').run({+ brandId: 'b1',+ now: new Date('2026-10-19T06:00:00Z'),+ weeklyVisits: async () => ({ cur, prev }),+ brokenLinks: async () => broken,+ });++describe('the AI Traffic alerts family', () => {+ it('raises a week-over-week drop of 40% from at least 30 visits, with the pages that fell', async () => {+ const found = await alerts({+ prev: week(50, [+ { page: '/menu', visits: 30 },+ { page: '/Gifts', visits: 12 },+ { page: '/about', visits: 8 },+ ]),+ cur: week(28, [+ { page: '/menu', visits: 12 },+ { page: '/gifts', visits: 12 },+ { page: '/blog', visits: 4 },+ ]),+ });++ expect(found).toEqual([+ {+ kind: 'ai_visits_weekly_drop',+ dedupKey: 'ai_visits_weekly_drop',+ source: ['ai_results'],+ payload: {+ entity: 'pages',+ targets: [+ { id: '/menu', label: '/menu', before: 30, now: 12 },+ { id: '/about', label: '/about', before: 8, now: 0 },+ ],+ pageCount: 2,+ },+ previousValue: 50,+ currentValue: 28,+ changeValue: -22,+ },+ ]);+ });++ it('stays quiet under 40%, or below 30 visits the week before', async () => {+ expect(await alerts({ prev: week(50), cur: week(31) })).toEqual([]);+ // 29 → 0 is a fall of 100%, but from a Low sample.+ expect(await alerts({ prev: week(29), cur: week(0) })).toEqual([]);+ // Exactly 40% from exactly 30 is enough.+ expect((await alerts({ prev: week(30), cur: week(18) })).map((f) => f.kind)).toEqual([+ 'ai_visits_weekly_drop',+ ]);+ });++ it('says Analytics when either week read it', async () => {+ const [found] = await alerts({+ // ai_traffic_merged's analytics_days is the list of days (00176).+ prev: week(40, [], { analytics_days: ['2026-10-06', '2026-10-07', '2026-10-08'] }),+ cur: week(10),+ });+ expect(found.source).toEqual(['ga4']);+ });++ it('lists the broken AI links with what visitors got and where to redirect them', async () => {+ const found = await alerts({+ prev: week(0),+ cur: week(0),+ broken: {+ count: 7,+ rows: [+ {+ page: '/guides/espresso-machine-for-beginner',+ visits: 3,+ platforms: ['chatgpt.com'],+ citations: 12,+ last_visit: '2026-10-19T05:00:00Z',+ status: '404',+ target: '/guides/espresso-machines-for-beginners',+ target_reason: 'similar',+ },+ {+ page: '/',+ visits: '1',+ platforms: [],+ citations: null,+ status: 'title',+ target: null,+ target_reason: null,+ },+ ],+ },+ });++ expect(found).toEqual([+ {+ kind: 'broken_citation_target',+ dedupKey: 'broken_citation_target',+ source: ['ai_results'],+ payload: {+ entity: 'pages',+ targets: [+ {+ id: '/guides/espresso-machine-for-beginner',+ label: '/guides/espresso-machine-for-beginner',+ visits: 3,+ status: '404',+ citations: 12,+ redirectTo: '/guides/espresso-machines-for-beginners',+ },+ {+ id: '/',+ label: '/',+ visits: 1,+ status: 'title',+ citations: 0,+ redirectTo: null,+ },+ ],+ },+ previousValue: null,+ // Every broken link, not only the 50 named.+ currentValue: 7,+ changeValue: null,+ },+ ]);+ });++ it('raises nothing when no AI visitor landed on a missing page, or the read answers nothing', async () => {+ expect(await alerts({ prev: week(0), cur: week(0) })).toEqual([]);+ expect(await alerts({ prev: week(0), cur: week(0), broken: null })).toEqual([]);+ });+});++describe('the AI bots family', () => {+ const bots = (report) =>+ family('aiBots').run({+ brandId: 'b1',+ now: new Date('2026-10-19T06:00:00Z'),+ botReport: async () => report,+ });++ it('raises the cited pages no AI search bot read in 30 days, counting them all', async () => {+ const found = await bots({+ first_day: '2026-09-01',+ alert_state: 'on',+ uncrawled_count: 14,+ uncrawled: [+ { page: '/guides/espresso-machines-for-beginners', citations: '14' },+ { page: '/gifts', citations: 9 },+ ],+ });+ expect(found).toEqual([+ {+ kind: 'cited_page_uncrawled',+ dedupKey: 'cited_page_uncrawled',+ source: ['ai_results'],+ payload: {+ entity: 'pages',+ targets: [+ {+ id: '/guides/espresso-machines-for-beginners',+ label: '/guides/espresso-machines-for-beginners',+ citations: 14,+ },+ { id: '/gifts', label: '/gifts', citations: 9 },+ ],+ },+ previousValue: null,+ currentValue: 14,+ changeValue: null,+ },+ ]);+ });++ it('waits for a connection and 30 days of AI-bot data, and stays quiet when every cited page was read', async () => {+ // No Cloudflare or Vercel connection: the report is empty.+ expect(await bots(null)).toEqual([]);+ // Connected, but the first request is under 30 days old (00185).+ expect(await bots({ first_day: '2026-10-10', uncrawled_count: null, uncrawled: null })).toEqual(+ [],+ );+ expect(+ await bots({ first_day: '2026-09-01', alert_state: 'on', uncrawled_count: 0, uncrawled: [] }),+ ).toEqual([]);+ });++ it("reads nothing while the bot data isn't whole, whatever the report lists", async () => {+ // A sender stopped, was revoked or hit its cap: the pages read drained.+ await expect(+ bots({+ first_day: '2026-09-01',+ alert_state: 'stale',+ uncrawled_count: 40,+ uncrawled: [{ page: '/gifts', citations: 9 }],+ }),+ ).rejects.toBeInstanceOf(DataNotWhole);+ });++ it('keeps open signals open while the bot data is stale: the kind is unread, not an error', async () => {+ rpc.mockImplementation(async (name) =>+ name === 'ai_bot_report'+ ? { data: { first_day: '2026-09-01', alert_state: 'stale' }, error: null }+ : { data: null, error: { message: 'not this test' } },+ );+ const { unreadKinds } = await libraryCandidates('b1', {+ now: new Date('2026-10-19T06:00:00Z'),+ sources: new Set(['tracking']),+ });+ expect(unreadKinds.has('cited_page_uncrawled')).toBe(true);+ expect(logger.info).toHaveBeenCalledWith(+ expect.objectContaining({ family: 'aiBots', reason: 'bot data is stale' }),+ '[signals] library family data not whole',+ );+ expect(logger.error).not.toHaveBeenCalledWith(+ expect.objectContaining({ family: 'aiBots' }),+ expect.anything(),+ );+ });++ it('declares the kinds it can write, so a failed night is not read as recovery', () => {+ expect(LIBRARY_EMITTED_KINDS).toEqual(+ expect.arrayContaining([+ 'ai_visits_weekly_drop',+ 'broken_citation_target',+ 'cited_page_uncrawled',+ ]),+ );+ });+});++describe('weeklyWindows', () => {+ it('ends each week a second before midnight, so its last day is in one week only', () => {+ // ai_traffic_merged keeps Analytics rows through p_to's day (00176).+ expect(weeklyWindows(new Date('2026-10-19T06:00:00Z'))).toEqual({+ cur: { from: '2026-10-12T00:00:00.000Z', to: '2026-10-18T23:59:59.000Z' },+ prev: { from: '2026-10-05T00:00:00.000Z', to: '2026-10-11T23:59:59.000Z' },+ });+ });+});diff --git a/server/src/lib/signals/library/classify.js b/server/src/lib/signals/library/classify.jsindex ea0d33e71..78fbf2827 100644--- a/server/src/lib/signals/library/classify.js+++ b/server/src/lib/signals/library/classify.js@@ -377,6 +377,14 @@ export function classifyGscQuery(q, prompt, t) {// ─── AI traffic ─────────────────────────────────────────────────────────────+/**+ * The days Analytics counted in an ai_traffic_merged read (00176): a jsonb+ * array of those days, not a number.+ */+export function analyticsDayCount(value) {+ return Array.isArray(value) ? value.length : 0;+}+/*** AI-referred traffic per page, from analytics where connected and the* tracking snippet otherwise. Analytics wins where both exist: it is the@@ -440,6 +448,31 @@ export function relativeFall(prev, cur) {return prev > 0 ? (prev - cur) / prev : 0;}+/**+ * The pages AI visits fell on between two windows of ai_traffic_merged+ * (00176), biggest fall first: what a week-over-week drop is made of+ * (AT-013). Its pages are paths, matched without case as the Pages section+ * matches them.+ */+export function fallingPages(prevPages = [], curPages = []) {+ const now = new Map();+ for (const p of curPages) {+ const key = String(p.page ?? '').toLowerCase();+ now.set(key, (now.get(key) ?? 0) + (Number(p.visits) || 0));+ }+ const before = new Map();+ for (const p of prevPages) {+ const key = String(p.page ?? '').toLowerCase();+ const entry = before.get(key) ?? { page: p.page, visits: 0 };+ entry.visits += Number(p.visits) || 0;+ before.set(key, entry);+ }+ return [...before.entries()]+ .map(([key, p]) => ({ page: p.page, before: p.visits, now: now.get(key) ?? 0 }))+ .filter((p) => p.before > p.now)+ .sort((a, b) => b.before - b.now - (a.before - a.now) || a.page.localeCompare(b.page));+}+// ─── Site Audit ─────────────────────────────────────────────────────────────/** Which failing audit check points at which fix. Checks not listed here arediff --git a/server/src/lib/signals/library/classify.test.js b/server/src/lib/signals/library/classify.test.jsindex fdd1513bc..7862c5963 100644--- a/server/src/lib/signals/library/classify.test.js+++ b/server/src/lib/signals/library/classify.test.js@@ -320,6 +320,29 @@ describe('classifyTrafficPage', () => {});});+describe('fallingPages', () => {+ it('lists the pages AI visits fell on, biggest fall first, matching paths without case (AT-013)', () => {+ expect(+ c.fallingPages(+ [+ { page: '/menu', visits: 30 },+ { page: '/Gifts', visits: 12 },+ { page: '/about', visits: 8 },+ ],+ [+ { page: '/menu', visits: 12 },+ { page: '/gifts', visits: 12 },+ { page: '/blog', visits: 4 },+ ],+ ),+ ).toEqual([+ { page: '/menu', before: 30, now: 12 },+ { page: '/about', before: 8, now: 0 },+ ]);+ expect(c.fallingPages(undefined, undefined)).toEqual([]);+ });+});+describe('the library’s signal kinds', () => {/*** `signals.category` has a check constraint. A kind outside it fails thediff --git a/server/src/lib/signals/library/detect.js b/server/src/lib/signals/library/detect.jsindex 2ed55e612..9b005599d 100644--- a/server/src/lib/signals/library/detect.js+++ b/server/src/lib/signals/library/detect.js@@ -36,6 +36,31 @@ const GSC = ['gsc'];const GA = ['ga4'];const AUDIT = ['site_audit'];+/** Midnight UTC `daysAgo` days before today's: whole days, so a pass early in+ * the morning compares full weeks rather than a few hours of today. */+function utcMidnight(now, daysAgo) {+ const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());+ return new Date(today - daysAgo * DAY_MS).toISOString();+}++/**+ * The second before `iso`. ai_traffic_merged keeps Analytics rows through+ * p_to's day (00176), so a window ending at midnight is read up to the+ * second before with p_to_inclusive: an exclusive midnight would put that+ * day's Analytics in both weeks.+ */+function lastSecond(iso) {+ return new Date(Date.parse(iso) - 1000).toISOString();+}++/** The last seven whole days and the seven before, each up to its last second. */+export function weeklyWindows(now) {+ return {+ cur: { from: utcMidnight(now, 7), to: lastSecond(utcMidnight(now, 0)) },+ prev: { from: utcMidnight(now, 14), to: lastSecond(utcMidnight(now, 7)) },+ };+}+function isoDay(now, daysAgo) {return new Date(now.getTime() - daysAgo * DAY_MS).toISOString().slice(0, 10);}@@ -180,6 +205,46 @@ function context(brandId, now, sources) {p_prev_to: isoDay(now, TRAFFIC_WINDOW_DAYS),}),),+ // AI visits as the AI Traffic page counts them (00176: the snippet on the+ // days it ran, Analytics on the rest), over the last seven whole days+ // and the seven before (AT-013).+ weeklyVisits: () =>+ once('weeklyVisits', async () => {+ const read = ({ from, to }) =>+ rpc('ai_traffic_merged', {+ p_brand_id: brandId,+ p_from: from,+ p_to: to,+ p_to_inclusive: true,+ p_analytics: true,+ });+ const windows = weeklyWindows(now);+ const [cur, prev] = await Promise.all([read(windows.cur), read(windows.prev)]);+ return { cur: cur ?? {}, prev: prev ?? {} };+ }),+ // The pages AI visitors landed on that don't exist, over the last seven+ // days (AT-012, 00186).+ brokenLinks: () =>+ once('brokenLinks', () =>+ rpc('ai_traffic_broken_links', {+ p_brand_id: brandId,+ p_from: utcMidnight(now, 7),+ p_to: now.toISOString(),+ p_limit: 50,+ p_offset: 0,+ }),+ ),+ // The AI bot report's alert: cited pages no search bot read in the last+ // 30 days (AT-011, 00185). Its window is its own, whatever days are asked.+ botReport: () =>+ once('botReport', () =>+ rpc('ai_bot_report', {+ p_brand_id: brandId,+ p_since: isoDay(now, 0),+ p_until: isoDay(now, 0),+ p_limit: 0,+ }),+ ),gsc: () =>once('gsc', () =>rpc('ae_gsc_queries', {@@ -635,6 +700,102 @@ const FAMILIES = [},},+ // AI Traffic Analytics' alerts (AT-013, spec §3.8). A new platform sending+ // visits is good news with no work behind it, so it is a recorder kind of+ // its own (signals/traffic-platforms.js), not a library one.+ {+ name: 'aiTrafficAlerts',+ requires: ['ai_traffic'],+ kinds: ['ai_visits_weekly_drop', 'broken_citation_target'],+ async run(ctx) {+ const found = [];+ const { cur, prev } = await ctx.weeklyVisits();+ const before = Number(prev.visits) || 0;+ const after = Number(cur.visits) || 0;+ if (+ before >= t.aiVisitsWeeklyMinVisits &&+ c.relativeFall(before, after) >= t.aiVisitsWeeklyDropRatio+ ) {+ const falling = c.fallingPages(prev.pages, cur.pages);+ const analytics =+ c.analyticsDayCount(prev.analytics_days) + c.analyticsDayCount(cur.analytics_days);+ found.push({+ // Its value is the site's visits; the pages that fell are its targets.+ ...group(+ 'ai_visits_weekly_drop',+ 'pages',+ falling,+ (p) => ({ id: p.page, label: p.page, before: p.before, now: p.now }),+ analytics > 0 ? GA : AI,+ { pageCount: falling.length },+ ),+ previousValue: before,+ currentValue: after,+ changeValue: after - before,+ });+ }++ // Each missing page with what AI visitors got and the working page to+ // redirect it to; the snippet is the only source (§3.8b).+ const broken = await ctx.brokenLinks();+ const rows = Array.isArray(broken?.rows) ? broken.rows : [];+ if (rows.length > 0) {+ found.push({+ ...group(+ 'broken_citation_target',+ 'pages',+ rows,+ (r) => ({+ id: r.page,+ label: r.page,+ visits: Number(r.visits) || 0,+ status: r.status,+ citations: Number(r.citations) || 0,+ redirectTo: r.target ?? null,+ }),+ AI,+ ),+ currentValue: Number(broken.count) || rows.length,+ });+ }+ return found;+ },+ },++ {+ name: 'aiBots',+ // Any brand can connect its Cloudflare or Vercel; the report says+ // whether it did.+ requires: ['tracking'],+ kinds: ['cited_page_uncrawled'],+ async run(ctx) {+ const report = await ctx.botReport();+ // Only while the bot data is whole (00185's alert_state 'on'). With a+ // sender stopped, revoked or past its cap ('stale'), the pages search+ // bots read drain and every cited page would read as uncrawled; the+ // kind is unread tonight, not recovered, so open signals and their+ // tasks stay open until data returns. Under 30 days ('waiting') there+ // is nothing to say yet.+ if (report?.alert_state === 'stale') throw new DataNotWhole('bot data is stale');+ if (report?.alert_state !== 'on') return [];+ const uncrawled = Array.isArray(report?.uncrawled) ? report.uncrawled : [];+ if (uncrawled.length === 0) return [];+ return [+ {+ ...group(+ 'cited_page_uncrawled',+ 'pages',+ uncrawled,+ (u) => ({ id: u.page, label: u.page, citations: Number(u.citations) || 0 }),+ AI,+ ),+ // The report names the ten most cited; the count is all of them.+ currentValue: Number(report.uncrawled_count) || uncrawled.length,+ },+ ];+ },+ },+{name: 'crossChannel',requires: ['ai_traffic'],@@ -770,6 +931,13 @@ const FAMILIES = [/** Every kind a library family can emit — what the registry checks against. */export const LIBRARY_EMITTED_KINDS = Object.freeze(FAMILIES.flatMap((f) => f.kinds));+/**+ * Thrown by a family whose data is there but not whole tonight — a bot+ * sender stopped, say. Its kinds are reported unread, as a failed read's are,+ * so open signals stay open until the data is whole again; it isn't an error.+ */+export class DataNotWhole extends Error {}+/*** Run every family the brand has the data for.*@@ -799,7 +967,14 @@ export async function libraryCandidates(brandId, { now = new Date(), sources } =} catch (err) {// One family's read failing costs that family's night, not the pass.for (const kind of family.kinds) unreadKinds.add(kind);- logger.error({ err, brandId, family: family.name }, '[signals] library family failed');+ if (err instanceof DataNotWhole) {+ logger.info(+ { brandId, family: family.name, reason: err.message },+ '[signals] library family data not whole',+ );+ } else {+ logger.error({ err, brandId, family: family.name }, '[signals] library family failed');+ }}}return { candidates, overflow, unreadKinds };diff --git a/server/src/lib/signals/library/kinds.js b/server/src/lib/signals/library/kinds.jsindex 70924f794..cf2066e26 100644--- a/server/src/lib/signals/library/kinds.js+++ b/server/src/lib/signals/library/kinds.js@@ -91,6 +91,12 @@ export const LIBRARY_KINDS = Object.freeze({converting_page_slipping: meta('traffic', 'high', ['ai_referral_traffic']),cross_channel_risk: meta('traffic', 'high', ['ai_referral_traffic']),visibility_traffic_loss: meta('traffic', 'high', ['ai_referral_traffic', 'ai_visibility']),+ // AI Traffic Analytics' alerts (AT-013, spec §3.8): the week-over-week drop,+ // the pages AI visitors landed on that don't exist (AT-012), and the cited+ // pages no AI search bot read in 30 days (AT-011).+ ai_visits_weekly_drop: meta('traffic', 'high', ['ai_referral_traffic']),+ broken_citation_target: meta('technical', 'high', ['ai_referral_traffic', 'citations']),+ cited_page_uncrawled: meta('technical', 'medium', ['citations']),// ── Site Audit findings ───────────────────────────────────────────────────crawler_blocked: meta('technical', 'high', []),diff --git a/server/src/lib/signals/record.js b/server/src/lib/signals/record.jsindex ac89bbf8d..f9df573ff 100644--- a/server/src/lib/signals/record.js+++ b/server/src/lib/signals/record.js@@ -37,6 +37,7 @@ import { readAllRpcRows } from '../rpc-pages.js';import { resolve } from '../../config/action-engine.js';import { EXCLUSIVE_KIND_GROUPS, LIBRARY_KINDS } from './library/kinds.js';import { libraryCandidates } from './library/detect.js';+import { newAiPlatformCandidates } from './traffic-platforms.js';const DAY_MS = 86_400_000;@@ -164,6 +165,14 @@ const BASE_KINDS = {kpiKeys: [],persistent: true,},+ // An AI platform started sending visits (AT-013): an event, like+ // new_engine, that no definition turns into work.+ ai_platform_new: {+ category: 'traffic',+ impact: 'medium',+ kpiKeys: ['ai_referral_traffic'],+ persistent: false,+ },};export const KIND_META = { ...BASE_KINDS, ...LIBRARY_KINDS };@@ -847,6 +856,7 @@ export async function recordSignalsForBrand(brandId, { now = new Date() } = {})candidates.push(...(await auditCandidates(brandId, now)));candidates.push(...(await platformGapCandidates(brandId)));candidates.push(...(await competitorCitationGapCandidates(brandId, now)));+ candidates.push(...(await newAiPlatformCandidates(brandId, { now })));// The V1 definition library's detectors (#818). Isolated per family inside:// a read that fails costs that family's signals for the night, and its kindsdiff --git a/server/src/lib/signals/traffic-platforms.js b/server/src/lib/signals/traffic-platforms.jsnew file mode 100644index 000000000..53da443cb--- /dev/null+++ b/server/src/lib/signals/traffic-platforms.js@@ -0,0 +1,110 @@+/**+ * "A new AI platform starts sending visits" (AT-013, spec §3.8).+ *+ * A platform with AI visits in the last seven whole days and none before+ * them, counted as the AI Traffic page counts them (ai_traffic_merged, 00176:+ * the snippet on the days it ran, Analytics on the rest). A brand with no AI+ * visits before the week has nothing to compare with — every platform would+ * be new — so it gets none.+ *+ * Only a source on the list (ai-sources.json) with NEW_PLATFORM_MIN_VISITS+ * or more visits: the beacon is public, so a made-up source key or one stray+ * visit would otherwise raise it.+ *+ * Good news with no work behind it, so it is a recorder kind of its own+ * (`ai_platform_new`, like `new_engine`) and no definition reads it. It is an+ * event: it stays until someone reads it, and a later week can't raise it+ * again because the platform is no longer new.+ */++import supabaseAdmin from '../../config/supabase.js';+import { AI_SOURCES } from '../ai-sources.js';+import { logger } from '../logger.js';+import { analyticsDayCount } from './library/classify.js';++const DAY_MS = 86_400_000;++/** Visits in the week a platform needs before it counts as new. */+export const NEW_PLATFORM_MIN_VISITS = 3;++const KNOWN_SOURCES = new Set(AI_SOURCES.map((source) => source.key));++/** The second before `iso`: see detect.js lastSecond. */+function lastSecond(iso) {+ return new Date(Date.parse(iso) - 1000).toISOString();+}++/** Midnight UTC `daysAgo` days before today's. */+function utcMidnight(now, daysAgo) {+ const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());+ return new Date(today - daysAgo * DAY_MS).toISOString();+}++/**+ * The platforms new this week, most visits first: the merged reads of the+ * week and of everything before it. `unknown` is a referrer the source list+ * couldn't name, not a platform.+ */+export function newPlatforms(week, before) {+ if ((Number(before?.visits) || 0) === 0) return [];+ const earlier = new Set(+ (before?.platforms ?? [])+ .filter((p) => (Number(p.visits) || 0) > 0)+ .map((p) => String(p.platform)),+ );+ const firstDay = new Map();+ for (const d of week?.days ?? []) {+ if ((Number(d.visits) || 0) === 0) continue;+ const day = String(d.day).slice(0, 10);+ const known = firstDay.get(d.platform);+ if (!known || day < known) firstDay.set(d.platform, day);+ }+ return (week?.platforms ?? [])+ .map((p) => ({ platform: String(p.platform ?? ''), visits: Number(p.visits) || 0 }))+ .filter((p) => p.visits >= NEW_PLATFORM_MIN_VISITS && KNOWN_SOURCES.has(p.platform))+ .filter((p) => !earlier.has(p.platform))+ .map((p) => ({ ...p, firstDay: firstDay.get(p.platform) ?? null }))+ .sort((a, b) => b.visits - a.visits || a.platform.localeCompare(b.platform));+}++async function merged(brandId, from, to) {+ const { data, error } = await supabaseAdmin.rpc('ai_traffic_merged', {+ p_brand_id: brandId,+ p_from: from,+ p_to: lastSecond(to),+ p_to_inclusive: true,+ p_analytics: true,+ });+ if (error) throw new Error(error.message);+ return data ?? {};+}++/**+ * Signal candidates for the platforms that started sending AI visits this+ * week. Best effort: a failed read costs this finding for the night, never+ * the pass, and an event kind is never closed for being unread.+ */+export async function newAiPlatformCandidates(brandId, { now = new Date() } = {}) {+ try {+ const weekStart = utcMidnight(now, 7);+ const [week, before] = await Promise.all([+ merged(brandId, weekStart, utcMidnight(now, 0)),+ merged(brandId, null, weekStart),+ ]);+ const analytics = analyticsDayCount(week.analytics_days) > 0;+ return newPlatforms(week, before).map((p) => ({+ kind: 'ai_platform_new',+ dedupKey: `ai_platform_new:${p.platform}`,+ source: analytics ? ['ga4'] : ['ai_results'],+ // Not `platform`: on a signal that names a tracked engine, where its+ // prompts run (web signals/where.ts). This is a referrer's source key.+ payload: { aiSource: p.platform, firstDay: p.firstDay },+ previousValue: 0,+ currentValue: p.visits,+ changeValue: p.visits,+ }));+ } catch (err) {+ logger.error({ err, brandId }, '[signals] new AI platform read failed');+ return [];+ }+}diff --git a/server/src/lib/signals/traffic-platforms.test.js b/server/src/lib/signals/traffic-platforms.test.jsnew file mode 100644index 000000000..3e7a6c4b2--- /dev/null+++ b/server/src/lib/signals/traffic-platforms.test.js@@ -0,0 +1,136 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * "A new AI platform starts sending visits" (AT-013, spec §3.8): a platform+ * with AI visits this week and none before, for a brand that had AI visits+ * before.+ */++const rpc = vi.fn();+vi.mock('../../config/supabase.js', () => ({ default: { rpc: (...args) => rpc(...args) } }));+const logger = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }));+vi.mock('../logger.js', () => ({ logger }));++const { newAiPlatformCandidates, newPlatforms } = await import('./traffic-platforms.js');++const NOW = new Date('2026-10-19T06:30:00Z');++beforeEach(() => {+ rpc.mockReset();+ logger.error.mockClear();+});++describe('newPlatforms', () => {+ const before = {+ visits: 40,+ platforms: [+ { platform: 'chatgpt.com', visits: 30 },+ { platform: 'gemini.google.com', visits: 10 },+ // Listed, but with no visits: never sent one.+ { platform: 'claude.ai', visits: 0 },+ ],+ };++ it('names the platforms sending visits for the first time, with their first day', () => {+ const week = {+ visits: 16,+ platforms: [+ { platform: 'chatgpt.com', visits: 9 },+ { platform: 'perplexity.ai', visits: 3 },+ { platform: 'claude.ai', visits: 5 },+ // A referrer the source list couldn't name is not a platform.+ { platform: 'unknown', visits: 4 },+ // Nor is a key the public beacon was sent that isn't on the list.+ { platform: 'made-up.example', visits: 50 },+ // One or two visits aren't a platform starting to send them.+ { platform: 'grok.com', visits: 2 },+ ],+ days: [+ { day: '2026-10-15', platform: 'claude.ai', visits: 3 },+ { day: '2026-10-14', platform: 'claude.ai', visits: 2 },+ { day: '2026-10-17', platform: 'perplexity.ai', visits: 3 },+ { day: '2026-10-12', platform: 'perplexity.ai', visits: 0 },+ ],+ };+ expect(newPlatforms(week, before)).toEqual([+ { platform: 'claude.ai', visits: 5, firstDay: '2026-10-14' },+ { platform: 'perplexity.ai', visits: 3, firstDay: '2026-10-17' },+ ]);+ });++ it('has nothing new for a brand with no AI visits before the week', () => {+ const week = { visits: 3, platforms: [{ platform: 'chatgpt.com', visits: 3 }] };+ expect(newPlatforms(week, { visits: 0, platforms: [] })).toEqual([]);+ expect(newPlatforms(week, null)).toEqual([]);+ });+});++describe('newAiPlatformCandidates', () => {+ it('reads the last seven whole days against everything before them', async () => {+ rpc.mockImplementation(async (_name, params) => ({+ data:+ params.p_from === null+ ? { visits: 12, platforms: [{ platform: 'chatgpt.com', visits: 12 }] }+ : {+ visits: 4,+ // A list of days, as ai_traffic_merged returns it (00176).+ analytics_days: [],+ platforms: [{ platform: 'perplexity.ai', visits: 4 }],+ days: [{ day: '2026-10-16', platform: 'perplexity.ai', visits: 4 }],+ },+ error: null,+ }));++ const found = await newAiPlatformCandidates('b1', { now: NOW });++ expect(rpc).toHaveBeenCalledWith('ai_traffic_merged', {+ p_brand_id: 'b1',+ p_from: '2026-10-12T00:00:00.000Z',+ // To the second before midnight, inclusive: that day's Analytics in one read only.+ p_to: '2026-10-18T23:59:59.000Z',+ p_to_inclusive: true,+ p_analytics: true,+ });+ expect(rpc).toHaveBeenCalledWith('ai_traffic_merged', {+ p_brand_id: 'b1',+ p_from: null,+ p_to: '2026-10-11T23:59:59.000Z',+ p_to_inclusive: true,+ p_analytics: true,+ });+ expect(found).toEqual([+ {+ kind: 'ai_platform_new',+ dedupKey: 'ai_platform_new:perplexity.ai',+ source: ['ai_results'],+ payload: { aiSource: 'perplexity.ai', firstDay: '2026-10-16' },+ previousValue: 0,+ currentValue: 4,+ changeValue: 4,+ },+ ]);+ });++ it('says Analytics when the week read it', async () => {+ rpc.mockImplementation(async (_name, params) => ({+ data:+ params.p_from === null+ ? { visits: 12, platforms: [{ platform: 'chatgpt.com', visits: 12 }] }+ : {+ visits: 4,+ analytics_days: ['2026-10-16'],+ platforms: [{ platform: 'perplexity.ai', visits: 4 }],+ days: [{ day: '2026-10-16', platform: 'perplexity.ai', visits: 4 }],+ },+ error: null,+ }));+ const [found] = await newAiPlatformCandidates('b1', { now: NOW });+ expect(found.source).toEqual(['ga4']);+ });++ it('costs only itself when a read fails', async () => {+ rpc.mockResolvedValue({ data: null, error: { message: 'statement timeout' } });+ expect(await newAiPlatformCandidates('b1', { now: NOW })).toEqual([]);+ expect(logger.error).toHaveBeenCalledTimes(1);+ });+});diff --git a/web/messages/en.json b/web/messages/en.jsonindex 0f0e40518..997e4c9f8 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -478,6 +478,7 @@"last_7_days": "Last 7 days","last_fortnight": "Last 14 days","last_four_weeks": "Last 28 days",+ "last_30_days": "Last 30 days","last_14_days": "Days with answers in the last 14 days","latest": "Latest data"},@@ -540,6 +541,10 @@"title": "New AI platform appearance","description": "Your brand appeared on {platform} for the first time."},+ "ai_platform_new": {+ "title": "{platform} started sending visitors",+ "description": "{visits, plural, one {# AI visit} other {# AI visits}} from {platform} in the last 7 days, the first it has sent."+ },"lost_citations": {"title": "Citations lost for “{prompt}”","titleOn": "Citations lost on {platform} for “{prompt}”",@@ -750,6 +755,18 @@"title": "Visibility and AI traffic falling together","description": "AI visibility and AI-referred traffic fell in the same window. A correlation, not a proven cause."},+ "ai_visits_weekly_drop": {+ "title": "AI visits fell from {from} to {to} week over week",+ "description": "AI-referred visits fell 40% or more against the week before, across {targets}."+ },+ "broken_citation_target": {+ "title": "Broken AI links on {targets}",+ "description": "AI answers send people to these pages and they answer 404. Redirect each one to a working page."+ },+ "cited_page_uncrawled": {+ "title": "AI search bots haven't read {targets} that AI answers cite",+ "description": "Your Cloudflare or Vercel saw no AI search bot read these cited pages in the last 30 days. Check that search crawlers can reach them."+ },"crawler_blocked": {"title": "AI crawlers blocked on {targets}","description": "Site Audit found these pages closed to AI crawlers."@@ -1117,7 +1134,11 @@"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}."+ "technicalIssueAll": "Site Audit flagged your site{issues}{when}.",+ "brokenLinks": "AI visitors landed on {subject}{when}, and {count, plural, one {it doesn't} other {they don't}} exist.",+ "brokenLinksAll": "AI visitors landed on pages that don't exist{when}.",+ "uncrawledPages": "AI answers cite {subject}, and no AI search bot read {count, plural, one {it} other {them}} in the last 30 days.",+ "uncrawledPagesAll": "AI answers cite pages no AI search bot read in the last 30 days."},"goal": {"citationLoss": "Citations back on {scope} by {date}.",@@ -1151,7 +1172,11 @@"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}."+ "technicalIssueAll": "Issues fixed by {date}.",+ "brokenLinks": "Working redirects for {scope} by {date}.",+ "brokenLinksAll": "Working redirects for every broken AI link by {date}.",+ "uncrawledPages": "AI search bots reading {scope} again by {date}.",+ "uncrawledPagesAll": "AI search bots reading your cited pages by {date}."}},"tasksProgress": "{completed} / {total} tasks completed",diff --git a/web/src/components/action-center/signal-table.tsx b/web/src/components/action-center/signal-table.tsxindex 081596e69..c50cfc617 100644--- a/web/src/components/action-center/signal-table.tsx+++ b/web/src/components/action-center/signal-table.tsx@@ -71,6 +71,7 @@ export const SIGNAL_ICONS: Partial<competitor_citation_gap: Quote,prompt_gain: TrendingUp,new_engine: Sparkles,+ ai_platform_new: Sparkles,lost_citations: Unlink,first_citation: Link2,competitor_surge: Swords,@@ -471,7 +472,9 @@ export function SignalTable({<SourceList sources={lead.source} /></TableCell><TableCell className="max-w-[180px]">- <p className="text-xs font-medium">{affectedLabel}</p>+ <p className="truncate text-xs font-medium" title={affectedLabel}>+ {affectedLabel}+ </p>{affected.detail && (<p className="truncate text-xs text-muted-foreground">{affected.detail}</p>)}diff --git a/web/src/lib/action-center/story.test.ts b/web/src/lib/action-center/story.test.tsindex a3b4e287a..9ed4c2702 100644--- a/web/src/lib/action-center/story.test.ts+++ b/web/src/lib/action-center/story.test.ts@@ -196,6 +196,43 @@ describe('actionStory', () => {expect(told.goal).toBe('Issues fixed on acme.example/pricing by Nov 8.');});+ it("tells AI Traffic's page findings by what visitors and bots found, not as Site Audit's (AT-013)", () => {+ const broken = tell([+ signal({+ category: 'technical',+ kind: 'broken_citation_target',+ payload: {+ entity: 'pages',+ targets: [+ { id: '/old-menu', label: '/old-menu', visits: 2, redirectTo: '/menu' },+ { id: '/gift-box', label: '/gift-box', visits: 1, redirectTo: '/gifts' },+ ],+ },+ currentValue: 2,+ }),+ ])!;+ expect(broken.family).toBe('brokenLinks');+ expect(broken.why).toBe("AI visitors landed on 2 pages on Oct 9, and they don't exist.");+ expect(broken.goal).toBe('Working redirects for both pages by Nov 8.');++ const unread = tell([+ signal({+ category: 'technical',+ kind: 'cited_page_uncrawled',+ payload: {+ entity: 'pages',+ targets: [{ id: '/guides/espresso', label: '/guides/espresso' }],+ },+ currentValue: 1,+ }),+ ])!;+ expect(unread.family).toBe('uncrawledPages');+ expect(unread.why).toBe(+ 'AI answers cite /guides/espresso, and no AI search bot read it in the last 30 days.',+ );+ expect(unread.goal).toBe('AI search bots reading /guides/espresso again by Nov 8.');+ });+it('quotes a brand-wide rate when nothing narrower is affected', () => {const told = tell([signal({diff --git a/web/src/lib/action-center/story.ts b/web/src/lib/action-center/story.tsindex 96134937b..d6e296ea2 100644--- a/web/src/lib/action-center/story.ts+++ b/web/src/lib/action-center/story.ts@@ -34,7 +34,11 @@ export type StoryFamily =| 'trafficGain'| 'searchLoss'| 'searchGap'- | 'technicalIssue';+ | 'technicalIssue'+ /** AI visitors landing on pages that don't exist (AT-012, AT-013). */+ | 'brokenLinks'+ /** Cited pages no AI search bot read in 30 days (AT-011, AT-013). */+ | 'uncrawledPages';type Translator = (key: string, values?: Record<string, string | number>) => string;@@ -59,6 +63,8 @@ const ALL_OF_THEM: readonly StoryFamily[] = ['competitorAhead','trafficGain','technicalIssue',+ 'brokenLinks',+ 'uncrawledPages',];/** Families told about pages first; the rest about prompts first. */@@ -69,6 +75,8 @@ const PAGE_FIRST: readonly StoryFamily[] = ['searchLoss','searchGap','technicalIssue',+ 'brokenLinks',+ 'uncrawledPages',];/** Brand-wide rates, in percent, whose before and after the sentence can quote. */@@ -76,6 +84,9 @@ const RATE_KINDS = ['sharp_drop', 'visibility_slipping'];/** The situation one signal describes. */export function storyFamily(signal: Pick<Signal, 'category' | 'kind'>): StoryFamily {+ // Technical, but found on the AI Traffic page, not by Site Audit.+ if (signal.kind === 'broken_citation_target') return 'brokenLinks';+ if (signal.kind === 'cited_page_uncrawled') return 'uncrawledPages';const meta = isSignalKind(signal.kind) ? SIGNAL_KINDS[signal.kind] : null;const state = meta?.stateKey ?? 'gap';const group = meta?.positivediff --git a/web/src/lib/signals/detail.test.ts b/web/src/lib/signals/detail.test.tsindex c09ec20e1..71b953699 100644--- a/web/src/lib/signals/detail.test.ts+++ b/web/src/lib/signals/detail.test.ts@@ -158,6 +158,42 @@ describe('signalChange', () => {it('has nothing to say when the row records no figures', () => {expect(signalChange(lostCitation)).toBeNull();});++ it("reads the weekly AI visits drop over seven days, and a new platform's first week (AT-013)", () => {+ expect(+ signalChange(+ signal({+ category: 'traffic',+ kind: 'ai_visits_weekly_drop',+ payload: { entity: 'pages', targets: [{ id: '/menu', label: '/menu' }] },+ previousValue: 50,+ currentValue: 28,+ changeValue: -22,+ }),+ ),+ ).toEqual({+ period: 'week_over_week',+ figures: [+ { metric: 'ai_sessions', role: 'before', value: 50 },+ { metric: 'ai_sessions', role: 'after', value: 28 },+ ],+ });+ expect(+ signalChange(+ signal({+ category: 'traffic',+ kind: 'ai_platform_new',+ payload: { aiSource: 'perplexity.ai' },+ previousValue: 0,+ currentValue: 4,+ changeValue: 4,+ }),+ ),+ ).toEqual({+ period: 'last_7_days',+ figures: [{ metric: 'ai_sessions', role: 'now', value: 4 }],+ });+ });});describe('signalWhereFields', () => {@@ -253,6 +289,38 @@ describe('signalLinks', () => {),).toEqual([{ kind: 'prompts', href: '/dashboard/prompts' }]);});++ it("points AI Traffic's page findings at AI Traffic and names only their pages (AT-013)", () => {+ const pages = { entity: 'pages', targets: [{ id: '/old-menu', label: '/old-menu' }] };+ const broken = signal({+ category: 'technical',+ kind: 'broken_citation_target',+ payload: pages,+ });+ const unread = signal({+ category: 'technical',+ kind: 'cited_page_uncrawled',+ payload: pages,+ currentValue: 3,+ });+ for (const s of [broken, unread]) {+ expect(signalLinks(s)).toEqual([{ kind: 'traffic', href: '/dashboard/traffic' }]);+ expect(signalWhereFields(s).map((f) => f.key)).toEqual(['pages']);+ }+ // Read over the bot report's 30 days.+ expect(signalChange(unread)?.period).toBe('last_30_days');++ const platform = signal({+ category: 'traffic',+ kind: 'ai_platform_new',+ payload: { aiSource: 'grok.com' },+ currentValue: 3,+ });+ expect(signalWhereFields(platform)).toEqual([+ { key: 'scope', value: { type: 'scope', scope: 'platform' } },+ ]);+ expect(signalLinks(platform)).toEqual([{ kind: 'traffic', href: '/dashboard/traffic' }]);+ });});describe('currentActionFirst', () => {diff --git a/web/src/lib/signals/detail.ts b/web/src/lib/signals/detail.tsindex 46776ab5e..af179b872 100644--- a/web/src/lib/signals/detail.ts+++ b/web/src/lib/signals/detail.ts@@ -2,6 +2,7 @@ import type { Signal } from './map';import { locationName, platformName } from './names';import { getPlatformName } from '@/lib/traffic-platforms';import { isLibrarySignalKind, type SignalCategory, type SignalKind } from './registry';+import { libraryTargetCount } from './display';/*** What a signal's detail says, as data (AC-001): where it happened, what@@ -115,6 +116,8 @@ export type ChangePeriod =| 'last_14_days'| 'last_fortnight'| 'last_four_weeks'+ /** The AI bot report's alert window (server 00185). */+ | 'last_30_days'| 'latest';/** Days in each window of a before-and-after period: "previous 14 days". */@@ -147,6 +150,9 @@ const WEEK_OVER_WEEK: Partial<Record<SignalKind, SignalMetric>> = {competitor_momentum: 'mentions',competitor_surge: 'mention_rate',ai_traffic_drop: 'ai_sessions',+ // The AI Traffic page's own visits, the last seven whole days against the+ // seven before (AT-013, server library/detect.js `ctx.weeklyVisits`).+ ai_visits_weekly_drop: 'ai_sessions',visibility_traffic_loss: 'ai_sessions',cross_channel_risk: 'ai_sessions',};@@ -160,6 +166,13 @@ const AI_TRAFFIC_KINDS: ReadonlySet<string> = new Set(['converting_page_slipping',]);+// Page targets that carry their AI visits before and after: the 14-day kinds+// and the weekly drop (AT-013).+const VISIT_PAGE_KINDS: ReadonlySet<string> = new Set([+ ...AI_TRAFFIC_KINDS,+ 'ai_visits_weekly_drop',+]);+// Compared over the last 28 days against the 28 before (`ctx.gsc`).const SEARCH_CONSOLE_KINDS: ReadonlySet<string> = new Set(['gsc_demand_gap',@@ -213,8 +226,12 @@ export function signalChange(signal: Signal): SignalChange | null {);}return {- // AI sessions are always read over 14 days (`ctx.traffic`).- period: overTime === 'ai_sessions' ? 'fortnight_over_fortnight' : 'week_over_week',+ // AI sessions are read over 14 days (`ctx.traffic`), the weekly drop's+ // over seven.+ period:+ overTime === 'ai_sessions' && signal.kind !== 'ai_visits_weekly_drop'+ ? 'fortnight_over_fortnight'+ : 'week_over_week',figures,};}@@ -344,6 +361,14 @@ export function signalChange(signal: Signal): SignalChange | null {return cur === null? null: { period: 'last_7_days', figures: [{ metric: 'prompts', role: 'total', value: cur }] };+ // Its first week's AI visits (AT-013).+ case 'ai_platform_new':+ return cur === null+ ? null+ : {+ period: 'last_7_days',+ figures: [{ metric: 'ai_sessions', role: 'now', value: cur }],+ };case 'audit_low_score':return cur === null? null@@ -374,7 +399,9 @@ export function signalChange(signal: Signal): SignalChange | null {? 'last_fortnight': SEARCH_CONSOLE_KINDS.has(signal.kind)? 'last_four_weeks'- : 'last_7_days';+ : signal.kind === 'cited_page_uncrawled'+ ? 'last_30_days'+ : 'last_7_days';return { period, figures: [{ metric: counted, role: 'total', value: cur }] };}return null;@@ -736,6 +763,17 @@ const CRAWLER_LAYOUT: WhereFieldKey[] = ['pages', 'issue', 'crawlers', 'evidence// A site-wide traffic finding has no page to cite: where its AI visits come from.const SITE_TRAFFIC_LAYOUT: WhereFieldKey[] = ['scope', 'aiReferrals'];+// The AI Traffic page's own findings (AT-013): broken AI links, and cited+// pages no AI search bot read. They name pages, not anything Site Audit checked.+const AI_TRAFFIC_PAGE_FINDINGS: readonly SignalKind[] = [+ 'broken_citation_target',+ 'cited_page_uncrawled',+];+const AI_TRAFFIC_PAGES_LAYOUT: WhereFieldKey[] = ['pages'];++// A platform that started sending AI visits: its title names it.+const NEW_AI_PLATFORM_LAYOUT: WhereFieldKey[] = ['scope'];+// A first citation is a gain: the page and the prompt, not who replaced it.const FIRST_CITATION_LAYOUT: WhereFieldKey[] = ['url', 'prompt', 'platforms', 'locations'];@@ -798,7 +836,7 @@ function fieldValue(signal: Signal, key: WhereFieldKey): WhereValue | null {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));+ const total = libraryTargetCount(signal, targets);switch (key) {case 'scope': {@@ -810,7 +848,8 @@ function fieldValue(signal: Signal, key: WhereFieldKey): WhereValue | null {if (entity === 'platforms' ||signal.kind === 'platform_gap' ||- signal.kind === 'new_engine'+ signal.kind === 'new_engine' ||+ signal.kind === 'ai_platform_new') {return { type: 'scope', scope: 'platform' };}@@ -894,15 +933,13 @@ function fieldValue(signal: Signal, key: WhereFieldKey): WhereValue | null {return url ? { type: 'text', text: url } : null;}case 'pages': {- if (AI_TRAFFIC_KINDS.has(signal.kind) && targets.length && !isSiteWide(signal)) {+ if (VISIT_PAGE_KINDS.has(signal.kind) && targets.length && !isSiteWide(signal)) {return {type: 'trafficPages',items: trafficPages(targets),- // A drop's value is the site's sessions; its pages are counted apart.- total:- signal.kind === 'ai_traffic_drop'- ? Math.max(targets.length, num(p.pageCount) ?? 0)- : total,+ // A drop's value is the site's visits; its pages are counted apart+ // (`pageCount`, read by libraryTargetCount).+ total,metrics: TRAFFIC_METRICS[signal.kind] ?? [],siteEngagedRate: num(p.siteEngagedRate),siteKeyRate: num(p.siteKeyRate),@@ -1036,9 +1073,13 @@ export function signalWhereFields(signal: Signal): WhereField[] {? CRAWLER_LAYOUT: CITATION_LOSS.includes(signal.kind)? CITATION_LOSS_LAYOUT- : signal.category === 'traffic' && isSiteWide(signal)- ? SITE_TRAFFIC_LAYOUT- : LAYOUT[signal.category];+ : AI_TRAFFIC_PAGE_FINDINGS.includes(signal.kind)+ ? AI_TRAFFIC_PAGES_LAYOUT+ : signal.kind === 'ai_platform_new'+ ? NEW_AI_PLATFORM_LAYOUT+ : signal.category === 'traffic' && isSiteWide(signal)+ ? SITE_TRAFFIC_LAYOUT+ : LAYOUT[signal.category];const named = namedPlaces(signal);// A mention's position, sentiment and quote are given per prompt when the// evidence is recorded; asked for on their own only when it is not.@@ -1100,6 +1141,9 @@ export function signalLinks(signal: Signal): SignalLink[] {if (entity === 'sources' || signal.category === 'citation') {return [{ kind: 'citations', href: '/dashboard/citations' }];}+ if (AI_TRAFFIC_PAGE_FINDINGS.includes(signal.kind)) {+ return [{ kind: 'traffic', href: '/dashboard/traffic' }];+ }switch (signal.category) {case 'competitor':return [{ kind: 'competitors', href: '/dashboard/competitors' }];diff --git a/web/src/lib/signals/display.test.ts b/web/src/lib/signals/display.test.tsindex bdb465d22..ddf2f30e8 100644--- a/web/src/lib/signals/display.test.ts+++ b/web/src/lib/signals/display.test.ts@@ -36,6 +36,57 @@ const signal = (over: Partial<Signal>): Signal => ({});describe('signalTexts', () => {+ it("names AI Traffic's alerts: the weekly drop, broken links, unread cited pages and a new platform (AT-013)", () => {+ const pages = (n: number) =>+ Array.from({ length: n }, (_, i) => ({ id: `/p${i}`, label: `/p${i}` }));+ const drop = signal({+ category: 'traffic',+ kind: 'ai_visits_weekly_drop',+ payload: { entity: 'pages', targets: pages(3), pageCount: 3 },+ previousValue: 50,+ currentValue: 28,+ });+ expect(signalTexts(drop, tTexts)).toEqual({+ title: 'AI visits fell from 50 to 28 week over week',+ description: 'AI-referred visits fell 40% or more against the week before, across 3 pages.',+ });+ // Its value is the site's visits; its pages are counted apart.+ expect(signalAffected(drop, tPage)).toEqual({ label: '3 pages', detail: '/p0' });++ const broken = signal({+ category: 'technical',+ kind: 'broken_citation_target',+ payload: { entity: 'pages', targets: pages(2) },+ currentValue: 2,+ });+ expect(signalTexts(broken, tTexts).title).toBe('Broken AI links on 2 pages');+ expect(signalAffected(broken, tPage)).toEqual({ label: '2 pages', detail: '/p0' });++ const unread = signal({+ category: 'technical',+ kind: 'cited_page_uncrawled',+ payload: { entity: 'pages', targets: pages(10) },+ currentValue: 14,+ });+ expect(signalTexts(unread, tTexts).title).toBe(+ "AI search bots haven't read 14 pages that AI answers cite",+ );++ const platform = signal({+ category: 'traffic',+ kind: 'ai_platform_new',+ payload: { aiSource: 'perplexity.ai', firstDay: '2026-10-16' },+ previousValue: 0,+ currentValue: 4,+ changeValue: 4,+ });+ expect(signalTexts(platform, tTexts)).toEqual({+ title: 'Perplexity started sending visitors',+ description: '4 AI visits from Perplexity in the last 7 days, the first it has sent.',+ });+ expect(signalAffected(platform, tPage)).toEqual({ label: 'Platform', detail: 'Perplexity' });+ });+it('names the platform and says how far its mention rate fell', () => {const drop = signal({payload: {diff --git a/web/src/lib/signals/display.ts b/web/src/lib/signals/display.tsindex 89a432056..33def4859 100644--- a/web/src/lib/signals/display.ts+++ b/web/src/lib/signals/display.ts@@ -1,6 +1,7 @@import type { Signal } from '@/lib/actions/signals';import { SIGNAL_KINDS, isLibrarySignalKind } from '@/lib/signals/registry';import { locationName, platformName, targetName } from '@/lib/signals/names';+import { getPlatformName } from '@/lib/traffic-platforms';/*** Composes the display strings a signal row shows from `kind` + `payload`.@@ -16,6 +17,17 @@ function str(payload: Record<string, unknown>, key: string): string {return typeof value === 'string' ? value : String(value ?? '');}+/**+ * How many things a library finding is about. A group's value is its count,+ * except for the AI traffic drops, whose value is the site's visits: they+ * record their pages as `pageCount` (server library/detect.js).+ */+export function libraryTargetCount(signal: Signal, targets: readonly unknown[]): number {+ const pageCount = signal.payload?.pageCount;+ if (typeof pageCount === 'number') return Math.max(targets.length, pageCount);+ return Math.max(targets.length, Number(signal.currentValue ?? 0));+}+/*** A library signal's copy: what it is about, named from its targets, and the* measured fact behind it.@@ -32,7 +44,7 @@ function librarySignalTexts(signal: Signal, t: Translator): { title: string; desconst p = signal.payload ?? {};const targets = Array.isArray(p.targets) ? (p.targets as Array<{ label?: string }>) : [];const entity = str(p, 'entity');- const count = entity === '' ? 0 : Math.max(targets.length, Number(signal.currentValue ?? 0));+ const count = entity === '' ? 0 : libraryTargetCount(signal, targets);const values: Record<string, string | number> = {targets: entity ? t(`targets.${entity}`, { count }) : '',name: targetName(entity, targets[0]?.label ?? ''),@@ -113,6 +125,9 @@ export function signalTexts(signal: Signal, t: Translator): { title: string; desreturn { prompt: str(p, 'promptText'), gain: signal.changeValue ?? 0 };case 'new_engine':return { platform: platformName(str(p, 'platform')) };+ // A referring platform, named as the AI Traffic page names it (AT-013).+ case 'ai_platform_new':+ return { platform: getPlatformName(str(p, 'aiSource')), visits: signal.currentValue ?? 0 };case 'first_citation':return { url: str(p, 'label') || str(p, 'url'), prompt: str(p, 'promptText') };case 'competitor_surge':@@ -166,7 +181,7 @@ export function signalAffected(// The count for a group, the thing itself for a single finding.const targets = Array.isArray(p.targets) ? (p.targets as Array<{ label?: string }>) : [];const entity = str(p, 'entity');- const count = Math.max(targets.length, Number(signal.currentValue ?? 0));+ const count = libraryTargetCount(signal, targets);if (targets.length === 1) {return { label: targetName(entity, targets[0]?.label ?? ''), detail: null };}@@ -188,6 +203,8 @@ export function signalAffected(return { label: t('affected.prompts', { count: 1 }), detail: str(p, 'promptText') };case 'new_engine':return { label: t('affected.platform'), detail: platformName(str(p, 'platform')) };+ case 'ai_platform_new':+ return { label: t('affected.platform'), detail: getPlatformName(str(p, 'aiSource')) };case 'first_citation':return { label: t('affected.urls', { count: 1 }), detail: str(p, 'label') || str(p, 'url') };case 'competitor_surge':diff --git a/web/src/lib/signals/library-kinds.ts b/web/src/lib/signals/library-kinds.tsindex 7412fcc64..12366c948 100644--- a/web/src/lib/signals/library-kinds.ts+++ b/web/src/lib/signals/library-kinds.ts@@ -47,6 +47,9 @@ export const LIBRARY_SIGNAL_KINDS = {converting_page_slipping: { stateKey: 'slipping', positive: false },cross_channel_risk: { stateKey: 'dropped', positive: false },visibility_traffic_loss: { stateKey: 'dropped', positive: false },+ ai_visits_weekly_drop: { stateKey: 'dropped', positive: false },+ broken_citation_target: { stateKey: 'issue', positive: false },+ cited_page_uncrawled: { stateKey: 'issue', positive: false },crawler_blocked: { stateKey: 'issue', positive: false },structured_data_issue: { stateKey: 'issue', positive: false },outdated_content: { stateKey: 'issue', positive: false },diff --git a/web/src/lib/signals/registry.ts b/web/src/lib/signals/registry.tsindex 184a942de..1eeabfc34 100644--- a/web/src/lib/signals/registry.ts+++ b/web/src/lib/signals/registry.ts@@ -33,6 +33,7 @@ export type BaseSignalKind =| 'competitor_citation_gap'| 'prompt_gain'| 'new_engine'+ | 'ai_platform_new'| 'lost_citations'| 'first_citation'| 'competitor_surge'@@ -97,6 +98,7 @@ const BASE_SIGNAL_KINDS: Record<BaseSignalKind, SignalKindMeta> = {competitor_citation_gap: { kind: 'competitor_citation_gap', stateKey: 'gap', positive: false },prompt_gain: { kind: 'prompt_gain', stateKey: 'gained', positive: true },new_engine: { kind: 'new_engine', stateKey: 'gained', positive: true },+ ai_platform_new: { kind: 'ai_platform_new', stateKey: 'gained', positive: true },lost_citations: { kind: 'lost_citations', stateKey: 'lost', positive: false },first_citation: { kind: 'first_citation', stateKey: 'gained', positive: true },competitor_surge: { kind: 'competitor_surge', stateKey: 'gain', positive: false },