Skip to content

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

feat(action-center): say what sets the brand's winning pages apart from its other pages (learning C4) (#1742)

Cihane71d2c753a49
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdx
index 12b5731bd..a88d5c44f 100644
--- a/docs/guides/action-center.mdx
+++ b/docs/guides/action-center.mdx
@@ -112,6 +112,8 @@ Some tasks that only read data, such as checking a page's traffic in your connec
**Analyze competitor content** is one of the tasks Ansvisor carries out itself. Overnight, it reads the pages AI answers cited for the action's prompts in the last two weeks: up to three, your competitors' pages first, then pages cited in answers that don't name your brand. It reads your own page cited there too, and runs Site Audit's checks on them all (structure, FAQ, schema, statistics, dates, length). The task then says which checks at least half of their pages pass that yours doesn't; it takes at least two of their pages to compare. Where the action names no prompts, it reads its topic's prompts, or for an action about competitors or sources, the prompts you track. Pages are read for free from their public address, at most 12 a day for a brand, never from a site whose robots.txt keeps crawlers out, and only what the checks found is kept, never the page's text. When there is nothing to compare (no prompts, no page cited, or none could be read), the task stays open for you with the reason, and Ansvisor tries again a week later.
+**Find what sets your winning pages apart** is another. It's part of **Scale Proven AI Landing Pages** (your AI landing pages that convert well above your site) and **Strengthen Emerging Content** (prompts whose visibility is rising), on brands with Site Audits. Overnight, it takes up to three winning pages, the action's landing pages or your pages cited in its prompts' answers in the last two weeks, and compares them with up to 30 of your other pages that Site Audit checked in the last 90 days. It lists the checks most of your winning pages pass and most of your other pages don't (FAQ, tables, statistics, author, dates, length…), and up to five of your pages missing the most of them: where what works on your site can go next. Your other pages are read from their audits only, never fetched again. A winning page without a recent audit is read from its public address within the same 12 reads a day, and only what the checks found is kept. Nothing is compared with another brand's pages. With fewer than three of your other pages audited, the task stays open for you with the reason, and Ansvisor tries again a week later. Actions opened before this task existed keep their tasks; new ones get it.
+
### Assigning work
An action with no one on it belongs to **Everyone** in the workspace until someone takes it. Pick a teammate in the action's **Assignee** field, and set a **Due date** if it has one. The **Assignee** filter on the Actions tab shows one person's actions, or **Everyone** for the unassigned ones.
diff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.js
index c597e62d6..b7ceb0101 100644
--- a/server/src/config/action-engine.js
+++ b/server/src/config/action-engine.js
@@ -434,6 +434,28 @@ export const ENGINE_THRESHOLDS = Object.freeze({
minPages: 2,
retryDays: 7,
}),
+
+ /**
+ * What the "Analyze your winning pages" task compares (learning C4): at
+ * most `perAction` of the action's winning pages (G14's landing pages, or
+ * G10's own pages its prompts' answers cite) with the brand's other pages
+ * that have a completed Site Audit from the last `auditDays`, at most
+ * `others` of them, the newest audit first. Those are read from their
+ * audits, never fetched. A winning page without one is read like a cited
+ * page (competitorPages' reader): within the same `perBrandPerDay` reads
+ * and reused while `freshDays` old. Fewer than `minOthers` other pages and
+ * nothing is compared: the task stays a person's and tries again after
+ * `retryDays`. The `missingPages` other pages missing the most of what the
+ * winners have are listed.
+ */
+ winningPages: Object.freeze({
+ perAction: 3,
+ auditDays: 90,
+ others: 30,
+ minOthers: 3,
+ missingPages: 5,
+ retryDays: 7,
+ }),
});
/**
diff --git a/server/src/lib/action-center/competitor-pages.js b/server/src/lib/action-center/competitor-pages.js
index 6f41923ca..824bc493a 100644
--- a/server/src/lib/action-center/competitor-pages.js
+++ b/server/src/lib/action-center/competitor-pages.js
@@ -79,7 +79,8 @@ const onDomain = (host, domain) => host === domain || host.endsWith(`.${domain}`
/**
* The pages to read from the answers: the competitors' most cited first, then
* the most cited in answers that don't name the brand, at most `perAction`;
- * and the brand's own page most cited there.
+ * and the brand's own page most cited there (`yours`), with all its own pages
+ * cited, the most cited first (`own`: learning C4's winning pages).
*
* @param {Array<{ mention_count?: number, citations?: Array<{ url?: string }> }>} answers
* @param {{ ownDomains: string[], competitorDomains: string[], perAction?: number }} options
@@ -112,7 +113,8 @@ export function citedPages(answers, { ownDomains, competitorDomains, perAction =
const ranked = (map) =>
[...map.values()].sort((a, b) => b.count - a.count || a.key.localeCompare(b.key));
const competitors = [...ranked(tally.rival), ...ranked(tally.other)].slice(0, perAction);
- return { competitors, yours: ranked(tally.own)[0] ?? null };
+ const ownPages = ranked(tally.own);
+ return { competitors, yours: ownPages[0] ?? null, own: ownPages };
}
const passing = (checks) => FEATURE_CHECKS.filter((key) => checks?.[key] === 'pass');
@@ -182,66 +184,20 @@ export async function scopePromptIds(brandId, payload) {
}
/**
- * The "Analyze competitor content" task's result: the competitor pages read,
- * the brand's, and the checks the first pass that the second doesn't.
- *
- * It throws ReadLaterError when it can't give one: the day's reads left
- * can't cover the pages (the next night), or there is nothing to compare —
- * no prompts, no page cited, none readable (`retryDays`, the reason as the
- * task's output).
+ * Each page's features, set on it as `features` when it could be read: one
+ * read (or found unreadable) within `freshDays` is reused, the rest are read
+ * now, unless their site's robots.txt shuts the reader out, and kept
+ * (cited_page_features) with what the checks found, never the text. All of
+ * the pages are read the same night, or none: ReadLaterError when the
+ * brand's reads left today (`perBrandPerDay`, shared by every task that
+ * reads pages: C1's and C4's) can't cover them.
*
- * @param {{ brandId: string, payload: object, now?: Date, read?: typeof fetchPage }} input
- * read: the page reader, for tests
+ * @param {{ brandId: string,
+ * pages: Array<{ key: string, url: string, domain: string, own?: boolean, features?: object }>,
+ * now: Date, read: typeof fetchPage }} input
*/
-export async function analyzeCompetitorPages({
- brandId,
- payload,
- now = new Date(),
- read = fetchPage,
-}) {
- const nothing = (reason, message, found = {}) =>
- new ReadLaterError(message, {
- output: {
- competitorPages: [],
- yourPage: null,
- gaps: [],
- unreadable: 0,
- ...found,
- reason,
- },
- retryDays: C.retryDays,
- });
-
- const promptIds = await scopePromptIds(brandId, payload);
- if (promptIds.length === 0) throw nothing('no_prompts', 'no prompts to read the answers of');
-
- const since = new Date(now.getTime() - C.answersDays * DAY_MS).toISOString();
- const [answersRes, domainsRes, competitorsRes] = await Promise.all([
- supabaseAdmin
- .from('prompt_results')
- .select('mention_count, citations')
- .eq('brand_id', brandId)
- .neq('platform', 'chatgpt-shopping')
- .in('prompt_id', promptIds)
- .gte('created_at', since)
- .order('created_at', { ascending: false })
- .limit(ANSWERS_READ),
- supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brandId),
- supabaseAdmin.from('competitors').select('domain').eq('brand_id', brandId),
- ]);
- for (const res of [answersRes, domainsRes, competitorsRes]) {
- if (res.error) throw new Error(res.error.message);
- }
- const picked = citedPages(answersRes.data ?? [], {
- ownDomains: (domainsRes.data ?? []).map((row) => row.domain).filter(Boolean),
- competitorDomains: (competitorsRes.data ?? []).map((row) => row.domain).filter(Boolean),
- });
- if (picked.competitors.length === 0) {
- throw nothing('none_cited', 'no competitor page cited for these prompts lately');
- }
-
- // What was read lately is reused, a page found unreadable too.
- const pages = [...picked.competitors, ...(picked.yours ? [{ ...picked.yours, own: true }] : [])];
+export async function readPages({ brandId, pages, now, read = fetchPage }) {
+ if (pages.length === 0) return;
const [knownRes, todayRes] = await Promise.all([
supabaseAdmin
.from('cited_page_features')
@@ -265,8 +221,7 @@ export async function analyzeCompetitorPages({
.filter((row) => Date.parse(row.read_at) >= freshSince)
.map((row) => [row.page_key, row.features ?? {}]),
);
- // All of an action's pages are read the same night, or none: a run that
- // read some would compare a part, and its task wouldn't run again.
+ // A run that read some would compare a part, and its task wouldn't run again.
const toRead = pages.filter((page) => !fresh.has(page.key)).length;
if (toRead > C.perBrandPerDay - (todayRes.count ?? 0)) {
throw new ReadLaterError("the brand's page reads for today can't cover this action's");
@@ -311,6 +266,69 @@ export async function analyzeCompetitorPages({
logger.warn({ err: error, brandId, page: page.key }, '[competitor-pages] read not kept');
}
}
+}
+
+/**
+ * The "Analyze competitor content" task's result: the competitor pages read,
+ * the brand's, and the checks the first pass that the second doesn't.
+ *
+ * It throws ReadLaterError when it can't give one: the day's reads left
+ * can't cover the pages (the next night), or there is nothing to compare —
+ * no prompts, no page cited, none readable (`retryDays`, the reason as the
+ * task's output).
+ *
+ * @param {{ brandId: string, payload: object, now?: Date, read?: typeof fetchPage }} input
+ * read: the page reader, for tests
+ */
+export async function analyzeCompetitorPages({
+ brandId,
+ payload,
+ now = new Date(),
+ read = fetchPage,
+}) {
+ const nothing = (reason, message, found = {}) =>
+ new ReadLaterError(message, {
+ output: {
+ competitorPages: [],
+ yourPage: null,
+ gaps: [],
+ unreadable: 0,
+ ...found,
+ reason,
+ },
+ retryDays: C.retryDays,
+ });
+
+ const promptIds = await scopePromptIds(brandId, payload);
+ if (promptIds.length === 0) throw nothing('no_prompts', 'no prompts to read the answers of');
+
+ const since = new Date(now.getTime() - C.answersDays * DAY_MS).toISOString();
+ const [answersRes, domainsRes, competitorsRes] = await Promise.all([
+ supabaseAdmin
+ .from('prompt_results')
+ .select('mention_count, citations')
+ .eq('brand_id', brandId)
+ .neq('platform', 'chatgpt-shopping')
+ .in('prompt_id', promptIds)
+ .gte('created_at', since)
+ .order('created_at', { ascending: false })
+ .limit(ANSWERS_READ),
+ supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brandId),
+ supabaseAdmin.from('competitors').select('domain').eq('brand_id', brandId),
+ ]);
+ for (const res of [answersRes, domainsRes, competitorsRes]) {
+ if (res.error) throw new Error(res.error.message);
+ }
+ const picked = citedPages(answersRes.data ?? [], {
+ ownDomains: (domainsRes.data ?? []).map((row) => row.domain).filter(Boolean),
+ competitorDomains: (competitorsRes.data ?? []).map((row) => row.domain).filter(Boolean),
+ });
+ if (picked.competitors.length === 0) {
+ throw nothing('none_cited', 'no competitor page cited for these prompts lately');
+ }
+
+ const pages = [...picked.competitors, ...(picked.yours ? [{ ...picked.yours, own: true }] : [])];
+ await readPages({ brandId, pages, now, read });
const unreadable = pages.filter((page) => !page.features).length;
const competitorPages = pages
diff --git a/server/src/lib/action-center/definitions/g10-strengthen-emerging-content.js b/server/src/lib/action-center/definitions/g10-strengthen-emerging-content.js
index 1d9fd9dfa..45fe413b5 100644
--- a/server/src/lib/action-center/definitions/g10-strengthen-emerging-content.js
+++ b/server/src/lib/action-center/definitions/g10-strengthen-emerging-content.js
@@ -9,7 +9,7 @@ import { targetPayload } from './_helpers.js';
export default {
id: 'strengthen_emerging_content',
code: 'G10',
- version: 1,
+ version: 2,
category: 'growth',
name: 'Strengthen Emerging Content',
signalKinds: ['prompt_gain'],
@@ -20,6 +20,8 @@ export default {
'identify_target_pages',
'analyze_visibility_change',
'analyze_citations',
+ // Learning C4: what its winning pages have that the brand's others don't.
+ 'analyze_winning_pages',
'identify_content_gaps',
'optimize_content',
'add_internal_links',
diff --git a/server/src/lib/action-center/definitions/g14-scale-ai-landing-pages.js b/server/src/lib/action-center/definitions/g14-scale-ai-landing-pages.js
index df706dc57..e494bbf83 100644
--- a/server/src/lib/action-center/definitions/g14-scale-ai-landing-pages.js
+++ b/server/src/lib/action-center/definitions/g14-scale-ai-landing-pages.js
@@ -9,7 +9,7 @@ import { targetPayload } from './_helpers.js';
export default {
id: 'scale_ai_landing_pages',
code: 'G14',
- version: 1,
+ version: 2,
category: 'growth',
name: 'Scale Proven AI Landing Pages',
signalKinds: ['ai_landing_page_winner'],
@@ -20,6 +20,8 @@ export default {
'analyze_ai_traffic',
'analyze_ga4_outcomes',
'identify_target_pages',
+ // Learning C4: what its winning pages have that the brand's others don't.
+ 'analyze_winning_pages',
'analyze_prompt_gap',
'identify_content_gaps',
{ branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
diff --git a/server/src/lib/action-center/execution/tools.js b/server/src/lib/action-center/execution/tools.js
index 8e25e1f45..f9b7e9da6 100644
--- a/server/src/lib/action-center/execution/tools.js
+++ b/server/src/lib/action-center/execution/tools.js
@@ -34,6 +34,7 @@ import supabaseAdmin from '../../../config/supabase.js';
import { runGaReport } from '../../composio.js';
import { resolve } from '../../../config/action-engine.js';
import { analyzeCompetitorPages } from '../competitor-pages.js';
+import { analyzeWinningPages } from '../winning-pages.js';
const DAY_MS = 86_400_000;
@@ -67,6 +68,21 @@ export const TOOLS = Object.freeze({
},
}),
+ /**
+ * What the brand's winning pages have that its other pages don't (learning
+ * C4): through Site Audit's rule checks, the other pages from their audits,
+ * a winning page without one read free like a cited page. Reading changes
+ * nothing, so no approval.
+ */
+ winning_page_features: tool('winning_page_features', {
+ source: 'site_audits',
+ description: "What the brand's winning pages have that its other audited pages don't.",
+
+ async run({ brandId, payload, now }) {
+ return analyzeWinningPages({ brandId, payload, now });
+ },
+ }),
+
/**
* The AI Visibility Score over the validation window and the one before it
* — what `validate` asks for, read from the daily rollups rather than the
diff --git a/server/src/lib/action-center/tasks/plan.test.js b/server/src/lib/action-center/tasks/plan.test.js
index edf669c32..9f1ce5249 100644
--- a/server/src/lib/action-center/tasks/plan.test.js
+++ b/server/src/lib/action-center/tasks/plan.test.js
@@ -182,8 +182,13 @@ describe('planTasks', () => {
});
describe('the task registry', () => {
- it('holds the specification’s sixty-two task primitives', () => {
- expect(libraryTasks()).toHaveLength(62);
+ it('holds the specification’s sixty-two task primitives, and learning C4’s', () => {
+ expect(libraryTasks()).toHaveLength(63);
+ expect(TASKS.analyze_winning_pages).toMatchObject({
+ mode: 'system',
+ requires: ['site_audits'],
+ tool: 'winning_page_features',
+ });
});
it.each(listTasks().map((entry) => [entry.id, entry]))('%s is well formed', (_id, entry) => {
diff --git a/server/src/lib/action-center/tasks/registry.js b/server/src/lib/action-center/tasks/registry.js
index 98c36a310..b273e2f3a 100644
--- a/server/src/lib/action-center/tasks/registry.js
+++ b/server/src/lib/action-center/tasks/registry.js
@@ -2,7 +2,8 @@
* The task registry (#818).
*
* The shared Task Library of the V1 specification: sixty-two primitives with
- * stable ids, which every definition builds its plan from. An action tells the
+ * stable ids, which every definition builds its plan from, and one added
+ * since (learning C4's analyze_winning_pages). An action tells the
* user what to achieve; its tasks say how, and a task is one of these.
*
* Each primitive declares, in the specification's terms:
@@ -171,6 +172,13 @@ export const TASKS = Object.freeze({
requires: ['site_audits'],
outputs: ['failingSignals'],
}),
+ // Learning C4: what the brand's winning pages have that its other audited
+ // pages don't, read by Ansvisor overnight.
+ analyze_winning_pages: system('analyze_winning_pages', {
+ requires: ['site_audits'],
+ outputs: ['patterns', 'missingPages'],
+ tool: 'winning_page_features',
+ }),
analyze_entity_signals: agent('analyze_entity_signals', { outputs: ['findings'] }),
analyze_internal_links: system('analyze_internal_links', {
requires: ['site_audits'],
diff --git a/server/src/lib/action-center/winning-pages.js b/server/src/lib/action-center/winning-pages.js
new file mode 100644
index 000000000..cf4aacd3c
--- /dev/null
+++ b/server/src/lib/action-center/winning-pages.js
@@ -0,0 +1,282 @@
+/**
+ * Why the brand's winning pages win (learning C4).
+ *
+ * G14 (AI landing pages converting well above the site) and G10 (prompts
+ * whose visibility is rising) point at pages that already work: nothing
+ * said what they have that the brand's other pages don't. This compares
+ * them, through Site Audit's own rule checks (page-features.js: structure,
+ * FAQ, schema, statistics, dates, length), with the brand's other pages a
+ * completed Site Audit read lately. The result is the brand's own "what
+ * works here": the checks most of its winning pages pass and most of its
+ * other pages don't, and the other pages missing the most of them.
+ *
+ * The other pages are read from their audits only, never fetched: no cost,
+ * and only pages the brand chose to audit. A winning page without a recent
+ * audit is read like a page AI answers cite (competitor-pages.js readPages):
+ * free, within the brand's daily reads, only what the checks found kept.
+ * Nothing leaves the brand: no other brand's pages are compared.
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+import { resolve } from '../../config/action-engine.js';
+import { fetchPage } from '../safe-fetch.js';
+import { extractHostname } from '../response-parser.js';
+import { opportunityKey } from '../audit/opportunities.js';
+import { describeSignal } from '../audit/rubric.js';
+import { ReadLaterError, citedPages, readPages, scopePromptIds } from './competitor-pages.js';
+import { FEATURE_CHECKS } from './page-features.js';
+
+const { competitorPages: CP, winningPages: W } = resolve();
+
+const DAY_MS = 86_400_000;
+/** Answers read for G10's prompts, newest first (as competitor-pages.js). */
+const ANSWERS_READ = 300;
+/** Audits read to find the brand's latest one per page. */
+const AUDITS_READ = 300;
+/** A check's results that say something; 'na' doesn't. */
+const DECIDED = new Set(['pass', 'warn', 'fail']);
+
+const hostOf = (value) => extractHostname(/^https?:\/\//i.test(value) ? value : `https://${value}`);
+const onDomain = (host, domain) => host === domain || host.endsWith(`.${domain}`);
+
+/**
+ * The checks most of the winning pages pass (at least half) and most of the
+ * other pages don't (at most half), the widest difference first. A check is
+ * counted on the pages it decides (pass, warn or fail), never 'na'.
+ *
+ * @param {Array<{ checks: Record<string, string> }>} winners
+ * @param {Array<{ checks: Record<string, string> }>} others
+ */
+export function winningPatterns(winners, others) {
+ const rate = (pages, key) => {
+ const decided = pages.filter((page) => DECIDED.has(page.checks?.[key]));
+ const passed = decided.filter((page) => page.checks[key] === 'pass').length;
+ return { passed, of: decided.length };
+ };
+ return FEATURE_CHECKS.flatMap((key) => {
+ const w = rate(winners, key);
+ const o = rate(others, key);
+ if (w.of === 0 || o.of === 0 || w.passed === 0) return [];
+ const wRate = w.passed / w.of;
+ const oRate = o.passed / o.of;
+ if (wRate < 0.5 || oRate > 0.5 || wRate <= oRate) return [];
+ return [
+ {
+ key,
+ label: describeSignal(key)?.label ?? key,
+ winners: w.passed,
+ ofWinners: w.of,
+ others: o.passed,
+ ofOthers: o.of,
+ lead: wRate - oRate,
+ },
+ ];
+ })
+ .sort((a, b) => b.lead - a.lead)
+ .map(({ lead: _lead, ...pattern }) => pattern);
+}
+
+/**
+ * The other pages missing the most of the patterns, at most `limit`: where
+ * what works at the brand can go next. A page missing none isn't listed.
+ */
+export function pagesMissing(others, patterns, limit = W.missingPages) {
+ return others
+ .map((page) => ({
+ url: page.url,
+ missing: patterns.map((p) => p.key).filter((key) => page.checks?.[key] !== 'pass'),
+ }))
+ .filter((page) => page.missing.length > 0)
+ .sort((a, b) => b.missing.length - a.missing.length || a.url.localeCompare(b.url))
+ .slice(0, limit);
+}
+
+/**
+ * The action's winning pages, at most `perAction`: G14's target pages (an
+ * Analytics landing path is read on the brand's primary domain), or the
+ * brand's own pages its prompts' answers cited lately, the most cited first.
+ */
+async function winningPagesOf(brandId, payload, domains, now) {
+ const entity = payload?.targetEntity ?? payload?.entity;
+ if (entity === 'pages') {
+ const primary = domains.find((d) => d.is_primary) ?? domains[0];
+ const host = primary ? hostOf(primary.domain) : null;
+ const listed = Array.isArray(payload.targets) ? payload.targets : [];
+ return listed
+ .map((target) => String(target?.id ?? target?.label ?? ''))
+ .flatMap((page) => {
+ const url = /^https?:\/\//i.test(page)
+ ? page
+ : host && page.startsWith('/')
+ ? `https://${host}${page}`
+ : null;
+ const key = url ? opportunityKey(url) : null;
+ return url && key ? [{ key, url, domain: hostOf(url) }] : [];
+ })
+ .filter((page, i, all) => all.findIndex((p) => p.key === page.key) === i)
+ .slice(0, W.perAction);
+ }
+
+ const promptIds = await scopePromptIds(brandId, payload);
+ if (promptIds.length === 0) return [];
+ const since = new Date(now.getTime() - CP.answersDays * DAY_MS).toISOString();
+ const { data, error } = await supabaseAdmin
+ .from('prompt_results')
+ .select('mention_count, citations')
+ .eq('brand_id', brandId)
+ .neq('platform', 'chatgpt-shopping')
+ .in('prompt_id', promptIds)
+ .gte('created_at', since)
+ .order('created_at', { ascending: false })
+ .limit(ANSWERS_READ);
+ if (error) throw new Error(error.message);
+ const { own } = citedPages(data ?? [], {
+ ownDomains: domains.map((d) => d.domain).filter(Boolean),
+ competitorDomains: [],
+ });
+ return own.slice(0, W.perAction).map(({ key, url, domain }) => ({ key, url, domain }));
+}
+
+/**
+ * The brand's pages with a completed Site Audit since `auditDays`, on its own
+ * domains, each with its latest audit: Map of page key → { url, auditId }.
+ */
+async function auditedPages(brandId, ownHosts, now) {
+ const since = new Date(now.getTime() - W.auditDays * DAY_MS).toISOString();
+ const { data, error } = await supabaseAdmin
+ .from('site_audits')
+ .select('id, url, final_url, completed_at')
+ .eq('brand_id', brandId)
+ .eq('status', 'completed')
+ .gte('completed_at', since)
+ .order('completed_at', { ascending: false })
+ .limit(AUDITS_READ);
+ if (error) throw new Error(error.message);
+ const pages = new Map();
+ for (const audit of data ?? []) {
+ const url = audit.final_url || audit.url;
+ const key = url ? opportunityKey(url) : null;
+ const host = url ? hostOf(url) : null;
+ if (!key || !host || pages.has(key)) continue;
+ if (!ownHosts.some((domain) => onDomain(host, domain))) continue;
+ pages.set(key, { key, url, auditId: audit.id });
+ }
+ return pages;
+}
+
+/** Each audit's compared checks: Map of audit id → { check key: status }. */
+async function auditChecks(auditIds) {
+ if (auditIds.length === 0) return new Map();
+ const { data, error } = await supabaseAdmin
+ .from('audit_signal_results')
+ .select('audit_id, signal_key, status')
+ .in('audit_id', auditIds)
+ .in('signal_key', [...FEATURE_CHECKS]);
+ if (error) throw new Error(error.message);
+ const checks = new Map(auditIds.map((id) => [id, {}]));
+ for (const row of data ?? []) checks.get(row.audit_id)[row.signal_key] = row.status;
+ return checks;
+}
+
+const passing = (checks) => FEATURE_CHECKS.filter((key) => checks?.[key] === 'pass');
+
+/**
+ * The "Analyze your winning pages" task's result: the winning pages, how
+ * many other pages they were compared with, the checks that set the winners
+ * apart, and the other pages missing the most of those.
+ *
+ * It throws ReadLaterError when it can't give one: a winning page to read
+ * that the day's reads left can't cover (the next night), or nothing to
+ * compare — no winning page, none readable, too few other pages audited
+ * (`retryDays`, the reason as the task's output).
+ *
+ * @param {{ brandId: string, payload: object, now?: Date, read?: typeof fetchPage }} input
+ * read: the page reader, for tests
+ */
+export async function analyzeWinningPages({
+ brandId,
+ payload,
+ now = new Date(),
+ read = fetchPage,
+}) {
+ const nothing = (reason, message, found = {}) =>
+ new ReadLaterError(message, {
+ output: {
+ winningPages: [],
+ others: 0,
+ patterns: [],
+ missingPages: [],
+ unreadable: 0,
+ ...found,
+ reason,
+ },
+ retryDays: W.retryDays,
+ });
+
+ const { data: domainRows, error } = await supabaseAdmin
+ .from('brand_domains')
+ .select('domain, is_primary')
+ .eq('brand_id', brandId);
+ if (error) throw new Error(error.message);
+ const domains = (domainRows ?? []).filter((d) => d.domain);
+ const ownHosts = domains.map((d) => hostOf(d.domain)).filter(Boolean);
+
+ const winners = await winningPagesOf(brandId, payload, domains, now);
+ if (winners.length === 0) throw nothing('no_winner', 'no winning page to compare');
+
+ const audited = await auditedPages(brandId, ownHosts, now);
+ const others = [...audited.values()]
+ .filter((page) => !winners.some((winner) => winner.key === page.key))
+ .slice(0, W.others);
+ if (others.length < W.minOthers) {
+ throw nothing('too_few_audited', 'too few of the brand’s other pages audited', {
+ others: others.length,
+ });
+ }
+
+ // A winning page's audit when it has one; else it is read, all the same night.
+ const toRead = winners
+ .filter((winner) => !audited.has(winner.key))
+ .map((winner) => ({ ...winner, own: true }));
+ await readPages({ brandId, pages: toRead, now, read });
+ const checks = await auditChecks([
+ ...winners.flatMap((winner) => audited.get(winner.key)?.auditId ?? []),
+ ...others.map((page) => page.auditId),
+ ]);
+
+ const winningPages = winners.flatMap((winner) => {
+ const audit = audited.get(winner.key);
+ if (audit) {
+ return [{ url: winner.url, source: 'audit', words: null, checks: checks.get(audit.auditId) }];
+ }
+ const fetched = toRead.find((page) => page.key === winner.key);
+ return fetched?.features
+ ? [
+ {
+ url: winner.url,
+ source: 'read',
+ words: fetched.features.words ?? null,
+ checks: fetched.features.checks ?? {},
+ },
+ ]
+ : [];
+ });
+ const unreadable = winners.length - winningPages.length;
+ if (winningPages.length === 0) {
+ throw nothing('winner_unreadable', 'no winning page could be read', { unreadable });
+ }
+
+ const otherPages = others.map((page) => ({ url: page.url, checks: checks.get(page.auditId) }));
+ const patterns = winningPatterns(winningPages, otherPages);
+ return {
+ winningPages: winningPages.map(({ checks: own, ...page }) => ({
+ ...page,
+ passes: passing(own),
+ })),
+ others: otherPages.length,
+ patterns,
+ missingPages: pagesMissing(otherPages, patterns),
+ unreadable,
+ reason: null,
+ };
+}
diff --git a/server/src/lib/action-center/winning-pages.test.js b/server/src/lib/action-center/winning-pages.test.js
new file mode 100644
index 000000000..5a7e75cf1
--- /dev/null
+++ b/server/src/lib/action-center/winning-pages.test.js
@@ -0,0 +1,306 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Why the brand's winning pages win (learning C4): which pages win, where
+ * their checks come from (an audit, else a free read within the day's
+ * reads), what sets them apart from the brand's other audited pages, and the
+ * runs that find nothing to compare.
+ */
+
+let tables;
+let writes;
+let todayReads;
+
+/** A table as the service role reads it: `eq` and `in` keep the rows that match. */
+vi.mock('../../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ const where = [];
+ let head = false;
+ const chain = {
+ select: (_cols, opts) => ((head = opts?.head ?? false), chain),
+ eq: (column, value) => (where.push((row) => row[column] === value), chain),
+ neq: () => chain,
+ in: (column, values) => (where.push((row) => values.includes(row[column])), chain),
+ gte: () => chain,
+ order: () => chain,
+ limit: () => chain,
+ upsert: async (row) => (writes.push(row), { error: null }),
+ then: (resolve) =>
+ resolve(
+ head
+ ? { count: todayReads, error: null }
+ : {
+ data: (tables[table] ?? []).filter((row) => where.every((keep) => keep(row))),
+ error: null,
+ },
+ ),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('../logger.js', () => ({ logger: { warn: vi.fn(), error: vi.fn() } }));
+
+const { analyzeWinningPages, pagesMissing, winningPatterns } = await import('./winning-pages.js');
+const { ReadLaterError } = await import('./competitor-pages.js');
+
+const NOW = new Date('2026-10-29T03:00:00Z');
+const BRAND = 'brand-1';
+
+/** Enough words that what was read is a page, not a wall. */
+const PROSE = `<p>${'A kettle boils water quickly and safely for tea. '.repeat(14)}</p>`;
+const FAQ_PAGE = `<html><head><script type="application/ld+json">${JSON.stringify({
+ '@type': 'FAQPage',
+ mainEntity: [{ '@type': 'Question' }, { '@type': 'Question' }],
+})}</script></head><body><h1>Kettles</h1><h2>Which kettle?</h2>${PROSE}
+<table><thead><tr><th>Kettle</th></tr></thead><tbody><tr><td>a</td></tr></tbody></table></body></html>`;
+const notFound = () =>
+ Object.assign(new Error('The page answered 404'), { code: 'http_error', status: 404 });
+
+/** An audit of a page, with the checks it found. */
+function audit(id, url, checks, completedAt = '2026-10-20T00:00:00Z') {
+ tables.site_audits.push({
+ id,
+ brand_id: BRAND,
+ url,
+ final_url: null,
+ status: 'completed',
+ completed_at: completedAt,
+ });
+ for (const [signal_key, status] of Object.entries(checks)) {
+ tables.audit_signal_results.push({ audit_id: id, signal_key, status });
+ }
+}
+
+const WINNING = { 'faq-schema': 'pass', tables: 'pass', 'author-byline': 'pass', lists: 'pass' };
+const PLAIN = { 'faq-schema': 'fail', tables: 'fail', 'author-byline': 'fail', lists: 'pass' };
+
+const g14 = { targetEntity: 'pages', targets: [{ id: '/kettles', label: '/kettles' }] };
+
+beforeEach(() => {
+ writes = [];
+ todayReads = 0;
+ tables = {
+ brand_domains: [
+ { brand_id: BRAND, domain: 'shop.acme.com', is_primary: false },
+ { brand_id: BRAND, domain: 'acme.com', is_primary: true },
+ ],
+ site_audits: [],
+ audit_signal_results: [],
+ cited_page_features: [],
+ prompt_results: [],
+ prompts: [],
+ };
+});
+
+describe('winningPatterns', () => {
+ it('keeps the checks most winners pass and most other pages don’t, the widest gap first', () => {
+ const patterns = winningPatterns(
+ [{ checks: WINNING }, { checks: { ...WINNING, tables: 'fail' } }],
+ [
+ { checks: PLAIN },
+ { checks: { ...PLAIN, tables: 'pass' } },
+ { checks: { ...PLAIN, 'faq-schema': 'na' } },
+ ],
+ );
+ // A tie keeps Site Audit's order of the checks.
+ expect(patterns).toEqual([
+ // 'na' decides nothing: two of the others are counted.
+ {
+ key: 'faq-schema',
+ label: expect.any(String),
+ winners: 2,
+ ofWinners: 2,
+ others: 0,
+ ofOthers: 2,
+ },
+ {
+ key: 'author-byline',
+ label: expect.any(String),
+ winners: 2,
+ ofWinners: 2,
+ others: 0,
+ ofOthers: 3,
+ },
+ {
+ key: 'tables',
+ label: expect.any(String),
+ winners: 1,
+ ofWinners: 2,
+ others: 1,
+ ofOthers: 3,
+ },
+ ]);
+ // Lists: every page has them, so they don't set the winners apart.
+ expect(patterns.map((p) => p.key)).not.toContain('lists');
+ });
+
+ it('names nothing where the other pages do as well', () => {
+ expect(
+ winningPatterns([{ checks: WINNING }], [{ checks: WINNING }, { checks: WINNING }]),
+ ).toEqual([]);
+ });
+});
+
+describe('pagesMissing', () => {
+ it('lists the other pages missing the most of the patterns, and none missing none', () => {
+ const patterns = [{ key: 'faq-schema' }, { key: 'tables' }];
+ expect(
+ pagesMissing(
+ [
+ { url: 'https://acme.com/b', checks: { 'faq-schema': 'fail', tables: 'pass' } },
+ { url: 'https://acme.com/a', checks: { 'faq-schema': 'fail', tables: 'fail' } },
+ { url: 'https://acme.com/c', checks: { 'faq-schema': 'pass', tables: 'pass' } },
+ ],
+ patterns,
+ 1,
+ ),
+ ).toEqual([{ url: 'https://acme.com/a', missing: ['faq-schema', 'tables'] }]);
+ });
+});
+
+describe('analyzeWinningPages', () => {
+ it('compares a G14 landing page’s audit with the brand’s other audited pages, reading nothing', async () => {
+ audit('a-win', 'https://acme.com/kettles/', WINNING);
+ audit('a-1', 'https://acme.com/tea', PLAIN);
+ audit('a-2', 'https://acme.com/cups', PLAIN);
+ audit('a-3', 'https://www.acme.com/about', { ...PLAIN, 'author-byline': 'pass' });
+ // Another site's page, though audited for the brand, isn't one of its pages.
+ audit('a-x', 'https://rival.com/kettles', PLAIN);
+ const read = vi.fn();
+
+ const result = await analyzeWinningPages({ brandId: BRAND, payload: g14, now: NOW, read });
+ expect(read).not.toHaveBeenCalled();
+ expect(writes).toEqual([]);
+ expect(result).toMatchObject({
+ // The Analytics path, on the brand's primary domain.
+ winningPages: [
+ {
+ url: 'https://acme.com/kettles',
+ source: 'audit',
+ words: null,
+ passes: ['lists', 'tables', 'faq-schema', 'author-byline'],
+ },
+ ],
+ others: 3,
+ unreadable: 0,
+ reason: null,
+ });
+ expect(
+ result.patterns.map((p) => [p.key, p.winners, p.ofWinners, p.others, p.ofOthers]),
+ ).toEqual([
+ ['tables', 1, 1, 0, 3],
+ ['faq-schema', 1, 1, 0, 3],
+ ['author-byline', 1, 1, 1, 3],
+ ]);
+ expect(result.missingPages).toEqual([
+ { url: 'https://acme.com/cups', missing: ['tables', 'faq-schema', 'author-byline'] },
+ { url: 'https://acme.com/tea', missing: ['tables', 'faq-schema', 'author-byline'] },
+ { url: 'https://www.acme.com/about', missing: ['tables', 'faq-schema'] },
+ ]);
+ });
+
+ it('reads a winning page without an audit, as a page AI cites, within the day’s reads', async () => {
+ audit('a-1', 'https://acme.com/tea', PLAIN);
+ audit('a-2', 'https://acme.com/cups', PLAIN);
+ audit('a-3', 'https://acme.com/about', PLAIN);
+ const read = vi.fn(async (url) => {
+ if (url.endsWith('/robots.txt')) throw notFound();
+ return { url, html: FAQ_PAGE };
+ });
+
+ const result = await analyzeWinningPages({ brandId: BRAND, payload: g14, now: NOW, read });
+ expect(read).toHaveBeenCalledWith('https://acme.com/kettles', expect.anything());
+ expect(writes).toEqual([
+ expect.objectContaining({
+ brand_id: BRAND,
+ page_key: 'acme.com/kettles',
+ own: true,
+ features: expect.objectContaining({ checks: expect.any(Object) }),
+ }),
+ ]);
+ expect(result.winningPages[0]).toMatchObject({ source: 'read', words: expect.any(Number) });
+ expect(result.patterns.map((p) => p.key)).toContain('faq-schema');
+ });
+
+ it("waits for the next night when the day's reads can't cover a winning page", async () => {
+ audit('a-1', 'https://acme.com/tea', PLAIN);
+ audit('a-2', 'https://acme.com/cups', PLAIN);
+ audit('a-3', 'https://acme.com/about', PLAIN);
+ todayReads = 12;
+ const err = await analyzeWinningPages({
+ brandId: BRAND,
+ payload: g14,
+ now: NOW,
+ read: vi.fn(),
+ }).then(
+ () => null,
+ (e) => e,
+ );
+ expect(err).toBeInstanceOf(ReadLaterError);
+ expect(err.output).toBeNull();
+ expect(err.retryDays).toBe(0);
+ });
+
+ it("takes G10's winners from the brand's pages its prompts' answers cite, the most cited first", async () => {
+ tables.prompt_results = [
+ {
+ brand_id: BRAND,
+ prompt_id: 'p1',
+ mention_count: 1,
+ citations: [{ url: 'https://acme.com/guide' }, { url: 'https://rival.com/x' }],
+ },
+ {
+ brand_id: BRAND,
+ prompt_id: 'p1',
+ mention_count: 1,
+ citations: [{ url: 'https://acme.com/guide' }, { url: 'https://acme.com/faq' }],
+ },
+ ];
+ audit('a-guide', 'https://acme.com/guide', WINNING);
+ audit('a-faq', 'https://acme.com/faq', WINNING);
+ audit('a-1', 'https://acme.com/tea', PLAIN);
+ audit('a-2', 'https://acme.com/cups', PLAIN);
+ audit('a-3', 'https://acme.com/about', PLAIN);
+
+ const result = await analyzeWinningPages({
+ brandId: BRAND,
+ payload: { targetEntity: 'prompts', targets: [{ id: 'p1', label: 'best kettle' }] },
+ now: NOW,
+ read: vi.fn(),
+ });
+ expect(result.winningPages.map((p) => p.url)).toEqual([
+ 'https://acme.com/guide',
+ 'https://acme.com/faq',
+ ]);
+ expect(result.others).toBe(3);
+ expect(result.patterns.map((p) => p.key)).toEqual(['tables', 'faq-schema', 'author-byline']);
+ });
+
+ it('leaves the task to a person, with why, when there is nothing to compare', async () => {
+ const run = (payload) =>
+ analyzeWinningPages({ brandId: BRAND, payload, now: NOW, read: vi.fn() }).then(
+ () => null,
+ (e) => e,
+ );
+ // No page of the brand's cited for the prompts.
+ tables.prompt_results = [
+ {
+ brand_id: BRAND,
+ prompt_id: 'p1',
+ mention_count: 0,
+ citations: [{ url: 'https://rival.com/x' }],
+ },
+ ];
+ let err = await run({ targetEntity: 'prompts', targets: [{ id: 'p1' }] });
+ expect(err.output).toMatchObject({ reason: 'no_winner', patterns: [] });
+ expect(err.retryDays).toBe(7);
+
+ // Two other pages audited: too few to say what sets the winner apart.
+ audit('a-1', 'https://acme.com/tea', PLAIN);
+ audit('a-2', 'https://acme.com/cups', PLAIN);
+ err = await run(g14);
+ expect(err.output).toMatchObject({ reason: 'too_few_audited', others: 2 });
+ });
+});
diff --git a/web/messages/en.json b/web/messages/en.json
index ddf75205b..50c648510 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1648,6 +1648,25 @@
"none_cited": "In the last two weeks, AI answers for these prompts cited no competitor page, and no page in answers that don't name your brand.",
"unreadable": "The pages cited couldn't be read: they may block readers."
}
+ },
+ "winning": {
+ "title": "What sets your winning pages apart",
+ "pattern": "— winning pages {winners} of {ofWinners}, your other pages {others} of {ofOthers}",
+ "noPattern": "Your other audited pages pass the same Site Audit checks your winning pages pass: none sets the winners apart.",
+ "winners": "{count, plural, one {Your winning page} other {Your # winning pages}}",
+ "fromAudit": "from its Site Audit",
+ "fromRead": "read for this task",
+ "words": "{count, plural, one {# word} other {{words} words}}",
+ "compared": "Compared with {count, plural, one {# other page} other {# other pages}} of yours that Site Audit checked in the last 90 days.",
+ "missing": "Pages of yours missing the most of it",
+ "missingLine": "missing {checks}",
+ "note": "From Site Audit's checks; a winning page without a recent audit is read from its public address, and only what the checks found is kept.",
+ "unreadable": "{count, plural, one {# winning page} other {# winning pages}} couldn't be read.",
+ "reasons": {
+ "no_winner": "There's no winning page to compare: none of your pages is named for this action, or cited in its prompts' answers in the last two weeks.",
+ "too_few_audited": "Fewer than three of your other pages have a Site Audit from the last 90 days. Audit more of your pages to compare them with your winning ones.",
+ "winner_unreadable": "Your winning pages couldn't be read: they may block readers. A Site Audit of them works too."
+ }
}
},
"noSignalsOpportunity": "This action was sent from Content Optimization. Its evidence is the opportunity on the Overview tab, not detection signals.",
@@ -2610,6 +2629,8 @@
"analyze_ga4_outcomes_target": "Inspect engagement and key events on {targets}",
"analyze_site_audit": "Review Site Audit findings",
"analyze_site_audit_target": "Review Site Audit findings on {targets}",
+ "analyze_winning_pages": "Find what sets your winning pages apart",
+ "analyze_winning_pages_target": "Find what sets your winning pages apart, across {targets}",
"analyze_entity_signals": "Audit entity consistency and coverage",
"analyze_entity_signals_target": "Audit entity signals on {targets}",
"analyze_internal_links": "Inspect internal linking",
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index 93ae02407..d5b30d6e3 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -1051,6 +1051,7 @@ function TaskRow({
check={check}
draftWork={draftWork}
competitor={task.competitorFindings}
+ winning={task.winningFindings}
/>
))}
diff --git a/web/src/components/action-center/task-detail.test.tsx b/web/src/components/action-center/task-detail.test.tsx
index 443da75ed..1cac46067 100644
--- a/web/src/components/action-center/task-detail.test.tsx
+++ b/web/src/components/action-center/task-detail.test.tsx
@@ -469,3 +469,74 @@ describe('TaskDetailView with competitor findings', () => {
expect(text).toContain('FAQ schema — on 2 of 2 of their pages');
});
});
+
+/** What Find what sets your winning pages apart found (learning C4), shown on the task. */
+describe('TaskDetailView with winning-page findings', () => {
+ const findings = {
+ winningPages: [
+ {
+ url: 'https://acme.com/kettles/',
+ source: 'audit' as const,
+ words: null,
+ passes: ['tables'],
+ },
+ { url: 'https://acme.com/guide', source: 'read' as const, words: 1400, passes: [] },
+ ],
+ others: 12,
+ patterns: [
+ { key: 'faq-schema', label: 'FAQ schema', winners: 2, ofWinners: 2, others: 1, ofOthers: 12 },
+ { key: 'tables', label: 'Tables', winners: 1, ofWinners: 2, others: 0, ofOthers: 12 },
+ ],
+ missingPages: [{ url: 'https://acme.com/tea', missing: ['faq-schema', 'tables'] }],
+ unreadable: 0,
+ reason: null,
+ };
+
+ it('says which checks set the winning pages apart, and the pages that miss them', () => {
+ render(<TaskDetailView details={null} disabled={false} onEdit={() => {}} winning={findings} />);
+ const text = container.textContent!;
+ expect(text).toContain('What sets your winning pages apart');
+ expect(text).toContain('FAQ schema — winning pages 2 of 2, your other pages 1 of 12');
+ expect(text).toContain('Your 2 winning pages');
+ expect(text).toContain('acme.com/kettlesfrom its Site Audit');
+ expect(text).toContain('acme.com/guideread for this task · 1,400 words');
+ expect(text).toContain('acme.com/teamissing FAQ schema, Tables');
+ expect(text).toContain(
+ 'Compared with 12 other pages of yours that Site Audit checked in the last 90 days.',
+ );
+ expect(container.querySelector('a[href="https://acme.com/tea"]')).not.toBeNull();
+ });
+
+ it('says when nothing sets them apart, and why nothing was compared', () => {
+ render(
+ <TaskDetailView
+ details={null}
+ disabled={false}
+ onEdit={() => {}}
+ winning={{ ...findings, patterns: [], missingPages: [] }}
+ />,
+ );
+ expect(container.textContent).toContain(
+ 'Your other audited pages pass the same Site Audit checks your winning pages pass',
+ );
+ render(
+ <TaskDetailView
+ details={null}
+ disabled={false}
+ onEdit={() => {}}
+ winning={{
+ ...findings,
+ winningPages: [],
+ patterns: [],
+ missingPages: [],
+ others: 2,
+ reason: 'too_few_audited',
+ }}
+ />,
+ );
+ expect(container.textContent).toContain(
+ 'Fewer than three of your other pages have a Site Audit from the last 90 days.',
+ );
+ expect(container.textContent).not.toContain('Compared with');
+ });
+});
diff --git a/web/src/components/action-center/task-detail.tsx b/web/src/components/action-center/task-detail.tsx
index 9b4fa2025..9b425dd3c 100644
--- a/web/src/components/action-center/task-detail.tsx
+++ b/web/src/components/action-center/task-detail.tsx
@@ -32,7 +32,9 @@ import { contentEditorPath, type DraftMethod } from '@/lib/content/drafts';
import { pagePath } from '@/lib/content/overlap';
import { cn } from '@/lib/utils';
import type { CompetitorFindings } from '@/lib/action-center/competitor-findings';
+import type { WinningFindings } from '@/lib/action-center/winning-findings';
import { CompetitorFindingsView } from './competitor-findings';
+import { WinningFindingsView } from './winning-findings';
/** The type of work, beside the task's text (AC-004). */
export function TaskTypeBadge({ type }: { type: ActionTaskDetails['type'] }) {
@@ -136,6 +138,7 @@ export function TaskDetailView({
draftWork,
check,
competitor = null,
+ winning = null,
}: {
details: ActionTaskDetails | null;
disabled: boolean;
@@ -147,6 +150,8 @@ export function TaskDetailView({
check?: TaskCheckOptions;
/** What Analyze competitor content found (learning C1). */
competitor?: CompetitorFindings | null;
+ /** What Find what sets your winning pages apart found (learning C4). */
+ winning?: WinningFindings | null;
}) {
const t = useTranslations('actionCenter.actionsPage.drawer.task');
const tChecks = useTranslations('actionCenter.taskChecks');
@@ -160,6 +165,7 @@ export function TaskDetailView({
return (
<div className="space-y-2 border-t px-4 py-3">
{competitor && <CompetitorFindingsView findings={competitor} />}
+ {winning && <WinningFindingsView findings={winning} />}
{details?.body && (
<p className="text-xs leading-relaxed whitespace-pre-line text-muted-foreground">
{details.body}
diff --git a/web/src/components/action-center/winning-findings.tsx b/web/src/components/action-center/winning-findings.tsx
new file mode 100644
index 000000000..617aa32a7
--- /dev/null
+++ b/web/src/components/action-center/winning-findings.tsx
@@ -0,0 +1,112 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { ArrowUpRight } from 'lucide-react';
+import type { WinningFindings } from '@/lib/action-center/winning-findings';
+import { formatNumber } from '@/lib/format';
+
+/** A page as a link: its host and path. */
+function PageUrl({ url }: { url: string }) {
+ const shown = url.replace(/^https?:\/\/(www\.)?/i, '').replace(/\/$/, '');
+ return (
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="break-all underline-offset-2 hover:underline"
+ >
+ {shown}
+ <ArrowUpRight className="ml-0.5 inline h-3 w-3" />
+ </a>
+ );
+}
+
+/**
+ * What "Find what sets your winning pages apart" found (learning C4): the
+ * Site Audit checks most of the brand's winning pages pass and most of its
+ * other audited pages don't, the winning pages, and the other pages missing
+ * the most of those checks; or why nothing was compared.
+ */
+export function WinningFindingsView({ findings }: { findings: WinningFindings }) {
+ const t = useTranslations('actionCenter.actionsPage.drawer.task.winning');
+ const winners = findings.winningPages.length;
+ const labelOf = new Map(findings.patterns.map((p) => [p.key, p.label]));
+
+ return (
+ <div className="space-y-2 text-xs">
+ <p className="font-medium">{t('title')}</p>
+ {winners === 0 ? (
+ <p className="text-muted-foreground">{t(`reasons.${findings.reason ?? 'no_winner'}`)}</p>
+ ) : (
+ <>
+ {findings.patterns.length > 0 ? (
+ <ul className="space-y-1">
+ {findings.patterns.map((pattern) => (
+ <li key={pattern.key} className="flex gap-1.5">
+ <span aria-hidden className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-current" />
+ <span>
+ <span className="font-medium">{pattern.label}</span>{' '}
+ <span className="text-muted-foreground">
+ {t('pattern', {
+ winners: pattern.winners,
+ ofWinners: pattern.ofWinners,
+ others: pattern.others,
+ ofOthers: pattern.ofOthers,
+ })}
+ </span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-muted-foreground">{t('noPattern')}</p>
+ )}
+ <div>
+ <p className="text-muted-foreground">{t('winners', { count: winners })}</p>
+ <ul className="mt-0.5 space-y-0.5">
+ {findings.winningPages.map((page) => (
+ <li key={page.url} className="flex flex-wrap items-baseline gap-x-2">
+ <PageUrl url={page.url} />
+ <span className="text-muted-foreground">
+ {[
+ t(page.source === 'read' ? 'fromRead' : 'fromAudit'),
+ page.words !== null
+ ? t('words', { count: page.words, words: formatNumber(page.words) })
+ : null,
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ {findings.missingPages.length > 0 && (
+ <div>
+ <p className="text-muted-foreground">{t('missing')}</p>
+ <ul className="mt-0.5 space-y-0.5">
+ {findings.missingPages.map((page) => (
+ <li key={page.url} className="flex flex-wrap items-baseline gap-x-2">
+ <PageUrl url={page.url} />
+ <span className="text-muted-foreground">
+ {t('missingLine', {
+ checks: page.missing.map((key) => labelOf.get(key) ?? key).join(', '),
+ })}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ <p className="text-muted-foreground">{t('compared', { count: findings.others })}</p>
+ </>
+ )}
+ <p className="text-[11px] text-muted-foreground">
+ {t('note')}
+ {findings.unreadable > 0 &&
+ winners > 0 &&
+ ` ${t('unreadable', { count: findings.unreadable })}`}
+ </p>
+ </div>
+ );
+}
diff --git a/web/src/lib/action-center/rows.ts b/web/src/lib/action-center/rows.ts
index 9b0597b24..610de8738 100644
--- a/web/src/lib/action-center/rows.ts
+++ b/web/src/lib/action-center/rows.ts
@@ -20,6 +20,7 @@ import {
type EntityCountRow,
} from '@/lib/action-center/entity-counts';
import { COMPETITOR_TASK_KEY, parseCompetitorFindings } from './competitor-findings';
+import { WINNING_TASK_KEY, parseWinningFindings } from './winning-findings';
/**
* Action Center rows → the shapes the dashboard reads, shared by its server
@@ -108,6 +109,8 @@ export function taskFromRow(task: Record<string, unknown>): ActionTask {
// What Analyze competitor content found, once it ran (learning C1).
competitorFindings:
task.task_key === COMPETITOR_TASK_KEY ? parseCompetitorFindings(task.output) : null,
+ // What Find what sets your winning pages apart found (learning C4).
+ winningFindings: task.task_key === WINNING_TASK_KEY ? parseWinningFindings(task.output) : null,
};
}
diff --git a/web/src/lib/action-center/winning-findings.test.ts b/web/src/lib/action-center/winning-findings.test.ts
new file mode 100644
index 000000000..882ecf3e5
--- /dev/null
+++ b/web/src/lib/action-center/winning-findings.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from 'vitest';
+import { parseWinningFindings } from './winning-findings';
+
+/** What "Find what sets your winning pages apart" stored (learning C4), read defensively. */
+describe('parseWinningFindings', () => {
+ it('reads the winning pages, the patterns and the pages missing them', () => {
+ expect(
+ parseWinningFindings({
+ winningPages: [
+ { url: 'https://acme.com/kettles', source: 'audit', words: null, passes: ['tables', 3] },
+ { url: 'javascript:alert(1)', source: 'read' },
+ { url: 'https://acme.com/guide', source: 'read', words: 1400, passes: [] },
+ ],
+ others: 12,
+ patterns: [
+ {
+ key: 'faq-schema',
+ label: 'FAQ schema',
+ winners: 2,
+ ofWinners: 2,
+ others: 1,
+ ofOthers: 12,
+ },
+ { key: 'tables', winners: 1, ofWinners: 2, others: 0, ofOthers: 0 },
+ { label: 'no key', winners: 1, ofWinners: 1, others: 0, ofOthers: 3 },
+ ],
+ missingPages: [
+ { url: 'https://acme.com/tea', missing: ['faq-schema'] },
+ { url: 'https://acme.com/cups', missing: [] },
+ ],
+ unreadable: 1,
+ reason: null,
+ }),
+ ).toEqual({
+ winningPages: [
+ { url: 'https://acme.com/kettles', source: 'audit', words: null, passes: ['tables'] },
+ { url: 'https://acme.com/guide', source: 'read', words: 1400, passes: [] },
+ ],
+ others: 12,
+ patterns: [
+ {
+ key: 'faq-schema',
+ label: 'FAQ schema',
+ winners: 2,
+ ofWinners: 2,
+ others: 1,
+ ofOthers: 12,
+ },
+ ],
+ missingPages: [{ url: 'https://acme.com/tea', missing: ['faq-schema'] }],
+ unreadable: 1,
+ reason: null,
+ });
+ });
+
+ it('keeps why nothing was compared, and nothing it does not know', () => {
+ expect(
+ parseWinningFindings({
+ winningPages: [],
+ patterns: [],
+ others: 2,
+ reason: 'too_few_audited',
+ }),
+ ).toMatchObject({ others: 2, reason: 'too_few_audited', missingPages: [] });
+ expect(parseWinningFindings({ winningPages: [], patterns: [], reason: 'other' })?.reason).toBe(
+ null,
+ );
+ });
+
+ it("isn't this task's output otherwise", () => {
+ expect(parseWinningFindings(null)).toBeNull();
+ expect(parseWinningFindings({ competitorPages: [], gaps: [] })).toBeNull();
+ });
+});
diff --git a/web/src/lib/action-center/winning-findings.ts b/web/src/lib/action-center/winning-findings.ts
new file mode 100644
index 000000000..877986aee
--- /dev/null
+++ b/web/src/lib/action-center/winning-findings.ts
@@ -0,0 +1,101 @@
+/**
+ * What the "Find what sets your winning pages apart" task found (learning
+ * C4): the brand's winning pages (G14's landing pages, or G10's pages its
+ * rising prompts' answers cite), compared through Site Audit's checks with
+ * its other audited pages; the checks that set the winners apart, and the
+ * other pages missing the most of them. The task's output, as the API's
+ * action-center/winning-pages.js writes it.
+ */
+
+/** The task whose output this is. */
+export const WINNING_TASK_KEY = 'analyze_winning_pages';
+
+export interface WinningPage {
+ url: string;
+ /** Its checks came from its Site Audit, or it was read for the task. */
+ source: 'audit' | 'read';
+ words: number | null;
+ /** Site Audit check keys it passes. */
+ passes: string[];
+}
+
+export interface WinningPattern {
+ key: string;
+ /** The check's name, as Site Audit's rubric gives it. */
+ label: string;
+ /** Winning pages passing it, of those it decides. */
+ winners: number;
+ ofWinners: number;
+ /** The brand's other pages passing it, of those it decides. */
+ others: number;
+ ofOthers: number;
+}
+
+export interface WinningFindings {
+ winningPages: WinningPage[];
+ /** The brand's other audited pages compared. */
+ others: number;
+ patterns: WinningPattern[];
+ /** Other pages missing the most of the patterns, by check key. */
+ missingPages: { url: string; missing: string[] }[];
+ /** Winning pages that couldn't be read. */
+ unreadable: number;
+ /** Why nothing was compared, when nothing was: the task is left to a person. */
+ reason: 'no_winner' | 'too_few_audited' | 'winner_unreadable' | null;
+}
+
+const REASONS = ['no_winner', 'too_few_audited', 'winner_unreadable'] as const;
+
+const count = (value: unknown) =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
+const strings = (value: unknown) =>
+ Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && v !== '') : [];
+const webUrl = (value: unknown): value is string =>
+ typeof value === 'string' && /^https?:\/\//i.test(value);
+
+/** The task's output read defensively; null when it isn't this task's. */
+export function parseWinningFindings(output: unknown): WinningFindings | null {
+ if (!output || typeof output !== 'object') return null;
+ const o = output as Record<string, unknown>;
+ if (!Array.isArray(o.winningPages) || !Array.isArray(o.patterns)) return null;
+ return {
+ winningPages: o.winningPages.flatMap((value) => {
+ const p = (value ?? {}) as Record<string, unknown>;
+ return webUrl(p.url)
+ ? [
+ {
+ url: p.url,
+ source: p.source === 'read' ? ('read' as const) : ('audit' as const),
+ words: typeof p.words === 'number' && Number.isFinite(p.words) ? p.words : null,
+ passes: strings(p.passes),
+ },
+ ]
+ : [];
+ }),
+ others: count(o.others),
+ patterns: o.patterns.flatMap((value) => {
+ const g = (value ?? {}) as Record<string, unknown>;
+ return typeof g.key === 'string' && g.key && count(g.ofWinners) > 0 && count(g.ofOthers) > 0
+ ? [
+ {
+ key: g.key,
+ label: typeof g.label === 'string' && g.label ? g.label : g.key,
+ winners: count(g.winners),
+ ofWinners: count(g.ofWinners),
+ others: count(g.others),
+ ofOthers: count(g.ofOthers),
+ },
+ ]
+ : [];
+ }),
+ missingPages: (Array.isArray(o.missingPages) ? o.missingPages : []).flatMap((value) => {
+ const p = (value ?? {}) as Record<string, unknown>;
+ const missing = strings(p.missing);
+ return webUrl(p.url) && missing.length > 0 ? [{ url: p.url, missing }] : [];
+ }),
+ unreadable: count(o.unreadable),
+ reason: (REASONS as readonly unknown[]).includes(o.reason)
+ ? (o.reason as WinningFindings['reason'])
+ : null,
+ };
+}
diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.ts
index 30fd40665..844c0053a 100644
--- a/web/src/lib/actions/action-center.ts
+++ b/web/src/lib/actions/action-center.ts
@@ -61,6 +61,7 @@ import {
} from '@/lib/action-center/task-details';
import type { PriorityLevel, PriorityReason } from '@/lib/action-center/priority';
import type { CompetitorFindings } from '@/lib/action-center/competitor-findings';
+import type { WinningFindings } from '@/lib/action-center/winning-findings';
import { assertWritable } from '@/lib/subscription-guard';
export interface ActionAssignee {
@@ -178,6 +179,8 @@ export interface ActionTask {
details: ActionTaskDetails | null;
/** What Analyze competitor content found, once it ran (learning C1). */
competitorFindings?: CompetitorFindings | null;
+ /** What Find what sets your winning pages apart found, once it ran (learning C4). */
+ winningFindings?: WinningFindings | null;
}
export interface ActionEvent {