Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(analytics): detect valuable pages AI engines send no traffic to (#724)

Gökhan Geyik1b505d2066c9
diff --git a/server/src/lib/ga-suggestions.js b/server/src/lib/ga-suggestions.js
index a367b2115..988614df6 100644
--- a/server/src/lib/ga-suggestions.js
+++ b/server/src/lib/ga-suggestions.js
@@ -9,7 +9,7 @@
*
* The first finds what is missing, the second finds what is already working.
* Everything up to the LLM handoff is deterministic: SQL aggregation →
- * transactional-page exclusion → ranking → page read → coverage filter. Any
+ * page-scope exclusion → ranking → page read → coverage filter. Any
* failure returns [] so the base suggestion flow never degrades, and brands
* without synced traffic short-circuit on the first (empty) query.
*/
@@ -18,6 +18,7 @@ import * as cheerio from 'cheerio';
import supabaseAdmin from '../config/supabase.js';
import { fetchViaScrapeDo } from './audit/fetcher.js';
import { isCoveredByPrompts } from './gsc-suggestions.js';
+import { isExcludedPath } from './page-paths.js';
import { logger } from './logger.js';
const WINDOW_DAYS = 28;
@@ -35,72 +36,12 @@ const READ_CONCURRENCY = 4;
const MIN_SESSIONS = 5;
const MIN_AI_SESSIONS = 3;
-/**
- * Paths that produce revenue attribution but no answerable question.
- *
- * A GA4 purchase event fires on the confirmation page, so without this the
- * highest-revenue "page" in most shops is the checkout — and no prompt exists
- * that a person would ask an AI to arrive there. Matched on path segments so
- * `/cart` and `/en/cart/` hit while `/cartography-guides` does not.
- */
-const TRANSACTIONAL_SEGMENTS = new Set([
- 'checkout',
- 'cart',
- 'basket',
- 'order',
- 'orders',
- 'order-confirmation',
- 'confirmation',
- 'thank-you',
- 'thanks',
- 'payment',
- 'pay',
- 'login',
- 'signin',
- 'sign-in',
- 'signup',
- 'sign-up',
- 'register',
- 'logout',
- 'account',
- 'my-account',
- 'profile',
- 'dashboard',
- 'admin',
- 'wishlist',
- 'favorites',
- 'search',
- 'cookie-policy',
- 'privacy',
- 'privacy-policy',
- 'terms',
- 'terms-of-service',
- 'legal',
- 'unsubscribe',
-]);
-
-/**
- * True for a page that cannot yield a sensible prompt.
- *
- * Also excludes GA4's own placeholders: a blank or "(not set)" landing page is
- * an unattributed session, not a page anyone can be sent to.
- */
-export function isTransactionalPath(path) {
- const raw = String(path ?? '').trim();
- if (!raw || raw === '(not set)' || raw === '(other)') return true;
- const withoutQuery = raw.split(/[?#]/)[0];
- return withoutQuery
- .split('/')
- .filter(Boolean)
- .some((segment) => TRANSACTIONAL_SEGMENTS.has(segment.toLowerCase()));
-}
-
/** Sum the per-day rows of one table into one row per landing page. */
export function aggregateByPage(rows, fields) {
const byPage = new Map();
for (const row of rows || []) {
const page = row.landing_page ?? '';
- if (isTransactionalPath(page)) continue;
+ if (isExcludedPath(page)) continue;
const acc = byPage.get(page) ?? { landing_page: page };
for (const field of fields) acc[field] = (acc[field] ?? 0) + (Number(row[field]) || 0);
byPage.set(page, acc);
diff --git a/server/src/lib/ga-suggestions.test.js b/server/src/lib/ga-suggestions.test.js
index 5ac781676..030fc0db1 100644
--- a/server/src/lib/ga-suggestions.test.js
+++ b/server/src/lib/ga-suggestions.test.js
@@ -9,7 +9,6 @@ import {
aiPlatformsByPage,
composeGaCandidates,
extractPageSummary,
- isTransactionalPath,
summaryText,
toAbsoluteUrl,
} from './ga-suggestions.js';
@@ -23,44 +22,6 @@ import {
* once and never trusts again.
*/
-describe('isTransactionalPath', () => {
- it('excludes the pages that carry revenue but answer no question', () => {
- // A GA4 purchase fires on the confirmation page, so without this the
- // top-revenue "page" in most shops is the checkout.
- for (const path of [
- '/checkout',
- '/cart/',
- '/en/order-confirmation',
- '/thank-you',
- '/account/orders',
- '/login',
- '/tr/sepet/../cart',
- ]) {
- expect(isTransactionalPath(path), path).toBe(true);
- }
- });
-
- it('matches whole path segments, not substrings', () => {
- // /cartography-guides is a content page that a naive `includes('cart')`
- // would silently delete from the candidate pool.
- expect(isTransactionalPath('/cartography-guides')).toBe(false);
- expect(isTransactionalPath('/blog/accountability-in-ai')).toBe(false);
- expect(isTransactionalPath('/products/searchlight-3000')).toBe(false);
- });
-
- it('excludes GA placeholders and blanks, which are not pages at all', () => {
- expect(isTransactionalPath('')).toBe(true);
- expect(isTransactionalPath('(not set)')).toBe(true);
- expect(isTransactionalPath(undefined)).toBe(true);
- });
-
- it('keeps ordinary content and category pages', () => {
- expect(isTransactionalPath('/')).toBe(false);
- expect(isTransactionalPath('/pricing')).toBe(false);
- expect(isTransactionalPath('/collections/headphones')).toBe(false);
- });
-});
-
describe('aggregateByPage', () => {
it('sums the per-day rows of one page', () => {
const rows = [
diff --git a/server/src/lib/page-opportunities.js b/server/src/lib/page-opportunities.js
new file mode 100644
index 000000000..be1820691
--- /dev/null
+++ b/server/src/lib/page-opportunities.js
@@ -0,0 +1,271 @@
+/**
+ * Page opportunity detection (#719, Phase 5).
+ *
+ * Answers one question per brand: which pages carry commercial weight, and
+ * get nothing from AI engines. Both halves come from tables the GA sync
+ * (#704) already aggregates, so detection is arithmetic over a few hundred
+ * rows — no model, no page fetching, and nothing that scans result citations.
+ *
+ * The ranking signal is chosen from what the property actually reports rather
+ * than assumed. A shop with ecommerce ranks on money; a site with no
+ * conversion events at all ranks on engagement. The signal used is stored on
+ * every finding, because a surface that calls an engagement rank "your most
+ * valuable page" is making a true statement about the wrong thing.
+ *
+ * Deliberately not here: LLM enrichment, clustering, and the full opportunity
+ * lifecycle. Those need more volume than this produces today, and a finding
+ * nobody can verify is worse than one that is merely narrow.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { isExcludedPath } from './page-paths.js';
+import { logger } from './logger.js';
+
+const WINDOW_DAYS = 28;
+
+/**
+ * A page below this has too little behind it for a finding, whatever its
+ * percentile. This is what stops the engine from producing a constant
+ * fraction of every site: a percentile alone always qualifies the same share
+ * of pages, so a brand with genuinely little to fix would still be handed a
+ * full list.
+ */
+const MIN_SESSIONS = 10;
+
+/** How far up its own site a page must rank before it is worth raising. */
+const MIN_PERCENTILE = 70;
+
+/**
+ * Ranking signals in order of how directly they express commercial value.
+ * The first one the property actually reports wins.
+ */
+const VALUE_SIGNALS = [
+ { name: 'revenue', of: (p) => p.revenue },
+ { name: 'transactions', of: (p) => p.transactions },
+ { name: 'key_events', of: (p) => p.keyEvents },
+ { name: 'engagement', of: (p) => p.engagementSeconds },
+];
+
+/**
+ * The strongest signal this brand's property reports.
+ *
+ * Falls back to engagement, which every property has: without it a site with
+ * no ecommerce and no configured key events would produce no findings at all,
+ * and "nobody has set up conversion tracking" is not a reason to tell a
+ * customer there is nothing to look at.
+ */
+export function pickValueSignal(pages) {
+ for (const signal of VALUE_SIGNALS) {
+ if ((pages ?? []).some((page) => (signal.of(page) ?? 0) > 0)) return signal.name;
+ }
+ return 'engagement';
+}
+
+function signalValue(page, signalName) {
+ const signal = VALUE_SIGNALS.find((s) => s.name === signalName);
+ return signal ? (signal.of(page) ?? 0) : 0;
+}
+
+/**
+ * Rank pages within their own site, so a small B2B site and a large shop are
+ * judged on the same scale.
+ *
+ * Percentile is the share of the brand's own pages this one beats, which
+ * makes 100 the top page rather than an unreachable ceiling. Ties share a
+ * percentile — two pages with identical revenue should not be separated by
+ * whichever happened to sort first.
+ */
+export function scorePages(pages, signalName) {
+ const values = (pages ?? []).map((page) => signalValue(page, signalName));
+ const total = values.length;
+
+ const ranked = (pages ?? [])
+ .map((page, i) => ({ page, value: values[i] }))
+ .sort((a, b) => b.value - a.value || b.page.sessions - a.page.sessions);
+
+ return ranked.map((entry, index) => ({
+ ...entry.page,
+ valueSignal: signalName,
+ value: entry.value,
+ valueRank: index + 1,
+ valuePercentile:
+ total <= 1
+ ? 100
+ : Math.round((values.filter((v) => v < entry.value).length / total) * 1000) / 10,
+ }));
+}
+
+/**
+ * Findings for one brand's pages.
+ *
+ * A page qualifies when it ranks high on its site AND clears the absolute
+ * floors — both conditions, because either alone misreports. The percentile
+ * without a floor hands every site the same number of findings; the floor
+ * without a percentile buries a small site's best page under a large one's
+ * long tail.
+ */
+export function detectPageOpportunities({ pages, aiByPage, windowDays = WINDOW_DAYS }) {
+ const signal = pickValueSignal(pages);
+ const scored = scorePages(pages, signal);
+
+ return scored
+ .filter((page) => page.sessions >= MIN_SESSIONS)
+ .filter((page) => page.value > 0)
+ .filter((page) => page.valuePercentile >= MIN_PERCENTILE)
+ .filter((page) => !(aiByPage?.get(page.landingPage)?.sessions > 0))
+ .map((page) => ({
+ landing_page: page.landingPage,
+ kind: 'no_ai_traffic',
+ value_signal: page.valueSignal,
+ value_percentile: page.valuePercentile,
+ value_rank: page.valueRank,
+ sessions: page.sessions,
+ engaged_sessions: page.engagedSessions,
+ key_events: page.keyEvents,
+ transactions: page.transactions,
+ revenue: page.revenue,
+ engagement_seconds: page.engagementSeconds,
+ ai_sessions: 0,
+ ai_platforms: [],
+ window_days: windowDays,
+ }));
+}
+
+/** Sum the per-day GA rows into one row per landing page. */
+export function aggregatePages(rows) {
+ const byPage = new Map();
+ for (const row of rows ?? []) {
+ const page = row.landing_page ?? '';
+ if (isExcludedPath(page)) continue;
+ const acc = byPage.get(page) ?? {
+ landingPage: page,
+ sessions: 0,
+ engagedSessions: 0,
+ keyEvents: 0,
+ transactions: 0,
+ revenue: 0,
+ engagementSeconds: 0,
+ };
+ acc.sessions += Number(row.sessions) || 0;
+ acc.engagedSessions += Number(row.engaged_sessions) || 0;
+ acc.keyEvents += Number(row.key_events) || 0;
+ acc.transactions += Number(row.transactions) || 0;
+ acc.revenue += Number(row.purchase_revenue) || 0;
+ acc.engagementSeconds += Number(row.engagement_duration_seconds) || 0;
+ byPage.set(page, acc);
+ }
+ return [...byPage.values()];
+}
+
+/**
+ * AI-referred sessions and platforms per landing page.
+ *
+ * A plain lookup, with no scope filtering: the candidate set is decided when
+ * pages are aggregated, and filtering here as well would only hide the answer
+ * to "does this page already get AI traffic".
+ */
+export function aggregateAiTraffic(rows) {
+ const byPage = new Map();
+ for (const row of rows ?? []) {
+ const page = row.landing_page ?? '';
+ if (!page) continue;
+ const acc = byPage.get(page) ?? { sessions: 0, platforms: new Set() };
+ acc.sessions += Number(row.sessions) || 0;
+ if (row.platform) acc.platforms.add(row.platform);
+ byPage.set(page, acc);
+ }
+ return new Map(
+ [...byPage].map(([page, acc]) => [
+ page,
+ { sessions: acc.sessions, platforms: [...acc.platforms] },
+ ]),
+ );
+}
+
+async function detectForBrand(brandId) {
+ const since = new Date(Date.now() - WINDOW_DAYS * 86_400_000).toISOString().slice(0, 10);
+
+ const [{ data: pageRows, error: pageErr }, { data: aiRows, error: aiErr }] = await Promise.all([
+ supabaseAdmin
+ .from('ga_page_stats')
+ .select(
+ 'landing_page, sessions, engaged_sessions, key_events, transactions, purchase_revenue, engagement_duration_seconds',
+ )
+ .eq('brand_id', brandId)
+ .gte('date', since),
+ supabaseAdmin
+ .from('ga_ai_traffic_stats')
+ .select('landing_page, platform, sessions')
+ .eq('brand_id', brandId)
+ .gte('date', since),
+ ]);
+ if (pageErr) throw new Error(pageErr.message);
+ if (aiErr) throw new Error(aiErr.message);
+ if (!pageRows?.length) return { found: 0, resolved: 0 };
+
+ const findings = detectPageOpportunities({
+ pages: aggregatePages(pageRows),
+ aiByPage: aggregateAiTraffic(aiRows),
+ });
+
+ const now = new Date().toISOString();
+ if (findings.length > 0) {
+ // first_detected_at is left to the column default so it survives the
+ // upsert: a finding that has been open for a week should say so, not
+ // reset its age every night.
+ const { error } = await supabaseAdmin.from('page_opportunities').upsert(
+ findings.map((f) => ({ ...f, brand_id: brandId, last_detected_at: now, resolved_at: null })),
+ { onConflict: 'brand_id,landing_page,kind' },
+ );
+ if (error) throw new Error(error.message);
+ }
+
+ // Anything still open that this run did not touch no longer qualifies — the
+ // page picked up AI traffic, lost its standing, or fell below the floors.
+ // Stamped rather than deleted so a surface can show that something improved
+ // instead of the row quietly disappearing.
+ //
+ // Selected by the timestamp the upsert above just wrote, not by excluding a
+ // list of paths: a `not.in.(...)` filter has to be built as a string, and a
+ // landing page containing a comma or a quote would silently change which
+ // rows it matched.
+ const { error: resolveErr } = await supabaseAdmin
+ .from('page_opportunities')
+ .update({ resolved_at: now })
+ .eq('brand_id', brandId)
+ .is('resolved_at', null)
+ .lt('last_detected_at', now);
+ if (resolveErr) throw new Error(resolveErr.message);
+
+ return { found: findings.length, signal: findings[0]?.value_signal ?? null };
+}
+
+/**
+ * Detect for every brand with synced GA data; optionally scoped to one
+ * organization. Per-brand failures are logged and skipped.
+ */
+export async function runPageOpportunityDetection({ organizationId } = {}) {
+ let brandQuery = supabaseAdmin
+ .from('brands')
+ .select('id, organization_id')
+ .eq('is_active', true)
+ .not('ga_property_id', 'is', null);
+ if (organizationId) brandQuery = brandQuery.eq('organization_id', organizationId);
+ const { data: brands, error } = await brandQuery;
+ if (error) throw new Error(error.message);
+ if (!brands?.length) return { scanned: 0, results: [] };
+
+ const results = [];
+ for (const brand of brands) {
+ try {
+ const outcome = await detectForBrand(brand.id);
+ results.push({ brandId: brand.id, ...outcome });
+ } catch (err) {
+ logger.error({ err, brandId: brand.id }, '[page-opportunities] detection failed');
+ results.push({ brandId: brand.id, error: err.message });
+ }
+ }
+
+ logger.info({ scanned: brands.length }, '[page-opportunities] detection completed');
+ return { scanned: brands.length, results };
+}
diff --git a/server/src/lib/page-opportunities.test.js b/server/src/lib/page-opportunities.test.js
new file mode 100644
index 000000000..6a078abcb
--- /dev/null
+++ b/server/src/lib/page-opportunities.test.js
@@ -0,0 +1,258 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// The module imports the supabase admin client, whose config hard-exits when
+// SUPABASE_* env is absent (as in CI) — stub it before the import chain.
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+
+import {
+ aggregateAiTraffic,
+ aggregatePages,
+ detectPageOpportunities,
+ pickValueSignal,
+ scorePages,
+} from './page-opportunities.js';
+
+/**
+ * Page opportunity detection (#719).
+ *
+ * The signal-selection and scoring paths carry most of the weight here,
+ * because the only connected property reports no revenue, no transactions and
+ * no key events. Those three branches cannot be exercised against real data
+ * today, so they are pinned here instead — a customer connecting a property
+ * with real conversions must get the right answer on the first night, with no
+ * code change.
+ */
+
+const page = (over = {}) => ({
+ landingPage: '/p',
+ sessions: 100,
+ engagedSessions: 50,
+ keyEvents: 0,
+ transactions: 0,
+ revenue: 0,
+ engagementSeconds: 1000,
+ ...over,
+});
+
+describe('pickValueSignal', () => {
+ it('ranks on revenue when the property reports any', () => {
+ expect(pickValueSignal([page({ revenue: 10, transactions: 1, keyEvents: 3 })])).toBe('revenue');
+ });
+
+ it('falls to transactions when revenue is absent', () => {
+ // A property tracking purchases without passing a value still knows what
+ // sold; ranking on engagement there would ignore real conversions.
+ expect(pickValueSignal([page({ transactions: 2, keyEvents: 5 })])).toBe('transactions');
+ });
+
+ it('falls to key events when nothing was purchased', () => {
+ // Lead-generation sites: no ecommerce at all, but signups and demo
+ // requests are exactly what "valuable" means for them.
+ expect(pickValueSignal([page({ keyEvents: 4 })])).toBe('key_events');
+ });
+
+ it('falls to engagement when the property reports no conversions at all', () => {
+ // The state of the only property connected today. Without this fallback
+ // the engine would tell a customer there is nothing to look at, when what
+ // is actually missing is their conversion tracking.
+ expect(pickValueSignal([page()])).toBe('engagement');
+ });
+
+ it('picks the strongest signal present anywhere, not on the first page', () => {
+ const pages = [page({ landingPage: '/a' }), page({ landingPage: '/b', revenue: 5 })];
+ expect(pickValueSignal(pages)).toBe('revenue');
+ });
+
+ it('ignores a signal that is present but always zero', () => {
+ expect(pickValueSignal([page({ revenue: 0, transactions: 0, keyEvents: 7 })])).toBe(
+ 'key_events',
+ );
+ });
+
+ it('handles an empty page list', () => {
+ expect(pickValueSignal([])).toBe('engagement');
+ expect(pickValueSignal(undefined)).toBe('engagement');
+ });
+});
+
+describe('scorePages', () => {
+ it('ranks by the chosen signal, best first', () => {
+ const scored = scorePages(
+ [
+ page({ landingPage: '/low', revenue: 10 }),
+ page({ landingPage: '/high', revenue: 900 }),
+ page({ landingPage: '/mid', revenue: 100 }),
+ ],
+ 'revenue',
+ );
+ expect(scored.map((p) => p.landingPage)).toEqual(['/high', '/mid', '/low']);
+ expect(scored[0].valueRank).toBe(1);
+ });
+
+ it('puts the top page at 100 and the bottom at 0', () => {
+ const scored = scorePages(
+ [page({ landingPage: '/a', revenue: 1 }), page({ landingPage: '/b', revenue: 2 })],
+ 'revenue',
+ );
+ expect(scored[0].valuePercentile).toBe(50);
+ expect(scored[1].valuePercentile).toBe(0);
+ });
+
+ it('gives tied pages the same percentile', () => {
+ // Two pages with identical revenue must not be separated by whichever
+ // happened to sort first — the percentile is a claim about the data.
+ const scored = scorePages(
+ [
+ page({ landingPage: '/a', revenue: 50 }),
+ page({ landingPage: '/b', revenue: 50 }),
+ page({ landingPage: '/c', revenue: 1 }),
+ ],
+ 'revenue',
+ );
+ const [a, b] = scored;
+ expect(a.valuePercentile).toBe(b.valuePercentile);
+ });
+
+ it('scores a single page as the top of its own site', () => {
+ const [only] = scorePages([page({ revenue: 5 })], 'revenue');
+ expect(only.valuePercentile).toBe(100);
+ expect(only.valueRank).toBe(1);
+ });
+
+ it('breaks ties on sessions so the order is stable, not arbitrary', () => {
+ const scored = scorePages(
+ [
+ page({ landingPage: '/quiet', revenue: 50, sessions: 10 }),
+ page({ landingPage: '/busy', revenue: 50, sessions: 900 }),
+ ],
+ 'revenue',
+ );
+ expect(scored[0].landingPage).toBe('/busy');
+ });
+});
+
+describe('detectPageOpportunities', () => {
+ // Ten pages so percentiles are meaningful: /top is the best earner.
+ const many = (over) =>
+ Array.from({ length: 10 }, (_, i) =>
+ page({ landingPage: `/p${i}`, revenue: i + 1, sessions: 100, ...over }),
+ );
+
+ it('raises a valuable page with no AI traffic', () => {
+ const found = detectPageOpportunities({ pages: many(), aiByPage: new Map() });
+ expect(found.length).toBeGreaterThan(0);
+ expect(found[0].kind).toBe('no_ai_traffic');
+ expect(found[0].value_signal).toBe('revenue');
+ });
+
+ it('does not raise a page AI engines already send traffic to', () => {
+ const pages = many();
+ const top = pages[pages.length - 1].landingPage;
+ const found = detectPageOpportunities({
+ pages,
+ aiByPage: new Map([[top, { sessions: 4, platforms: ['chatgpt.com'] }]]),
+ });
+ expect(found.map((f) => f.landing_page)).not.toContain(top);
+ });
+
+ it('ignores a page with too little traffic to argue from', () => {
+ // The absolute floor. A page can rank first on its site and still be one
+ // visit; raising it would be a finding about nothing.
+ const pages = [page({ landingPage: '/tiny', revenue: 999, sessions: 2 })];
+ expect(detectPageOpportunities({ pages, aiByPage: new Map() })).toEqual([]);
+ });
+
+ it('ignores a page with no value on the chosen signal', () => {
+ const pages = [
+ ...many(),
+ page({ landingPage: '/zero', revenue: 0, sessions: 5000, engagementSeconds: 99999 }),
+ ];
+ const found = detectPageOpportunities({ pages, aiByPage: new Map() });
+ expect(found.map((f) => f.landing_page)).not.toContain('/zero');
+ });
+
+ it('raises fewer findings on a site with less to fix, not the same fraction', () => {
+ // The percentile alone would qualify a constant share of any site. The
+ // session floor is what makes the count follow the site, so a brand with
+ // one real page gets one finding rather than a list padded to length.
+ const busy = many();
+ const quiet = [
+ page({ landingPage: '/one', revenue: 10, sessions: 50 }),
+ ...Array.from({ length: 9 }, (_, i) =>
+ page({ landingPage: `/q${i}`, revenue: 1, sessions: 2 }),
+ ),
+ ];
+ const busyFound = detectPageOpportunities({ pages: busy, aiByPage: new Map() });
+ const quietFound = detectPageOpportunities({ pages: quiet, aiByPage: new Map() });
+ expect(quietFound.length).toBeLessThan(busyFound.length);
+ expect(quietFound).toHaveLength(1);
+ });
+
+ it('falls back to engagement and says so, for a property without conversions', () => {
+ // The live case: the finding must be labelled 'engagement' so no surface
+ // can describe it as revenue.
+ const pages = Array.from({ length: 10 }, (_, i) =>
+ page({ landingPage: `/e${i}`, engagementSeconds: (i + 1) * 100 }),
+ );
+ const found = detectPageOpportunities({ pages, aiByPage: new Map() });
+ expect(found.length).toBeGreaterThan(0);
+ expect(found.every((f) => f.value_signal === 'engagement')).toBe(true);
+ expect(found.every((f) => f.revenue === 0)).toBe(true);
+ });
+
+ it('carries the evidence the finding was raised from', () => {
+ const found = detectPageOpportunities({
+ pages: many({ engagedSessions: 40, keyEvents: 3, transactions: 2 }),
+ aiByPage: new Map(),
+ });
+ const top = found[0];
+ expect(top.sessions).toBe(100);
+ expect(top.engaged_sessions).toBe(40);
+ expect(top.ai_sessions).toBe(0);
+ expect(top.window_days).toBe(28);
+ });
+
+ it('returns nothing for a brand with no pages', () => {
+ expect(detectPageOpportunities({ pages: [], aiByPage: new Map() })).toEqual([]);
+ });
+});
+
+describe('aggregatePages', () => {
+ it('sums a page across its daily rows', () => {
+ const rows = [
+ { landing_page: '/a', sessions: 3, purchase_revenue: 10.5, key_events: 1 },
+ { landing_page: '/a', sessions: 4, purchase_revenue: 4.5, key_events: 0 },
+ ];
+ const [a] = aggregatePages(rows);
+ expect(a.sessions).toBe(7);
+ expect(a.revenue).toBe(15);
+ expect(a.keyEvents).toBe(1);
+ });
+
+ it('drops rows GA could not attribute to a page', () => {
+ expect(aggregatePages([{ landing_page: '', sessions: 9 }])).toEqual([]);
+ });
+
+ it('treats missing metrics as zero rather than NaN', () => {
+ const [a] = aggregatePages([{ landing_page: '/a' }]);
+ expect(a.sessions).toBe(0);
+ expect(a.revenue).toBe(0);
+ });
+});
+
+describe('aggregateAiTraffic', () => {
+ it('sums AI sessions and collects the platforms per page', () => {
+ const map = aggregateAiTraffic([
+ { landing_page: '/a', platform: 'chatgpt.com', sessions: 3 },
+ { landing_page: '/a', platform: 'claude.ai', sessions: 2 },
+ ]);
+ expect(map.get('/a').sessions).toBe(5);
+ expect(map.get('/a').platforms.sort()).toEqual(['chatgpt.com', 'claude.ai']);
+ });
+
+ it('counts sessions from an unclassified source, which still arrived', () => {
+ const map = aggregateAiTraffic([{ landing_page: '/a', platform: null, sessions: 4 }]);
+ expect(map.get('/a').sessions).toBe(4);
+ expect(map.get('/a').platforms).toEqual([]);
+ });
+});
diff --git a/server/src/lib/page-paths.js b/server/src/lib/page-paths.js
new file mode 100644
index 000000000..bfa0d699f
--- /dev/null
+++ b/server/src/lib/page-paths.js
@@ -0,0 +1,85 @@
+/**
+ * Which landing pages can carry an AI-visibility opportunity at all (#705,
+ * #719).
+ *
+ * Shared because both surfaces ask the same question and would otherwise
+ * answer it differently: the suggestion generator needs "could a prompt lead
+ * someone here", and the detection engine needs "is this page worth raising".
+ * A page that fails one fails the other, and two copies of this list would
+ * drift the first time either is extended.
+ *
+ * Two groups, excluded for different reasons:
+ *
+ * Transactional — checkout, cart, confirmation, login, account. A GA4
+ * purchase event fires on the confirmation page, so without this the
+ * highest-revenue "page" in most shops is /checkout, and no prompt exists
+ * that a person would ask an assistant in order to arrive there.
+ *
+ * Non-commercial — careers, legal, privacy. These take real traffic and
+ * real engagement, so they rank, but AI visibility on a job posting does
+ * not move the business the product is measuring. Leaving them in fills
+ * the list with findings nobody will act on.
+ */
+
+const EXCLUDED_SEGMENTS = new Set([
+ // Transactional
+ 'checkout',
+ 'cart',
+ 'basket',
+ 'order',
+ 'orders',
+ 'order-confirmation',
+ 'confirmation',
+ 'thank-you',
+ 'thanks',
+ 'payment',
+ 'pay',
+ 'login',
+ 'signin',
+ 'sign-in',
+ 'signup',
+ 'sign-up',
+ 'register',
+ 'logout',
+ 'account',
+ 'my-account',
+ 'profile',
+ 'dashboard',
+ 'admin',
+ 'wishlist',
+ 'favorites',
+ 'search',
+ // Non-commercial
+ 'career',
+ 'careers',
+ 'jobs',
+ 'job',
+ 'cookie-policy',
+ 'privacy',
+ 'privacy-policy',
+ 'terms',
+ 'terms-of-service',
+ 'legal',
+ 'unsubscribe',
+]);
+
+/**
+ * True for a page that cannot carry an opportunity.
+ *
+ * Matched on whole path segments, never as a substring: `/cart` is excluded
+ * while `/cartography-guides` is kept, and `/careers` while
+ * `/blog/career-advice-for-analysts` is kept. A substring check would delete
+ * real content silently, which is the worst way to be wrong here.
+ *
+ * GA4's own placeholders count as excluded: a blank or "(not set)" landing
+ * page is an unattributed session, not a page anyone can be sent to.
+ */
+export function isExcludedPath(path) {
+ const raw = String(path ?? '').trim();
+ if (!raw || raw === '(not set)' || raw === '(other)') return true;
+ return raw
+ .split(/[?#]/)[0]
+ .split('/')
+ .filter(Boolean)
+ .some((segment) => EXCLUDED_SEGMENTS.has(segment.toLowerCase()));
+}
diff --git a/server/src/lib/page-paths.test.js b/server/src/lib/page-paths.test.js
new file mode 100644
index 000000000..170e2aed0
--- /dev/null
+++ b/server/src/lib/page-paths.test.js
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest';
+
+import { isExcludedPath } from './page-paths.js';
+
+/**
+ * Page scope (#705, #719).
+ *
+ * Shared by the suggestion generator and the detection engine, so a mistake
+ * here is a mistake in two places at once — and both failure directions are
+ * costly: excluding too much deletes real content silently, excluding too
+ * little fills the customer's list with pages nobody will act on.
+ */
+
+describe('isExcludedPath', () => {
+ it('excludes transactional pages', () => {
+ // A GA4 purchase fires on the confirmation page, so without this the
+ // top-revenue "page" in most shops is the checkout.
+ for (const path of [
+ '/checkout',
+ '/cart/',
+ '/en/order-confirmation',
+ '/thank-you',
+ '/account/orders',
+ '/login',
+ ]) {
+ expect(isExcludedPath(path), path).toBe(true);
+ }
+ });
+
+ it('excludes pages whose AI visibility cannot move the business', () => {
+ // These take real traffic and rank on engagement, so they surface unless
+ // excluded — but nobody acts on "your job posting is invisible to AI".
+ for (const path of ['/career/visual-designer', '/careers', '/jobs/backend', '/privacy']) {
+ expect(isExcludedPath(path), path).toBe(true);
+ }
+ });
+
+ it('matches whole segments, never substrings', () => {
+ // The dangerous direction: a substring check would delete real content
+ // and nobody would notice it had gone.
+ expect(isExcludedPath('/cartography-guides')).toBe(false);
+ expect(isExcludedPath('/blog/career-advice-for-analysts')).toBe(false);
+ expect(isExcludedPath('/blog/accountability-in-ai')).toBe(false);
+ expect(isExcludedPath('/products/searchlight-3000')).toBe(false);
+ });
+
+ it('excludes GA placeholders and blanks, which are not pages', () => {
+ expect(isExcludedPath('')).toBe(true);
+ expect(isExcludedPath('(not set)')).toBe(true);
+ expect(isExcludedPath(undefined)).toBe(true);
+ });
+
+ it('keeps ordinary content, category and marketing pages', () => {
+ for (const path of ['/', '/pricing', '/compare', '/features/insights', '/blog/a-guide']) {
+ expect(isExcludedPath(path), path).toBe(false);
+ }
+ });
+
+ it('ignores a query string when deciding', () => {
+ expect(isExcludedPath('/checkout?step=2')).toBe(true);
+ expect(isExcludedPath('/pricing?ref=ai')).toBe(false);
+ });
+});
diff --git a/server/src/server.js b/server/src/server.js
index cd632a082..1ab0cfb78 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -32,6 +32,7 @@ import { getPlan, hasFeature, isCloud, isSubscriptionActive } from './config/pla
import { analyzeBrandVolumes } from './lib/volume-analysis.js';
import { runGscSync } from './lib/gsc-sync.js';
import { runGaSync } from './lib/ga-sync.js';
+import { runPageOpportunityDetection } from './lib/page-opportunities.js';
import { runPulseCatchUp } from './lib/pulse/engine.js';
const app = express();
@@ -190,9 +191,20 @@ async function runDailyTracking() {
// Google Analytics sync (#704) — same contract as the Search Console sync
// above: independent, never blocks or fails the tracking run, no-ops when
// Composio or the Analytics auth config isn't set.
- runGaSync().catch((err) => {
- logger.error({ err }, '[ga-sync] daily run failed');
- });
+ //
+ // Page opportunity detection (#719) is chained onto it rather than fired
+ // alongside: it reads the tables the sync writes, so running the two
+ // concurrently would score yesterday's window. A sync failure skips
+ // detection instead of letting it publish findings from stale data.
+ runGaSync()
+ .then(() =>
+ runPageOpportunityDetection().catch((err) => {
+ logger.error({ err }, '[page-opportunities] daily run failed');
+ }),
+ )
+ .catch((err) => {
+ logger.error({ err }, '[ga-sync] daily run failed');
+ });
return { triggered, total: brands.length };
}
diff --git a/supabase/migrations/00056_page_opportunities.sql b/supabase/migrations/00056_page_opportunities.sql
new file mode 100644
index 000000000..4b3802ffd
--- /dev/null
+++ b/supabase/migrations/00056_page_opportunities.sql
@@ -0,0 +1,78 @@
+-- Page opportunities: valuable pages AI engines are not sending traffic to
+-- (#719, Phase 5 detection).
+--
+-- Named for its key, not just its subject, because content_opportunities
+-- already exists and means something different. That table is prompt-keyed
+-- and LLM-written: "what content should I make, given prompts where I am
+-- weak". This one is page-keyed and deterministic: "which of my pages earn,
+-- and get nothing from AI". A reader can tell them apart by the key in the
+-- name, and a surface can show them together later without either having to
+-- pretend to be the other.
+--
+-- Detection is pure SQL and JavaScript arithmetic — no model runs in this
+-- path. Enrichment, clustering and the full lifecycle are deliberately not
+-- here; they need volume this has not produced yet.
+--
+-- One row per (brand, page, kind), upserted daily. A finding that stops
+-- qualifying is stamped resolved_at rather than deleted, so the list can show
+-- that something improved instead of silently shrinking.
+
+CREATE TABLE public.page_opportunities (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
+ landing_page text NOT NULL,
+ kind text NOT NULL,
+
+ -- Which signal ranked this page, and where it ranked. Stored rather than
+ -- inferred because the answer differs per property: a shop is ranked on
+ -- money, a site with no ecommerce and no conversion events on engagement.
+ -- Every surface must say which one it used — calling an engagement rank
+ -- "your most valuable page" would be a true sentence about the wrong
+ -- thing.
+ value_signal text NOT NULL,
+ value_percentile numeric NOT NULL,
+ value_rank integer NOT NULL,
+
+ -- The figures the finding was raised from, so it can be explained and
+ -- audited without recomputing the window.
+ sessions integer NOT NULL DEFAULT 0,
+ engaged_sessions integer NOT NULL DEFAULT 0,
+ key_events integer NOT NULL DEFAULT 0,
+ transactions integer NOT NULL DEFAULT 0,
+ revenue double precision NOT NULL DEFAULT 0,
+ engagement_seconds integer NOT NULL DEFAULT 0,
+ ai_sessions integer NOT NULL DEFAULT 0,
+ ai_platforms text[] NOT NULL DEFAULT '{}',
+
+ window_days integer NOT NULL,
+ first_detected_at timestamptz NOT NULL DEFAULT now(),
+ last_detected_at timestamptz NOT NULL DEFAULT now(),
+ resolved_at timestamptz,
+
+ CONSTRAINT page_opportunities_kind_check
+ CHECK (kind = ANY (ARRAY['no_ai_traffic'::text])),
+ CONSTRAINT page_opportunities_signal_check
+ CHECK (value_signal = ANY (ARRAY[
+ 'revenue'::text, 'transactions'::text, 'key_events'::text, 'engagement'::text
+ ])),
+ UNIQUE (brand_id, landing_page, kind)
+);
+
+-- The list surface reads open findings for one brand, worst gap first.
+CREATE INDEX page_opportunities_brand_open_idx
+ ON public.page_opportunities (brand_id, value_percentile DESC)
+ WHERE resolved_at IS NULL;
+
+ALTER TABLE public.page_opportunities ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "page_opportunities: member select" ON public.page_opportunities
+ FOR SELECT USING (
+ brand_id IN (
+ SELECT b.id
+ FROM public.brands b
+ JOIN public.profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
+
+GRANT SELECT ON public.page_opportunities TO authenticated;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index e899235ea..989eb04d5 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -5524,3 +5524,85 @@ $$;
GRANT EXECUTE ON FUNCTION public.prompt_visibility_summaries(uuid, timestamptz, timestamptz)
TO authenticated;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00056_page_opportunities.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Page opportunities: valuable pages AI engines are not sending traffic to
+-- (#719, Phase 5 detection).
+--
+-- Named for its key, not just its subject, because content_opportunities
+-- already exists and means something different. That table is prompt-keyed
+-- and LLM-written: "what content should I make, given prompts where I am
+-- weak". This one is page-keyed and deterministic: "which of my pages earn,
+-- and get nothing from AI". A reader can tell them apart by the key in the
+-- name, and a surface can show them together later without either having to
+-- pretend to be the other.
+--
+-- Detection is pure SQL and JavaScript arithmetic — no model runs in this
+-- path. Enrichment, clustering and the full lifecycle are deliberately not
+-- here; they need volume this has not produced yet.
+--
+-- One row per (brand, page, kind), upserted daily. A finding that stops
+-- qualifying is stamped resolved_at rather than deleted, so the list can show
+-- that something improved instead of silently shrinking.
+
+CREATE TABLE public.page_opportunities (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
+ landing_page text NOT NULL,
+ kind text NOT NULL,
+
+ -- Which signal ranked this page, and where it ranked. Stored rather than
+ -- inferred because the answer differs per property: a shop is ranked on
+ -- money, a site with no ecommerce and no conversion events on engagement.
+ -- Every surface must say which one it used — calling an engagement rank
+ -- "your most valuable page" would be a true sentence about the wrong
+ -- thing.
+ value_signal text NOT NULL,
+ value_percentile numeric NOT NULL,
+ value_rank integer NOT NULL,
+
+ -- The figures the finding was raised from, so it can be explained and
+ -- audited without recomputing the window.
+ sessions integer NOT NULL DEFAULT 0,
+ engaged_sessions integer NOT NULL DEFAULT 0,
+ key_events integer NOT NULL DEFAULT 0,
+ transactions integer NOT NULL DEFAULT 0,
+ revenue double precision NOT NULL DEFAULT 0,
+ engagement_seconds integer NOT NULL DEFAULT 0,
+ ai_sessions integer NOT NULL DEFAULT 0,
+ ai_platforms text[] NOT NULL DEFAULT '{}',
+
+ window_days integer NOT NULL,
+ first_detected_at timestamptz NOT NULL DEFAULT now(),
+ last_detected_at timestamptz NOT NULL DEFAULT now(),
+ resolved_at timestamptz,
+
+ CONSTRAINT page_opportunities_kind_check
+ CHECK (kind = ANY (ARRAY['no_ai_traffic'::text])),
+ CONSTRAINT page_opportunities_signal_check
+ CHECK (value_signal = ANY (ARRAY[
+ 'revenue'::text, 'transactions'::text, 'key_events'::text, 'engagement'::text
+ ])),
+ UNIQUE (brand_id, landing_page, kind)
+);
+
+-- The list surface reads open findings for one brand, worst gap first.
+CREATE INDEX page_opportunities_brand_open_idx
+ ON public.page_opportunities (brand_id, value_percentile DESC)
+ WHERE resolved_at IS NULL;
+
+ALTER TABLE public.page_opportunities ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "page_opportunities: member select" ON public.page_opportunities
+ FOR SELECT USING (
+ brand_id IN (
+ SELECT b.id
+ FROM public.brands b
+ JOIN public.profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
+
+GRANT SELECT ON public.page_opportunities TO authenticated;
+