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): ship the V1 definition library — all 62 definitions (#839)

Gökhan Geyikca65570ce99f
diff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.js
index af479391e..d7f1e7ce9 100644
--- a/server/src/config/action-engine.js
+++ b/server/src/config/action-engine.js
@@ -128,6 +128,110 @@ export const ENGINE_THRESHOLDS = Object.freeze({
pageWindowDays: 28,
}),
+ /**
+ * The V1 definition library's detectors (#818).
+ *
+ * These are first settings, not calibrations. Every number that the
+ * original detectors use was measured against production before being
+ * written down; these forty-odd could not all be, in the time it took to
+ * build the definitions they feed. They are chosen to be conservative —
+ * a detector that is quiet for a week is easy to loosen, one that floods a
+ * brand's Action Center on its first night teaches people to ignore it —
+ * and the per-kind signal cap below bounds the worst case either way.
+ *
+ * Recalibrate against a few clean nights of `signals` rows, the way
+ * `platformGapPoints` and `citationGapMultiple` were.
+ */
+ library: Object.freeze({
+ /** Current and previous windows, in days. */
+ windowDays: 7,
+ /** No detector writes more than this many signals of one kind per brand
+ * per night; the strongest are kept. A definition consolidates them into
+ * one action anyway, so the rest would be rows nobody reads. Measured on
+ * the first read-only run: at 10, the five citation-source kinds hit the
+ * ceiling on most brands and wrote 730 rows between them. */
+ maxSignalsPerKind: 5,
+
+ // Prompts
+ /** Tracked on at least this many days of the window before absence counts. */
+ promptMinDays: 3,
+ /** Mentioned on at least this many days before, and not at all now, is a
+ * lost mention rather than noise. */
+ lostMentionMinDays: 3,
+ /** Estimated AI demand at or above this makes a prompt high-value. */
+ highDemandVolume: 100,
+ /** Citation days falling below this fraction of before, but not to zero,
+ * is a citation at risk. Zero is lost, which the original detector owns. */
+ citationRiskRatio: 0.5,
+ citationRiskMinDays: 3,
+ /** Fewer absent prompts than this is not an action's worth. */
+ promptGroupMin: 3,
+
+ // Topics
+ topicMinPrompts: 4,
+ /** Coverage bands: below `uncovered` a topic needs new content; between
+ * that and `partial` it needs expanding. */
+ topicUncoveredCoverage: 0.2,
+ topicPartialCoverage: 0.6,
+ /** A topic worth protecting had at least this coverage before. */
+ topicLeadershipCoverage: 0.4,
+
+ // Platforms, regions and relative declines
+ platformMinAnswers: 20,
+ slipRatio: 0.1,
+ dropRatio: 0.3,
+ /** A platform or region has to have been worth something to slip. */
+ rateFloor: 0.1,
+ countryGapPoints: 0.15,
+
+ // Competitors
+ /** A competitor mentioned this many times the brand's count leads it. */
+ competitorLeadMultiple: 1.5,
+ competitorLeadMinMentions: 20,
+ /** Mentions growing by this fraction, from at least `min`, is momentum. */
+ competitorMomentumRatio: 0.5,
+ competitorMomentumMin: 10,
+ competitorTopicShare: 0.5,
+ competitorPromptMinDays: 3,
+
+ // Citation sources
+ /** A domain needs this many answers citing it before it is a source. */
+ sourceMinResults: 20,
+ sourceMinPrompts: 3,
+ /** Competitor-only share above which a source is competitor-winning. */
+ competitorSourceShare: 0.5,
+ /** A source the brand appears alongside in fewer than this share of
+ * answers is one it has little authority on. */
+ authorityBrandShare: 0.25,
+ authorityMinResults: 25,
+
+ // Owned pages
+ ownedPageMinCitations: 5,
+ ownedPageSlipRatio: 0.7,
+
+ // Fan-outs
+ fanoutMinPrompts: 2,
+ fanoutGroupMin: 5,
+
+ // Search Console
+ gscMinImpressions: 100,
+ gscMinClicks: 10,
+ /** Word-overlap needed to map a search query to a tracked prompt. */
+ gscMatchOverlap: 0.5,
+ gscDeclineRatio: 0.3,
+ /** CTR below this fraction of what its position usually earns. */
+ gscCtrShortfall: 0.5,
+
+ // AI traffic
+ aiTrafficMinSessions: 10,
+ aiTrafficSlipRatio: 0.1,
+ aiTrafficDropRatio: 0.3,
+ /** Key events per session above this multiple of the site's rate is a
+ * winning page; engagement below `underperform` of it is a weak one. */
+ landingWinnerMultiple: 1.5,
+ landingUnderperformMultiple: 0.6,
+ }),
+
/** Guards against the engine talking over itself. */
noise: Object.freeze({
/**
diff --git a/server/src/lib/action-center/definitions/_helpers.js b/server/src/lib/action-center/definitions/_helpers.js
new file mode 100644
index 000000000..5d1aa9961
--- /dev/null
+++ b/server/src/lib/action-center/definitions/_helpers.js
@@ -0,0 +1,79 @@
+/**
+ * Payload building shared by the definition library.
+ *
+ * Not a definition — the registry skips files starting with an underscore.
+ *
+ * Every action names its targets: the prompts, pages, sources, queries,
+ * topics, platforms or competitors it is about. The specification is plain
+ * about titles: "Recover 7 lost citations", not "Recover citations". So every
+ * payload carries `targetEntity`, `targetCount` and a bounded `targets` list,
+ * collected from the signals that triggered it and snapshotted at creation.
+ *
+ * Library detectors put targets on their signals directly. The original ones
+ * predate that, so their targets are read off the fields they do carry.
+ */
+
+function legacyTargets(signal) {
+ const p = signal.payload ?? {};
+ if (Array.isArray(p.targets)) return p.targets;
+ if (p.promptId) return [{ id: p.promptId, label: p.promptText ?? '' }];
+ if (p.competitorName)
+ return [{ id: p.competitorId ?? p.competitorName, label: p.competitorName }];
+ if (p.landingPage) return [{ id: p.landingPage, label: p.landingPage }];
+ if (Array.isArray(p.urls)) return p.urls.map((url) => ({ id: url, label: url }));
+ if (p.platform) return [{ id: p.platform, label: p.platform }];
+ return [];
+}
+
+/** Every target across the matched signals, once each. */
+export function collectTargets(byKind) {
+ const seen = new Map();
+ for (const signals of byKind.values()) {
+ for (const signal of signals) {
+ for (const target of legacyTargets(signal)) {
+ const key = String(target.id ?? target.label ?? '');
+ if (key && !seen.has(key)) seen.set(key, target);
+ }
+ }
+ }
+ return [...seen.values()];
+}
+
+/**
+ * The target half of every payload.
+ *
+ * `contentExists` tells the planner which branch of an `optimise | create`
+ * plan to take: prompt targets carry whether a page is mapped to them or has
+ * ever been cited. Where nothing says, it is left undefined and the planner
+ * optimises what exists — the conservative choice, since creating a page
+ * that duplicates one is worse than improving it.
+ */
+export function targetPayload(byKind, entity, extra = {}) {
+ const targets = collectTargets(byKind);
+ const mapped = targets.filter((t) => typeof t.mapped === 'boolean');
+ return {
+ targetEntity: entity,
+ targetCount: targets.length,
+ targets: targets.slice(0, 50),
+ ...(mapped.length > 0 ? { contentExists: mapped.some((t) => t.mapped) } : {}),
+ ...extra,
+ };
+}
+
+/** The first matched signal, for payload fields that describe the whole
+ * condition rather than one target. */
+export function first(byKind, kind) {
+ return (byKind.get(kind) ?? [])[0] ?? null;
+}
+
+/** Competitor names across the matched signals, up to three. */
+export function competitorNames(byKind) {
+ const names = new Set();
+ for (const signals of byKind.values()) {
+ for (const signal of signals) {
+ const name = signal.payload?.competitorName;
+ if (name) names.add(name);
+ }
+ }
+ return [...names].slice(0, 3);
+}
diff --git a/server/src/lib/action-center/definitions/c01-close-competitor-gap.js b/server/src/lib/action-center/definitions/c01-close-competitor-gap.js
new file mode 100644
index 000000000..a5ea0a198
--- /dev/null
+++ b/server/src/lib/action-center/definitions/c01-close-competitor-gap.js
@@ -0,0 +1,36 @@
+/**
+ * C01 — Close Visibility Gap.
+ *
+ * Signal: A competitor mentioned well more often than the brand.
+ *
+ * Version 2: the task plan now follows the specification's library, and the
+ * payload names its targets.
+ */
+
+import { competitorNames, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'close_competitor_gap',
+ code: 'C01',
+ version: 2,
+ category: 'compete',
+ name: 'Close Visibility Gap',
+ signalKinds: ['competitor_leads'],
+ requires: ['tracking', 'competitors'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_competitor_visibility',
+ 'analyze_ai_responses',
+ 'analyze_competitor_content',
+ 'analyze_citations',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_competitive_gap',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return { ...targetPayload(byKind, 'competitors'), competitorNames: competitorNames(byKind) };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/c02-close-citation-gap.js b/server/src/lib/action-center/definitions/c02-close-citation-gap.js
new file mode 100644
index 000000000..ce97c30e8
--- /dev/null
+++ b/server/src/lib/action-center/definitions/c02-close-citation-gap.js
@@ -0,0 +1,43 @@
+/**
+ * C02 — Close Citation Gap.
+ *
+ * Signal: A competitor cited a multiple of the brand’s count.
+ *
+ * Version 2: the task plan now follows the specification's library, and the
+ * payload names its targets.
+ */
+
+import { competitorNames, first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'close_citation_gap',
+ code: 'C02',
+ version: 2,
+ category: 'compete',
+ name: 'Close Citation Gap',
+ signalKinds: ['competitor_citation_gap'],
+ requires: ['tracking', 'competitors'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_citations',
+ 'analyze_competitor_citations',
+ 'identify_citation_gaps',
+ 'identify_target_sources',
+ 'strengthen_reference_asset',
+ 'prepare_outreach',
+ 'validate_citations',
+ 'validate_competitive_gap',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const gap = first(byKind, 'competitor_citation_gap');
+ return {
+ ...targetPayload(byKind, 'competitors'),
+ competitorNames: competitorNames(byKind),
+ citationCount: gap?.current_value,
+ competitorCitations: gap?.payload?.competitorCitations,
+ };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/c03-capture-competitor-cited-sources.js b/server/src/lib/action-center/definitions/c03-capture-competitor-cited-sources.js
new file mode 100644
index 000000000..6bad5795e
--- /dev/null
+++ b/server/src/lib/action-center/definitions/c03-capture-competitor-cited-sources.js
@@ -0,0 +1,35 @@
+/**
+ * C03 — Capture Competitor-Cited Sources.
+ *
+ * Signal: Sources cited where competitors appear and the brand does not.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'capture_competitor_cited_sources',
+ code: 'C03',
+ version: 1,
+ category: 'compete',
+ name: 'Capture Competitor-Cited Sources',
+ signalKinds: ['competitor_cited_source'],
+ requires: ['tracking', 'competitors'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_competitor_citations',
+ 'analyze_third_party_sources',
+ 'identify_target_sources',
+ 'identify_inclusion_path',
+ 'strengthen_reference_asset',
+ 'prepare_outreach',
+ 'execute_outreach',
+ 'track_third_party_status',
+ 'validate_third_party_citation',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'sources');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/c04-close-topic-coverage-gap.js b/server/src/lib/action-center/definitions/c04-close-topic-coverage-gap.js
new file mode 100644
index 000000000..930bda7e3
--- /dev/null
+++ b/server/src/lib/action-center/definitions/c04-close-topic-coverage-gap.js
@@ -0,0 +1,36 @@
+/**
+ * C04 — Close Topic Coverage Gap.
+ *
+ * Signal: A competitor holding a topic the brand has pages for but no presence
+ * in.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'close_topic_coverage_gap',
+ code: 'C04',
+ version: 1,
+ category: 'compete',
+ name: 'Close Topic Coverage Gap',
+ signalKinds: ['competitor_topic_lead'],
+ requires: ['tracking', 'competitors', 'topics'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_topic_gap',
+ 'analyze_competitor_visibility',
+ 'analyze_competitor_content',
+ 'cluster_prompts',
+ 'map_prompts_to_content',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_topic_sov',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const lead = first(byKind, 'competitor_topic_lead');
+ return { ...targetPayload(byKind, 'topics'), topicName: lead?.payload?.topicName };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/c05-compete-on-high-value-prompts.js b/server/src/lib/action-center/definitions/c05-compete-on-high-value-prompts.js
new file mode 100644
index 000000000..adc37b580
--- /dev/null
+++ b/server/src/lib/action-center/definitions/c05-compete-on-high-value-prompts.js
@@ -0,0 +1,34 @@
+/**
+ * C05 — Compete on High-Value Prompts.
+ *
+ * Signal: A competitor present on high-demand prompts where the brand is
+ * absent.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'compete_on_high_value_prompts',
+ code: 'C05',
+ version: 1,
+ category: 'compete',
+ name: 'Compete on High-Value Prompts',
+ signalKinds: ['competitor_high_value_lead'],
+ requires: ['tracking', 'competitors', 'volumes'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'prioritize_targets',
+ 'analyze_competitor_visibility',
+ 'analyze_ai_responses',
+ 'analyze_competitor_citations',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_competitive_gap',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/c06-capture-competitor-fanouts.js b/server/src/lib/action-center/definitions/c06-capture-competitor-fanouts.js
new file mode 100644
index 000000000..5dcd8a638
--- /dev/null
+++ b/server/src/lib/action-center/definitions/c06-capture-competitor-fanouts.js
@@ -0,0 +1,33 @@
+/**
+ * C06 — Capture Competitor Query Fan-Outs.
+ *
+ * Signal: Fan-out queries where competitors appear and the brand does not.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'capture_competitor_fanouts',
+ code: 'C06',
+ version: 1,
+ category: 'compete',
+ name: 'Capture Competitor Query Fan-Outs',
+ signalKinds: ['competitor_fanout_gap'],
+ requires: ['tracking', 'competitors'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_fanout_gap',
+ 'analyze_competitor_visibility',
+ 'cluster_prompts',
+ 'map_prompts_to_content',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_competitive_gap',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'queries');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/c07-respond-to-competitor-momentum.js b/server/src/lib/action-center/definitions/c07-respond-to-competitor-momentum.js
new file mode 100644
index 000000000..ec991cb65
--- /dev/null
+++ b/server/src/lib/action-center/definitions/c07-respond-to-competitor-momentum.js
@@ -0,0 +1,35 @@
+/**
+ * C07 — Respond to Competitor Momentum.
+ *
+ * Signal: A competitor’s mentions growing fast.
+ */
+
+import { competitorNames, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'respond_to_competitor_momentum',
+ code: 'C07',
+ version: 1,
+ category: 'compete',
+ name: 'Respond to Competitor Momentum',
+ signalKinds: ['competitor_momentum'],
+ requires: ['tracking', 'competitors'],
+ optional: ['search_console', 'analytics'],
+ enabled: true,
+ tasks: [
+ 'analyze_competitor_visibility',
+ 'analyze_competitor_citations',
+ 'analyze_competitor_content',
+ 'analyze_gsc_demand',
+ 'analyze_ga4_outcomes',
+ 'prioritize_targets',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_competitive_gap',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return { ...targetPayload(byKind, 'competitors'), competitorNames: competitorNames(byKind) };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/c08-earn-competitor-source-presence.js b/server/src/lib/action-center/definitions/c08-earn-competitor-source-presence.js
new file mode 100644
index 000000000..8fb874f02
--- /dev/null
+++ b/server/src/lib/action-center/definitions/c08-earn-competitor-source-presence.js
@@ -0,0 +1,37 @@
+/**
+ * C08 — Earn Presence on Competitor-Winning Sources.
+ *
+ * Signal: Sources that competitors win across several prompts, with no brand
+ * presence.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'earn_competitor_source_presence',
+ code: 'C08',
+ version: 1,
+ category: 'compete',
+ name: 'Earn Presence on Competitor-Winning Sources',
+ signalKinds: ['competitor_winning_source'],
+ requires: ['tracking', 'competitors'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_third_party_sources',
+ 'analyze_competitor_content',
+ 'identify_target_sources',
+ 'identify_inclusion_path',
+ 'prepare_contribution',
+ 'prepare_outreach',
+ 'execute_outreach',
+ 'track_third_party_status',
+ 'validate_third_party_presence',
+ 'validate_competitive_gap',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'sources');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/c09-create-content-for-competitor-gaps.js b/server/src/lib/action-center/definitions/c09-create-content-for-competitor-gaps.js
new file mode 100644
index 000000000..9a905d96e
--- /dev/null
+++ b/server/src/lib/action-center/definitions/c09-create-content-for-competitor-gaps.js
@@ -0,0 +1,37 @@
+/**
+ * C09 — Create Content to Close Competitor Gaps.
+ *
+ * Signal: A competitor leading a topic the brand has no content for.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'create_content_for_competitor_gaps',
+ code: 'C09',
+ version: 1,
+ category: 'compete',
+ name: 'Create Content to Close Competitor Gaps',
+ signalKinds: ['competitor_uncovered_topic'],
+ requires: ['tracking', 'competitors', 'topics'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_competitor_visibility',
+ 'analyze_competitor_content',
+ 'analyze_topic_gap',
+ 'cluster_prompts',
+ 'identify_new_content_need',
+ 'create_content_brief',
+ 'create_content_draft',
+ 'add_internal_links',
+ 'publish_content',
+ 'validate_competitive_gap',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const lead = first(byKind, 'competitor_uncovered_topic');
+ return { ...targetPayload(byKind, 'topics'), topicName: lead?.payload?.topicName };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/capture-ai-traffic.js b/server/src/lib/action-center/definitions/capture-ai-traffic.js
deleted file mode 100644
index e95d39a03..000000000
--- a/server/src/lib/action-center/definitions/capture-ai-traffic.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * Growth — pages already earning traffic that AI answers do not cite.
- *
- * The only definition whose evidence comes from outside our own tracking:
- * page opportunities are landing pages read from the brand's analytics
- * connection, so without one the definition has nothing to stand on.
- */
-export default {
- id: 'capture_ai_traffic',
- version: 1,
- category: 'growth',
- signalKinds: ['page_opportunity'],
- requires: ['analytics'],
- optional: ['site_audits'],
- tasks: ['review_pages', 'page_readiness', 'coverage_gaps', 'optimize_content', 'validate'],
-
- payload(byKind) {
- return { pageCount: (byKind.get('page_opportunity') ?? []).length };
- },
-};
diff --git a/server/src/lib/action-center/definitions/close-citation-gap.js b/server/src/lib/action-center/definitions/close-citation-gap.js
deleted file mode 100644
index 5e439f272..000000000
--- a/server/src/lib/action-center/definitions/close-citation-gap.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Compete — a competitor is cited far more often than the brand.
- *
- * Distinct from close_competitor_gap, which is about visibility: this one is
- * about who gets referenced, and the work is earning sources rather than
- * ranking answers.
- */
-export default {
- id: 'close_citation_gap',
- version: 1,
- category: 'compete',
- signalKinds: ['competitor_citation_gap'],
- requires: ['tracking', 'competitors'],
- optional: [],
- tasks: ['compare_citations', 'identify_sources', 'strengthen_sources', 'validate'],
-
- payload(byKind) {
- const gap = (byKind.get('competitor_citation_gap') ?? [])[0];
- if (!gap) return {};
- return {
- competitorNames: gap.payload?.competitorName ? [gap.payload.competitorName] : [],
- citationCount: gap.current_value,
- competitorCitations: gap.payload?.competitorCitations,
- };
- },
-};
diff --git a/server/src/lib/action-center/definitions/close-competitor-gap.js b/server/src/lib/action-center/definitions/close-competitor-gap.js
deleted file mode 100644
index baf7a961d..000000000
--- a/server/src/lib/action-center/definitions/close-competitor-gap.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Compete — a competitor is gaining visibility, or has passed the brand.
- *
- * One action per cycle however many competitors moved: the response is the
- * same piece of work, and three rows would be three copies of it.
- */
-export default {
- id: 'close_competitor_gap',
- version: 1,
- category: 'compete',
- signalKinds: ['competitor_surge', 'competitor_crossed'],
- requires: ['tracking', 'competitors'],
- optional: [],
- tasks: ['analyze_competitor', 'coverage_gaps', 'strengthen_content', 'validate'],
-
- payload(byKind) {
- const names = new Set();
- for (const signals of byKind.values()) {
- for (const signal of signals) {
- const name = signal.payload?.competitorName;
- if (name) names.add(name);
- }
- }
- return { competitorNames: [...names].slice(0, 3) };
- },
-};
diff --git a/server/src/lib/action-center/definitions/convert-mentions.js b/server/src/lib/action-center/definitions/convert-mentions.js
deleted file mode 100644
index e76101499..000000000
--- a/server/src/lib/action-center/definitions/convert-mentions.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Growth — the brand is named in answers but not linked from them.
- *
- * A mention without a citation is recognition the brand earns nothing from:
- * the reader has no route back. The work is making the claim citable, not
- * winning more answers.
- */
-export default {
- id: 'convert_mentions',
- version: 1,
- category: 'growth',
- signalKinds: ['uncited_mentions'],
- requires: ['tracking'],
- optional: [],
- tasks: ['identify_prompts', 'create_citable_content', 'strengthen_sources'],
-
- payload(byKind) {
- const mentions = (byKind.get('uncited_mentions') ?? [])[0];
- return { promptCount: Number(mentions?.current_value ?? 0) };
- },
-};
diff --git a/server/src/lib/action-center/definitions/expand-platform-visibility.js b/server/src/lib/action-center/definitions/expand-platform-visibility.js
deleted file mode 100644
index 1f3d5d61a..000000000
--- a/server/src/lib/action-center/definitions/expand-platform-visibility.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Growth — the brand ranks on one engine and is absent on another.
- *
- * It is the engine, not the material, that differs: content that already
- * ranks somewhere proves the content can rank, which is what separates this
- * from a brand that is simply weak everywhere.
- */
-export default {
- id: 'expand_platform_visibility',
- version: 1,
- category: 'growth',
- signalKinds: ['platform_gap'],
- requires: ['tracking'],
- optional: [],
- tasks: ['compare_platforms', 'coverage_gaps', 'optimize_content', 'validate'],
-
- payload(byKind) {
- const gap = (byKind.get('platform_gap') ?? [])[0];
- if (!gap) return {};
- return {
- platform: gap.payload?.platform,
- bestPlatform: gap.payload?.bestPlatform,
- dropFrom: gap.previous_value,
- dropTo: gap.current_value,
- };
- },
-};
diff --git a/server/src/lib/action-center/definitions/f01-fix-low-scores.js b/server/src/lib/action-center/definitions/f01-fix-low-scores.js
new file mode 100644
index 000000000..f051d4331
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f01-fix-low-scores.js
@@ -0,0 +1,35 @@
+/**
+ * F01 — Fix Low AI-Readiness Pages.
+ *
+ * Signal: Pages whose Site Audit score is below threshold.
+ *
+ * Version 2: the task plan now follows the specification's library, and the
+ * payload names its targets.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_low_scores',
+ code: 'F01',
+ version: 2,
+ category: 'fix',
+ name: 'Fix Low AI-Readiness Pages',
+ signalKinds: ['audit_low_score'],
+ requires: ['site_audits'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_site_audit',
+ 'prioritize_targets',
+ { branch: [['fix_technical_issue'], ['optimize_content']] },
+ 'validate_technical_fix',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const audit = first(byKind, 'audit_low_score');
+ const pageCount = Number(audit?.current_value ?? 0);
+ return { ...targetPayload(byKind, 'pages'), targetCount: pageCount, pageCount };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f02-fix-crawler-access.js b/server/src/lib/action-center/definitions/f02-fix-crawler-access.js
new file mode 100644
index 000000000..dbe6d21f4
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f02-fix-crawler-access.js
@@ -0,0 +1,30 @@
+/**
+ * F02 — Fix AI Crawler Accessibility.
+ *
+ * Signal: Pages AI crawlers are blocked from.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_crawler_access',
+ code: 'F02',
+ version: 1,
+ category: 'fix',
+ name: 'Fix AI Crawler Accessibility',
+ signalKinds: ['crawler_blocked'],
+ requires: ['site_audits'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_site_audit',
+ 'identify_target_pages',
+ 'fix_crawler_access',
+ 'validate_technical_fix',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f03-fix-structured-data.js b/server/src/lib/action-center/definitions/f03-fix-structured-data.js
new file mode 100644
index 000000000..9fd3301b3
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f03-fix-structured-data.js
@@ -0,0 +1,30 @@
+/**
+ * F03 — Fix Structured Data Issues.
+ *
+ * Signal: Structured data missing or invalid on audited pages.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_structured_data',
+ code: 'F03',
+ version: 1,
+ category: 'fix',
+ name: 'Fix Structured Data Issues',
+ signalKinds: ['structured_data_issue'],
+ requires: ['site_audits'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_site_audit',
+ 'identify_target_pages',
+ 'fix_structured_data',
+ 'validate_technical_fix',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f04-fix-content-gaps.js b/server/src/lib/action-center/definitions/f04-fix-content-gaps.js
new file mode 100644
index 000000000..6a49796f9
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f04-fix-content-gaps.js
@@ -0,0 +1,34 @@
+/**
+ * F04 — Fix Content Gaps.
+ *
+ * Signal: Audited pages that do not cover the queries they target.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_content_gaps',
+ code: 'F04',
+ version: 1,
+ category: 'fix',
+ name: 'Fix Content Gaps',
+ signalKinds: ['content_gap'],
+ requires: ['site_audits'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_ai_responses',
+ 'analyze_prompt_gap',
+ 'map_prompts_to_content',
+ 'identify_content_gaps',
+ 'create_content_brief',
+ { branch: [['optimize_content'], ['create_content_draft']] },
+ 'publish_content',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f05-fix-outdated-content.js b/server/src/lib/action-center/definitions/f05-fix-outdated-content.js
new file mode 100644
index 000000000..1d3cc051a
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f05-fix-outdated-content.js
@@ -0,0 +1,33 @@
+/**
+ * F05 — Fix Outdated Content.
+ *
+ * Signal: Audited pages failing freshness checks.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_outdated_content',
+ code: 'F05',
+ version: 1,
+ category: 'fix',
+ name: 'Fix Outdated Content',
+ signalKinds: ['outdated_content'],
+ requires: ['site_audits'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'identify_target_pages',
+ 'analyze_ai_responses',
+ 'identify_content_gaps',
+ 'refresh_content',
+ 'publish_content',
+ 'validate_ai_visibility',
+ 'validate_citations',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f06-fix-entity-signals.js b/server/src/lib/action-center/definitions/f06-fix-entity-signals.js
new file mode 100644
index 000000000..b802bce7e
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f06-fix-entity-signals.js
@@ -0,0 +1,32 @@
+/**
+ * F06 — Fix Weak Entity Signals.
+ *
+ * Signal: Audited pages failing brand-entity and entity-coverage checks.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_entity_signals',
+ code: 'F06',
+ version: 1,
+ category: 'fix',
+ name: 'Fix Weak Entity Signals',
+ signalKinds: ['weak_entity'],
+ requires: ['site_audits'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_entity_signals',
+ 'identify_target_pages',
+ 'strengthen_entity_content',
+ 'fix_structured_data',
+ 'validate_technical_fix',
+ 'validate_mentions',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f07-fix-broken-citation-targets.js b/server/src/lib/action-center/definitions/f07-fix-broken-citation-targets.js
new file mode 100644
index 000000000..70102423f
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f07-fix-broken-citation-targets.js
@@ -0,0 +1,36 @@
+/**
+ * F07 — Fix Broken Citation Targets.
+ *
+ * Signal: Owned URLs AI answers cite that are unavailable.
+ *
+ * Disabled. Cited owned URLs are not health-checked yet, so there is nothing
+ * to detect a broken one from. Registered; enabled once URL checks exist.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_broken_citation_targets',
+ code: 'F07',
+ version: 1,
+ category: 'fix',
+ name: 'Fix Broken Citation Targets',
+ signalKinds: ['broken_citation_target'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: false,
+ disabledReason:
+ 'Cited owned URLs are not health-checked yet, so there is nothing to detect a broken one from. Registered; enabled once URL checks exist.',
+ tasks: [
+ 'analyze_citations',
+ 'identify_target_pages',
+ 'fix_broken_target',
+ 'validate_technical_fix',
+ 'validate_citations',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f08-fix-brand-inconsistency.js b/server/src/lib/action-center/definitions/f08-fix-brand-inconsistency.js
new file mode 100644
index 000000000..46f183a5a
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f08-fix-brand-inconsistency.js
@@ -0,0 +1,39 @@
+/**
+ * F08 — Fix Brand Information Inconsistency.
+ *
+ * Signal: Stored AI answers contradicting each other on brand attributes.
+ *
+ * Disabled. Needs deterministic attribute extraction from stored answers,
+ * which does not exist yet; the specification rules out an LLM judging what is
+ * true. Registered; no detector feeds it.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_brand_inconsistency',
+ code: 'F08',
+ version: 1,
+ category: 'fix',
+ name: 'Fix Brand Information Inconsistency',
+ signalKinds: ['brand_inconsistency'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: false,
+ disabledReason:
+ 'Needs deterministic attribute extraction from stored answers, which does not exist yet; the specification rules out an LLM judging what is true. Registered; no detector feeds it.',
+ tasks: [
+ 'analyze_mention_context',
+ 'analyze_entity_signals',
+ 'identify_target_pages',
+ 'strengthen_entity_content',
+ 'optimize_content',
+ 'publish_content',
+ 'validate_mentions',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f09-fix-underperforming-ai-landing-pages.js b/server/src/lib/action-center/definitions/f09-fix-underperforming-ai-landing-pages.js
new file mode 100644
index 000000000..80c9e5352
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f09-fix-underperforming-ai-landing-pages.js
@@ -0,0 +1,36 @@
+/**
+ * F09 — Fix Underperforming AI Landing Pages.
+ *
+ * Signal: AI traffic arriving, and engaging well below the site rate.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_underperforming_ai_landing_pages',
+ code: 'F09',
+ version: 1,
+ category: 'fix',
+ name: 'Fix Underperforming AI Landing Pages',
+ signalKinds: ['ai_landing_underperforming'],
+ requires: ['analytics'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_ai_traffic',
+ 'analyze_ga4_outcomes',
+ 'identify_target_pages',
+ 'analyze_ai_responses',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'improve_cta_path',
+ 'publish_content',
+ 'validate_ai_traffic',
+ 'validate_ga4',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f10-fix-internal-connectivity.js b/server/src/lib/action-center/definitions/f10-fix-internal-connectivity.js
new file mode 100644
index 000000000..ad28a6f93
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f10-fix-internal-connectivity.js
@@ -0,0 +1,31 @@
+/**
+ * F10 — Fix Internal Content Connectivity.
+ *
+ * Signal: Audited pages failing the internal-linking check.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_internal_connectivity',
+ code: 'F10',
+ version: 1,
+ category: 'fix',
+ name: 'Fix Internal Content Connectivity',
+ signalKinds: ['weak_internal_links'],
+ requires: ['site_audits'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_internal_links',
+ 'identify_target_pages',
+ 'prioritize_targets',
+ 'add_internal_links',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f11-fix-prompt-content-coverage.js b/server/src/lib/action-center/definitions/f11-fix-prompt-content-coverage.js
new file mode 100644
index 000000000..944d1868b
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f11-fix-prompt-content-coverage.js
@@ -0,0 +1,34 @@
+/**
+ * F11 — Fix Prompt-to-Content Coverage.
+ *
+ * Signal: Tracked prompts with no owned page mapped to them, and never cited.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'fix_prompt_content_coverage',
+ code: 'F11',
+ version: 1,
+ category: 'fix',
+ name: 'Fix Prompt-to-Content Coverage',
+ signalKinds: ['prompt_unmapped'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_prompt_gap',
+ 'map_prompts_to_content',
+ 'identify_new_content_need',
+ 'cluster_prompts',
+ 'create_content_brief',
+ { branch: [['optimize_content'], ['create_content_draft']] },
+ 'publish_content',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f12-improve-low-ctr-pages.js b/server/src/lib/action-center/definitions/f12-improve-low-ctr-pages.js
new file mode 100644
index 000000000..38531edc5
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f12-improve-low-ctr-pages.js
@@ -0,0 +1,36 @@
+/**
+ * F12 — Improve High-Impression Low-CTR AI-Relevant Pages.
+ *
+ * Signal: Queries tied to tracked prompts earning far fewer clicks than their
+ * position usually does.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'improve_low_ctr_pages',
+ code: 'F12',
+ version: 1,
+ category: 'fix',
+ name: 'Improve High-Impression Low-CTR AI-Relevant Pages',
+ signalKinds: ['gsc_low_ctr'],
+ requires: ['tracking', 'search_console'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_gsc_ctr',
+ 'analyze_gsc_demand',
+ 'map_queries_to_prompts',
+ 'identify_target_pages',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'publish_content',
+ 'validate_gsc',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'queries');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/f13-align-search-and-ai-content.js b/server/src/lib/action-center/definitions/f13-align-search-and-ai-content.js
new file mode 100644
index 000000000..a79b0a940
--- /dev/null
+++ b/server/src/lib/action-center/definitions/f13-align-search-and-ai-content.js
@@ -0,0 +1,37 @@
+/**
+ * F13 — Fix Search-to-AI Content Misalignment.
+ *
+ * Signal: Queries the brand ranks in the top three for in Google, with no AI
+ * visibility.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'align_search_and_ai_content',
+ code: 'F13',
+ version: 1,
+ category: 'fix',
+ name: 'Fix Search-to-AI Content Misalignment',
+ signalKinds: ['search_ai_misalignment'],
+ requires: ['tracking', 'search_console'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_gsc_demand',
+ 'map_queries_to_prompts',
+ 'analyze_ai_responses',
+ 'analyze_prompt_gap',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'strengthen_reference_asset',
+ 'publish_content',
+ 'validate_gsc',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'queries');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/fix-low-scores.js b/server/src/lib/action-center/definitions/fix-low-scores.js
deleted file mode 100644
index 29d9d12f3..000000000
--- a/server/src/lib/action-center/definitions/fix-low-scores.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Fix — pages whose Site Audit score is low enough to be the reason.
- *
- * Requires audits for the same reason the traffic definition requires
- * analytics: without them there is no evidence, and a definition with no
- * possible evidence should not be offered to the brand at all.
- */
-export default {
- id: 'fix_low_scores',
- version: 1,
- category: 'fix',
- signalKinds: ['audit_low_score'],
- requires: ['site_audits'],
- optional: [],
- tasks: ['review_audits', 'fix_issues', 'revalidate'],
-
- payload(byKind) {
- const audit = (byKind.get('audit_low_score') ?? [])[0];
- return { pageCount: Number(audit?.current_value ?? 0) };
- },
-};
diff --git a/server/src/lib/action-center/definitions/g01-capture-ai-traffic.js b/server/src/lib/action-center/definitions/g01-capture-ai-traffic.js
new file mode 100644
index 000000000..0f69af9a3
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g01-capture-ai-traffic.js
@@ -0,0 +1,39 @@
+/**
+ * G01 — Capture AI Traffic.
+ *
+ * Signal: High AI visibility or citations, but AI referral traffic below
+ * potential.
+ *
+ * Version 2: the task plan now follows the specification's library, and the
+ * payload names its targets.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'capture_ai_traffic',
+ code: 'G01',
+ version: 2,
+ category: 'growth',
+ name: 'Capture AI Traffic',
+ signalKinds: ['page_opportunity'],
+ requires: ['analytics'],
+ optional: ['site_audits'],
+ enabled: true,
+ tasks: [
+ 'identify_target_pages',
+ 'analyze_ai_traffic',
+ 'analyze_citations',
+ 'analyze_prompt_gap',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'improve_cta_path',
+ 'validate_ai_traffic',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const base = targetPayload(byKind, 'pages');
+ return { ...base, pageCount: base.targetCount };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g02-convert-mentions.js b/server/src/lib/action-center/definitions/g02-convert-mentions.js
new file mode 100644
index 000000000..caa81125f
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g02-convert-mentions.js
@@ -0,0 +1,37 @@
+/**
+ * G02 — Convert Mentions into Citations.
+ *
+ * Signal: The brand appears in AI answers but its own domain is not cited.
+ *
+ * Version 2: the task plan now follows the specification's library, and the
+ * payload names its targets.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'convert_mentions',
+ code: 'G02',
+ version: 2,
+ category: 'growth',
+ name: 'Convert Mentions into Citations',
+ signalKinds: ['uncited_mentions'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_mention_context',
+ 'analyze_citations',
+ 'identify_citation_gaps',
+ 'map_prompts_to_content',
+ 'strengthen_reference_asset',
+ 'validate_citations',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const mentions = first(byKind, 'uncited_mentions');
+ const promptCount = Number(mentions?.current_value ?? 0);
+ return { ...targetPayload(byKind, 'prompts'), targetCount: promptCount, promptCount };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g03-expand-prompt-visibility.js b/server/src/lib/action-center/definitions/g03-expand-prompt-visibility.js
new file mode 100644
index 000000000..fdcb7044a
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g03-expand-prompt-visibility.js
@@ -0,0 +1,34 @@
+/**
+ * G03 — Expand Prompt Visibility.
+ *
+ * Signal: The brand is absent across tracked prompts it has been cited on
+ * before.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'expand_prompt_visibility',
+ code: 'G03',
+ version: 1,
+ category: 'growth',
+ name: 'Expand Prompt Visibility',
+ signalKinds: ['prompt_visibility_gap'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_prompt_gap',
+ 'analyze_ai_responses',
+ 'map_prompts_to_content',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'publish_content',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g04-capture-high-demand-prompts.js b/server/src/lib/action-center/definitions/g04-capture-high-demand-prompts.js
new file mode 100644
index 000000000..96c801c47
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g04-capture-high-demand-prompts.js
@@ -0,0 +1,34 @@
+/**
+ * G04 — Capture High-Demand Prompts.
+ *
+ * Signal: High prompt demand and no AI visibility.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'capture_high_demand_prompts',
+ code: 'G04',
+ version: 1,
+ category: 'growth',
+ name: 'Capture High-Demand Prompts',
+ signalKinds: ['high_demand_gap'],
+ requires: ['tracking', 'volumes'],
+ optional: ['search_console'],
+ enabled: true,
+ tasks: [
+ 'prioritize_targets',
+ 'analyze_prompt_gap',
+ 'analyze_gsc_demand',
+ 'map_prompts_to_content',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'publish_content',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g05-expand-topic-visibility.js b/server/src/lib/action-center/definitions/g05-expand-topic-visibility.js
new file mode 100644
index 000000000..882ae5fc0
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g05-expand-topic-visibility.js
@@ -0,0 +1,34 @@
+/**
+ * G05 — Expand Topic Visibility.
+ *
+ * Signal: Partial presence in a topic, with an uncovered prompt cluster.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'expand_topic_visibility',
+ code: 'G05',
+ version: 1,
+ category: 'growth',
+ name: 'Expand Topic Visibility',
+ signalKinds: ['topic_gap'],
+ requires: ['tracking', 'topics'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_topic_gap',
+ 'cluster_prompts',
+ 'map_prompts_to_content',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'publish_content',
+ 'validate_topic_sov',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const lead = first(byKind, 'topic_gap');
+ return { ...targetPayload(byKind, 'topics'), topicName: lead?.payload?.topicName };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g06-capture-fanout-opportunities.js b/server/src/lib/action-center/definitions/g06-capture-fanout-opportunities.js
new file mode 100644
index 000000000..4c01e8a89
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g06-capture-fanout-opportunities.js
@@ -0,0 +1,35 @@
+/**
+ * G06 — Capture Query Fan-Out Opportunities.
+ *
+ * Signal: Fan-out queries the engines ran across several prompts, with no
+ * brand presence.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'capture_fanout_opportunities',
+ code: 'G06',
+ version: 1,
+ category: 'growth',
+ name: 'Capture Query Fan-Out Opportunities',
+ signalKinds: ['fanout_gap'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_fanout_gap',
+ 'cluster_prompts',
+ 'prioritize_targets',
+ 'map_prompts_to_content',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'publish_content',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'queries');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g07-increase-authority-citations.js b/server/src/lib/action-center/definitions/g07-increase-authority-citations.js
new file mode 100644
index 000000000..670b84ada
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g07-increase-authority-citations.js
@@ -0,0 +1,34 @@
+/**
+ * G07 — Increase Authority Citations.
+ *
+ * Signal: High-traffic sources the brand rarely appears beside.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'increase_authority_citations',
+ code: 'G07',
+ version: 1,
+ category: 'growth',
+ name: 'Increase Authority Citations',
+ signalKinds: ['authority_citation_gap'],
+ requires: ['tracking'],
+ optional: ['competitors'],
+ enabled: true,
+ tasks: [
+ 'analyze_citations',
+ 'analyze_competitor_citations',
+ 'identify_citation_gaps',
+ 'identify_target_sources',
+ 'strengthen_reference_asset',
+ 'prepare_outreach',
+ 'execute_outreach',
+ 'validate_citations',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'sources');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g08-expand-platform-visibility.js b/server/src/lib/action-center/definitions/g08-expand-platform-visibility.js
new file mode 100644
index 000000000..8c9724a26
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g08-expand-platform-visibility.js
@@ -0,0 +1,42 @@
+/**
+ * G08 — Expand Platform Visibility.
+ *
+ * Signal: Strong on some AI platforms, weak on others.
+ *
+ * Version 2: the task plan now follows the specification's library, and the
+ * payload names its targets.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'expand_platform_visibility',
+ code: 'G08',
+ version: 2,
+ category: 'growth',
+ name: 'Expand Platform Visibility',
+ signalKinds: ['platform_gap'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_platform_gap',
+ 'analyze_ai_responses',
+ 'analyze_citations',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_platform_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const gap = first(byKind, 'platform_gap');
+ return {
+ ...targetPayload(byKind, 'platforms'),
+ platform: gap?.payload?.platform,
+ bestPlatform: gap?.payload?.bestPlatform,
+ dropFrom: gap?.previous_value,
+ dropTo: gap?.current_value,
+ };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g09-expand-country-visibility.js b/server/src/lib/action-center/definitions/g09-expand-country-visibility.js
new file mode 100644
index 000000000..b72a8e357
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g09-expand-country-visibility.js
@@ -0,0 +1,34 @@
+/**
+ * G09 — Expand Country Visibility.
+ *
+ * Signal: Strong in one tracked country, weak in another.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'expand_country_visibility',
+ code: 'G09',
+ version: 1,
+ category: 'growth',
+ name: 'Expand Country Visibility',
+ signalKinds: ['country_gap'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_country_gap',
+ 'analyze_prompt_gap',
+ 'map_prompts_to_content',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'publish_content',
+ 'validate_country_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const lead = first(byKind, 'country_gap');
+ return { ...targetPayload(byKind, 'regions'), region: lead?.payload?.region };
+ },
+};
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
new file mode 100644
index 000000000..1d9fd9dfa
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g10-strengthen-emerging-content.js
@@ -0,0 +1,35 @@
+/**
+ * G10 — Strengthen Emerging Content.
+ *
+ * Signal: Visibility improving on prompts, but not yet at its potential.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'strengthen_emerging_content',
+ code: 'G10',
+ version: 1,
+ category: 'growth',
+ name: 'Strengthen Emerging Content',
+ signalKinds: ['prompt_gain'],
+ requires: ['tracking'],
+ optional: ['analytics', 'search_console'],
+ enabled: true,
+ tasks: [
+ 'identify_target_pages',
+ 'analyze_visibility_change',
+ 'analyze_citations',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'add_internal_links',
+ 'publish_content',
+ 'validate_ai_visibility',
+ 'validate_citations',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g11-expand-brand-associations.js b/server/src/lib/action-center/definitions/g11-expand-brand-associations.js
new file mode 100644
index 000000000..c7f5a5073
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g11-expand-brand-associations.js
@@ -0,0 +1,39 @@
+/**
+ * G11 — Expand Brand Associations.
+ *
+ * Signal: The brand is under-associated with strategic topics or attributes.
+ *
+ * Disabled. Needs association extraction from mention contexts, which the
+ * product does not do yet. Registered so the slot exists; no detector feeds
+ * it.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'expand_brand_associations',
+ code: 'G11',
+ version: 1,
+ category: 'growth',
+ name: 'Expand Brand Associations',
+ signalKinds: ['brand_association_gap'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: false,
+ disabledReason:
+ 'Needs association extraction from mention contexts, which the product does not do yet. Registered so the slot exists; no detector feeds it.',
+ tasks: [
+ 'analyze_mention_context',
+ 'analyze_entity_signals',
+ 'identify_content_gaps',
+ 'map_prompts_to_content',
+ 'strengthen_entity_content',
+ 'optimize_content',
+ 'validate_mentions',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g12-convert-search-demand.js b/server/src/lib/action-center/definitions/g12-convert-search-demand.js
new file mode 100644
index 000000000..a0d18f998
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g12-convert-search-demand.js
@@ -0,0 +1,36 @@
+/**
+ * G12 — Convert Search Demand into AI Visibility.
+ *
+ * Signal: Strong Search Console demand where the related AI prompts show no
+ * visibility.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'convert_search_demand',
+ code: 'G12',
+ version: 1,
+ category: 'growth',
+ name: 'Convert Search Demand into AI Visibility',
+ signalKinds: ['gsc_demand_gap'],
+ requires: ['tracking', 'search_console'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_gsc_demand',
+ 'map_queries_to_prompts',
+ 'prioritize_targets',
+ 'analyze_prompt_gap',
+ 'map_prompts_to_content',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_ai_visibility',
+ 'validate_gsc',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'queries');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g13-expand-organic-pages.js b/server/src/lib/action-center/definitions/g13-expand-organic-pages.js
new file mode 100644
index 000000000..74712d9f3
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g13-expand-organic-pages.js
@@ -0,0 +1,41 @@
+/**
+ * G13 — Expand High-Performing Organic Pages into AI.
+ *
+ * Signal: Strong organic pages with weak AI visibility.
+ *
+ * Disabled. The Search Console sync stores queries, not pages, so there is no
+ * organic page performance to compare against. Registered; enabled once
+ * page-level sync exists.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'expand_organic_pages',
+ code: 'G13',
+ version: 1,
+ category: 'growth',
+ name: 'Expand High-Performing Organic Pages into AI',
+ signalKinds: ['gsc_page_gap'],
+ requires: ['tracking', 'search_console'],
+ optional: [],
+ enabled: false,
+ disabledReason:
+ 'The Search Console sync stores queries, not pages, so there is no organic page performance to compare against. Registered; enabled once page-level sync exists.',
+ tasks: [
+ 'analyze_gsc_demand',
+ 'identify_target_pages',
+ 'map_queries_to_prompts',
+ 'analyze_prompt_gap',
+ 'analyze_citations',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'validate_ai_visibility',
+ 'validate_citations',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
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
new file mode 100644
index 000000000..df706dc57
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g14-scale-ai-landing-pages.js
@@ -0,0 +1,35 @@
+/**
+ * G14 — Scale Proven AI Landing Pages.
+ *
+ * Signal: AI-referred landing pages converting well above the site rate.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'scale_ai_landing_pages',
+ code: 'G14',
+ version: 1,
+ category: 'growth',
+ name: 'Scale Proven AI Landing Pages',
+ signalKinds: ['ai_landing_page_winner'],
+ requires: ['analytics'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_ai_traffic',
+ 'analyze_ga4_outcomes',
+ 'identify_target_pages',
+ 'analyze_prompt_gap',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'add_internal_links',
+ 'validate_ai_traffic',
+ 'validate_ga4',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g15-create-content-for-demand.js b/server/src/lib/action-center/definitions/g15-create-content-for-demand.js
new file mode 100644
index 000000000..b47924c25
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g15-create-content-for-demand.js
@@ -0,0 +1,35 @@
+/**
+ * G15 — Create Content for Uncovered Demand.
+ *
+ * Signal: High-demand prompts with no owned page that covers them.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'create_content_for_demand',
+ code: 'G15',
+ version: 1,
+ category: 'growth',
+ name: 'Create Content for Uncovered Demand',
+ signalKinds: ['uncovered_demand'],
+ requires: ['tracking', 'volumes'],
+ optional: ['search_console'],
+ enabled: true,
+ tasks: [
+ 'cluster_prompts',
+ 'prioritize_targets',
+ 'identify_new_content_need',
+ 'create_content_brief',
+ 'create_content_draft',
+ 'strengthen_reference_asset',
+ 'add_internal_links',
+ 'publish_content',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g16-create-content-for-topics.js b/server/src/lib/action-center/definitions/g16-create-content-for-topics.js
new file mode 100644
index 000000000..e16a0fd98
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g16-create-content-for-topics.js
@@ -0,0 +1,35 @@
+/**
+ * G16 — Create Content for Topic Gaps.
+ *
+ * Signal: A relevant topic the brand barely appears in.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'create_content_for_topics',
+ code: 'G16',
+ version: 1,
+ category: 'growth',
+ name: 'Create Content for Topic Gaps',
+ signalKinds: ['topic_uncovered'],
+ requires: ['tracking', 'topics'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_topic_gap',
+ 'cluster_prompts',
+ 'identify_new_content_need',
+ 'create_content_brief',
+ 'create_content_draft',
+ 'add_internal_links',
+ 'publish_content',
+ 'validate_topic_sov',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const lead = first(byKind, 'topic_uncovered');
+ return { ...targetPayload(byKind, 'topics'), topicName: lead?.payload?.topicName };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g17-optimize-content-for-ai.js b/server/src/lib/action-center/definitions/g17-optimize-content-for-ai.js
new file mode 100644
index 000000000..b4c684b2e
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g17-optimize-content-for-ai.js
@@ -0,0 +1,38 @@
+/**
+ * G17 — Optimize Content for AI Visibility.
+ *
+ * Signal: A page exists for these prompts, and the brand is still not visible
+ * on them.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'optimize_content_for_ai',
+ code: 'G17',
+ version: 1,
+ category: 'growth',
+ name: 'Optimize Content for AI Visibility',
+ signalKinds: ['content_underperforming'],
+ requires: ['tracking'],
+ optional: ['search_console', 'analytics'],
+ enabled: true,
+ tasks: [
+ 'analyze_ai_responses',
+ 'analyze_prompt_gap',
+ 'analyze_citations',
+ 'analyze_gsc_demand',
+ 'analyze_ga4_outcomes',
+ 'identify_target_pages',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'add_internal_links',
+ 'publish_content',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g18-earn-third-party-presence.js b/server/src/lib/action-center/definitions/g18-earn-third-party-presence.js
new file mode 100644
index 000000000..e5a5da3aa
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g18-earn-third-party-presence.js
@@ -0,0 +1,35 @@
+/**
+ * G18 — Earn Third-Party Brand Presence.
+ *
+ * Signal: Sources AI answers cite where the brand never appears.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'earn_third_party_presence',
+ code: 'G18',
+ version: 1,
+ category: 'growth',
+ name: 'Earn Third-Party Brand Presence',
+ signalKinds: ['third_party_presence_gap'],
+ requires: ['tracking'],
+ optional: ['competitors'],
+ enabled: true,
+ tasks: [
+ 'analyze_third_party_sources',
+ 'analyze_competitor_content',
+ 'identify_target_sources',
+ 'identify_inclusion_path',
+ 'prepare_contribution',
+ 'prepare_outreach',
+ 'execute_outreach',
+ 'track_third_party_status',
+ 'validate_third_party_presence',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'sources');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/g19-earn-third-party-citations.js b/server/src/lib/action-center/definitions/g19-earn-third-party-citations.js
new file mode 100644
index 000000000..904fcad2d
--- /dev/null
+++ b/server/src/lib/action-center/definitions/g19-earn-third-party-citations.js
@@ -0,0 +1,37 @@
+/**
+ * G19 — Earn Third-Party Citations.
+ *
+ * Signal: Sources used when answers discuss the brand, which could reference
+ * the brand’s own pages.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'earn_third_party_citations',
+ code: 'G19',
+ version: 1,
+ category: 'growth',
+ name: 'Earn Third-Party Citations',
+ signalKinds: ['third_party_citation_gap'],
+ requires: ['tracking'],
+ optional: ['competitors'],
+ enabled: true,
+ tasks: [
+ 'analyze_citations',
+ 'analyze_third_party_sources',
+ 'analyze_competitor_citations',
+ 'identify_target_sources',
+ 'identify_inclusion_path',
+ 'strengthen_reference_asset',
+ 'prepare_outreach',
+ 'execute_outreach',
+ 'track_third_party_status',
+ 'validate_third_party_citation',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'sources');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/index.js b/server/src/lib/action-center/definitions/index.js
index 61029ad9f..3316472a2 100644
--- a/server/src/lib/action-center/definitions/index.js
+++ b/server/src/lib/action-center/definitions/index.js
@@ -39,6 +39,27 @@ const DIR = dirname(fileURLToPath(import.meta.url));
export const CATEGORIES = Object.freeze(['growth', 'protect', 'recover', 'fix', 'compete']);
const ID_PATTERN = /^[a-z][a-z0-9_]*$/;
+const CODE_PATTERN = /^[GPRFC]\d{2}$/;
+const CODE_FAMILY = { G: 'growth', P: 'protect', R: 'recover', F: 'fix', C: 'compete' };
+
+/**
+ * A plan is task ids, conditional entries, and `optimise | create` branches.
+ * Anything else is a typo that would plan nothing.
+ */
+function assertTaskPlan(tasks, file) {
+ if (!Array.isArray(tasks) || tasks.length === 0) fail(file, 'tasks must not be empty');
+ for (const entry of tasks) {
+ if (typeof entry === 'string') continue;
+ if (entry && Array.isArray(entry.branch) && entry.branch.length === 2) {
+ if (entry.branch.some((b) => !Array.isArray(b) || b.some((id) => typeof id !== 'string'))) {
+ fail(file, 'a branch is two lists of task ids');
+ }
+ continue;
+ }
+ if (entry && typeof entry.id === 'string') continue;
+ fail(file, 'a task entry is an id, { id, requires }, or { branch: [[…], […]] }');
+ }
+}
function fail(file, message) {
throw new Error(`[action definitions] ${file}: ${message}`);
@@ -73,11 +94,22 @@ function validate(definition, file) {
if (typeof id !== 'string' || !ID_PATTERN.test(id)) {
fail(file, 'id must be a lower_snake_case string');
}
+ // The specification's stable code — G01, P04, R11 — alongside the stored id.
+ if (typeof definition.code !== 'string' || !CODE_PATTERN.test(definition.code)) {
+ fail(file, 'code must look like G01 / P01 / R01 / F01 / C01');
+ }
+ if (CODE_FAMILY[definition.code[0]] !== category) {
+ fail(file, `code ${definition.code} does not belong to the ${category} family`);
+ }
+ if (typeof definition.enabled !== 'boolean') fail(file, 'enabled must be true or false');
+ if (!definition.enabled && typeof definition.disabledReason !== 'string') {
+ fail(file, 'a disabled definition must say why');
+ }
if (!Number.isInteger(version) || version < 1) fail(file, 'version must be a positive integer');
if (!CATEGORIES.includes(category)) fail(file, `category "${category}" is not a known family`);
assertStringList(signalKinds, { file, field: 'signalKinds' });
- assertStringList(tasks, { file, field: 'tasks' });
+ assertTaskPlan(tasks, file);
assertStringList(requires, { file, field: 'requires', allowed: SOURCES });
assertStringList(optional ?? [], { file, field: 'optional', allowed: SOURCES, allowEmpty: true });
@@ -100,7 +132,13 @@ export async function loadDefinitions() {
if (cache) return cache;
const files = readdirSync(DIR)
- .filter((file) => file.endsWith('.js') && file !== 'index.js' && !file.endsWith('.test.js'))
+ .filter(
+ (file) =>
+ file.endsWith('.js') &&
+ file !== 'index.js' &&
+ !file.startsWith('_') &&
+ !file.endsWith('.test.js'),
+ )
.sort();
const definitions = [];
@@ -129,5 +167,7 @@ export async function loadDefinitions() {
* @param {Set<string>} available
*/
export function isEligible(definition, available) {
- return definition.requires.every((source) => available.has(source));
+ return (
+ definition.enabled !== false && definition.requires.every((source) => available.has(source))
+ );
}
diff --git a/server/src/lib/action-center/definitions/p01-protect-visibility.js b/server/src/lib/action-center/definitions/p01-protect-visibility.js
new file mode 100644
index 000000000..404294813
--- /dev/null
+++ b/server/src/lib/action-center/definitions/p01-protect-visibility.js
@@ -0,0 +1,41 @@
+/**
+ * P01 — Protect High-Visibility Prompts.
+ *
+ * Signal: A real visibility position losing ground before it collapses.
+ *
+ * Version 2: the task plan now follows the specification's library, and the
+ * payload names its targets.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'protect_visibility',
+ code: 'P01',
+ version: 2,
+ category: 'protect',
+ name: 'Protect High-Visibility Prompts',
+ signalKinds: ['visibility_slipping'],
+ requires: ['tracking'],
+ optional: ['competitors'],
+ enabled: true,
+ tasks: [
+ 'analyze_visibility_change',
+ 'analyze_ai_responses',
+ 'analyze_citations',
+ 'analyze_competitor_visibility',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const slip = first(byKind, 'visibility_slipping');
+ return {
+ ...targetPayload(byKind, 'prompts'),
+ dropFrom: slip?.previous_value,
+ dropTo: slip?.current_value,
+ };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/p02-protect-valuable-citations.js b/server/src/lib/action-center/definitions/p02-protect-valuable-citations.js
new file mode 100644
index 000000000..327bf590d
--- /dev/null
+++ b/server/src/lib/action-center/definitions/p02-protect-valuable-citations.js
@@ -0,0 +1,32 @@
+/**
+ * P02 — Protect Valuable Citations.
+ *
+ * Signal: Citations thinning on prompts where they were steady.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'protect_valuable_citations',
+ code: 'P02',
+ version: 1,
+ category: 'protect',
+ name: 'Protect Valuable Citations',
+ signalKinds: ['citation_at_risk'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_citations',
+ 'identify_citation_gaps',
+ 'identify_target_pages',
+ 'refresh_content',
+ 'strengthen_reference_asset',
+ 'validate_citations',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/p03-protect-ai-traffic-pages.js b/server/src/lib/action-center/definitions/p03-protect-ai-traffic-pages.js
new file mode 100644
index 000000000..dabd3b7ec
--- /dev/null
+++ b/server/src/lib/action-center/definitions/p03-protect-ai-traffic-pages.js
@@ -0,0 +1,33 @@
+/**
+ * P03 — Protect AI Traffic Pages.
+ *
+ * Signal: AI referral pages beginning to lose traffic.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'protect_ai_traffic_pages',
+ code: 'P03',
+ version: 1,
+ category: 'protect',
+ name: 'Protect AI Traffic Pages',
+ signalKinds: ['ai_traffic_slipping'],
+ requires: ['ai_traffic'],
+ optional: ['analytics'],
+ enabled: true,
+ tasks: [
+ 'analyze_ai_traffic',
+ 'analyze_visibility_change',
+ 'analyze_citations',
+ 'analyze_ga4_outcomes',
+ 'identify_target_pages',
+ 'optimize_content',
+ 'validate_ai_traffic',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/p04-defend-competitor-gains.js b/server/src/lib/action-center/definitions/p04-defend-competitor-gains.js
new file mode 100644
index 000000000..838c58a8b
--- /dev/null
+++ b/server/src/lib/action-center/definitions/p04-defend-competitor-gains.js
@@ -0,0 +1,33 @@
+/**
+ * P04 — Defend Against Competitor Gains.
+ *
+ * Signal: A competitor gaining fast while the brand still holds its position.
+ */
+
+import { competitorNames, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'defend_competitor_gains',
+ code: 'P04',
+ version: 1,
+ category: 'protect',
+ name: 'Defend Against Competitor Gains',
+ signalKinds: ['competitor_surge'],
+ requires: ['tracking', 'competitors'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_competitor_visibility',
+ 'analyze_competitor_citations',
+ 'analyze_competitor_content',
+ 'cluster_prompts',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_competitive_gap',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return { ...targetPayload(byKind, 'competitors'), competitorNames: competitorNames(byKind) };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/p05-protect-topic-leadership.js b/server/src/lib/action-center/definitions/p05-protect-topic-leadership.js
new file mode 100644
index 000000000..959f6258c
--- /dev/null
+++ b/server/src/lib/action-center/definitions/p05-protect-topic-leadership.js
@@ -0,0 +1,33 @@
+/**
+ * P05 — Protect Topic Leadership.
+ *
+ * Signal: Strong coverage of a topic beginning to decline.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'protect_topic_leadership',
+ code: 'P05',
+ version: 1,
+ category: 'protect',
+ name: 'Protect Topic Leadership',
+ signalKinds: ['topic_slipping'],
+ requires: ['tracking', 'topics'],
+ optional: ['competitors'],
+ enabled: true,
+ tasks: [
+ 'analyze_topic_gap',
+ 'analyze_competitor_visibility',
+ 'analyze_citations',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_topic_sov',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const lead = first(byKind, 'topic_slipping');
+ return { ...targetPayload(byKind, 'topics'), topicName: lead?.payload?.topicName };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/p06-protect-high-performing-content.js b/server/src/lib/action-center/definitions/p06-protect-high-performing-content.js
new file mode 100644
index 000000000..0da264bec
--- /dev/null
+++ b/server/src/lib/action-center/definitions/p06-protect-high-performing-content.js
@@ -0,0 +1,34 @@
+/**
+ * P06 — Protect High-Performing Content.
+ *
+ * Signal: Owned pages that were cited often, now cited less.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'protect_high_performing_content',
+ code: 'P06',
+ version: 1,
+ category: 'protect',
+ name: 'Protect High-Performing Content',
+ signalKinds: ['page_citation_slipping'],
+ requires: ['tracking'],
+ optional: ['site_audits'],
+ enabled: true,
+ tasks: [
+ 'identify_target_pages',
+ 'analyze_visibility_change',
+ 'analyze_citations',
+ 'analyze_site_audit',
+ 'identify_content_gaps',
+ { branch: [['refresh_content'], ['optimize_content']] },
+ 'validate_ai_visibility',
+ 'validate_citations',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/p07-protect-platform-visibility.js b/server/src/lib/action-center/definitions/p07-protect-platform-visibility.js
new file mode 100644
index 000000000..730a31eb0
--- /dev/null
+++ b/server/src/lib/action-center/definitions/p07-protect-platform-visibility.js
@@ -0,0 +1,33 @@
+/**
+ * P07 — Protect Platform Visibility.
+ *
+ * Signal: Visibility on one AI platform beginning to decline.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'protect_platform_visibility',
+ code: 'P07',
+ version: 1,
+ category: 'protect',
+ name: 'Protect Platform Visibility',
+ signalKinds: ['platform_slipping'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_platform_gap',
+ 'analyze_ai_responses',
+ 'analyze_citations',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'validate_platform_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const lead = first(byKind, 'platform_slipping');
+ return { ...targetPayload(byKind, 'platforms'), platform: lead?.payload?.platform };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/p08-protect-organic-on-ai-pages.js b/server/src/lib/action-center/definitions/p08-protect-organic-on-ai-pages.js
new file mode 100644
index 000000000..378c29621
--- /dev/null
+++ b/server/src/lib/action-center/definitions/p08-protect-organic-on-ai-pages.js
@@ -0,0 +1,35 @@
+/**
+ * P08 — Protect Organic Traffic on AI-Exposed Pages.
+ *
+ * Signal: Queries earning organic clicks whose AI visibility is slipping.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'protect_organic_on_ai_pages',
+ code: 'P08',
+ version: 1,
+ category: 'protect',
+ name: 'Protect Organic Traffic on AI-Exposed Pages',
+ signalKinds: ['gsc_risk'],
+ requires: ['tracking', 'search_console'],
+ optional: ['competitors'],
+ enabled: true,
+ tasks: [
+ 'analyze_gsc_demand',
+ 'identify_target_pages',
+ 'analyze_visibility_change',
+ 'analyze_citations',
+ 'analyze_competitor_visibility',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'validate_gsc',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'queries');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/p09-protect-search-and-ai-assets.js b/server/src/lib/action-center/definitions/p09-protect-search-and-ai-assets.js
new file mode 100644
index 000000000..f27823cfe
--- /dev/null
+++ b/server/src/lib/action-center/definitions/p09-protect-search-and-ai-assets.js
@@ -0,0 +1,37 @@
+/**
+ * P09 — Protect Search & AI Traffic Assets.
+ *
+ * Signal: Organic clicks and AI referrals falling together.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'protect_search_and_ai_assets',
+ code: 'P09',
+ version: 1,
+ category: 'protect',
+ name: 'Protect Search & AI Traffic Assets',
+ signalKinds: ['cross_channel_risk'],
+ requires: ['analytics', 'search_console'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_gsc_demand',
+ 'analyze_ai_traffic',
+ 'analyze_ga4_outcomes',
+ 'identify_target_pages',
+ 'analyze_visibility_change',
+ 'analyze_citations',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'validate_gsc',
+ 'validate_ai_traffic',
+ 'validate_ga4',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/p10-protect-converting-ai-pages.js b/server/src/lib/action-center/definitions/p10-protect-converting-ai-pages.js
new file mode 100644
index 000000000..400c5b89a
--- /dev/null
+++ b/server/src/lib/action-center/definitions/p10-protect-converting-ai-pages.js
@@ -0,0 +1,35 @@
+/**
+ * P10 — Protect High-Converting AI Landing Pages.
+ *
+ * Signal: AI landing pages with key events beginning to lose their traffic.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'protect_converting_ai_pages',
+ code: 'P10',
+ version: 1,
+ category: 'protect',
+ name: 'Protect High-Converting AI Landing Pages',
+ signalKinds: ['converting_page_slipping'],
+ requires: ['analytics'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_ai_traffic',
+ 'analyze_ga4_outcomes',
+ 'analyze_visibility_change',
+ 'analyze_citations',
+ 'identify_target_pages',
+ 'optimize_content',
+ 'improve_cta_path',
+ 'validate_ai_traffic',
+ 'validate_ga4',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/protect-visibility.js b/server/src/lib/action-center/definitions/protect-visibility.js
deleted file mode 100644
index 78c591b3e..000000000
--- a/server/src/lib/action-center/definitions/protect-visibility.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Protect — a real position losing ground, caught before it collapses.
- *
- * The Protect family's first definition (#823). Its trigger is the relative
- * slip detector rather than the collapse, so the two grades differ in
- * severity and in the work they ask for, not in how they are measured.
- */
-export default {
- id: 'protect_visibility',
- version: 1,
- category: 'protect',
- signalKinds: ['visibility_slipping'],
- requires: ['tracking'],
- // Who is taking the ground is context, not a precondition.
- optional: ['competitors'],
- tasks: [
- 'diagnose_slip',
- 'competitor_pressure',
- 'review_responses',
- 'reinforce_content',
- 'validate',
- ],
-
- payload(byKind) {
- const slip = (byKind.get('visibility_slipping') ?? [])[0];
- if (!slip) return {};
- return { dropFrom: slip.previous_value, dropTo: slip.current_value };
- },
-};
diff --git a/server/src/lib/action-center/definitions/r01-recover-visibility.js b/server/src/lib/action-center/definitions/r01-recover-visibility.js
new file mode 100644
index 000000000..7bda51521
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r01-recover-visibility.js
@@ -0,0 +1,41 @@
+/**
+ * R01 — Recover Lost Visibility.
+ *
+ * Signal: A meaningful fall in AI visibility.
+ *
+ * Version 2: the task plan now follows the specification's library, and the
+ * payload names its targets.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_visibility',
+ code: 'R01',
+ version: 2,
+ category: 'recover',
+ name: 'Recover Lost Visibility',
+ signalKinds: ['sharp_drop'],
+ requires: ['tracking'],
+ optional: ['analytics'],
+ enabled: true,
+ tasks: [
+ 'analyze_visibility_change',
+ 'analyze_ai_responses',
+ 'analyze_competitor_visibility',
+ 'analyze_citations',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const drop = first(byKind, 'sharp_drop');
+ return {
+ ...targetPayload(byKind, 'prompts'),
+ dropFrom: drop?.previous_value,
+ dropTo: drop?.current_value,
+ };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/r02-recover-lost-citations.js b/server/src/lib/action-center/definitions/r02-recover-lost-citations.js
new file mode 100644
index 000000000..a7bc28a83
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r02-recover-lost-citations.js
@@ -0,0 +1,33 @@
+/**
+ * R02 — Recover Lost Citations.
+ *
+ * Signal: Citations the brand held consistently, now gone.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_lost_citations',
+ code: 'R02',
+ version: 1,
+ category: 'recover',
+ name: 'Recover Lost Citations',
+ signalKinds: ['lost_citations'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_citations',
+ 'identify_citation_gaps',
+ 'identify_target_pages',
+ 'strengthen_reference_asset',
+ 'refresh_content',
+ 'prepare_outreach',
+ 'validate_citations',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/r03-recover-ai-traffic.js b/server/src/lib/action-center/definitions/r03-recover-ai-traffic.js
new file mode 100644
index 000000000..9785b642d
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r03-recover-ai-traffic.js
@@ -0,0 +1,34 @@
+/**
+ * R03 — Recover AI Traffic.
+ *
+ * Signal: AI referral traffic falling significantly.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_ai_traffic',
+ code: 'R03',
+ version: 1,
+ category: 'recover',
+ name: 'Recover AI Traffic',
+ signalKinds: ['ai_traffic_drop'],
+ requires: ['ai_traffic'],
+ optional: ['analytics'],
+ enabled: true,
+ tasks: [
+ 'analyze_ai_traffic',
+ 'analyze_visibility_change',
+ 'analyze_citations',
+ 'analyze_ga4_outcomes',
+ 'identify_target_pages',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'validate_ai_traffic',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/r04-recover-lost-mentions.js b/server/src/lib/action-center/definitions/r04-recover-lost-mentions.js
new file mode 100644
index 000000000..ac9bc9849
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r04-recover-lost-mentions.js
@@ -0,0 +1,33 @@
+/**
+ * R04 — Recover Lost Mentions.
+ *
+ * Signal: The brand disappearing from prompts where it was mentioned.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_lost_mentions',
+ code: 'R04',
+ version: 1,
+ category: 'recover',
+ name: 'Recover Lost Mentions',
+ signalKinds: ['lost_mentions'],
+ requires: ['tracking'],
+ optional: ['competitors'],
+ enabled: true,
+ tasks: [
+ 'analyze_mention_context',
+ 'analyze_ai_responses',
+ 'analyze_competitor_visibility',
+ 'analyze_citations',
+ 'identify_content_gaps',
+ { branch: [['strengthen_entity_content'], ['optimize_content']] },
+ 'validate_mentions',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/r05-recover-topic-visibility.js b/server/src/lib/action-center/definitions/r05-recover-topic-visibility.js
new file mode 100644
index 000000000..a01902bf7
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r05-recover-topic-visibility.js
@@ -0,0 +1,34 @@
+/**
+ * R05 — Recover Topic Visibility.
+ *
+ * Signal: Coverage of a topic falling significantly.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_topic_visibility',
+ code: 'R05',
+ version: 1,
+ category: 'recover',
+ name: 'Recover Topic Visibility',
+ signalKinds: ['topic_drop'],
+ requires: ['tracking', 'topics'],
+ optional: ['competitors'],
+ enabled: true,
+ tasks: [
+ 'analyze_topic_gap',
+ 'analyze_competitor_visibility',
+ 'analyze_citations',
+ 'cluster_prompts',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_topic_sov',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const lead = first(byKind, 'topic_drop');
+ return { ...targetPayload(byKind, 'topics'), topicName: lead?.payload?.topicName };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/r06-recover-platform-visibility.js b/server/src/lib/action-center/definitions/r06-recover-platform-visibility.js
new file mode 100644
index 000000000..710164ac9
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r06-recover-platform-visibility.js
@@ -0,0 +1,34 @@
+/**
+ * R06 — Recover Platform Visibility.
+ *
+ * Signal: Visibility on one AI platform falling significantly.
+ */
+
+import { first, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_platform_visibility',
+ code: 'R06',
+ version: 1,
+ category: 'recover',
+ name: 'Recover Platform Visibility',
+ signalKinds: ['platform_drop'],
+ requires: ['tracking'],
+ optional: ['competitors'],
+ enabled: true,
+ tasks: [
+ 'analyze_platform_gap',
+ 'analyze_ai_responses',
+ 'analyze_citations',
+ 'analyze_competitor_visibility',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'validate_platform_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ const lead = first(byKind, 'platform_drop');
+ return { ...targetPayload(byKind, 'platforms'), platform: lead?.payload?.platform };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/r07-recover-after-competitor-gains.js b/server/src/lib/action-center/definitions/r07-recover-after-competitor-gains.js
new file mode 100644
index 000000000..7d861dd02
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r07-recover-after-competitor-gains.js
@@ -0,0 +1,33 @@
+/**
+ * R07 — Recover After Competitor Gains.
+ *
+ * Signal: The brand losing ground as a competitor passes it.
+ */
+
+import { competitorNames, targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_after_competitor_gains',
+ code: 'R07',
+ version: 1,
+ category: 'recover',
+ name: 'Recover After Competitor Gains',
+ signalKinds: ['competitor_crossed'],
+ requires: ['tracking', 'competitors'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_visibility_change',
+ 'analyze_competitor_visibility',
+ 'analyze_competitor_citations',
+ 'analyze_competitor_content',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_competitive_gap',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return { ...targetPayload(byKind, 'competitors'), competitorNames: competitorNames(byKind) };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/r08-recover-cited-pages.js b/server/src/lib/action-center/definitions/r08-recover-cited-pages.js
new file mode 100644
index 000000000..35b44b168
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r08-recover-cited-pages.js
@@ -0,0 +1,32 @@
+/**
+ * R08 — Recover Previously Cited Pages.
+ *
+ * Signal: Owned pages that were cited, now cited nowhere.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_cited_pages',
+ code: 'R08',
+ version: 1,
+ category: 'recover',
+ name: 'Recover Previously Cited Pages',
+ signalKinds: ['owned_page_citation_lost'],
+ requires: ['tracking'],
+ optional: [],
+ enabled: true,
+ tasks: [
+ 'analyze_citations',
+ 'identify_target_pages',
+ 'identify_citation_gaps',
+ 'refresh_content',
+ 'strengthen_reference_asset',
+ 'validate_citations',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/r09-recover-high-value-prompts.js b/server/src/lib/action-center/definitions/r09-recover-high-value-prompts.js
new file mode 100644
index 000000000..471b038a2
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r09-recover-high-value-prompts.js
@@ -0,0 +1,34 @@
+/**
+ * R09 — Recover High-Value Prompt Coverage.
+ *
+ * Signal: High-demand prompts losing the brand’s presence.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_high_value_prompts',
+ code: 'R09',
+ version: 1,
+ category: 'recover',
+ name: 'Recover High-Value Prompt Coverage',
+ signalKinds: ['high_value_prompt_lost'],
+ requires: ['tracking', 'volumes'],
+ optional: ['competitors'],
+ enabled: true,
+ tasks: [
+ 'analyze_prompt_gap',
+ 'prioritize_targets',
+ 'map_prompts_to_content',
+ 'analyze_competitor_visibility',
+ 'analyze_citations',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] },
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'prompts');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/r10-recover-search-performance.js b/server/src/lib/action-center/definitions/r10-recover-search-performance.js
new file mode 100644
index 000000000..54797864c
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r10-recover-search-performance.js
@@ -0,0 +1,36 @@
+/**
+ * R10 — Recover Search Performance on AI-Relevant Pages.
+ *
+ * Signal: Search Console clicks falling on queries tied to tracked prompts.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_search_performance',
+ code: 'R10',
+ version: 1,
+ category: 'recover',
+ name: 'Recover Search Performance on AI-Relevant Pages',
+ signalKinds: ['gsc_decline'],
+ requires: ['tracking', 'search_console'],
+ optional: ['site_audits'],
+ enabled: true,
+ tasks: [
+ 'analyze_gsc_demand',
+ 'analyze_gsc_ctr',
+ 'identify_target_pages',
+ 'map_queries_to_prompts',
+ 'analyze_visibility_change',
+ 'analyze_site_audit',
+ 'identify_content_gaps',
+ { branch: [['optimize_content'], ['fix_technical_issue']] },
+ 'validate_gsc',
+ 'validate_ai_visibility',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'queries');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/r11-recover-traffic-after-visibility-loss.js b/server/src/lib/action-center/definitions/r11-recover-traffic-after-visibility-loss.js
new file mode 100644
index 000000000..22362cec3
--- /dev/null
+++ b/server/src/lib/action-center/definitions/r11-recover-traffic-after-visibility-loss.js
@@ -0,0 +1,37 @@
+/**
+ * R11 — Recover Traffic After AI Visibility Loss.
+ *
+ * Signal: AI visibility and AI referral traffic falling in the same window. A
+ * correlation, not a proven cause.
+ */
+
+import { targetPayload } from './_helpers.js';
+
+export default {
+ id: 'recover_traffic_after_visibility_loss',
+ code: 'R11',
+ version: 1,
+ category: 'recover',
+ name: 'Recover Traffic After AI Visibility Loss',
+ signalKinds: ['visibility_traffic_loss'],
+ requires: ['ai_traffic'],
+ optional: ['analytics'],
+ enabled: true,
+ tasks: [
+ 'analyze_visibility_change',
+ 'analyze_ai_traffic',
+ 'analyze_ga4_outcomes',
+ 'analyze_citations',
+ 'identify_target_pages',
+ 'identify_content_gaps',
+ 'optimize_content',
+ 'validate_ai_visibility',
+ 'validate_ai_traffic',
+ 'validate_ga4',
+ 'measure_action_outcome',
+ ],
+
+ payload(byKind) {
+ return targetPayload(byKind, 'pages');
+ },
+};
diff --git a/server/src/lib/action-center/definitions/recover-visibility.js b/server/src/lib/action-center/definitions/recover-visibility.js
deleted file mode 100644
index 1f7f8ea24..000000000
--- a/server/src/lib/action-center/definitions/recover-visibility.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Recover — the brand held a position and lost it.
- *
- * Kept apart from protect_visibility on purpose: the work differs. Recovering
- * asks what was lost and how to win it back; protecting asks what is slipping
- * and how to hold it, while the position still exists to hold.
- */
-export default {
- id: 'recover_visibility',
- version: 1,
- category: 'recover',
- signalKinds: ['sharp_drop', 'lost_citations'],
- requires: ['tracking'],
- // Traffic is not needed to raise the action, but with it connected the plan
- // can show what the drop cost in sessions rather than only in points.
- optional: ['analytics'],
- // measure_traffic_impact requires the analytics source, so it is planned
- // only for a brand that has one — the difference the planner exists for.
- tasks: [
- 'analyze_losses',
- 'measure_traffic_impact',
- 'coverage_gaps',
- 'update_content',
- 'internal_links',
- 'validate',
- ],
-
- payload(byKind) {
- const out = { promptCount: (byKind.get('lost_citations') ?? []).length };
- const drop = (byKind.get('sharp_drop') ?? [])[0];
- if (drop) {
- out.dropFrom = drop.previous_value;
- out.dropTo = drop.current_value;
- }
- return out;
- },
-};
diff --git a/server/src/lib/action-center/definitions/registry.test.js b/server/src/lib/action-center/definitions/registry.test.js
index 385b43a36..0b512207d 100644
--- a/server/src/lib/action-center/definitions/registry.test.js
+++ b/server/src/lib/action-center/definitions/registry.test.js
@@ -9,6 +9,7 @@ vi.mock('../../pulse/metrics.js', () => ({ computePulseMetrics: vi.fn() }));
import { CATEGORIES, isEligible, loadDefinitions } from './index.js';
import { SOURCES } from '../sources.js';
import { KIND_META } from '../../signals/record.js';
+import { LIBRARY_EMITTED_KINDS } from '../../signals/library/detect.js';
const definitions = await loadDefinitions();
@@ -52,7 +53,7 @@ describe('the definition registry', () => {
* would say so — it would simply be quiet forever. Cheaper to fail here
* than to wonder in three months why a family never produced an action.
*/
- it.each(definitions.map((definition) => [definition.id, definition]))(
+ it.each(definitions.filter((d) => d.enabled).map((definition) => [definition.id, definition]))(
'%s only listens for signal kinds a detector emits',
(_id, definition) => {
for (const kind of definition.signalKinds) {
@@ -61,6 +62,41 @@ describe('the definition registry', () => {
},
);
+ /**
+ * The V1 specification's library: 62 definitions, 19 Growth, 10 Protect,
+ * 11 Recover, 13 Fix, 9 Compete. Anything else is not the V1 library.
+ */
+ it('registers the specification’s sixty-two definitions', () => {
+ const byFamily = {};
+ for (const d of definitions) byFamily[d.category] = (byFamily[d.category] ?? 0) + 1;
+ expect(definitions).toHaveLength(62);
+ expect(byFamily).toEqual({ growth: 19, protect: 10, recover: 11, fix: 13, compete: 9 });
+ });
+
+ /**
+ * The reverse of "listens for kinds a detector emits": every kind the
+ * library detectors write has a definition to go to. A kind nothing consumes
+ * fills the Signals page with findings that can never become work.
+ */
+ it('gives every library signal kind a definition', () => {
+ const consumed = new Set(definitions.flatMap((d) => d.signalKinds));
+ for (const kind of LIBRARY_EMITTED_KINDS) {
+ expect({ kind, consumed: consumed.has(kind) }).toEqual({ kind, consumed: true });
+ }
+ });
+
+ it('gives every definition its own specification code', () => {
+ expect(new Set(definitions.map((d) => d.code)).size).toBe(62);
+ });
+
+ /** A disabled definition is a promise with nothing behind it; it has to
+ * say which data it is waiting for. */
+ it('explains every definition it cannot run yet', () => {
+ for (const d of definitions.filter((x) => !x.enabled)) {
+ expect(d.disabledReason?.length ?? 0).toBeGreaterThan(40);
+ }
+ });
+
/**
* Two definitions consuming the same signal kind would both fire on it,
* giving the brand two actions for one condition.
diff --git a/server/src/lib/action-center/execution/run.js b/server/src/lib/action-center/execution/run.js
index c5d634a60..d5cd09cc8 100644
--- a/server/src/lib/action-center/execution/run.js
+++ b/server/src/lib/action-center/execution/run.js
@@ -32,7 +32,7 @@
import supabaseAdmin from '../../../config/supabase.js';
import { logger } from '../../logger.js';
-import { getTask } from '../tasks/registry.js';
+import { APPROVAL_PERMISSIONS, AUTOMATABLE_MODES, getTask } from '../tasks/registry.js';
import { resolveBrandSources } from '../sources.js';
import { getTool } from './tools.js';
import { resolve } from '../../../config/action-engine.js';
@@ -84,11 +84,17 @@ export function blockedReason({ task, primitive, tool, sources, siblings }) {
return `task is ${task.status}`;
}
if (!primitive) return `no task primitive named ${task.task_key}`;
- if (primitive.mode !== 'agent') return 'task is carried out by a person, not automatically';
+ if (!AUTOMATABLE_MODES.includes(primitive.mode)) {
+ return 'task is carried out by a person, not automatically';
+ }
if (!tool) return `no tool implements ${task.task_key} yet`;
if (!sources.has(tool.source)) return `brand has no ${tool.source} source`;
- if (tool.writesExternally && !task.approved_by) {
+ // WRITE and EXECUTE need a person's approval, and so does any tool that
+ // changes something outside Ansvisor, whatever the task says (spec §5).
+ const permission = task.permission ?? primitive.permission;
+ const needsApproval = tool.writesExternally || APPROVAL_PERMISSIONS.includes(permission);
+ if (needsApproval && !task.approved_by) {
return 'changes something outside Ansvisor and has not been approved';
}
@@ -131,7 +137,7 @@ function buildInput({ action, siblings, dependsOn }) {
export async function runTask(taskId, { now = new Date(), sources } = {}) {
const { data: task, error: taskErr } = await supabaseAdmin
.from('action_tasks')
- .select('id, action_id, task_key, status, depends_on, approved_by')
+ .select('id, action_id, task_key, status, depends_on, approved_by, permission')
.eq('id', taskId)
.single();
if (taskErr) throw new Error(taskErr.message);
@@ -174,7 +180,8 @@ export async function runTask(taskId, { now = new Date(), sources } = {}) {
});
// A task held for approval says so in its own status, so the person who
// has to decide can find it without reading the run log.
- if (tool?.writesExternally && !task.approved_by && task.status !== 'waiting_approval') {
+ const heldForApproval = refusal.includes('not been approved');
+ if (heldForApproval && task.status !== 'waiting_approval') {
await supabaseAdmin
.from('action_tasks')
.update({ status: 'waiting_approval', updated_at: now.toISOString() })
diff --git a/server/src/lib/action-center/generate.js b/server/src/lib/action-center/generate.js
index 71119ae3a..c3488d693 100644
--- a/server/src/lib/action-center/generate.js
+++ b/server/src/lib/action-center/generate.js
@@ -227,6 +227,9 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc
let queued = 0;
for (const definition of definitions) {
+ // Registered but switched off — the specification's slot exists, the data
+ // behind it does not yet. Nothing to queue and nothing to raise.
+ if (definition.enabled === false) continue;
const matched = (openSignals ?? []).filter((signal) =>
definition.signalKinds.includes(signal.kind),
);
diff --git a/server/src/lib/action-center/generate.test.js b/server/src/lib/action-center/generate.test.js
index 06e3a4203..5d92968ac 100644
--- a/server/src/lib/action-center/generate.test.js
+++ b/server/src/lib/action-center/generate.test.js
@@ -44,8 +44,10 @@ function mockDb({ signals = [], activeActions = [], closedActions = [], candidat
return builder;
},
in: () => builder,
+ gte: () => builder,
order: () => builder,
limit: () => builder,
+ range: () => builder,
single: () => Promise.resolve(result()),
insert: (payload) => {
state.op = 'insert';
@@ -119,7 +121,12 @@ describe('generateActionsForBrand', () => {
});
// Its own baseline — the "before" half of a future measurement.
expect(action.rows[0].baseline.signals).toHaveLength(1);
- expect(writes.inserted.find((w) => w.table === 'action_tasks').rows).toHaveLength(5);
+ // The plan comes from the specification's library, and ends in validation.
+ const keys = writes.inserted
+ .find((w) => w.table === 'action_tasks')
+ .rows.map((r) => r.task_key);
+ expect(keys).toContain('validate_ai_visibility');
+ expect(keys.at(-1)).toBe('measure_action_outcome');
});
/**
@@ -400,21 +407,71 @@ describe('the task plan the action is created with', () => {
(row) => row.task_key,
);
- it('asks a brand with analytics what the drop cost in sessions', async () => {
- const writes = mockDb({ signals: [signal()] });
+ /** Task Library acceptance tests 1 and 2: G17 without Search Console gets
+ * no Search Console task; with it, the planner may include one. */
+ const underperforming = () =>
+ signal({ kind: 'content_underperforming', impact: 'medium', payload: { targets: [] } });
- await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+ it('plans a Search Console task for a brand that has Search Console', async () => {
+ const writes = mockDb({ signals: [underperforming()] });
- expect(taskRows(writes)).toContain('measure_traffic_impact');
+ await generateActionsForBrand(BRAND, {
+ now: NOW,
+ sources: new Set(['tracking', 'search_console']),
+ });
+
+ expect(taskRows(writes)).toContain('analyze_gsc_demand');
});
- it('does not ask a brand that has no analytics connected', async () => {
- const writes = mockDb({ signals: [signal()] });
+ it('plans none for a brand that does not', async () => {
+ const writes = mockDb({ signals: [underperforming()] });
await generateActionsForBrand(BRAND, { now: NOW, sources: new Set(['tracking']) });
- expect(taskRows(writes)).not.toContain('measure_traffic_impact');
- expect(taskRows(writes).length).toBeGreaterThan(0);
+ expect(taskRows(writes)).not.toContain('analyze_gsc_demand');
+ expect(taskRows(writes)).toContain('optimize_content');
+ });
+
+ /** Task Library acceptance tests 3 and 4: an existing page is optimised; a
+ * missing one is briefed and drafted — never both. */
+ const promptTargets = (mapped) =>
+ signal({
+ kind: 'prompt_visibility_gap',
+ impact: 'medium',
+ payload: { targets: [{ id: 'p1', label: 'a prompt', mapped }] },
+ });
+
+ it('optimises the page that exists', async () => {
+ const writes = mockDb({ signals: [promptTargets(true)] });
+
+ await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(taskRows(writes)).toContain('optimize_content');
+ expect(taskRows(writes)).not.toContain('create_content_draft');
+ });
+
+ it('briefs and drafts the page that does not', async () => {
+ const writes = mockDb({ signals: [promptTargets(false)] });
+
+ await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(taskRows(writes)).toEqual(
+ expect.arrayContaining(['create_content_brief', 'create_content_draft']),
+ );
+ expect(taskRows(writes)).not.toContain('optimize_content');
+ });
+
+ /** Task Library acceptance test 5: no publishing integration does not block
+ * the action — a person publishes. */
+ it('gives publishing to a person when no publishing tool exists', async () => {
+ const writes = mockDb({ signals: [promptTargets(false)] });
+
+ await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ const publish = writes.inserted
+ .find((w) => w.table === 'action_tasks')
+ .rows.find((row) => row.task_key === 'publish_content');
+ expect(publish).toMatchObject({ mode: 'human', permission: 'execute' });
});
it('records how each task may be carried out, and what it waits on', async () => {
@@ -424,8 +481,8 @@ describe('the task plan the action is created with', () => {
const rows = writes.inserted.find((w) => w.table === 'action_tasks').rows;
for (const row of rows) {
- expect(['manual', 'agent']).toContain(row.mode);
- expect(['none', 'approval']).toContain(row.permission);
+ expect(['system', 'agent', 'human', 'human_or_agent']).toContain(row.mode);
+ expect(['read', 'write', 'execute']).toContain(row.permission);
expect(Array.isArray(row.depends_on)).toBe(true);
expect(row.task_version).toBeGreaterThanOrEqual(1);
}
@@ -446,13 +503,12 @@ describe('the task plan the action is created with', () => {
await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+ // "Compare how gemini-web answers…" — the task names what it acts on as a
+ // count and an entity, rendered by the web in the reader's language.
const compare = writes.inserted
.find((w) => w.table === 'action_tasks')
- .rows.find((row) => row.task_key === 'compare_platforms');
- expect(compare.title_params).toEqual({
- platform: 'gemini-web',
- bestPlatform: 'chatgpt-web',
- });
+ .rows.find((row) => row.task_key === 'analyze_platform_gap');
+ expect(compare.title_params).toEqual({ count: 1, entity: 'platforms' });
});
});
diff --git a/server/src/lib/action-center/sources.js b/server/src/lib/action-center/sources.js
index a0803741f..9ef579f10 100644
--- a/server/src/lib/action-center/sources.js
+++ b/server/src/lib/action-center/sources.js
@@ -1,38 +1,49 @@
/**
- * What a brand actually has to work with (#818, phase 4).
+ * What a brand actually has to work with (#818).
*
* A definition declares the data it needs; this module answers whether a
- * given brand has it. Today that answer only gates generation — a brand with
- * no analytics connection is not offered the traffic definition — but the
- * same answer is what phase 5's task planner needs in order to give two
- * brands different plans for the same action kind, so it is computed once
- * here rather than inferred twice.
+ * given brand has it. It gates generation — a brand with no Search Console
+ * connection is not offered a Search Console definition — and the task planner
+ * reads the same answer to decide which tasks a plan can contain.
*
- * Deliberately coarse. "Does this brand have competitors configured" is a
- * stable fact about the workspace; "are there competitor rows in the last
- * seven days" is a detector's question, and detectors already ask it.
+ * Deliberately coarse. "Does this brand have X at all" is a stable fact about
+ * the workspace; whether X moved this week is a detector's question.
*/
import supabaseAdmin from '../../config/supabase.js';
/**
- * Every source a definition may declare. Validation rejects anything else,
- * so a typo in a definition file fails at load rather than silently making
- * that definition ineligible for every brand forever.
+ * Every source a definition may declare. Validation rejects anything else, so
+ * a typo in a definition fails at load rather than silently making that
+ * definition ineligible for every brand forever.
*/
export const SOURCES = Object.freeze([
- /** Our own prompt tracking. Every brand has it — a brand without it is not
- * a brand yet — so it is the source a definition declares when it needs
- * nothing beyond what the product collects by itself. */
+ /** Our own prompt tracking. Every brand has it. */
'tracking',
/** Competitors configured on the brand. */
'competitors',
/** Site Audit runs. */
'site_audits',
- /** An analytics integration connected for the brand's organization. */
+ /** A Google Analytics connection for the brand's organization. */
'analytics',
+ /** A Google Search Console connection with synced query data. */
+ 'search_console',
+ /** Search/AI demand estimates on at least one tracked prompt. */
+ 'volumes',
+ /** AI-referred traffic from either analytics or the tracking snippet. */
+ 'ai_traffic',
+ /** Prompts organised into topics. */
+ 'topics',
]);
+const DAY_MS = 86_400_000;
+
+async function hasRow(query) {
+ const { data, error } = await query.limit(1);
+ if (error) throw new Error(error.message);
+ return (data ?? []).length > 0;
+}
+
/**
* The sources available to one brand.
*
@@ -41,34 +52,86 @@ export const SOURCES = Object.freeze([
*/
export async function resolveBrandSources(brandId) {
const available = new Set(['tracking']);
+ const recent = new Date(Date.now() - 30 * DAY_MS).toISOString();
- const [competitors, audits, brand] = await Promise.all([
- supabaseAdmin.from('competitors').select('id').eq('brand_id', brandId).limit(1),
- supabaseAdmin.from('site_audits').select('id').eq('brand_id', brandId).limit(1),
- supabaseAdmin.from('brands').select('organization_id').eq('id', brandId).limit(1),
- ]);
+ const { data: brand, error: brandErr } = await supabaseAdmin
+ .from('brands')
+ .select('organization_id')
+ .eq('id', brandId)
+ .limit(1);
+ if (brandErr) throw new Error(brandErr.message);
+ const organizationId = (brand ?? [])[0]?.organization_id;
- if (competitors.error) throw new Error(competitors.error.message);
- if (audits.error) throw new Error(audits.error.message);
- if (brand.error) throw new Error(brand.error.message);
+ const [competitors, audits, gscRows, analyticsPages, snippetRows, topics, volumes] =
+ await Promise.all([
+ hasRow(supabaseAdmin.from('competitors').select('id').eq('brand_id', brandId)),
+ hasRow(supabaseAdmin.from('site_audits').select('id').eq('brand_id', brandId)),
+ hasRow(supabaseAdmin.from('gsc_query_stats').select('id').eq('brand_id', brandId)),
+ hasRow(
+ supabaseAdmin
+ .from('ga_ai_traffic_stats')
+ .select('id')
+ .eq('brand_id', brandId)
+ .gte('date', recent.slice(0, 10)),
+ ),
+ hasRow(
+ supabaseAdmin
+ .from('ai_traffic_logs')
+ .select('id')
+ .eq('brand_id', brandId)
+ .gte('created_at', recent),
+ ),
+ hasRow(
+ supabaseAdmin.from('topics').select('id').eq('brand_id', brandId).eq('is_active', true),
+ ),
+ hasVolumes(brandId),
+ ]);
- if ((competitors.data ?? []).length > 0) available.add('competitors');
- if ((audits.data ?? []).length > 0) available.add('site_audits');
+ if (competitors) available.add('competitors');
+ if (audits) available.add('site_audits');
+ if (gscRows) available.add('search_console');
+ if (analyticsPages || snippetRows) available.add('ai_traffic');
+ if (topics) available.add('topics');
+ if (volumes) available.add('volumes');
- // Integrations are connected per organization, not per brand: every brand
- // in a workspace sees the same analytics connection.
- const organizationId = (brand.data ?? [])[0]?.organization_id;
+ // Integrations are connected per organization, not per brand: every brand in
+ // a workspace sees the same analytics connection.
if (organizationId) {
- const { data, error } = await supabaseAdmin
- .from('integration_connections')
- .select('id')
- .eq('organization_id', organizationId)
- .eq('provider', 'google-analytics')
- .eq('status', 'connected')
- .limit(1);
- if (error) throw new Error(error.message);
- if ((data ?? []).length > 0) available.add('analytics');
+ const connected = await hasRow(
+ supabaseAdmin
+ .from('integration_connections')
+ .select('id')
+ .eq('organization_id', organizationId)
+ .eq('provider', 'google-analytics')
+ .eq('status', 'connected'),
+ );
+ if (connected) available.add('analytics');
}
return available;
}
+
+/** Volumes hang off prompts, which hang off prompt sets, which hang off the
+ * brand — so this is the one source that needs a join to answer. */
+async function hasVolumes(brandId) {
+ const { data: sets, error } = await supabaseAdmin
+ .from('prompt_sets')
+ .select('id')
+ .eq('brand_id', brandId);
+ if (error) throw new Error(error.message);
+ const setIds = (sets ?? []).map((s) => s.id);
+ if (setIds.length === 0) return false;
+
+ const { data: prompts, error: promptErr } = await supabaseAdmin
+ .from('prompts')
+ .select('id')
+ .in('prompt_set_id', setIds)
+ .limit(500);
+ if (promptErr) throw new Error(promptErr.message);
+ const promptIds = (prompts ?? []).map((p) => p.id);
+ if (promptIds.length === 0) return false;
+
+ return hasRow(
+ supabaseAdmin.from('prompt_volumes').select('id').in('prompt_id', promptIds.slice(0, 100)),
+ );
+}
diff --git a/server/src/lib/action-center/sources.test.js b/server/src/lib/action-center/sources.test.js
index 39e0c0379..61df6e740 100644
--- a/server/src/lib/action-center/sources.test.js
+++ b/server/src/lib/action-center/sources.test.js
@@ -3,21 +3,21 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const from = vi.fn();
vi.mock('../../config/supabase.js', () => ({ default: { from: (...a) => from(...a) } }));
-import { resolveBrandSources } from './sources.js';
+import { SOURCES, resolveBrandSources } from './sources.js';
const BRAND = 'brand-1';
/**
- * Answers one row per table that has something, nothing for the rest.
- *
- * `tables` is what the brand HAS; anything absent answers empty, which is
- * what a brand without competitors or audits looks like.
+ * Answers one row per table the brand has something in, nothing for the rest
+ * — which is what a brand without Search Console or audits looks like.
*/
function mockDb(tables) {
from.mockImplementation((table) => {
const builder = {
select: () => builder,
eq: () => builder,
+ in: () => builder,
+ gte: () => builder,
limit: () => builder,
then: (resolve, reject) =>
Promise.resolve({ data: tables[table] ?? [], error: null }).then(resolve, reject),
@@ -34,30 +34,62 @@ describe('resolveBrandSources', () => {
expect([...(await resolveBrandSources(BRAND))]).toEqual(['tracking']);
});
- it('reports the competitors and audits the brand has', async () => {
- mockDb({ competitors: [{ id: 'c1' }], site_audits: [{ id: 'a1' }] });
+ it('reports the competitors, audits and topics the brand has', async () => {
+ mockDb({ competitors: [{ id: 'c' }], site_audits: [{ id: 'a' }], topics: [{ id: 't' }] });
const sources = await resolveBrandSources(BRAND);
expect(sources.has('competitors')).toBe(true);
expect(sources.has('site_audits')).toBe(true);
+ expect(sources.has('topics')).toBe(true);
expect(sources.has('analytics')).toBe(false);
});
+ it('reports Search Console once its queries have synced', async () => {
+ mockDb({ gsc_query_stats: [{ id: 'q' }] });
+ expect((await resolveBrandSources(BRAND)).has('search_console')).toBe(true);
+ });
+
+ /** AI traffic is one source whether it comes from analytics or the
+ * snippet: the definitions that need it need the traffic, not the pipe. */
+ it('counts AI traffic from either analytics or the tracking snippet', async () => {
+ mockDb({ ai_traffic_logs: [{ id: 'l' }] });
+ expect((await resolveBrandSources(BRAND)).has('ai_traffic')).toBe(true);
+
+ mockDb({ ga_ai_traffic_stats: [{ id: 'g' }] });
+ expect((await resolveBrandSources(BRAND)).has('ai_traffic')).toBe(true);
+ });
+
+ it('reports demand estimates on the brand’s prompts', async () => {
+ mockDb({ prompt_sets: [{ id: 's' }], prompts: [{ id: 'p' }], prompt_volumes: [{ id: 'v' }] });
+ expect((await resolveBrandSources(BRAND)).has('volumes')).toBe(true);
+ });
+
/** Integrations are connected per organization, so the brand has to be
* resolved to one before the connection can be found. */
it('finds an analytics connection through the brand’s organization', async () => {
- mockDb({
- brands: [{ organization_id: 'org-1' }],
- integration_connections: [{ id: 'i1' }],
- });
-
+ mockDb({ brands: [{ organization_id: 'org-1' }], integration_connections: [{ id: 'i' }] });
expect((await resolveBrandSources(BRAND)).has('analytics')).toBe(true);
});
it('claims no analytics for a brand with no organization', async () => {
- mockDb({ integration_connections: [{ id: 'i1' }] });
-
+ mockDb({ integration_connections: [{ id: 'i' }] });
expect((await resolveBrandSources(BRAND)).has('analytics')).toBe(false);
});
+
+ it('only ever reports sources the registry knows', async () => {
+ mockDb({
+ competitors: [{}],
+ site_audits: [{}],
+ gsc_query_stats: [{}],
+ ai_traffic_logs: [{}],
+ topics: [{}],
+ prompt_sets: [{ id: 's' }],
+ prompts: [{ id: 'p' }],
+ prompt_volumes: [{}],
+ brands: [{ organization_id: 'o' }],
+ integration_connections: [{}],
+ });
+ for (const source of await resolveBrandSources(BRAND)) expect(SOURCES).toContain(source);
+ });
});
diff --git a/server/src/lib/action-center/tasks/plan.js b/server/src/lib/action-center/tasks/plan.js
index 424fe760f..d092d1bb1 100644
--- a/server/src/lib/action-center/tasks/plan.js
+++ b/server/src/lib/action-center/tasks/plan.js
@@ -35,12 +35,34 @@ import { getTask } from './registry.js';
*/
function titleValues(payload) {
const names = Array.isArray(payload.competitorNames) ? payload.competitorNames : [];
- return { ...payload, competitor: names[0] };
+ const count = Number(payload.targetCount ?? 0);
+ return {
+ ...payload,
+ competitor: names[0],
+ // Library tasks name what they act on as a count and an entity. Nothing to
+ // name is no title parameters, and the plain message renders instead.
+ count: count > 0 ? count : undefined,
+ entity: count > 0 ? payload.targetEntity : undefined,
+ };
}
-/** A spec entry is a bare task id, or an id with extra conditions. */
-function normalise(entry) {
- return typeof entry === 'string' ? { id: entry, requires: [] } : { requires: [], ...entry };
+/**
+ * A plan entry, expanded into the task ids it stands for.
+ *
+ * - `'analyze_citations'` — one task;
+ * - `{ id, requires }` — one task, only where the brand has those sources;
+ * - `{ branch: [[…], […]] }` — the specification's `A|B+C`: optimise the
+ * page that exists, or brief and draft the one that does not. The first
+ * branch unless the action says no adequate content exists (spec §7,
+ * tests 3 and 4). Never both.
+ */
+function expand(entry, payload) {
+ if (typeof entry === 'string') return [{ id: entry, requires: [] }];
+ if (entry.branch) {
+ const chosen = payload.contentExists === false ? entry.branch[1] : entry.branch[0];
+ return chosen.map((id) => ({ id, requires: entry.requires ?? [] }));
+ }
+ return [{ requires: [], ...entry }];
}
/**
@@ -55,11 +77,15 @@ export function planTasks(definition, { sources, payload = {} }) {
const values = titleValues(payload);
const chosen = [];
- for (const entry of definition.tasks.map(normalise)) {
+ const seen = new Set();
+ for (const entry of definition.tasks.flatMap((e) => expand(e, payload))) {
const primitive = getTask(entry.id);
- if (!primitive) continue;
+ if (!primitive || seen.has(primitive.id)) continue;
const needed = [...primitive.requires, ...entry.requires];
if (!needed.every((source) => sources.has(source))) continue;
+ // One task per primitive: two capabilities implying the same analysis are
+ // one task over the combined scope (spec §7, test 12).
+ seen.add(primitive.id);
chosen.push(primitive);
}
diff --git a/server/src/lib/action-center/tasks/plan.test.js b/server/src/lib/action-center/tasks/plan.test.js
index 0b0470519..b604d6cb2 100644
--- a/server/src/lib/action-center/tasks/plan.test.js
+++ b/server/src/lib/action-center/tasks/plan.test.js
@@ -6,7 +6,7 @@ import { describe, expect, it, vi } from 'vitest';
vi.mock('../../../config/supabase.js', () => ({ default: { from: vi.fn(), rpc: vi.fn() } }));
import { planTasks } from './plan.js';
-import { TASKS, listTasks, validateTask } from './registry.js';
+import { AUTOMATABLE_MODES, TASKS, libraryTasks, listTasks, validateTask } from './registry.js';
import { loadDefinitions } from '../definitions/index.js';
import { TOOLS } from '../execution/tools.js';
@@ -67,11 +67,44 @@ describe('planTasks', () => {
it('carries the task primitive’s mode, permission and version onto the row', () => {
const plan = planTasks(
- { id: 'x', tasks: ['strengthen_sources', 'validate'] },
+ { id: 'x', tasks: ['publish_content', 'validate_ai_visibility'] },
{ sources: ALL },
);
- expect(plan[0]).toMatchObject({ mode: 'manual', permission: 'approval', version: 1 });
- expect(plan[1]).toMatchObject({ mode: 'agent', permission: 'none' });
+ expect(plan[0]).toMatchObject({ mode: 'human', permission: 'execute', version: 1 });
+ expect(plan[1]).toMatchObject({ mode: 'system', permission: 'read' });
+ });
+
+ describe('branches', () => {
+ const definition = {
+ id: 'x',
+ tasks: [{ branch: [['optimize_content'], ['create_content_brief', 'create_content_draft']] }],
+ };
+
+ it('optimises when content exists', () => {
+ expect(
+ keys(planTasks(definition, { sources: ALL, payload: { contentExists: true } })),
+ ).toEqual(['optimize_content']);
+ });
+
+ it('creates when it does not', () => {
+ expect(
+ keys(planTasks(definition, { sources: ALL, payload: { contentExists: false } })),
+ ).toEqual(['create_content_brief', 'create_content_draft']);
+ });
+
+ /** Creating a page that duplicates one is worse than improving it. */
+ it('optimises when nothing says either way', () => {
+ expect(keys(planTasks(definition, { sources: ALL }))).toEqual(['optimize_content']);
+ });
+ });
+
+ /** Task Library acceptance test 12: one task per primitive. */
+ it('plans a primitive once however many entries imply it', () => {
+ const plan = planTasks(
+ { id: 'x', tasks: ['analyze_citations', 'analyze_citations', 'validate_citations'] },
+ { sources: ALL },
+ );
+ expect(keys(plan)).toEqual(['analyze_citations', 'validate_citations']);
});
it('ignores a task id that no longer exists in the registry', () => {
@@ -121,6 +154,10 @@ describe('planTasks', () => {
});
describe('the task registry', () => {
+ it('holds the specification’s sixty-two task primitives', () => {
+ expect(libraryTasks()).toHaveLength(62);
+ });
+
it.each(listTasks().map((entry) => [entry.id, entry]))('%s is well formed', (_id, entry) => {
expect(validateTask(entry)).toEqual([]);
});
@@ -150,12 +187,16 @@ describe('the task registry', () => {
it('backs every task the shipped definitions ask for', async () => {
const definitions = await loadDefinitions();
for (const definition of definitions) {
- for (const entry of definition.tasks) {
- const id = typeof entry === 'string' ? entry : entry.id;
- expect({ definition: definition.id, id, known: Boolean(TASKS[id]) }).toEqual({
+ const ids = definition.tasks.flatMap((entry) =>
+ typeof entry === 'string' ? [entry] : entry.branch ? entry.branch.flat() : [entry.id],
+ );
+ for (const id of ids) {
+ // Known, and from the library — legacy primitives exist only so old
+ // rows still render; no definition may plan them.
+ expect({ definition: definition.id, id, library: TASKS[id]?.legacy === false }).toEqual({
definition: definition.id,
id,
- known: true,
+ library: true,
});
}
}
@@ -201,8 +242,12 @@ describe('the task registry', () => {
const named = [...messages[`${entry.id}_target`].matchAll(/\{\s*(\w+)\s*[,}]/g)].map(
(m) => m[1],
);
+ // `{targets}` is rendered by the web from the count and entity the
+ // planner stores ("11 prompts"), so it is declared when those are.
+ const declared = new Set(entry.titleKeys);
+ if (declared.has('count') && declared.has('entity')) declared.add('targets');
for (const name of named) {
- expect({ id: entry.id, name, declared: entry.titleKeys.includes(name) }).toEqual({
+ expect({ id: entry.id, name, declared: declared.has(name) }).toEqual({
id: entry.id,
name,
declared: true,
@@ -232,12 +277,21 @@ describe('the task registry', () => {
* brand needs the tool's source as well as the task's own — otherwise a
* task is planned that can never run.
*/
- it('only gives tools to agent tasks, whose requirements cover the tool’s', () => {
+ it('only gives tools to tasks that can run without a person, whose requirements cover the tool’s', () => {
for (const entry of listTasks()) {
if (!entry.tool) continue;
- expect({ id: entry.id, mode: entry.mode }).toEqual({ id: entry.id, mode: 'agent' });
+ expect({ id: entry.id, automatable: AUTOMATABLE_MODES.includes(entry.mode) }).toEqual({
+ id: entry.id,
+ automatable: true,
+ });
+ // A tool reading analytics may sit on a task that only needs AI traffic:
+ // the runner then refuses brands whose traffic comes from the snippet,
+ // and says why.
const source = TOOLS[entry.tool].source;
- const covered = source === 'tracking' || entry.requires.includes(source);
+ const covered =
+ source === 'tracking' ||
+ entry.requires.includes(source) ||
+ (source === 'analytics' && entry.requires.includes('ai_traffic'));
expect({ id: entry.id, source, covered }).toEqual({ id: entry.id, source, covered: true });
}
});
diff --git a/server/src/lib/action-center/tasks/registry.js b/server/src/lib/action-center/tasks/registry.js
index e38840b13..8870ffcc8 100644
--- a/server/src/lib/action-center/tasks/registry.js
+++ b/server/src/lib/action-center/tasks/registry.js
@@ -1,166 +1,398 @@
/**
- * The task registry (#818, phase 5).
+ * The task registry (#818).
*
- * Every action of a given kind got the same task list, inline in its
- * definition, regardless of what the brand actually has. Both specifications
- * rule that out: a plan should follow from the action's targets and the data
- * the workspace holds, not from the kind alone.
+ * 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
+ * user what to achieve; its tasks say how, and a task is one of these.
*
- * So the task text stops being a string in a definition and becomes a
- * primitive with an identity. Each one declares:
+ * Each primitive declares, in the specification's terms:
*
- * - `requires` — the sources a brand needs before this task is worth
- * planning. A task asking someone to read their analytics is noise for a
- * brand with no analytics connected;
- * - `mode` — who can carry it out. `agent` means the work is reading and
- * reasoning over data we already hold, which is the half a tool could do;
- * `manual` means it changes something we do not own — a page, a CMS, a
- * relationship;
- * - `permission` — whether carrying it out reaches outside Ansvisor. Nothing
- * executes yet (phase 7), but the declaration is what phase 7 reads, and
- * deciding it task by task now is safer than deciding it in a hurry later;
- * - `dependsOn` — what must be finished first. Ordering was previously
- * implied by array position and nothing enforced it;
- * - `outputs` — the keys this task's result carries, so one task's finding
- * can feed the next rather than living in someone's head.
+ * - `mode` — SYSTEM (a deterministic comparison Ansvisor does), AGENT,
+ * HUMAN, or HUMAN_OR_AGENT (either, depending on the tools connected);
+ * - `permission` — READ, WRITE (changes the brand's own content) or EXECUTE
+ * (acts externally: publishing, sending outreach). WRITE and EXECUTE need a
+ * person's approval unless the workspace authorises autonomy;
+ * - `requires` — sources the brand must have for the task to be planned.
+ * Missing optional data removes a task, never the action (spec §7);
+ * - `dependsOn` — what must finish first (spec §10). The planner drops a
+ * dependency on a task that is not in the plan;
+ * - `outputs` — the structured result, so the next task can read it (§12);
+ * - `tool` — the tool that carries it out automatically, where one exists.
*
- * `version` belongs to the task, bumped when what it asks for changes. An
- * action's tasks record the version they were planned from, for the same
- * reason actions record their definition's.
+ * Every primitive's user-facing text lives in i18n as `<id>` and, naming what
+ * it acts on, `<id>_target` ("Analyze citations across 11 sources"). Internal
+ * ids are never shown (spec §11).
+ *
+ * The twenty-three `legacy` entries are the tasks actions were given before
+ * the library existed. They stay so those rows still render and still run;
+ * no definition may plan them.
*/
/** A brand source, as resolved by action-center/sources.js. */
-const SOURCES = ['tracking', 'competitors', 'site_audits', 'analytics'];
+const SOURCES = [
+ 'tracking',
+ 'competitors',
+ 'site_audits',
+ 'analytics',
+ 'search_console',
+ 'volumes',
+ 'ai_traffic',
+ 'topics',
+];
+
+export const MODES = Object.freeze(['system', 'agent', 'human', 'human_or_agent']);
+export const PERMISSIONS = Object.freeze(['read', 'write', 'execute']);
-/** Who carries the task out. */
-export const MODES = Object.freeze(['manual', 'agent']);
+/** Modes the runner may carry out without a person. */
+export const AUTOMATABLE_MODES = Object.freeze(['system', 'agent', 'human_or_agent']);
-/** Whether carrying it out reaches outside Ansvisor. */
-export const PERMISSIONS = Object.freeze(['none', 'approval']);
+/** Permissions that need a person's approval before anything is done. */
+export const APPROVAL_PERMISSIONS = Object.freeze(['write', 'execute']);
const task = (id, spec) =>
Object.freeze({
id,
version: 1,
- mode: 'manual',
- permission: 'none',
+ mode: 'human',
+ permission: 'read',
+ legacy: false,
...spec,
requires: Object.freeze(spec.requires ?? []),
dependsOn: Object.freeze(spec.dependsOn ?? []),
outputs: Object.freeze(spec.outputs ?? []),
- /** Payload keys whose values the task's text can name. When every one is
- * present the planner stores them and the web renders the `_target`
- * variant of the task's message; otherwise the plain one. */
- titleKeys: Object.freeze(spec.titleKeys ?? []),
- /** The tool that carries this task out, if one does yet. A task with a
- * mode of `agent` and no tool is one we mean to automate and have not —
- * the runner says exactly that rather than improvising. */
+ /** Payload keys the `_target` message names. Library tasks all name their
+ * targets as a count and an entity — "11 prompts", "6 sources". */
+ titleKeys: Object.freeze(spec.titleKeys ?? (spec.legacy ? [] : ['count', 'entity'])),
tool: spec.tool ?? null,
});
-/**
- * Every task primitive, keyed by id. The id is what `action_tasks.task_key`
- * stores and what the web resolves its text from, so it is permanent.
- */
+/** Every execution step a validation can wait on. The planner keeps only the
+ * ones actually in a plan. */
+const EXECUTION = [
+ 'optimize_content',
+ 'refresh_content',
+ 'create_content_draft',
+ 'strengthen_reference_asset',
+ 'strengthen_entity_content',
+ 'add_internal_links',
+ 'improve_cta_path',
+ 'publish_content',
+ 'fix_crawler_access',
+ 'fix_structured_data',
+ 'fix_broken_target',
+ 'fix_technical_issue',
+ 'execute_outreach',
+];
+
+const VALIDATIONS = [
+ 'validate_ai_visibility',
+ 'validate_mentions',
+ 'validate_citations',
+ 'validate_topic_sov',
+ 'validate_platform_visibility',
+ 'validate_country_visibility',
+ 'validate_ai_traffic',
+ 'validate_gsc',
+ 'validate_ga4',
+ 'validate_competitive_gap',
+ 'validate_technical_fix',
+ 'validate_third_party_presence',
+ 'validate_third_party_citation',
+];
+
+const system = (id, spec = {}) => task(id, { mode: 'system', ...spec });
+const agent = (id, spec = {}) => task(id, { mode: 'agent', ...spec });
+const either = (id, spec = {}) => task(id, { mode: 'human_or_agent', ...spec });
+const human = (id, spec = {}) => task(id, { mode: 'human', ...spec });
+const validation = (id, spec = {}) =>
+ system(id, {
+ dependsOn: EXECUTION,
+ outputs: ['baseline', 'current', 'absoluteChange', 'relativeChange'],
+ ...spec,
+ });
+
export const TASKS = Object.freeze({
- // ── Reading what happened ────────────────────────────────────────────────
+ // ── Research / diagnosis ──────────────────────────────────────────────────
+ analyze_ai_responses: agent('analyze_ai_responses', { outputs: ['findings', 'targetRefs'] }),
+ analyze_visibility_change: system('analyze_visibility_change', {
+ outputs: ['baseline', 'current', 'targetRefs'],
+ }),
+ analyze_platform_gap: system('analyze_platform_gap', { outputs: ['platformRates'] }),
+ analyze_country_gap: system('analyze_country_gap', { outputs: ['regionRates'] }),
+ analyze_topic_gap: system('analyze_topic_gap', {
+ requires: ['topics'],
+ outputs: ['missingTopics', 'targetRefs'],
+ }),
+ analyze_prompt_gap: system('analyze_prompt_gap', { outputs: ['promptIds', 'findings'] }),
+ analyze_fanout_gap: system('analyze_fanout_gap', { outputs: ['queries', 'targetRefs'] }),
+ analyze_mention_context: agent('analyze_mention_context', { outputs: ['contexts', 'findings'] }),
+ analyze_citations: system('analyze_citations', {
+ outputs: [
+ 'affectedCitationIds',
+ 'lostSources',
+ 'currentSources',
+ 'competitorSources',
+ 'targetRefs',
+ 'findings',
+ ],
+ }),
+ analyze_competitor_visibility: system('analyze_competitor_visibility', {
+ requires: ['competitors'],
+ outputs: ['competitorRates'],
+ }),
+ analyze_competitor_citations: system('analyze_competitor_citations', {
+ requires: ['competitors'],
+ outputs: ['competitorSources'],
+ }),
+ analyze_competitor_content: agent('analyze_competitor_content', {
+ requires: ['competitors'],
+ outputs: ['findings'],
+ }),
+ analyze_ai_traffic: system('analyze_ai_traffic', {
+ requires: ['ai_traffic'],
+ outputs: ['sessions', 'pages'],
+ tool: 'ga_traffic_window',
+ }),
+ analyze_gsc_demand: system('analyze_gsc_demand', {
+ requires: ['search_console'],
+ outputs: ['queries'],
+ }),
+ analyze_gsc_ctr: system('analyze_gsc_ctr', {
+ requires: ['search_console'],
+ outputs: ['queries'],
+ }),
+ analyze_ga4_outcomes: system('analyze_ga4_outcomes', {
+ requires: ['analytics'],
+ outputs: ['keyEvents', 'engagement'],
+ }),
+ analyze_site_audit: system('analyze_site_audit', {
+ requires: ['site_audits'],
+ outputs: ['failingSignals'],
+ }),
+ analyze_entity_signals: agent('analyze_entity_signals', { outputs: ['findings'] }),
+ analyze_internal_links: system('analyze_internal_links', {
+ requires: ['site_audits'],
+ outputs: ['linkGaps'],
+ }),
+ analyze_third_party_sources: agent('analyze_third_party_sources', {
+ outputs: ['sources', 'findings'],
+ }),
+
+ // ── Mapping / prioritisation ──────────────────────────────────────────────
+ cluster_prompts: agent('cluster_prompts', { outputs: ['clusters'] }),
+ map_prompts_to_content: agent('map_prompts_to_content', { outputs: ['mapping'] }),
+ map_queries_to_prompts: system('map_queries_to_prompts', {
+ requires: ['search_console'],
+ outputs: ['mapping'],
+ }),
+ identify_target_pages: agent('identify_target_pages', { outputs: ['targetPageIds'] }),
+ identify_content_gaps: agent('identify_content_gaps', {
+ outputs: [
+ 'targetPageIds',
+ 'promptIds',
+ 'missingTopics',
+ 'missingEntities',
+ 'missingQuestions',
+ 'recommendedChanges',
+ ],
+ }),
+ identify_new_content_need: agent('identify_new_content_need', { outputs: ['assetsNeeded'] }),
+ identify_citation_gaps: agent('identify_citation_gaps', { outputs: ['citationGaps'] }),
+ identify_target_sources: agent('identify_target_sources', { outputs: ['sources'] }),
+ identify_inclusion_path: agent('identify_inclusion_path', {
+ dependsOn: ['identify_target_sources'],
+ outputs: ['paths'],
+ }),
+ prioritize_targets: system('prioritize_targets', { outputs: ['orderedTargets'] }),
+ define_validation_baseline: system('define_validation_baseline', {
+ outputs: ['baseline', 'window'],
+ }),
+
+ // ── Content execution ─────────────────────────────────────────────────────
+ create_content_brief: agent('create_content_brief', {
+ outputs: [
+ 'targetTopic',
+ 'targetPrompts',
+ 'intent',
+ 'recommendedSections',
+ 'entities',
+ 'citationOpportunities',
+ 'internalLinkTargets',
+ ],
+ }),
+ create_content_draft: agent('create_content_draft', {
+ dependsOn: ['create_content_brief'],
+ outputs: ['draft'],
+ }),
+ optimize_content: either('optimize_content', {
+ permission: 'write',
+ dependsOn: ['identify_content_gaps'],
+ outputs: ['changes'],
+ }),
+ refresh_content: either('refresh_content', {
+ permission: 'write',
+ dependsOn: ['identify_content_gaps'],
+ outputs: ['changes'],
+ }),
+ strengthen_reference_asset: either('strengthen_reference_asset', {
+ permission: 'write',
+ outputs: ['changes'],
+ }),
+ strengthen_entity_content: either('strengthen_entity_content', {
+ permission: 'write',
+ outputs: ['changes'],
+ }),
+ add_internal_links: either('add_internal_links', { permission: 'write', outputs: ['links'] }),
+ improve_cta_path: either('improve_cta_path', { permission: 'write', outputs: ['changes'] }),
+ // No publishing integration exists yet, so a person publishes — the action is
+ // not blocked for want of a CMS tool (spec §7, test 5).
+ publish_content: human('publish_content', {
+ permission: 'execute',
+ dependsOn: ['create_content_draft', 'optimize_content', 'refresh_content'],
+ outputs: ['targetId', 'integrationId', 'toolCallId', 'publishedUrl', 'publishedAt', 'status'],
+ }),
+
+ // ── Technical execution ───────────────────────────────────────────────────
+ fix_crawler_access: human('fix_crawler_access', { permission: 'write', outputs: ['changes'] }),
+ fix_structured_data: human('fix_structured_data', { permission: 'write', outputs: ['changes'] }),
+ fix_broken_target: human('fix_broken_target', { permission: 'write', outputs: ['changes'] }),
+ fix_technical_issue: human('fix_technical_issue', { permission: 'write', outputs: ['changes'] }),
+ validate_technical_fix: validation('validate_technical_fix', { requires: ['site_audits'] }),
+
+ // ── Third-party / authority ───────────────────────────────────────────────
+ // Nothing here edits a third-party site. Inclusion is earned through a
+ // legitimate path a person, or an approved tool, carries out (spec §22).
+ prepare_outreach: either('prepare_outreach', {
+ dependsOn: ['identify_inclusion_path'],
+ outputs: ['messages'],
+ }),
+ execute_outreach: human('execute_outreach', {
+ permission: 'execute',
+ dependsOn: ['prepare_outreach'],
+ outputs: ['sent'],
+ }),
+ prepare_contribution: either('prepare_contribution', {
+ dependsOn: ['identify_inclusion_path'],
+ outputs: ['material'],
+ }),
+ track_third_party_status: human('track_third_party_status', {
+ dependsOn: ['execute_outreach'],
+ outputs: ['status'],
+ }),
+ validate_third_party_presence: validation('validate_third_party_presence', {
+ dependsOn: ['track_third_party_status'],
+ }),
+ validate_third_party_citation: validation('validate_third_party_citation', {
+ dependsOn: ['track_third_party_status'],
+ }),
+
+ // ── Validation ────────────────────────────────────────────────────────────
+ validate_ai_visibility: validation('validate_ai_visibility', { tool: 'visibility_window' }),
+ validate_mentions: validation('validate_mentions'),
+ validate_citations: validation('validate_citations'),
+ validate_topic_sov: validation('validate_topic_sov', { requires: ['topics'] }),
+ validate_platform_visibility: validation('validate_platform_visibility'),
+ validate_country_visibility: validation('validate_country_visibility'),
+ validate_ai_traffic: validation('validate_ai_traffic', {
+ requires: ['ai_traffic'],
+ tool: 'ga_traffic_window',
+ }),
+ validate_gsc: validation('validate_gsc', { requires: ['search_console'] }),
+ validate_ga4: validation('validate_ga4', { requires: ['analytics'] }),
+ validate_competitive_gap: validation('validate_competitive_gap', { requires: ['competitors'] }),
+ // The outcome itself is measured by the nightly validation sweep once the
+ // window has passed; this task is its place in the plan.
+ measure_action_outcome: system('measure_action_outcome', {
+ dependsOn: VALIDATIONS,
+ outputs: ['outcome'],
+ }),
+
+ // ── Legacy — tasks raised before the library existed ──────────────────────
analyze_losses: task('analyze_losses', {
+ legacy: true,
mode: 'agent',
titleKeys: ['promptCount'],
- outputs: ['lostPrompts', 'competitorSources'],
}),
- diagnose_slip: task('diagnose_slip', { mode: 'agent', outputs: ['slippingPrompts'] }),
+ diagnose_slip: task('diagnose_slip', { legacy: true, mode: 'agent' }),
review_responses: task('review_responses', {
+ legacy: true,
mode: 'agent',
dependsOn: ['diagnose_slip'],
- outputs: ['weakAnswers'],
- }),
- review_pages: task('review_pages', {
- mode: 'agent',
- titleKeys: ['pageCount'],
- outputs: ['pages'],
}),
+ review_pages: task('review_pages', { legacy: true, mode: 'agent', titleKeys: ['pageCount'] }),
review_audits: task('review_audits', {
+ legacy: true,
mode: 'agent',
requires: ['site_audits'],
titleKeys: ['pageCount'],
- outputs: ['failingSignals'],
}),
identify_prompts: task('identify_prompts', {
+ legacy: true,
mode: 'agent',
titleKeys: ['promptCount'],
- outputs: ['prompts'],
}),
compare_platforms: task('compare_platforms', {
+ legacy: true,
mode: 'agent',
titleKeys: ['platform', 'bestPlatform'],
- outputs: ['platformRates'],
}),
compare_citations: task('compare_citations', {
+ legacy: true,
mode: 'agent',
requires: ['competitors'],
titleKeys: ['competitor'],
- outputs: ['competitorSources'],
}),
analyze_competitor: task('analyze_competitor', {
+ legacy: true,
mode: 'agent',
requires: ['competitors'],
titleKeys: ['competitor'],
- outputs: ['competitorPrompts'],
}),
- coverage_gaps: task('coverage_gaps', { mode: 'agent', outputs: ['gaps'] }),
+ coverage_gaps: task('coverage_gaps', { legacy: true, mode: 'agent' }),
identify_sources: task('identify_sources', {
+ legacy: true,
mode: 'agent',
dependsOn: ['compare_citations'],
- outputs: ['sources'],
}),
-
- // ── Reading what it cost, when the brand has the data to say ─────────────
- // The three tasks that exist only for a connected source. They are what
- // makes two brands' plans for the same action differ — see plan.js.
measure_traffic_impact: task('measure_traffic_impact', {
+ legacy: true,
mode: 'agent',
requires: ['analytics'],
dependsOn: ['analyze_losses'],
- outputs: ['sessionsLost'],
tool: 'ga_traffic_window',
}),
competitor_pressure: task('competitor_pressure', {
+ legacy: true,
mode: 'agent',
requires: ['competitors'],
dependsOn: ['diagnose_slip'],
- outputs: ['gainingCompetitors'],
}),
page_readiness: task('page_readiness', {
+ legacy: true,
mode: 'agent',
requires: ['site_audits'],
dependsOn: ['review_pages'],
- outputs: ['failingSignals'],
}),
-
- // ── Changing something we do not own ─────────────────────────────────────
- update_content: task('update_content', { dependsOn: ['coverage_gaps'] }),
- optimize_content: task('optimize_content', { dependsOn: ['coverage_gaps'] }),
- reinforce_content: task('reinforce_content', { dependsOn: ['review_responses'] }),
- strengthen_content: task('strengthen_content', { dependsOn: ['coverage_gaps'] }),
- create_citable_content: task('create_citable_content', { dependsOn: ['identify_prompts'] }),
- internal_links: task('internal_links', { dependsOn: ['update_content'] }),
- fix_issues: task('fix_issues', { requires: ['site_audits'], dependsOn: ['review_audits'] }),
-
- // ── Reaching outside ─────────────────────────────────────────────────────
- // Manual today, but declared as needing approval: whoever makes this
- // executable in phase 7 should not have to decide that under deadline.
+ update_content: task('update_content', { legacy: true, dependsOn: ['coverage_gaps'] }),
+ reinforce_content: task('reinforce_content', { legacy: true, dependsOn: ['review_responses'] }),
+ strengthen_content: task('strengthen_content', { legacy: true, dependsOn: ['coverage_gaps'] }),
+ create_citable_content: task('create_citable_content', {
+ legacy: true,
+ dependsOn: ['identify_prompts'],
+ }),
+ internal_links: task('internal_links', { legacy: true, dependsOn: ['update_content'] }),
+ fix_issues: task('fix_issues', {
+ legacy: true,
+ requires: ['site_audits'],
+ dependsOn: ['review_audits'],
+ }),
strengthen_sources: task('strengthen_sources', {
- permission: 'approval',
+ legacy: true,
+ permission: 'execute',
dependsOn: ['identify_sources'],
}),
-
- // ── Checking whether it worked ───────────────────────────────────────────
- // The two tasks a tool carries out today. `mode: 'agent'` says a task
- // could be automated; `tool` says it is. The rest keep the mode and wait
- // for a tool, the same way definitions waited for detectors.
- validate: task('validate', { mode: 'agent', tool: 'visibility_window' }),
- revalidate: task('revalidate', { mode: 'agent', requires: ['site_audits'] }),
+ validate: task('validate', { legacy: true, mode: 'agent', tool: 'visibility_window' }),
+ revalidate: task('revalidate', { legacy: true, mode: 'agent', requires: ['site_audits'] }),
});
export function getTask(id) {
@@ -171,11 +403,12 @@ export function listTasks() {
return Object.values(TASKS);
}
-/**
- * Everything a task must get right. Called by the registry's own test rather
- * than at import time: the registry is a literal in this file, so a mistake
- * is caught by CI, not by production starting up.
- */
+/** The primitives definitions plan from — the specification's library. */
+export function libraryTasks() {
+ return listTasks().filter((entry) => !entry.legacy);
+}
+
+/** Everything a primitive must get right; run by the registry's own test. */
export function validateTask(entry) {
const problems = [];
if (!entry.id || !/^[a-z][a-z0-9_]*$/.test(entry.id))
diff --git a/server/src/lib/signals/library/classify.js b/server/src/lib/signals/library/classify.js
new file mode 100644
index 000000000..2e224a624
--- /dev/null
+++ b/server/src/lib/signals/library/classify.js
@@ -0,0 +1,450 @@
+/**
+ * The V1 library's detectors, as decisions over numbers already fetched.
+ *
+ * Each function takes the compact summaries the `ae_*` reads return and says
+ * which signal kinds they amount to. No database, no clock beyond what is
+ * passed in — the same split as `classifyVisibilityFall` and
+ * `classifyPlatformGap`, for the same reason: the decision is the part worth
+ * testing, and it should be testable without a brand.
+ *
+ * Two rules run through all of them.
+ *
+ * Every prompt, source, page or query lands in at most one kind per family.
+ * The specification gives similar conditions separate definitions with
+ * separate work — a prompt with demand and no page needs content created, one
+ * with a page needs it optimised — and a target counted twice would put the
+ * same work in front of the user under two titles.
+ *
+ * Groups are signals; single rows are not. A prompt-level finding becomes one
+ * signal listing the prompts, because the action it feeds is "Expand
+ * visibility across 14 prompts", not fourteen actions.
+ */
+
+const round1 = (n) => Math.round(n * 10) / 10;
+const ratio = (part, whole) => (whole > 0 ? part / whole : 0);
+
+/** Keeps the strongest `max`, so a noisy night writes a bounded number of rows. */
+export function strongest(items, score, max) {
+ return [...items].sort((a, b) => score(b) - score(a)).slice(0, max);
+}
+
+// ─── Prompts ────────────────────────────────────────────────────────────────
+
+/**
+ * Which absence or loss a prompt amounts to, if any.
+ *
+ * Losses are checked first: a prompt that was visible and is not has a
+ * history worth recovering, which is different work from one that was never
+ * visible. Among the never-visible, demand and an existing page decide the
+ * work: create content, optimise the page that exists, or map one.
+ */
+export function classifyPrompt(p, t) {
+ const tracked = p.cur_days >= t.promptMinDays;
+ const highValue = (p.volume ?? 0) >= t.highDemandVolume;
+
+ if (tracked && p.cur_mention_days === 0 && p.prev_mention_days >= t.lostMentionMinDays) {
+ return highValue ? 'high_value_prompt_lost' : 'lost_mentions';
+ }
+ if (!tracked || p.cur_mention_days > 0) return null;
+
+ const everCited = Boolean(p.last_citation_day);
+ if (highValue && !p.has_target_url && !everCited) return 'uncovered_demand';
+ if (highValue) return 'high_demand_gap';
+ if (p.has_target_url) return 'content_underperforming';
+ if (!everCited) return 'prompt_unmapped';
+ return 'prompt_visibility_gap';
+}
+
+/** Citations thinning without disappearing — the Protect grade of what
+ * `lost_citations` reports once they are gone. */
+export function isCitationAtRisk(p, t) {
+ return (
+ p.prev_citation_days >= t.citationRiskMinDays &&
+ p.cur_citation_days > 0 &&
+ p.cur_citation_days < p.prev_citation_days * t.citationRiskRatio
+ );
+}
+
+/**
+ * Prompt rows → grouped findings, one list per kind.
+ *
+ * A loss of one prompt stands on its own; an absence needs company before it
+ * is an action's worth — three prompts nobody sees is a pattern, one is a
+ * prompt.
+ */
+export function groupPrompts(prompts, t) {
+ const groups = {};
+ const add = (kind, p) => (groups[kind] ??= []).push(p);
+
+ for (const p of prompts) {
+ const kind = classifyPrompt(p, t);
+ if (kind) add(kind, p);
+ if (isCitationAtRisk(p, t)) add('citation_at_risk', p);
+ }
+
+ const minimum = {
+ lost_mentions: 2,
+ high_value_prompt_lost: 1,
+ citation_at_risk: 2,
+ };
+ for (const [kind, list] of Object.entries(groups)) {
+ if (list.length < (minimum[kind] ?? t.promptGroupMin)) delete groups[kind];
+ }
+ return groups;
+}
+
+// ─── Topics ─────────────────────────────────────────────────────────────────
+
+/**
+ * A topic's coverage — the share of its tracked prompts the brand appeared on
+ * — now and before, and what that amounts to.
+ *
+ * Declines are judged before levels, relatively, the way the visibility fall
+ * is: a topic that went from 60% to 45% coverage is slipping even though 45%
+ * would be a fine place to be for a topic that had never been higher.
+ */
+export function classifyTopic({ tracked, visible, prevTracked, prevVisible }, t) {
+ if (tracked < t.topicMinPrompts) return null;
+ const cur = ratio(visible, tracked);
+ const prev = ratio(prevVisible, prevTracked);
+
+ if (prevTracked >= t.topicMinPrompts && prev > 0) {
+ const fall = (prev - cur) / prev;
+ if (prev >= t.topicLeadershipCoverage && fall >= t.slipRatio && fall < t.dropRatio) {
+ return 'topic_slipping';
+ }
+ if (prev >= t.topicUncoveredCoverage && fall >= t.dropRatio) return 'topic_drop';
+ }
+ if (cur < t.topicUncoveredCoverage) return 'topic_uncovered';
+ if (cur < t.topicPartialCoverage) return 'topic_gap';
+ return null;
+}
+
+export function topicCoverage(prompts, t) {
+ const byTopic = new Map();
+ for (const p of prompts) {
+ if (!p.topic_id) continue;
+ const e = byTopic.get(p.topic_id) ?? {
+ topicId: p.topic_id,
+ tracked: 0,
+ visible: 0,
+ prevTracked: 0,
+ prevVisible: 0,
+ prompts: [],
+ mapped: 0,
+ };
+ if (p.cur_days >= t.promptMinDays) {
+ e.tracked += 1;
+ if (p.cur_mention_days > 0) e.visible += 1;
+ }
+ if (p.prev_days >= t.promptMinDays) {
+ e.prevTracked += 1;
+ if (p.prev_mention_days > 0) e.prevVisible += 1;
+ }
+ if (p.has_target_url) e.mapped += 1;
+ e.prompts.push(p);
+ byTopic.set(p.topic_id, e);
+ }
+ return [...byTopic.values()];
+}
+
+// ─── Platforms and regions ──────────────────────────────────────────────────
+
+/** A platform's mention rate, now against before: slipping, collapsing, or
+ * neither. A platform that was never worth anything cannot slip. */
+export function classifyRateFall(row, t, { slip, drop }) {
+ if ((row.prev_answers ?? 0) < t.platformMinAnswers) return null;
+ if ((row.cur_answers ?? 0) < t.platformMinAnswers) return null;
+ const prev = ratio(row.prev_mentions, row.prev_answers);
+ const cur = ratio(row.cur_mentions, row.cur_answers);
+ if (prev < t.rateFloor) return null;
+ const fall = (prev - cur) / prev;
+ if (fall >= t.dropRatio) return drop;
+ if (fall >= t.slipRatio) return slip;
+ return null;
+}
+
+/** Strong in one tracked region, weak in another. Needs two regions with
+ * enough answers to be regions at all, which few brands have. */
+export function classifyCountryGap(regions, t) {
+ const rated = regions
+ .filter((r) => (r.cur_answers ?? 0) >= t.platformMinAnswers && r.key)
+ .map((r) => ({ key: r.key, rate: ratio(r.cur_mentions, r.cur_answers) }));
+ if (rated.length < 2) return null;
+ const sorted = [...rated].sort((a, b) => b.rate - a.rate);
+ const best = sorted[0];
+ const worst = sorted[sorted.length - 1];
+ if (best.rate < t.rateFloor) return null;
+ if (best.rate - worst.rate < t.countryGapPoints) return null;
+ return { best, worst, points: round1((best.rate - worst.rate) * 100) };
+}
+
+// ─── Competitors ────────────────────────────────────────────────────────────
+
+/**
+ * What each competitor's week amounts to against the brand's.
+ *
+ * Leading and gaining are separate kinds and a competitor can be both: one is
+ * a standing gap to close, the other a trend to answer, and the specification
+ * gives them separate work.
+ */
+export function classifyCompetitor(c, brandMentions, t) {
+ const kinds = [];
+ const cur = c.cur_mentions ?? 0;
+ const prev = c.prev_mentions ?? 0;
+ if (cur >= t.competitorLeadMinMentions && cur >= brandMentions * t.competitorLeadMultiple) {
+ kinds.push('competitor_leads');
+ }
+ if (prev >= t.competitorMomentumMin && (cur - prev) / prev >= t.competitorMomentumRatio) {
+ kinds.push('competitor_momentum');
+ }
+ return kinds;
+}
+
+/**
+ * A topic a competitor holds and the brand does not. Split by whether the
+ * brand has a page for any of it: with one, the work is optimising; without,
+ * it is creating — and the specification gives those different definitions.
+ */
+export function classifyCompetitorTopic(topic, competitorPresent, t) {
+ const contested = topic.prompts.filter((p) => p.cur_days >= t.promptMinDays);
+ if (contested.length < t.topicMinPrompts) return null;
+ const lost = contested.filter(
+ (p) => p.cur_mention_days === 0 && competitorPresent.has(p.prompt_id),
+ );
+ if (ratio(lost.length, contested.length) < t.competitorTopicShare) return null;
+ return topic.mapped === 0 ? 'competitor_uncovered_topic' : 'competitor_topic_lead';
+}
+
+// ─── Citation sources ───────────────────────────────────────────────────────
+
+/**
+ * Which third-party gap a cited domain represents, if any.
+ *
+ * In order: a source competitors win and the brand never appears beside;
+ * one where only a competitor sometimes appears; one where the brand simply
+ * never appears; a high-traffic source the brand rarely appears beside; and
+ * a source used when answers talk about the brand, which could reference the
+ * brand's own pages and does not. Owned domains are not third parties.
+ */
+export function classifySource(d, t) {
+ if (d.owned) return null;
+ if ((d.results ?? 0) < t.sourceMinResults || (d.prompts ?? 0) < t.sourceMinPrompts) return null;
+
+ const brandShare = ratio(d.with_brand, d.results);
+ const competitorShare = ratio(d.competitor_only, d.results);
+
+ if (d.with_brand === 0) {
+ if (competitorShare >= t.competitorSourceShare && d.prompts >= 3) {
+ return 'competitor_winning_source';
+ }
+ if (d.competitor_only > 0) return 'competitor_cited_source';
+ return 'third_party_presence_gap';
+ }
+ if (d.results >= t.authorityMinResults && brandShare < t.authorityBrandShare) {
+ return 'authority_citation_gap';
+ }
+ return 'third_party_citation_gap';
+}
+
+// ─── Owned pages ────────────────────────────────────────────────────────────
+
+export function classifyOwnedPage(u, t) {
+ const prev = u.prev_citations ?? 0;
+ const cur = u.cur_citations ?? 0;
+ if (prev < t.ownedPageMinCitations) return null;
+ if (cur === 0) return 'owned_page_citation_lost';
+ if (cur < prev * t.ownedPageSlipRatio) return 'page_citation_slipping';
+ return null;
+}
+
+// ─── Fan-outs ───────────────────────────────────────────────────────────────
+
+/** A fan-out query engines ran across several prompts where the brand never
+ * appeared; a competitor appearing on it makes it a competitive one. */
+export function classifyFanout(q, t) {
+ if ((q.prompts ?? 0) < t.fanoutMinPrompts) return null;
+ return (q.competitor_only ?? 0) >= 2 ? 'competitor_fanout_gap' : 'fanout_gap';
+}
+
+// ─── Search Console ─────────────────────────────────────────────────────────
+
+const STOPWORDS = new Set([
+ 'the',
+ 'and',
+ 'for',
+ 'with',
+ 'what',
+ 'how',
+ 'best',
+ 'are',
+ 'is',
+ 'of',
+ 'to',
+ 'in',
+ 'a',
+ 'an',
+ 've',
+ 'ile',
+ 'için',
+ 'nedir',
+ 'nasıl',
+ 'en',
+ 'bir',
+ 'mi',
+ 'mı',
+ 'da',
+ 'de',
+]);
+
+export function tokens(text) {
+ return new Set(
+ String(text ?? '')
+ .toLowerCase()
+ .split(/[^\p{L}\p{N}]+/u)
+ .filter((w) => w.length >= 3 && !STOPWORDS.has(w)),
+ );
+}
+
+/**
+ * The tracked prompt a search query is about, if one is close enough.
+ *
+ * Share of the query's words the prompt also uses. Deliberately simple — a
+ * query is short, a prompt is a sentence, and "most of what was searched for
+ * is in what we track" is the relation the Search Console definitions need.
+ * A semantic match would be better and would be the first LLM call in the
+ * detection path, which the specification rules out.
+ */
+export function matchPrompt(queryTokens, promptTokens, t) {
+ if (queryTokens.size === 0) return null;
+ let best = null;
+ for (const [id, words] of promptTokens) {
+ let shared = 0;
+ for (const w of queryTokens) if (words.has(w)) shared += 1;
+ const overlap = shared / queryTokens.size;
+ if (overlap >= t.gscMatchOverlap && (!best || overlap > best.overlap)) best = { id, overlap };
+ }
+ return best;
+}
+
+/** Organic CTR a query usually earns at a position — a published industry
+ * curve, rounded. Used only to say "far below", never as a target. */
+export function expectedCtr(position) {
+ if (position <= 1.5) return 0.28;
+ if (position <= 2.5) return 0.15;
+ if (position <= 3.5) return 0.1;
+ if (position <= 5.5) return 0.06;
+ if (position <= 10.5) return 0.03;
+ return 0.01;
+}
+
+export function classifyGscQuery(q, prompt, t) {
+ const kinds = [];
+ const curClicks = q.cur_clicks ?? 0;
+ const prevClicks = q.prev_clicks ?? 0;
+ const impressions = q.cur_impressions ?? 0;
+ if (impressions < t.gscMinImpressions || !prompt) return kinds;
+
+ if (prevClicks >= t.gscMinClicks && curClicks <= prevClicks * (1 - t.gscDeclineRatio)) {
+ kinds.push('gsc_decline');
+ } else if (
+ curClicks >= t.gscMinClicks &&
+ prompt.prev_mention_days > 0 &&
+ prompt.cur_mention_days < prompt.prev_mention_days
+ ) {
+ kinds.push('gsc_risk');
+ } else if (prompt.cur_mention_days === 0) {
+ const position = q.cur_position ?? 100;
+ kinds.push(
+ position <= 3 && curClicks >= t.gscMinClicks ? 'search_ai_misalignment' : 'gsc_demand_gap',
+ );
+ }
+
+ const ctr = impressions > 0 ? curClicks / impressions : 0;
+ if (ctr < expectedCtr(q.cur_position ?? 100) * t.gscCtrShortfall) kinds.push('gsc_low_ctr');
+ return kinds;
+}
+
+// ─── AI traffic ─────────────────────────────────────────────────────────────
+
+/**
+ * AI-referred traffic per page, from analytics where connected and the
+ * tracking snippet otherwise. Analytics wins where both exist: it is the
+ * brand's own measurement, and the snippet is ours.
+ */
+export function mergeTrafficPages({ analytics = [], snippet = [] }) {
+ const pages = new Map();
+ for (const s of snippet) pages.set(s.page, { ...s, source: 'snippet' });
+ for (const g of analytics) pages.set(g.page, { ...g, source: 'analytics' });
+ return [...pages.values()];
+}
+
+export function classifyTrafficPage(p, site, t) {
+ const kinds = [];
+ const cur = p.cur_sessions ?? 0;
+ const prev = p.prev_sessions ?? 0;
+
+ if (prev >= t.aiTrafficMinSessions) {
+ const fall = (prev - cur) / prev;
+ if (fall >= t.aiTrafficSlipRatio && fall < t.aiTrafficDropRatio)
+ kinds.push('ai_traffic_slipping');
+ }
+ if (p.source !== 'analytics' || cur < t.aiTrafficMinSessions) return kinds;
+
+ const keyRate = ratio(p.cur_key_events, cur);
+ const engaged = ratio(p.cur_engaged, cur);
+ if (
+ (p.cur_key_events ?? 0) >= 1 &&
+ site.keyRate > 0 &&
+ keyRate >= site.keyRate * t.landingWinnerMultiple
+ ) {
+ kinds.push('ai_landing_page_winner');
+ }
+ if (site.engagedRate > 0 && engaged < site.engagedRate * t.landingUnderperformMultiple) {
+ kinds.push('ai_landing_underperforming');
+ }
+ if ((p.prev_key_events ?? 0) >= 1 && prev > 0 && cur < prev * (1 - t.aiTrafficSlipRatio)) {
+ kinds.push('converting_page_slipping');
+ }
+ return kinds;
+}
+
+export function siteTrafficRates(pages) {
+ const analytics = pages.filter((p) => p.source === 'analytics');
+ const sessions = analytics.reduce((s, p) => s + (p.cur_sessions ?? 0), 0);
+ return {
+ keyRate: ratio(
+ analytics.reduce((s, p) => s + (p.cur_key_events ?? 0), 0),
+ sessions,
+ ),
+ engagedRate: ratio(
+ analytics.reduce((s, p) => s + (p.cur_engaged ?? 0), 0),
+ sessions,
+ ),
+ cur: pages.reduce((s, p) => s + (p.cur_sessions ?? 0), 0),
+ prev: pages.reduce((s, p) => s + (p.prev_sessions ?? 0), 0),
+ };
+}
+
+export function relativeFall(prev, cur) {
+ return prev > 0 ? (prev - cur) / prev : 0;
+}
+
+// ─── Site Audit ─────────────────────────────────────────────────────────────
+
+/** Which failing audit check points at which fix. Checks not listed here are
+ * already covered by the overall low-score definition. */
+export const AUDIT_SIGNAL_KINDS = Object.freeze({
+ 'ai-bot-access': 'crawler_blocked',
+ 'json-ld-presence': 'structured_data_issue',
+ 'json-ld-validity': 'structured_data_issue',
+ 'json-ld-relevance': 'structured_data_issue',
+ 'faq-schema': 'structured_data_issue',
+ freshness: 'outdated_content',
+ 'date-markup': 'outdated_content',
+ 'brand-entity': 'weak_entity',
+ 'entity-coverage': 'weak_entity',
+ 'internal-linking': 'weak_internal_links',
+ 'query-coverage': 'content_gap',
+ 'sub-query-coverage': 'content_gap',
+});
diff --git a/server/src/lib/signals/library/classify.test.js b/server/src/lib/signals/library/classify.test.js
new file mode 100644
index 000000000..769dbcd43
--- /dev/null
+++ b/server/src/lib/signals/library/classify.test.js
@@ -0,0 +1,306 @@
+import { describe, expect, it } from 'vitest';
+import * as c from './classify.js';
+import { LIBRARY_KINDS, SIGNAL_CATEGORIES } from './kinds.js';
+import { ENGINE_THRESHOLDS } from '../../../config/action-engine.js';
+
+const t = ENGINE_THRESHOLDS.library;
+
+const prompt = (over = {}) => ({
+ prompt_id: 'p',
+ topic_id: null,
+ cur_days: 7,
+ cur_mention_days: 0,
+ cur_citation_days: 0,
+ prev_days: 7,
+ prev_mention_days: 0,
+ prev_citation_days: 0,
+ last_mention_day: null,
+ last_citation_day: null,
+ volume: 0,
+ has_target_url: false,
+ ...over,
+});
+
+describe('classifyPrompt', () => {
+ it('calls a prompt that was visible and is not a lost mention', () => {
+ expect(c.classifyPrompt(prompt({ prev_mention_days: 5 }), t)).toBe('lost_mentions');
+ });
+
+ it('calls it a high-value loss when the prompt has demand', () => {
+ expect(c.classifyPrompt(prompt({ prev_mention_days: 5, volume: 500 }), t)).toBe(
+ 'high_value_prompt_lost',
+ );
+ });
+
+ /** Spec G15 against G04: demand with no page is content to create; demand
+ * with a page, or a citation history, is visibility to win. */
+ it('sends demand with no page to content creation', () => {
+ expect(c.classifyPrompt(prompt({ volume: 500 }), t)).toBe('uncovered_demand');
+ });
+
+ it('sends demand with a page to the demand gap', () => {
+ expect(c.classifyPrompt(prompt({ volume: 500, has_target_url: true }), t)).toBe(
+ 'high_demand_gap',
+ );
+ });
+
+ /** Spec G17: a page exists and the brand is still not visible — optimise. */
+ it('sends an invisible prompt with a mapped page to optimisation', () => {
+ expect(c.classifyPrompt(prompt({ has_target_url: true }), t)).toBe('content_underperforming');
+ });
+
+ it('sends an invisible, never-cited, unmapped prompt to content coverage', () => {
+ expect(c.classifyPrompt(prompt(), t)).toBe('prompt_unmapped');
+ });
+
+ it('calls the rest a plain visibility gap', () => {
+ expect(c.classifyPrompt(prompt({ last_citation_day: '2026-09-01' }), t)).toBe(
+ 'prompt_visibility_gap',
+ );
+ });
+
+ it('says nothing about a prompt the brand is visible on', () => {
+ expect(c.classifyPrompt(prompt({ cur_mention_days: 2 }), t)).toBeNull();
+ });
+
+ it('says nothing about a prompt tracked too few days to judge', () => {
+ expect(c.classifyPrompt(prompt({ cur_days: t.promptMinDays - 1 }), t)).toBeNull();
+ });
+});
+
+describe('groupPrompts', () => {
+ /** A target counted twice would put the same work in front of the user
+ * under two titles. */
+ it('puts each prompt in at most one absence group', () => {
+ const prompts = Array.from({ length: 12 }, (_, i) =>
+ prompt({
+ prompt_id: `p${i}`,
+ volume: i % 3 === 0 ? 500 : 0,
+ has_target_url: i % 2 === 0,
+ }),
+ );
+ const groups = c.groupPrompts(prompts, t);
+ const seen = new Map();
+ for (const [kind, rows] of Object.entries(groups)) {
+ if (kind === 'citation_at_risk') continue;
+ for (const row of rows) {
+ expect(seen.get(row.prompt_id)).toBeUndefined();
+ seen.set(row.prompt_id, kind);
+ }
+ }
+ });
+
+ /** Three prompts nobody sees is a pattern; one is a prompt. */
+ it('drops an absence group too small to be an action', () => {
+ const groups = c.groupPrompts([prompt({ prompt_id: 'a' })], t);
+ expect(groups.prompt_unmapped).toBeUndefined();
+ });
+
+ it('keeps a single high-value loss, which is an action on its own', () => {
+ const groups = c.groupPrompts([prompt({ prev_mention_days: 5, volume: 500 })], t);
+ expect(groups.high_value_prompt_lost).toHaveLength(1);
+ });
+});
+
+describe('isCitationAtRisk', () => {
+ it('flags citations thinning to under half', () => {
+ expect(c.isCitationAtRisk(prompt({ prev_citation_days: 6, cur_citation_days: 2 }), t)).toBe(
+ true,
+ );
+ });
+
+ /** Gone is lost, which the original detector owns. */
+ it('leaves citations that are gone to the loss detector', () => {
+ expect(c.isCitationAtRisk(prompt({ prev_citation_days: 6, cur_citation_days: 0 }), t)).toBe(
+ false,
+ );
+ });
+});
+
+describe('classifyTopic', () => {
+ const topic = (tracked, visible, prevTracked, prevVisible) => ({
+ tracked,
+ visible,
+ prevTracked,
+ prevVisible,
+ });
+
+ it('calls a strong topic losing a little of its coverage slipping', () => {
+ expect(c.classifyTopic(topic(10, 7, 10, 8), t)).toBe('topic_slipping');
+ });
+
+ it('calls a large fall a drop', () => {
+ expect(c.classifyTopic(topic(10, 2, 10, 6), t)).toBe('topic_drop');
+ });
+
+ it('calls a topic the brand barely appears in uncovered', () => {
+ expect(c.classifyTopic(topic(10, 1, 10, 1), t)).toBe('topic_uncovered');
+ });
+
+ it('calls partial coverage a gap', () => {
+ expect(c.classifyTopic(topic(10, 4, 10, 4), t)).toBe('topic_gap');
+ });
+
+ it('says nothing about a well-covered, steady topic', () => {
+ expect(c.classifyTopic(topic(10, 8, 10, 8), t)).toBeNull();
+ });
+
+ it('says nothing about a topic too small to judge', () => {
+ expect(c.classifyTopic(topic(t.topicMinPrompts - 1, 0, 3, 0), t)).toBeNull();
+ });
+});
+
+describe('classifyRateFall', () => {
+ const row = (prevMentions, curMentions) => ({
+ prev_answers: 100,
+ prev_mentions: prevMentions,
+ cur_answers: 100,
+ cur_mentions: curMentions,
+ });
+ const kinds = { slip: 'platform_slipping', drop: 'platform_drop' };
+
+ it('grades a small fall as slipping and a large one as a drop', () => {
+ expect(c.classifyRateFall(row(40, 34), t, kinds)).toBe('platform_slipping');
+ expect(c.classifyRateFall(row(40, 20), t, kinds)).toBe('platform_drop');
+ });
+
+ it('ignores a platform that was never worth anything', () => {
+ expect(c.classifyRateFall(row(2, 0), t, kinds)).toBeNull();
+ });
+});
+
+describe('classifyCompetitor', () => {
+ it('names a competitor mentioned a multiple of the brand', () => {
+ expect(c.classifyCompetitor({ cur_mentions: 60, prev_mentions: 55 }, 20, t)).toEqual([
+ 'competitor_leads',
+ ]);
+ });
+
+ it('names one growing fast, separately', () => {
+ expect(c.classifyCompetitor({ cur_mentions: 30, prev_mentions: 10 }, 40, t)).toEqual([
+ 'competitor_momentum',
+ ]);
+ });
+
+ it('can be both', () => {
+ expect(c.classifyCompetitor({ cur_mentions: 90, prev_mentions: 30 }, 20, t)).toEqual([
+ 'competitor_leads',
+ 'competitor_momentum',
+ ]);
+ });
+});
+
+describe('classifySource', () => {
+ const source = (over = {}) => ({
+ domain: 'example.com',
+ owned: false,
+ results: 50,
+ prompts: 5,
+ with_brand: 0,
+ competitor_only: 0,
+ ...over,
+ });
+
+ it('never calls the brand’s own domain a third party', () => {
+ expect(c.classifySource(source({ owned: true }), t)).toBeNull();
+ });
+
+ it('sorts sources by who wins them', () => {
+ expect(c.classifySource(source({ competitor_only: 40 }), t)).toBe('competitor_winning_source');
+ expect(c.classifySource(source({ competitor_only: 5 }), t)).toBe('competitor_cited_source');
+ expect(c.classifySource(source(), t)).toBe('third_party_presence_gap');
+ expect(c.classifySource(source({ with_brand: 5 }), t)).toBe('authority_citation_gap');
+ expect(c.classifySource(source({ with_brand: 30 }), t)).toBe('third_party_citation_gap');
+ });
+
+ it('ignores a source too rarely cited to matter', () => {
+ expect(c.classifySource(source({ results: t.sourceMinResults - 1 }), t)).toBeNull();
+ });
+});
+
+describe('classifyGscQuery', () => {
+ const q = (over = {}) => ({
+ query: 'x',
+ cur_impressions: 1000,
+ cur_clicks: 50,
+ prev_clicks: 50,
+ cur_position: 5,
+ ...over,
+ });
+ const absent = prompt();
+ const visible = prompt({ cur_mention_days: 3, prev_mention_days: 3 });
+
+ it('needs a tracked prompt to be about', () => {
+ expect(c.classifyGscQuery(q(), null, t)).toEqual([]);
+ });
+
+ it('splits AI-invisible demand by where the brand ranks in Google', () => {
+ expect(c.classifyGscQuery(q({ cur_position: 2 }), absent, t)).toContain(
+ 'search_ai_misalignment',
+ );
+ expect(c.classifyGscQuery(q({ cur_position: 8 }), absent, t)).toContain('gsc_demand_gap');
+ });
+
+ it('reports falling clicks first', () => {
+ expect(c.classifyGscQuery(q({ cur_clicks: 10, prev_clicks: 50 }), visible, t)).toContain(
+ 'gsc_decline',
+ );
+ });
+
+ it('reports a click-through rate far below its position', () => {
+ expect(c.classifyGscQuery(q({ cur_clicks: 1, cur_position: 1 }), visible, t)).toContain(
+ 'gsc_low_ctr',
+ );
+ });
+});
+
+describe('matchPrompt', () => {
+ const prompts = new Map([
+ ['a', c.tokens('best running shoes for flat feet')],
+ ['b', c.tokens('how to clean leather boots')],
+ ]);
+
+ it('maps a query to the prompt that shares most of its words', () => {
+ expect(c.matchPrompt(c.tokens('running shoes flat feet'), prompts, t)?.id).toBe('a');
+ });
+
+ it('maps nothing when too little is shared', () => {
+ expect(c.matchPrompt(c.tokens('pizza delivery'), prompts, t)).toBeNull();
+ });
+});
+
+describe('classifyTrafficPage', () => {
+ const site = { keyRate: 0.02, engagedRate: 0.6 };
+
+ it('calls a page losing some AI sessions slipping', () => {
+ expect(
+ c.classifyTrafficPage({ prev_sessions: 100, cur_sessions: 85, source: 'snippet' }, site, t),
+ ).toEqual(['ai_traffic_slipping']);
+ });
+
+ it('only judges conversion where analytics measured it', () => {
+ const page = { prev_sessions: 50, cur_sessions: 50, cur_key_events: 5, cur_engaged: 40 };
+ expect(c.classifyTrafficPage({ ...page, source: 'snippet' }, site, t)).toEqual([]);
+ expect(c.classifyTrafficPage({ ...page, source: 'analytics' }, site, t)).toContain(
+ 'ai_landing_page_winner',
+ );
+ });
+});
+
+describe('the library’s signal kinds', () => {
+ /**
+ * `signals.category` has a check constraint. A kind outside it fails the
+ * insert, and one failed insert throws the brand's whole nightly pass —
+ * the shape of #829 and #834.
+ */
+ it('only use categories the database accepts', () => {
+ for (const [kind, meta] of Object.entries(LIBRARY_KINDS)) {
+ expect({ kind, ok: SIGNAL_CATEGORIES.includes(meta.category) }).toEqual({ kind, ok: true });
+ }
+ });
+
+ it('map every audit check they read to a kind they declare', () => {
+ for (const kind of Object.values(c.AUDIT_SIGNAL_KINDS))
+ expect(LIBRARY_KINDS[kind]).toBeDefined();
+ });
+});
diff --git a/server/src/lib/signals/library/detect.js b/server/src/lib/signals/library/detect.js
new file mode 100644
index 000000000..68e28d97c
--- /dev/null
+++ b/server/src/lib/signals/library/detect.js
@@ -0,0 +1,749 @@
+/**
+ * The V1 library's detectors, run for one brand (#818).
+ *
+ * Ten families, one per read. Each asks Postgres for a compact summary
+ * through an `ae_*` function (00091), hands it to the pure classifiers in
+ * classify.js, and turns what they decide into signal candidates the
+ * recorder writes like any other.
+ *
+ * Every family is isolated. A read that fails — a timeout on a large brand,
+ * a source that errors — costs that family's signals for the night and
+ * nothing else. That is the lesson of #829 and #834, where one call site's
+ * timeout threw the whole pass. And a family that failed reports its kinds as
+ * unread, so the recorder does not take its silence for recovery and close
+ * every open signal of those kinds.
+ *
+ * Families whose source the brand lacks do not run at all. Search Console
+ * detectors for a brand without Search Console would read nothing and cost a
+ * round trip; worse, they would report their kinds as read and resolve
+ * nothing — which is right — but only by accident.
+ */
+
+import supabaseAdmin from '../../../config/supabase.js';
+import { logger } from '../../logger.js';
+import { resolve } from '../../../config/action-engine.js';
+import { resolveBrandSources } from '../../action-center/sources.js';
+import * as c from './classify.js';
+import { isTransientDbError } from '../../pulse/metrics.js';
+
+const { library: t } = resolve();
+const DAY_MS = 86_400_000;
+
+const AI = ['ai_results'];
+const GSC = ['gsc'];
+const GA = ['ga4'];
+const AUDIT = ['site_audit'];
+
+function isoDay(now, daysAgo) {
+ return new Date(now.getTime() - daysAgo * DAY_MS).toISOString().slice(0, 10);
+}
+
+const RPC_RETRIES = 2;
+const RPC_RETRY_DELAY_MS = 3_000;
+
+/**
+ * One read, retried on a transient timeout.
+ *
+ * The largest brand's citation read runs in under two seconds alone and timed
+ * out under load on the first end-to-end run. A timeout is transient by
+ * nature; the pulse has retried its reads since #687, and these did not.
+ */
+async function rpc(name, params, attempt = 0) {
+ const { data, error } = await supabaseAdmin.rpc(name, params);
+ if (error) {
+ if (attempt < RPC_RETRIES && isTransientDbError(error.message)) {
+ await new Promise((resolve) => setTimeout(resolve, RPC_RETRY_DELAY_MS * (attempt + 1)));
+ return rpc(name, params, attempt + 1);
+ }
+ throw new Error(`${name}: ${error.message}`);
+ }
+ return data;
+}
+
+/** Pages through a select, because PostgREST caps a response at 1000 rows
+ * and a silent cap is how a detector ends up judging part of the data. */
+async function selectAll(build) {
+ const rows = [];
+ for (let from = 0; ; from += 1000) {
+ const { data, error } = await build().range(from, from + 999);
+ if (error) throw new Error(error.message);
+ rows.push(...(data ?? []));
+ if ((data ?? []).length < 1000) return rows;
+ }
+}
+
+/** A finding about a group — prompts, pages, queries — as one signal. */
+function group(kind, entity, rows, toTarget, source, extra = {}) {
+ return {
+ kind,
+ dedupKey: kind,
+ source,
+ payload: { entity, targets: rows.slice(0, 50).map(toTarget), ...extra },
+ previousValue: null,
+ currentValue: rows.length,
+ changeValue: null,
+ };
+}
+
+/** A finding about one thing — a topic, a platform, a source, a competitor. */
+function single(kind, key, entity, target, source, values = {}, extra = {}) {
+ return {
+ kind,
+ dedupKey: `${kind}:${key}`,
+ source,
+ payload: { entity, targets: [target], ...extra },
+ previousValue: values.previous ?? null,
+ currentValue: values.current ?? null,
+ changeValue: values.change ?? null,
+ };
+}
+
+/** Keeps a kind's signals to the configured maximum, strongest first. */
+function cap(candidates, score) {
+ const byKind = new Map();
+ for (const candidate of candidates) {
+ byKind.set(candidate.kind, [...(byKind.get(candidate.kind) ?? []), candidate]);
+ }
+ return [...byKind.values()].flatMap((list) => c.strongest(list, score, t.maxSignalsPerKind));
+}
+
+/**
+ * Lazily-loaded, memoised reads shared between families, so the prompt
+ * summary two families need is fetched once.
+ */
+function context(brandId, now, sources) {
+ const memo = new Map();
+ const once = (key, load) => {
+ if (!memo.has(key)) memo.set(key, load());
+ return memo.get(key);
+ };
+ const week = {
+ p_brand_id: brandId,
+ p_cur_from: isoDay(now, t.windowDays - 1),
+ p_cur_to: isoDay(now, 0),
+ p_prev_from: isoDay(now, 2 * t.windowDays - 1),
+ p_prev_to: isoDay(now, t.windowDays),
+ };
+
+ return {
+ brandId,
+ now,
+ sources,
+ week,
+ prompts: () => once('prompts', () => rpc('ae_prompt_stats', week)),
+ dimensions: () => once('dimensions', () => rpc('ae_dimension_stats', week)),
+ promptTexts: () =>
+ once('promptTexts', async () => {
+ const sets = await selectAll(() =>
+ supabaseAdmin.from('prompt_sets').select('id').eq('brand_id', brandId),
+ );
+ if (sets.length === 0) return new Map();
+ const rows = await selectAll(() =>
+ supabaseAdmin
+ .from('prompts')
+ .select('id, text')
+ .in(
+ 'prompt_set_id',
+ sets.map((s) => s.id),
+ ),
+ );
+ return new Map(rows.map((r) => [r.id, r.text]));
+ }),
+ topicNames: () =>
+ once('topicNames', async () => {
+ const rows = await selectAll(() =>
+ supabaseAdmin.from('topics').select('id, name').eq('brand_id', brandId),
+ );
+ return new Map(rows.map((r) => [r.id, r.name]));
+ }),
+ traffic: () =>
+ once('traffic', () =>
+ rpc('ae_ai_traffic_pages', {
+ p_brand_id: brandId,
+ p_cur_from: isoDay(now, 13),
+ p_cur_to: isoDay(now, 0),
+ p_prev_from: isoDay(now, 27),
+ p_prev_to: isoDay(now, 14),
+ }),
+ ),
+ gsc: () =>
+ once('gsc', () =>
+ rpc('ae_gsc_queries', {
+ p_brand_id: brandId,
+ p_cur_from: isoDay(now, 27),
+ p_cur_to: isoDay(now, 0),
+ p_prev_from: isoDay(now, 55),
+ p_prev_to: isoDay(now, 28),
+ }),
+ ),
+ };
+}
+
+const promptTarget = (texts) => (p) => ({
+ id: p.prompt_id,
+ label: String(texts.get(p.prompt_id) ?? '').slice(0, 160),
+ volume: p.volume ?? 0,
+});
+
+// ─── The families ───────────────────────────────────────────────────────────
+
+const FAMILIES = [
+ {
+ name: 'prompts',
+ requires: ['tracking'],
+ kinds: [
+ 'prompt_visibility_gap',
+ 'high_demand_gap',
+ 'uncovered_demand',
+ 'prompt_unmapped',
+ 'content_underperforming',
+ 'lost_mentions',
+ 'high_value_prompt_lost',
+ 'citation_at_risk',
+ ],
+ async run(ctx) {
+ const [prompts, texts] = await Promise.all([ctx.prompts(), ctx.promptTexts()]);
+ const groups = c.groupPrompts(prompts, t);
+ return Object.entries(groups).map(([kind, rows]) => {
+ const ordered = [...rows].sort(
+ (a, b) => (b.volume ?? 0) - (a.volume ?? 0) || b.prev_mention_days - a.prev_mention_days,
+ );
+ return group(kind, 'prompts', ordered, promptTarget(texts), AI);
+ });
+ },
+ },
+
+ {
+ name: 'topics',
+ requires: ['tracking', 'topics'],
+ kinds: ['topic_gap', 'topic_uncovered', 'topic_slipping', 'topic_drop'],
+ async run(ctx) {
+ const [prompts, names] = await Promise.all([ctx.prompts(), ctx.topicNames()]);
+ const found = [];
+ for (const topic of c.topicCoverage(prompts, t)) {
+ const kind = c.classifyTopic(topic, t);
+ if (!kind) continue;
+ const coverage = Math.round((topic.visible / Math.max(topic.tracked, 1)) * 100);
+ const previous = Math.round((topic.prevVisible / Math.max(topic.prevTracked, 1)) * 100);
+ found.push(
+ single(
+ kind,
+ topic.topicId,
+ 'topics',
+ { id: topic.topicId, label: names.get(topic.topicId) ?? '' },
+ AI,
+ { previous, current: coverage, change: coverage - previous },
+ { topicName: names.get(topic.topicId) ?? '', prompts: topic.tracked },
+ ),
+ );
+ }
+ return cap(found, (x) => x.payload.prompts);
+ },
+ },
+
+ {
+ name: 'dimensions',
+ requires: ['tracking'],
+ kinds: ['platform_slipping', 'platform_drop', 'country_gap'],
+ async run(ctx) {
+ const dims = await ctx.dimensions();
+ const found = [];
+ for (const row of dims.platforms ?? []) {
+ const kind = c.classifyRateFall(row, t, {
+ slip: 'platform_slipping',
+ drop: 'platform_drop',
+ });
+ if (!kind) continue;
+ const prev = Math.round((row.prev_mentions / row.prev_answers) * 1000) / 10;
+ const cur = Math.round((row.cur_mentions / row.cur_answers) * 1000) / 10;
+ found.push(
+ single(
+ kind,
+ row.key,
+ 'platforms',
+ { id: row.key, label: row.key },
+ AI,
+ {
+ previous: prev,
+ current: cur,
+ change: Math.round((cur - prev) * 10) / 10,
+ },
+ { platform: row.key },
+ ),
+ );
+ }
+ const gap = c.classifyCountryGap(dims.regions ?? [], t);
+ if (gap) {
+ found.push(
+ single(
+ 'country_gap',
+ gap.worst.key,
+ 'regions',
+ { id: gap.worst.key, label: gap.worst.key },
+ AI,
+ {
+ previous: Math.round(gap.best.rate * 1000) / 10,
+ current: Math.round(gap.worst.rate * 1000) / 10,
+ change: -gap.points,
+ },
+ { region: gap.worst.key, bestRegion: gap.best.key },
+ ),
+ );
+ }
+ return found;
+ },
+ },
+
+ {
+ name: 'competitors',
+ requires: ['tracking', 'competitors'],
+ kinds: ['competitor_leads', 'competitor_momentum'],
+ async run(ctx) {
+ const dims = await ctx.dimensions();
+ const brandMentions = (dims.platforms ?? []).reduce((s, p) => s + (p.cur_mentions ?? 0), 0);
+ const found = [];
+ for (const competitor of dims.competitors ?? []) {
+ for (const kind of c.classifyCompetitor(competitor, brandMentions, t)) {
+ found.push(
+ single(
+ kind,
+ competitor.key,
+ 'competitors',
+ { id: competitor.key, label: competitor.name ?? '' },
+ AI,
+ {
+ previous: kind === 'competitor_leads' ? brandMentions : competitor.prev_mentions,
+ current: competitor.cur_mentions,
+ change:
+ competitor.cur_mentions -
+ (kind === 'competitor_leads' ? brandMentions : competitor.prev_mentions),
+ },
+ { competitorName: competitor.name ?? '', competitorId: competitor.key },
+ ),
+ );
+ }
+ }
+ return cap(found, (x) => x.currentValue ?? 0);
+ },
+ },
+
+ {
+ name: 'competitorPrompts',
+ requires: ['tracking', 'competitors'],
+ kinds: ['competitor_high_value_lead', 'competitor_topic_lead', 'competitor_uncovered_topic'],
+ async run(ctx) {
+ const [prompts, compRows, texts, dims] = await Promise.all([
+ ctx.prompts(),
+ rpc('ae_competitor_prompt_stats', ctx.week),
+ ctx.promptTexts(),
+ ctx.dimensions(),
+ ]);
+ const names = new Map((dims.competitors ?? []).map((x) => [x.key, x.name]));
+ const leader = new Map();
+ for (const row of compRows) {
+ if (row.cur_days < t.competitorPromptMinDays) continue;
+ const current = leader.get(row.prompt_id);
+ if (!current || row.cur_days > current.cur_days) leader.set(row.prompt_id, row);
+ }
+ const present = new Set(leader.keys());
+ const found = [];
+
+ if (ctx.sources.has('volumes')) {
+ const contested = prompts.filter(
+ (p) =>
+ (p.volume ?? 0) >= t.highDemandVolume &&
+ p.cur_days >= t.promptMinDays &&
+ p.cur_mention_days === 0 &&
+ present.has(p.prompt_id),
+ );
+ if (contested.length > 0) {
+ const target = promptTarget(texts);
+ found.push(
+ group(
+ 'competitor_high_value_lead',
+ 'prompts',
+ contested,
+ (p) => ({
+ ...target(p),
+ competitor: names.get(leader.get(p.prompt_id)?.competitor_id) ?? '',
+ }),
+ AI,
+ ),
+ );
+ }
+ }
+
+ if (ctx.sources.has('topics')) {
+ const topicNames = await ctx.topicNames();
+ for (const topic of c.topicCoverage(prompts, t)) {
+ const kind = c.classifyCompetitorTopic(topic, present, t);
+ if (!kind) continue;
+ found.push(
+ single(
+ kind,
+ topic.topicId,
+ 'topics',
+ {
+ id: topic.topicId,
+ label: topicNames.get(topic.topicId) ?? '',
+ },
+ AI,
+ { current: topic.tracked },
+ { topicName: topicNames.get(topic.topicId) ?? '' },
+ ),
+ );
+ }
+ }
+ return cap(found, (x) => x.currentValue ?? 0);
+ },
+ },
+
+ {
+ name: 'sources',
+ requires: ['tracking'],
+ kinds: [
+ 'authority_citation_gap',
+ 'third_party_citation_gap',
+ 'third_party_presence_gap',
+ 'competitor_cited_source',
+ 'competitor_winning_source',
+ ],
+ async run(ctx) {
+ const domains = await rpc('ae_citation_sources', {
+ p_brand_id: ctx.brandId,
+ p_from: new Date(ctx.now.getTime() - t.windowDays * DAY_MS).toISOString(),
+ });
+ const found = [];
+ for (const d of domains) {
+ const kind = c.classifySource(d, t);
+ if (!kind) continue;
+ found.push(
+ single(
+ kind,
+ d.domain,
+ 'sources',
+ { id: d.domain, label: d.domain },
+ AI,
+ {
+ current: d.results,
+ previous: d.with_brand,
+ change: d.competitor_only,
+ },
+ { domain: d.domain, prompts: d.prompts, results: d.results },
+ ),
+ );
+ }
+ return cap(found, (x) => x.currentValue ?? 0);
+ },
+ },
+
+ {
+ name: 'ownedPages',
+ requires: ['tracking'],
+ kinds: ['page_citation_slipping', 'owned_page_citation_lost'],
+ async run(ctx) {
+ const urls = await rpc('ae_owned_citations', {
+ p_brand_id: ctx.brandId,
+ p_cur_from: new Date(ctx.now.getTime() - t.windowDays * DAY_MS).toISOString(),
+ p_prev_from: new Date(ctx.now.getTime() - 2 * t.windowDays * DAY_MS).toISOString(),
+ });
+ const groups = {};
+ for (const u of urls) {
+ const kind = c.classifyOwnedPage(u, t);
+ if (kind) (groups[kind] ??= []).push(u);
+ }
+ return Object.entries(groups).map(([kind, rows]) =>
+ group(
+ kind,
+ 'pages',
+ rows,
+ (u) => ({
+ id: u.url,
+ label: u.url,
+ before: u.prev_citations,
+ now: u.cur_citations,
+ }),
+ AI,
+ ),
+ );
+ },
+ },
+
+ {
+ name: 'fanouts',
+ requires: ['tracking'],
+ kinds: ['fanout_gap', 'competitor_fanout_gap'],
+ async run(ctx) {
+ const queries = await rpc('ae_fanout_gaps', {
+ p_brand_id: ctx.brandId,
+ p_from: new Date(ctx.now.getTime() - t.windowDays * DAY_MS).toISOString(),
+ });
+ const groups = {};
+ for (const q of queries) {
+ const kind = c.classifyFanout(q, t);
+ if (kind) (groups[kind] ??= []).push(q);
+ }
+ return Object.entries(groups)
+ .filter(([, rows]) => rows.length >= t.fanoutGroupMin)
+ .map(([kind, rows]) =>
+ group(
+ kind,
+ 'queries',
+ rows,
+ (q) => ({ id: q.query, label: q.query, prompts: q.prompts }),
+ AI,
+ ),
+ );
+ },
+ },
+
+ {
+ name: 'searchConsole',
+ requires: ['tracking', 'search_console'],
+ kinds: ['gsc_demand_gap', 'search_ai_misalignment', 'gsc_low_ctr', 'gsc_risk', 'gsc_decline'],
+ async run(ctx) {
+ const [queries, prompts, texts] = await Promise.all([
+ ctx.gsc(),
+ ctx.prompts(),
+ ctx.promptTexts(),
+ ]);
+ const byId = new Map(prompts.map((p) => [p.prompt_id, p]));
+ const promptTokens = new Map([...texts].map(([id, text]) => [id, c.tokens(text)]));
+ const groups = {};
+ for (const q of queries) {
+ const match = c.matchPrompt(c.tokens(q.query), promptTokens, t);
+ const prompt = match ? byId.get(match.id) : null;
+ for (const kind of c.classifyGscQuery(q, prompt, t)) {
+ (groups[kind] ??= []).push({ q, promptId: match?.id });
+ }
+ }
+ return Object.entries(groups).map(([kind, rows]) =>
+ group(
+ kind,
+ 'queries',
+ rows,
+ ({ q, promptId }) => ({
+ id: q.query,
+ label: q.query,
+ impressions: q.cur_impressions,
+ clicks: q.cur_clicks,
+ prompt: String(texts.get(promptId) ?? '').slice(0, 160),
+ }),
+ GSC,
+ ),
+ );
+ },
+ },
+
+ {
+ name: 'aiTraffic',
+ requires: ['ai_traffic'],
+ kinds: [
+ 'ai_traffic_slipping',
+ 'ai_traffic_drop',
+ 'ai_landing_page_winner',
+ 'ai_landing_underperforming',
+ 'converting_page_slipping',
+ ],
+ async run(ctx) {
+ const pages = c.mergeTrafficPages(await ctx.traffic());
+ const site = c.siteTrafficRates(pages);
+ const source = pages.some((p) => p.source === 'analytics') ? GA : AI;
+ const groups = {};
+ for (const page of pages) {
+ for (const kind of c.classifyTrafficPage(page, site, t)) (groups[kind] ??= []).push(page);
+ }
+ const found = Object.entries(groups).map(([kind, rows]) =>
+ group(
+ kind,
+ 'pages',
+ rows,
+ (p) => ({
+ id: p.page,
+ label: p.page,
+ before: p.prev_sessions ?? 0,
+ now: p.cur_sessions ?? 0,
+ }),
+ source,
+ ),
+ );
+ if (
+ site.prev >= t.aiTrafficMinSessions * 3 &&
+ c.relativeFall(site.prev, site.cur) >= t.aiTrafficDropRatio
+ ) {
+ const falling = pages.filter((p) => (p.prev_sessions ?? 0) > (p.cur_sessions ?? 0));
+ found.push({
+ ...group(
+ 'ai_traffic_drop',
+ 'pages',
+ falling,
+ (p) => ({
+ id: p.page,
+ label: p.page,
+ before: p.prev_sessions ?? 0,
+ now: p.cur_sessions ?? 0,
+ }),
+ source,
+ ),
+ previousValue: site.prev,
+ currentValue: site.cur,
+ changeValue: site.cur - site.prev,
+ });
+ }
+ return found;
+ },
+ },
+
+ {
+ name: 'crossChannel',
+ requires: ['ai_traffic'],
+ kinds: ['cross_channel_risk', 'visibility_traffic_loss'],
+ async run(ctx) {
+ const pages = c.mergeTrafficPages(await ctx.traffic());
+ const site = c.siteTrafficRates(pages);
+ const trafficFall = c.relativeFall(site.prev, site.cur);
+ const found = [];
+ if (site.prev < t.aiTrafficMinSessions * 3) return found;
+
+ const dims = await ctx.dimensions();
+ const prevMentions = (dims.platforms ?? []).reduce((s, p) => s + (p.prev_mentions ?? 0), 0);
+ const curMentions = (dims.platforms ?? []).reduce((s, p) => s + (p.cur_mentions ?? 0), 0);
+ // Correlation, not cause: both fell in the same window. The definition's
+ // copy says so, per the specification.
+ if (trafficFall >= 0.2 && c.relativeFall(prevMentions, curMentions) >= 0.2) {
+ found.push(
+ single(
+ 'visibility_traffic_loss',
+ 'site',
+ 'pages',
+ { id: 'site', label: '' },
+ GA,
+ {
+ previous: site.prev,
+ current: site.cur,
+ change: site.cur - site.prev,
+ },
+ { mentionsBefore: prevMentions, mentionsNow: curMentions },
+ ),
+ );
+ }
+
+ if (ctx.sources.has('analytics') && ctx.sources.has('search_console')) {
+ const queries = await ctx.gsc();
+ const prevClicks = queries.reduce((s, q) => s + (q.prev_clicks ?? 0), 0);
+ const curClicks = queries.reduce((s, q) => s + (q.cur_clicks ?? 0), 0);
+ if (
+ trafficFall >= t.aiTrafficSlipRatio &&
+ c.relativeFall(prevClicks, curClicks) >= t.aiTrafficSlipRatio
+ ) {
+ found.push(
+ single(
+ 'cross_channel_risk',
+ 'site',
+ 'pages',
+ { id: 'site', label: '' },
+ [...GA, ...GSC],
+ {
+ previous: site.prev,
+ current: site.cur,
+ change: site.cur - site.prev,
+ },
+ { clicksBefore: prevClicks, clicksNow: curClicks },
+ ),
+ );
+ }
+ }
+ return found;
+ },
+ },
+
+ {
+ name: 'audits',
+ requires: ['site_audits'],
+ kinds: [
+ 'crawler_blocked',
+ 'structured_data_issue',
+ 'outdated_content',
+ 'weak_entity',
+ 'weak_internal_links',
+ 'content_gap',
+ ],
+ async run(ctx) {
+ const since = new Date(ctx.now.getTime() - 90 * DAY_MS).toISOString();
+ const audits = await selectAll(() =>
+ supabaseAdmin
+ .from('site_audits')
+ .select('id, url, final_url, completed_at')
+ .eq('brand_id', ctx.brandId)
+ .eq('status', 'completed')
+ .gte('completed_at', since)
+ .order('completed_at', { ascending: false }),
+ );
+ // The latest audit per page: an issue fixed and re-audited is fixed.
+ const latest = new Map();
+ for (const a of audits) {
+ const page = a.final_url || a.url;
+ if (!latest.has(page)) latest.set(page, a);
+ }
+ if (latest.size === 0) return [];
+
+ const ids = [...latest.values()].map((a) => a.id);
+ const failures = await selectAll(() =>
+ supabaseAdmin
+ .from('audit_signal_results')
+ .select('audit_id, signal_key')
+ .in('audit_id', ids)
+ .eq('status', 'fail'),
+ );
+ const pageOf = new Map([...latest].map(([page, a]) => [a.id, page]));
+ const groups = {};
+ for (const f of failures) {
+ const kind = c.AUDIT_SIGNAL_KINDS[f.signal_key];
+ if (!kind) continue;
+ const page = pageOf.get(f.audit_id);
+ const set = (groups[kind] ??= new Map());
+ const entry = set.get(page) ?? { page, checks: [] };
+ entry.checks.push(f.signal_key);
+ set.set(page, entry);
+ }
+ return Object.entries(groups).map(([kind, pages]) =>
+ group(
+ kind,
+ 'pages',
+ [...pages.values()],
+ (e) => ({ id: e.page, label: e.page, checks: e.checks }),
+ AUDIT,
+ ),
+ );
+ },
+ },
+];
+
+/** Every kind a library family can emit — what the registry checks against. */
+export const LIBRARY_EMITTED_KINDS = Object.freeze(FAMILIES.flatMap((f) => f.kinds));
+
+/**
+ * Run every family the brand has the data for.
+ *
+ * @returns {Promise<{ candidates: object[], unreadKinds: Set<string> }>}
+ */
+export async function libraryCandidates(brandId, { now = new Date(), sources } = {}) {
+ const available = sources ?? (await resolveBrandSources(brandId));
+ const ctx = context(brandId, now, available);
+ const candidates = [];
+ const unreadKinds = new Set();
+
+ for (const family of FAMILIES) {
+ if (!family.requires.every((s) => available.has(s))) continue;
+ try {
+ candidates.push(...(await family.run(ctx)));
+ } catch (err) {
+ // One family's read failing costs that family's night, not the pass.
+ for (const kind of family.kinds) unreadKinds.add(kind);
+ logger.error({ err, brandId, family: family.name }, '[signals] library family failed');
+ }
+ }
+ return { candidates, unreadKinds };
+}
+
+export { FAMILIES as LIBRARY_FAMILIES };
diff --git a/server/src/lib/signals/library/kinds.js b/server/src/lib/signals/library/kinds.js
new file mode 100644
index 000000000..4a1f0074d
--- /dev/null
+++ b/server/src/lib/signals/library/kinds.js
@@ -0,0 +1,102 @@
+/**
+ * The signal kinds behind the V1 definition library (#818).
+ *
+ * Same shape as the original KIND_META in record.js — category, impact, the
+ * KPIs the kind speaks to, and whether the condition persists — and merged
+ * into it, so the recorder, the registry checks and the web treat them all
+ * alike. Kept in their own file only because there are forty-five of them.
+ *
+ * Every kind here is read by exactly one definition. Several describe the
+ * same data at different severities (a platform slipping versus a platform
+ * collapsing), and those are separate kinds on purpose: the specification
+ * gives them separate definitions with different work, and one kind feeding
+ * two definitions would raise two actions for one condition.
+ */
+
+/**
+ * Categories are the six the `signals.category` check constraint allows.
+ * Anything else fails the insert — and one failed insert throws the whole
+ * nightly pass for that brand, the shape of #829 and #834. So content gaps
+ * file under `visibility` (a gap in what the brand is seen for) and audit
+ * findings under `technical`, and a test pins the list to the constraint.
+ */
+export const SIGNAL_CATEGORIES = Object.freeze([
+ 'visibility',
+ 'citation',
+ 'mention',
+ 'traffic',
+ 'technical',
+ 'competitor',
+]);
+
+const meta = (category, impact, kpiKeys) =>
+ Object.freeze({ category, impact, kpiKeys: Object.freeze(kpiKeys), persistent: true });
+
+export const LIBRARY_KINDS = Object.freeze({
+ // ── Prompts ───────────────────────────────────────────────────────────────
+ prompt_visibility_gap: meta('visibility', 'medium', ['ai_visibility']),
+ high_demand_gap: meta('visibility', 'high', ['ai_visibility']),
+ uncovered_demand: meta('visibility', 'high', ['ai_visibility', 'citations']),
+ prompt_unmapped: meta('visibility', 'medium', ['ai_visibility']),
+ content_underperforming: meta('visibility', 'medium', ['ai_visibility', 'citations']),
+ lost_mentions: meta('visibility', 'high', ['mentions', 'ai_visibility']),
+ high_value_prompt_lost: meta('visibility', 'high', ['ai_visibility']),
+ citation_at_risk: meta('citation', 'medium', ['citations']),
+
+ // ── Topics ────────────────────────────────────────────────────────────────
+ topic_gap: meta('visibility', 'medium', ['ai_visibility', 'share_of_voice']),
+ topic_uncovered: meta('visibility', 'medium', ['ai_visibility', 'share_of_voice']),
+ topic_slipping: meta('visibility', 'medium', ['share_of_voice']),
+ topic_drop: meta('visibility', 'high', ['share_of_voice', 'ai_visibility']),
+
+ // ── Platforms and regions ─────────────────────────────────────────────────
+ platform_slipping: meta('visibility', 'medium', ['ai_visibility']),
+ platform_drop: meta('visibility', 'high', ['ai_visibility']),
+ country_gap: meta('visibility', 'medium', ['ai_visibility']),
+
+ // ── Competitors ───────────────────────────────────────────────────────────
+ competitor_leads: meta('competitor', 'high', ['share_of_voice', 'ai_visibility']),
+ competitor_momentum: meta('competitor', 'medium', ['share_of_voice']),
+ competitor_topic_lead: meta('competitor', 'medium', ['share_of_voice']),
+ competitor_high_value_lead: meta('competitor', 'high', ['share_of_voice', 'ai_visibility']),
+ competitor_uncovered_topic: meta('competitor', 'medium', ['share_of_voice']),
+
+ // ── Citation sources ──────────────────────────────────────────────────────
+ authority_citation_gap: meta('citation', 'medium', ['citations']),
+ third_party_citation_gap: meta('citation', 'medium', ['citations']),
+ third_party_presence_gap: meta('citation', 'medium', ['mentions', 'citations']),
+ competitor_cited_source: meta('competitor', 'medium', ['citations', 'share_of_voice']),
+ competitor_winning_source: meta('competitor', 'medium', ['mentions', 'share_of_voice']),
+
+ // ── Owned pages ───────────────────────────────────────────────────────────
+ page_citation_slipping: meta('citation', 'medium', ['citations']),
+ owned_page_citation_lost: meta('citation', 'high', ['citations']),
+
+ // ── Query fan-outs ────────────────────────────────────────────────────────
+ fanout_gap: meta('visibility', 'medium', ['ai_visibility']),
+ competitor_fanout_gap: meta('competitor', 'medium', ['share_of_voice']),
+
+ // ── Search Console ────────────────────────────────────────────────────────
+ gsc_demand_gap: meta('visibility', 'medium', ['ai_visibility']),
+ search_ai_misalignment: meta('visibility', 'medium', ['ai_visibility']),
+ gsc_low_ctr: meta('traffic', 'medium', ['ai_visibility']),
+ gsc_risk: meta('traffic', 'medium', ['ai_visibility']),
+ gsc_decline: meta('traffic', 'high', ['ai_visibility']),
+
+ // ── AI traffic ────────────────────────────────────────────────────────────
+ ai_traffic_slipping: meta('traffic', 'medium', ['ai_referral_traffic']),
+ ai_traffic_drop: meta('traffic', 'high', ['ai_referral_traffic']),
+ ai_landing_page_winner: meta('traffic', 'medium', ['ai_referral_traffic']),
+ ai_landing_underperforming: meta('traffic', 'medium', ['ai_referral_traffic']),
+ converting_page_slipping: meta('traffic', 'high', ['ai_referral_traffic']),
+ cross_channel_risk: meta('traffic', 'high', ['ai_referral_traffic']),
+ visibility_traffic_loss: meta('traffic', 'high', ['ai_referral_traffic', 'ai_visibility']),
+
+ // ── Site Audit findings ───────────────────────────────────────────────────
+ crawler_blocked: meta('technical', 'high', []),
+ structured_data_issue: meta('technical', 'medium', []),
+ outdated_content: meta('technical', 'medium', ['ai_visibility']),
+ weak_entity: meta('technical', 'medium', ['mentions']),
+ weak_internal_links: meta('technical', 'low', []),
+ content_gap: meta('technical', 'medium', ['ai_visibility']),
+});
diff --git a/server/src/lib/signals/record.js b/server/src/lib/signals/record.js
index 1e4cc954b..bc911794c 100644
--- a/server/src/lib/signals/record.js
+++ b/server/src/lib/signals/record.js
@@ -30,6 +30,8 @@ import supabaseAdmin from '../../config/supabase.js';
import { computePulseMetrics } from '../pulse/metrics.js';
import { logger } from '../logger.js';
import { resolve } from '../../config/action-engine.js';
+import { LIBRARY_KINDS } from './library/kinds.js';
+import { libraryCandidates } from './library/detect.js';
const DAY_MS = 86_400_000;
@@ -41,13 +43,34 @@ function utcDay(date) {
// 2.5), alongside every other threshold the engine judges by.
const { detection } = resolve();
+/**
+ * Library kinds that report a fall. Suppressed during a platform outage, when
+ * a fall in collected answers is ours and not the brand's.
+ */
+const DECLINE_KINDS = new Set([
+ 'lost_mentions',
+ 'high_value_prompt_lost',
+ 'citation_at_risk',
+ 'topic_slipping',
+ 'topic_drop',
+ 'platform_slipping',
+ 'platform_drop',
+ 'page_citation_slipping',
+ 'owned_page_citation_lost',
+]);
+
/**
* Static knowledge per detector kind. Mirrored by the web registry
* (web/src/lib/signals/registry.ts) which owns the display templates —
* this side owns what gets STORED: category, impact, sources, KPI links,
* and whether the condition persists.
*/
-export const KIND_META = {
+/**
+ * The original detectors' kinds. The V1 library's forty-seven are in
+ * library/kinds.js and merged below, so everything downstream — the recorder,
+ * the registry checks, the web — treats them alike.
+ */
+const BASE_KINDS = {
sharp_drop: {
category: 'visibility',
impact: 'high',
@@ -138,6 +161,8 @@ export const KIND_META = {
},
};
+export const KIND_META = { ...BASE_KINDS, ...LIBRARY_KINDS };
+
/** Pulse highlight/warning → signal candidate. Returns null for entries that
* describe engine health rather than the brand (degraded platforms). */
function fromPulseEntry(entry) {
@@ -504,6 +529,18 @@ export async function recordSignalsForBrand(brandId, { now = new Date() } = {})
candidates.push(...(await platformGapCandidates(brandId)));
candidates.push(...(await competitorCitationGapCandidates(brandId, now)));
+ // The V1 definition library's detectors (#818). Isolated per family inside:
+ // a read that fails costs that family's signals for the night, and its kinds
+ // are reported unread so the resolution step below does not take the
+ // silence for recovery.
+ const library = await libraryCandidates(brandId, { now });
+ // During a platform outage a fall is our collection, not the brand's
+ // visibility — the same suppression the pulse applies to its own warnings.
+ candidates.push(
+ ...library.candidates.filter((candidate) => !(outage && DECLINE_KINDS.has(candidate.kind))),
+ );
+ const unreadKinds = library.unreadKinds;
+
// Existing rows decide insert vs update vs reopen. A brand's signal set is
// small (tens), so reading it whole is cheaper than being clever.
const { data: existingRows, error: readErr } = await supabaseAdmin
@@ -578,7 +615,10 @@ export async function recordSignalsForBrand(brandId, { now = new Date() } = {})
(row) =>
KIND_META[row.kind]?.persistent &&
(row.status === 'new' || row.status === 'acknowledged') &&
- !detectedKeys.has(row.dedup_key),
+ !detectedKeys.has(row.dedup_key) &&
+ // A kind whose detector failed tonight was not looked at, and a
+ // condition nobody looked at has not ended.
+ !unreadKinds.has(row.kind),
);
for (const row of toResolve) {
const { error } = await supabaseAdmin
diff --git a/supabase/migrations/00091_action_engine_detector_reads.sql b/supabase/migrations/00091_action_engine_detector_reads.sql
new file mode 100644
index 000000000..a4d72a5f8
--- /dev/null
+++ b/supabase/migrations/00091_action_engine_detector_reads.sql
@@ -0,0 +1,294 @@
+-- Action Engine (#818): the reads behind the V1 definition library.
+--
+-- The V1 specification asks for 62 action definitions. Each needs a signal
+-- that can trigger it, and each signal needs a read over data the product
+-- already collects — prompt visibility per day, competitor presence per
+-- prompt, citation sources, fan-out queries, Search Console queries, AI
+-- landing-page traffic.
+--
+-- Doing those reads from the server row by row is how the nightly pass died on
+-- the largest brand twice (#829, #834): a query that scans a brand's history
+-- crosses the 8s statement timeout once the brand is large enough. So every
+-- read here aggregates in Postgres and returns a compact summary — one row per
+-- prompt, per competitor, per domain, per query, per page — measured on the
+-- largest brand before being written down:
+--
+-- ae_citation_sources 1.5s (was 15s as a naive join)
+-- ae_fanout_gaps 0.45s
+--
+-- All are service-role only. They take a brand id and aggregate across it, and
+-- nothing in the web calls them; granting them to authenticated users would
+-- only widen the surface for no reader.
+
+-- ─── Prompts: presence per day, current window against the previous one ─────
+
+create or replace function public.ae_prompt_stats(
+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date
+) returns jsonb
+language sql stable
+as $$
+ with days as (
+ select prompt_id, day, bool_or(has_mention) as m, bool_or(has_citation) as c
+ from public.insights_prompt_daily
+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to
+ group by prompt_id, day
+ ),
+ active as (
+ select p.id, p.topic_id
+ from public.prompts p
+ join public.prompt_sets s on s.id = p.prompt_set_id
+ where s.brand_id = p_brand_id and p.is_active
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select a.id as prompt_id, a.topic_id,
+ count(d.day) filter (where d.day between p_cur_from and p_cur_to) as cur_days,
+ count(d.day) filter (where d.day between p_cur_from and p_cur_to and d.m) as cur_mention_days,
+ count(d.day) filter (where d.day between p_cur_from and p_cur_to and d.c) as cur_citation_days,
+ count(d.day) filter (where d.day between p_prev_from and p_prev_to) as prev_days,
+ count(d.day) filter (where d.day between p_prev_from and p_prev_to and d.m) as prev_mention_days,
+ count(d.day) filter (where d.day between p_prev_from and p_prev_to and d.c) as prev_citation_days,
+ max(d.day) filter (where d.m) as last_mention_day,
+ max(d.day) filter (where d.c) as last_citation_day,
+ (select coalesce(max(v.est_ai_volume), 0) from public.prompt_volumes v where v.prompt_id = a.id) as volume,
+ exists (select 1 from public.prompt_target_urls t where t.prompt_id = a.id) as has_target_url
+ from active a
+ left join days d on d.prompt_id = a.id
+ group by a.id, a.topic_id
+ ) x
+$$;
+
+-- ─── Competitors: presence per prompt ───────────────────────────────────────
+
+create or replace function public.ae_competitor_prompt_stats(
+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date
+) returns jsonb
+language sql stable
+as $$
+ with days as (
+ select prompt_id, competitor_id, day
+ from public.insights_competitor_prompt_daily
+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to
+ group by prompt_id, competitor_id, day
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select prompt_id, competitor_id,
+ count(*) filter (where day between p_cur_from and p_cur_to) as cur_days,
+ count(*) filter (where day between p_prev_from and p_prev_to) as prev_days
+ from days
+ group by prompt_id, competitor_id
+ ) x
+$$;
+
+-- ─── Dimensions: visibility by platform, by region, and per competitor ───────
+
+create or replace function public.ae_dimension_stats(
+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date
+) returns jsonb
+language sql stable
+as $$
+ select jsonb_build_object(
+ 'platforms', (
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select platform as key,
+ sum(answer_count) filter (where day between p_cur_from and p_cur_to) as cur_answers,
+ sum(mention_answers) filter (where day between p_cur_from and p_cur_to) as cur_mentions,
+ sum(answer_count) filter (where day between p_prev_from and p_prev_to) as prev_answers,
+ sum(mention_answers) filter (where day between p_prev_from and p_prev_to) as prev_mentions
+ from public.insights_brand_daily
+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to
+ group by platform
+ ) x
+ ),
+ 'regions', (
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select region as key,
+ sum(answer_count) filter (where day between p_cur_from and p_cur_to) as cur_answers,
+ sum(mention_answers) filter (where day between p_cur_from and p_cur_to) as cur_mentions,
+ sum(answer_count) filter (where day between p_prev_from and p_prev_to) as prev_answers,
+ sum(mention_answers) filter (where day between p_prev_from and p_prev_to) as prev_mentions
+ from public.insights_brand_daily
+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to
+ group by region
+ ) x
+ ),
+ 'competitors', (
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select c.competitor_id as key, max(co.name) as name,
+ sum(c.mention_answers) filter (where c.day between p_cur_from and p_cur_to) as cur_mentions,
+ sum(c.mention_answers) filter (where c.day between p_prev_from and p_prev_to) as prev_mentions,
+ sum(c.citation_answers) filter (where c.day between p_cur_from and p_cur_to) as cur_citations
+ from public.insights_competitor_daily c
+ left join public.competitors co on co.id::text = c.competitor_id
+ where c.brand_id = p_brand_id and c.day between p_prev_from and p_cur_to
+ group by c.competitor_id
+ ) x
+ )
+ )
+$$;
+
+-- ─── Citation sources: which domains answers cite, and whose answers ────────
+
+create or replace function public.ae_citation_sources(p_brand_id uuid, p_from timestamptz)
+returns jsonb
+language sql stable
+as $$
+ with owned as (
+ select regexp_replace(lower(domain), '^www\.', '') as d
+ from public.brand_domains where brand_id = p_brand_id
+ ),
+ r as materialized (
+ select id, prompt_id, coalesce(mention_count, 0) > 0 as bm,
+ coalesce(competitor_mentions @? '$[*] ? (@.mention_count > 0)', false) as cm
+ from public.prompt_results
+ where brand_id = p_brand_id and created_at >= p_from
+ ),
+ rd as materialized (
+ select distinct prc.prompt_result_id as rid, regexp_replace(lower(u.domain), '^www\.', '') as domain
+ from public.prompt_result_citations prc
+ join public.citation_urls u on u.id = prc.url_id
+ where prc.brand_id = p_brand_id and prc.created_at >= p_from
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select rd.domain,
+ exists (select 1 from owned o where rd.domain = o.d or rd.domain like '%.' || o.d) as owned,
+ count(*) as results,
+ count(distinct r.prompt_id) as prompts,
+ count(*) filter (where r.bm) as with_brand,
+ count(*) filter (where r.cm and not r.bm) as competitor_only,
+ count(*) filter (where not r.bm) as without_brand
+ from rd join r on r.id = rd.rid
+ group by rd.domain
+ order by count(*) desc
+ limit 300
+ ) x
+$$;
+
+-- ─── Owned URLs: how often each owned page was cited, now and before ────────
+
+create or replace function public.ae_owned_citations(
+ p_brand_id uuid, p_cur_from timestamptz, p_prev_from timestamptz
+) returns jsonb
+language sql stable
+as $$
+ with owned as (
+ select regexp_replace(lower(domain), '^www\.', '') as d
+ from public.brand_domains where brand_id = p_brand_id
+ ),
+ cites as materialized (
+ select prc.created_at, u.url, regexp_replace(lower(u.domain), '^www\.', '') as domain
+ from public.prompt_result_citations prc
+ join public.citation_urls u on u.id = prc.url_id
+ where prc.brand_id = p_brand_id and prc.created_at >= p_prev_from
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select c.url,
+ count(*) filter (where c.created_at >= p_cur_from) as cur_citations,
+ count(*) filter (where c.created_at < p_cur_from) as prev_citations
+ from cites c
+ where exists (select 1 from owned o where c.domain = o.d or c.domain like '%.' || o.d)
+ group by c.url
+ order by count(*) desc
+ limit 300
+ ) x
+$$;
+
+-- ─── Fan-out queries the engines ran where the brand never appeared ─────────
+
+create or replace function public.ae_fanout_gaps(p_brand_id uuid, p_from timestamptz)
+returns jsonb
+language sql stable
+as $$
+ with r as materialized (
+ select id, prompt_id, coalesce(mention_count, 0) > 0 as bm,
+ coalesce(competitor_mentions @? '$[*] ? (@.mention_count > 0)', false) as cm,
+ search_queries
+ from public.prompt_results
+ where brand_id = p_brand_id and created_at >= p_from
+ and jsonb_typeof(search_queries) = 'array'
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select lower(trim(q->>'query')) as query,
+ count(*) as results,
+ count(distinct r.prompt_id) as prompts,
+ count(*) filter (where r.cm and not r.bm) as competitor_only
+ from r cross join lateral jsonb_array_elements(r.search_queries) q
+ where coalesce(trim(q->>'query'), '') <> ''
+ group by 1
+ having count(*) filter (where r.bm) = 0
+ order by count(distinct r.prompt_id) desc, count(*) desc
+ limit 300
+ ) x
+$$;
+
+-- ─── Search Console: per query, now against before ──────────────────────────
+
+create or replace function public.ae_gsc_queries(
+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date
+) returns jsonb
+language sql stable
+as $$
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select query,
+ sum(clicks) filter (where date between p_cur_from and p_cur_to) as cur_clicks,
+ sum(impressions) filter (where date between p_cur_from and p_cur_to) as cur_impressions,
+ avg(position) filter (where date between p_cur_from and p_cur_to) as cur_position,
+ sum(clicks) filter (where date between p_prev_from and p_prev_to) as prev_clicks,
+ sum(impressions) filter (where date between p_prev_from and p_prev_to) as prev_impressions
+ from public.gsc_query_stats
+ where brand_id = p_brand_id and date between p_prev_from and p_cur_to
+ group by query
+ order by sum(impressions) filter (where date between p_cur_from and p_cur_to) desc nulls last
+ limit 500
+ ) x
+$$;
+
+-- ─── AI landing pages: analytics and the tracking snippet, per page ─────────
+
+create or replace function public.ae_ai_traffic_pages(
+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date
+) returns jsonb
+language sql stable
+as $$
+ with ga as (
+ select landing_page as page,
+ sum(sessions) filter (where date between p_cur_from and p_cur_to) as cur_sessions,
+ sum(sessions) filter (where date between p_prev_from and p_prev_to) as prev_sessions,
+ sum(engaged_sessions) filter (where date between p_cur_from and p_cur_to) as cur_engaged,
+ sum(key_events) filter (where date between p_cur_from and p_cur_to) as cur_key_events,
+ sum(key_events) filter (where date between p_prev_from and p_prev_to) as prev_key_events
+ from public.ga_ai_traffic_stats
+ where brand_id = p_brand_id and date between p_prev_from and p_cur_to
+ group by landing_page
+ ),
+ snippet as (
+ select url as page,
+ count(*) filter (where created_at::date between p_cur_from and p_cur_to) as cur_sessions,
+ count(*) filter (where created_at::date between p_prev_from and p_prev_to) as prev_sessions
+ from public.ai_traffic_logs
+ where brand_id = p_brand_id and created_at >= p_prev_from
+ group by url
+ )
+ select jsonb_build_object(
+ 'analytics', (select coalesce(jsonb_agg(row_to_json(g)), '[]'::jsonb) from (select * from ga order by cur_sessions desc nulls last limit 300) g),
+ 'snippet', (select coalesce(jsonb_agg(row_to_json(s)), '[]'::jsonb) from (select * from snippet order by cur_sessions desc nulls last limit 300) s)
+ )
+$$;
+
+-- Service-role only.
+revoke all on function public.ae_prompt_stats(uuid, date, date, date, date) from public, anon, authenticated;
+revoke all on function public.ae_competitor_prompt_stats(uuid, date, date, date, date) from public, anon, authenticated;
+revoke all on function public.ae_dimension_stats(uuid, date, date, date, date) from public, anon, authenticated;
+revoke all on function public.ae_citation_sources(uuid, timestamptz) from public, anon, authenticated;
+revoke all on function public.ae_owned_citations(uuid, timestamptz, timestamptz) from public, anon, authenticated;
+revoke all on function public.ae_fanout_gaps(uuid, timestamptz) from public, anon, authenticated;
+revoke all on function public.ae_gsc_queries(uuid, date, date, date, date) from public, anon, authenticated;
+revoke all on function public.ae_ai_traffic_pages(uuid, date, date, date, date) from public, anon, authenticated;
+
+grant execute on function public.ae_prompt_stats(uuid, date, date, date, date) to service_role;
+grant execute on function public.ae_competitor_prompt_stats(uuid, date, date, date, date) to service_role;
+grant execute on function public.ae_dimension_stats(uuid, date, date, date, date) to service_role;
+grant execute on function public.ae_citation_sources(uuid, timestamptz) to service_role;
+grant execute on function public.ae_owned_citations(uuid, timestamptz, timestamptz) to service_role;
+grant execute on function public.ae_fanout_gaps(uuid, timestamptz) to service_role;
+grant execute on function public.ae_gsc_queries(uuid, date, date, date, date) to service_role;
+grant execute on function public.ae_ai_traffic_pages(uuid, date, date, date, date) to service_role;
diff --git a/supabase/migrations/00092_action_engine_owned_citations_fast.sql b/supabase/migrations/00092_action_engine_owned_citations_fast.sql
new file mode 100644
index 000000000..6775d230f
--- /dev/null
+++ b/supabase/migrations/00092_action_engine_owned_citations_fast.sql
@@ -0,0 +1,40 @@
+-- Replaces ae_owned_citations from 00091, which took 6.1s on the largest
+-- brand: it joined every citation of the last fortnight to its URL (≈480k
+-- rows) and only then asked which were owned. This counts per URL id first,
+-- straight off the (brand_id, created_at) covering index, and joins the few
+-- thousand distinct URLs afterwards. 0.95s on the same brand — well clear of
+-- the 8s statement timeout that took the nightly pass down twice (#829, #834).
+
+create or replace function public.ae_owned_citations(
+ p_brand_id uuid, p_cur_from timestamptz, p_prev_from timestamptz
+) returns jsonb
+language sql stable
+as $$
+ with owned as (
+ select regexp_replace(lower(domain), '^www\.', '') as d
+ from public.brand_domains where brand_id = p_brand_id
+ ),
+ per_url as materialized (
+ select url_id,
+ count(*) filter (where created_at >= p_cur_from) as cur_citations,
+ count(*) filter (where created_at < p_cur_from) as prev_citations
+ from public.prompt_result_citations
+ where brand_id = p_brand_id and created_at >= p_prev_from
+ group by url_id
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select u.url, p.cur_citations, p.prev_citations
+ from per_url p
+ join public.citation_urls u on u.id = p.url_id
+ where exists (
+ select 1 from owned o
+ where regexp_replace(lower(u.domain), '^www\.', '') = o.d
+ or regexp_replace(lower(u.domain), '^www\.', '') like '%.' || o.d
+ )
+ order by p.cur_citations + p.prev_citations desc
+ limit 300
+ ) x
+$$;
+
+revoke all on function public.ae_owned_citations(uuid, timestamptz, timestamptz) from public, anon, authenticated;
+grant execute on function public.ae_owned_citations(uuid, timestamptz, timestamptz) to service_role;
diff --git a/supabase/migrations/00093_task_modes_per_spec.sql b/supabase/migrations/00093_task_modes_per_spec.sql
new file mode 100644
index 000000000..000f99348
--- /dev/null
+++ b/supabase/migrations/00093_task_modes_per_spec.sql
@@ -0,0 +1,41 @@
+-- Task execution modes and permission levels, in the specification's terms.
+--
+-- Phase 5 (00088) stored a simplification: `mode` as manual/agent and
+-- `permission` as none/approval. The V1 Task Library specification defines
+-- four execution modes and three permission levels, and the difference is not
+-- cosmetic — SYSTEM work (a deterministic comparison) and HUMAN_OR_AGENT work
+-- (either may do it, depending on the tools connected) are both things the
+-- planner and the runner have to be able to say, and manual/agent cannot.
+--
+-- mode system | agent | human | human_or_agent
+-- permission read | write | execute
+--
+-- WRITE and EXECUTE require approval unless a workspace explicitly authorises
+-- autonomy; READ does not. That is the specification's default and what the
+-- runner enforces.
+--
+-- The constraints are dropped before the rows are rewritten: 00083 rewrote
+-- rows first and the old constraint rejected them, rolling the migration back.
+
+alter table public.action_tasks drop constraint if exists action_tasks_mode_check;
+alter table public.action_tasks drop constraint if exists action_tasks_permission_check;
+
+update public.action_tasks
+set mode = case mode when 'manual' then 'human' else mode end,
+ permission = case permission when 'none' then 'read' when 'approval' then 'execute' else permission end;
+
+alter table public.action_tasks alter column mode set default 'human';
+alter table public.action_tasks alter column permission set default 'read';
+
+alter table public.action_tasks
+ add constraint action_tasks_mode_check
+ check (mode in ('system', 'agent', 'human', 'human_or_agent'));
+
+alter table public.action_tasks
+ add constraint action_tasks_permission_check
+ check (permission in ('read', 'write', 'execute'));
+
+comment on column public.action_tasks.mode is
+ 'Who carries the task out: system (deterministic, by Ansvisor), agent, human, or human_or_agent.';
+comment on column public.action_tasks.permission is
+ 'read, write (modifies owned content) or execute (acts externally). write and execute require approval unless autonomy is authorised.';
diff --git a/supabase/migrations/00094_task_modes_transition_window.sql b/supabase/migrations/00094_task_modes_transition_window.sql
new file mode 100644
index 000000000..08aaf8d56
--- /dev/null
+++ b/supabase/migrations/00094_task_modes_transition_window.sql
@@ -0,0 +1,22 @@
+-- Keeps the old task vocabulary valid until the code that writes the new one
+-- is deployed.
+--
+-- 00093 moved `mode` and `permission` to the specification's terms and
+-- constrained them to those. The server that was live when it was applied
+-- still inserted `manual` / `none` / `approval`, and a rejected insert while
+-- raising an action throws the whole nightly pass — the failure #829 and #834
+-- were about. So both vocabularies are accepted for the transition.
+--
+-- A later migration drops the old values once the deploy that stops writing
+-- them has run for a night; existing rows were already rewritten by 00093.
+
+alter table public.action_tasks drop constraint if exists action_tasks_mode_check;
+alter table public.action_tasks drop constraint if exists action_tasks_permission_check;
+
+alter table public.action_tasks
+ add constraint action_tasks_mode_check
+ check (mode in ('system', 'agent', 'human', 'human_or_agent', 'manual'));
+
+alter table public.action_tasks
+ add constraint action_tasks_permission_check
+ check (permission in ('read', 'write', 'execute', 'none', 'approval'));
diff --git a/supabase/migrations/00095_action_engine_citation_sources_fast.sql b/supabase/migrations/00095_action_engine_citation_sources_fast.sql
new file mode 100644
index 000000000..4c4cfda98
--- /dev/null
+++ b/supabase/migrations/00095_action_engine_citation_sources_fast.sql
@@ -0,0 +1,53 @@
+-- Replaces ae_citation_sources from 00091.
+--
+-- It normalised every citation's domain — `regexp_replace` on ≈240k rows for
+-- the largest brand — before deduplicating. It ran in 2.4s alone and timed
+-- out under load during the first end-to-end run. Deduplicating on URL ids
+-- first and normalising the ≈50k distinct URLs once brings it to 1.6s on the
+-- same brand, and the detector retries a transient timeout on top.
+
+create or replace function public.ae_citation_sources(p_brand_id uuid, p_from timestamptz)
+returns jsonb
+language sql stable
+as $$
+ with owned as (
+ select regexp_replace(lower(domain), '^www\.', '') as d
+ from public.brand_domains where brand_id = p_brand_id
+ ),
+ r as materialized (
+ select id, prompt_id, coalesce(mention_count, 0) > 0 as bm,
+ coalesce(competitor_mentions @? '$[*] ? (@.mention_count > 0)', false) as cm
+ from public.prompt_results
+ where brand_id = p_brand_id and created_at >= p_from
+ ),
+ rd as materialized (
+ select distinct prc.prompt_result_id as rid, prc.url_id
+ from public.prompt_result_citations prc
+ where prc.brand_id = p_brand_id and prc.created_at >= p_from
+ ),
+ url_domain as materialized (
+ select ids.url_id, regexp_replace(lower(u.domain), '^www\.', '') as domain
+ from (select distinct url_id from rd) ids
+ join public.citation_urls u on u.id = ids.url_id
+ ),
+ dom as materialized (
+ select distinct rd.rid, ud.domain
+ from rd join url_domain ud on ud.url_id = rd.url_id
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select dom.domain,
+ exists (select 1 from owned o where dom.domain = o.d or dom.domain like '%.' || o.d) as owned,
+ count(*) as results,
+ count(distinct r.prompt_id) as prompts,
+ count(*) filter (where r.bm) as with_brand,
+ count(*) filter (where r.cm and not r.bm) as competitor_only,
+ count(*) filter (where not r.bm) as without_brand
+ from dom join r on r.id = dom.rid
+ group by dom.domain
+ order by count(*) desc
+ limit 300
+ ) x
+$$;
+
+revoke all on function public.ae_citation_sources(uuid, timestamptz) from public, anon, authenticated;
+grant execute on function public.ae_citation_sources(uuid, timestamptz) to service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 675cc61d3..db7063148 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -10727,3 +10727,473 @@ alter table public.action_task_runs enable row level security;
comment on table public.action_task_runs is
'One row per attempt to carry out a task automatically. Inputs, tool, result and error — never the model''s reasoning.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00091_action_engine_detector_reads.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Action Engine (#818): the reads behind the V1 definition library.
+--
+-- The V1 specification asks for 62 action definitions. Each needs a signal
+-- that can trigger it, and each signal needs a read over data the product
+-- already collects — prompt visibility per day, competitor presence per
+-- prompt, citation sources, fan-out queries, Search Console queries, AI
+-- landing-page traffic.
+--
+-- Doing those reads from the server row by row is how the nightly pass died on
+-- the largest brand twice (#829, #834): a query that scans a brand's history
+-- crosses the 8s statement timeout once the brand is large enough. So every
+-- read here aggregates in Postgres and returns a compact summary — one row per
+-- prompt, per competitor, per domain, per query, per page — measured on the
+-- largest brand before being written down:
+--
+-- ae_citation_sources 1.5s (was 15s as a naive join)
+-- ae_fanout_gaps 0.45s
+--
+-- All are service-role only. They take a brand id and aggregate across it, and
+-- nothing in the web calls them; granting them to authenticated users would
+-- only widen the surface for no reader.
+
+-- ─── Prompts: presence per day, current window against the previous one ─────
+
+create or replace function public.ae_prompt_stats(
+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date
+) returns jsonb
+language sql stable
+as $$
+ with days as (
+ select prompt_id, day, bool_or(has_mention) as m, bool_or(has_citation) as c
+ from public.insights_prompt_daily
+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to
+ group by prompt_id, day
+ ),
+ active as (
+ select p.id, p.topic_id
+ from public.prompts p
+ join public.prompt_sets s on s.id = p.prompt_set_id
+ where s.brand_id = p_brand_id and p.is_active
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select a.id as prompt_id, a.topic_id,
+ count(d.day) filter (where d.day between p_cur_from and p_cur_to) as cur_days,
+ count(d.day) filter (where d.day between p_cur_from and p_cur_to and d.m) as cur_mention_days,
+ count(d.day) filter (where d.day between p_cur_from and p_cur_to and d.c) as cur_citation_days,
+ count(d.day) filter (where d.day between p_prev_from and p_prev_to) as prev_days,
+ count(d.day) filter (where d.day between p_prev_from and p_prev_to and d.m) as prev_mention_days,
+ count(d.day) filter (where d.day between p_prev_from and p_prev_to and d.c) as prev_citation_days,
+ max(d.day) filter (where d.m) as last_mention_day,
+ max(d.day) filter (where d.c) as last_citation_day,
+ (select coalesce(max(v.est_ai_volume), 0) from public.prompt_volumes v where v.prompt_id = a.id) as volume,
+ exists (select 1 from public.prompt_target_urls t where t.prompt_id = a.id) as has_target_url
+ from active a
+ left join days d on d.prompt_id = a.id
+ group by a.id, a.topic_id
+ ) x
+$$;
+
+-- ─── Competitors: presence per prompt ───────────────────────────────────────
+
+create or replace function public.ae_competitor_prompt_stats(
+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date
+) returns jsonb
+language sql stable
+as $$
+ with days as (
+ select prompt_id, competitor_id, day
+ from public.insights_competitor_prompt_daily
+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to
+ group by prompt_id, competitor_id, day
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select prompt_id, competitor_id,
+ count(*) filter (where day between p_cur_from and p_cur_to) as cur_days,
+ count(*) filter (where day between p_prev_from and p_prev_to) as prev_days
+ from days
+ group by prompt_id, competitor_id
+ ) x
+$$;
+
+-- ─── Dimensions: visibility by platform, by region, and per competitor ───────
+
+create or replace function public.ae_dimension_stats(
+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date
+) returns jsonb
+language sql stable
+as $$
+ select jsonb_build_object(
+ 'platforms', (
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select platform as key,
+ sum(answer_count) filter (where day between p_cur_from and p_cur_to) as cur_answers,
+ sum(mention_answers) filter (where day between p_cur_from and p_cur_to) as cur_mentions,
+ sum(answer_count) filter (where day between p_prev_from and p_prev_to) as prev_answers,
+ sum(mention_answers) filter (where day between p_prev_from and p_prev_to) as prev_mentions
+ from public.insights_brand_daily
+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to
+ group by platform
+ ) x
+ ),
+ 'regions', (
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select region as key,
+ sum(answer_count) filter (where day between p_cur_from and p_cur_to) as cur_answers,
+ sum(mention_answers) filter (where day between p_cur_from and p_cur_to) as cur_mentions,
+ sum(answer_count) filter (where day between p_prev_from and p_prev_to) as prev_answers,
+ sum(mention_answers) filter (where day between p_prev_from and p_prev_to) as prev_mentions
+ from public.insights_brand_daily
+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to
+ group by region
+ ) x
+ ),
+ 'competitors', (
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select c.competitor_id as key, max(co.name) as name,
+ sum(c.mention_answers) filter (where c.day between p_cur_from and p_cur_to) as cur_mentions,
+ sum(c.mention_answers) filter (where c.day between p_prev_from and p_prev_to) as prev_mentions,
+ sum(c.citation_answers) filter (where c.day between p_cur_from and p_cur_to) as cur_citations
+ from public.insights_competitor_daily c
+ left join public.competitors co on co.id::text = c.competitor_id
+ where c.brand_id = p_brand_id and c.day between p_prev_from and p_cur_to
+ group by c.competitor_id
+ ) x
+ )
+ )
+$$;
+
+-- ─── Citation sources: which domains answers cite, and whose answers ────────
+
+create or replace function public.ae_citation_sources(p_brand_id uuid, p_from timestamptz)
+returns jsonb
+language sql stable
+as $$
+ with owned as (
+ select regexp_replace(lower(domain), '^www\.', '') as d
+ from public.brand_domains where brand_id = p_brand_id
+ ),
+ r as materialized (
+ select id, prompt_id, coalesce(mention_count, 0) > 0 as bm,
+ coalesce(competitor_mentions @? '$[*] ? (@.mention_count > 0)', false) as cm
+ from public.prompt_results
+ where brand_id = p_brand_id and created_at >= p_from
+ ),
+ rd as materialized (
+ select distinct prc.prompt_result_id as rid, regexp_replace(lower(u.domain), '^www\.', '') as domain
+ from public.prompt_result_citations prc
+ join public.citation_urls u on u.id = prc.url_id
+ where prc.brand_id = p_brand_id and prc.created_at >= p_from
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select rd.domain,
+ exists (select 1 from owned o where rd.domain = o.d or rd.domain like '%.' || o.d) as owned,
+ count(*) as results,
+ count(distinct r.prompt_id) as prompts,
+ count(*) filter (where r.bm) as with_brand,
+ count(*) filter (where r.cm and not r.bm) as competitor_only,
+ count(*) filter (where not r.bm) as without_brand
+ from rd join r on r.id = rd.rid
+ group by rd.domain
+ order by count(*) desc
+ limit 300
+ ) x
+$$;
+
+-- ─── Owned URLs: how often each owned page was cited, now and before ────────
+
+create or replace function public.ae_owned_citations(
+ p_brand_id uuid, p_cur_from timestamptz, p_prev_from timestamptz
+) returns jsonb
+language sql stable
+as $$
+ with owned as (
+ select regexp_replace(lower(domain), '^www\.', '') as d
+ from public.brand_domains where brand_id = p_brand_id
+ ),
+ cites as materialized (
+ select prc.created_at, u.url, regexp_replace(lower(u.domain), '^www\.', '') as domain
+ from public.prompt_result_citations prc
+ join public.citation_urls u on u.id = prc.url_id
+ where prc.brand_id = p_brand_id and prc.created_at >= p_prev_from
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select c.url,
+ count(*) filter (where c.created_at >= p_cur_from) as cur_citations,
+ count(*) filter (where c.created_at < p_cur_from) as prev_citations
+ from cites c
+ where exists (select 1 from owned o where c.domain = o.d or c.domain like '%.' || o.d)
+ group by c.url
+ order by count(*) desc
+ limit 300
+ ) x
+$$;
+
+-- ─── Fan-out queries the engines ran where the brand never appeared ─────────
+
+create or replace function public.ae_fanout_gaps(p_brand_id uuid, p_from timestamptz)
+returns jsonb
+language sql stable
+as $$
+ with r as materialized (
+ select id, prompt_id, coalesce(mention_count, 0) > 0 as bm,
+ coalesce(competitor_mentions @? '$[*] ? (@.mention_count > 0)', false) as cm,
+ search_queries
+ from public.prompt_results
+ where brand_id = p_brand_id and created_at >= p_from
+ and jsonb_typeof(search_queries) = 'array'
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select lower(trim(q->>'query')) as query,
+ count(*) as results,
+ count(distinct r.prompt_id) as prompts,
+ count(*) filter (where r.cm and not r.bm) as competitor_only
+ from r cross join lateral jsonb_array_elements(r.search_queries) q
+ where coalesce(trim(q->>'query'), '') <> ''
+ group by 1
+ having count(*) filter (where r.bm) = 0
+ order by count(distinct r.prompt_id) desc, count(*) desc
+ limit 300
+ ) x
+$$;
+
+-- ─── Search Console: per query, now against before ──────────────────────────
+
+create or replace function public.ae_gsc_queries(
+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date
+) returns jsonb
+language sql stable
+as $$
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select query,
+ sum(clicks) filter (where date between p_cur_from and p_cur_to) as cur_clicks,
+ sum(impressions) filter (where date between p_cur_from and p_cur_to) as cur_impressions,
+ avg(position) filter (where date between p_cur_from and p_cur_to) as cur_position,
+ sum(clicks) filter (where date between p_prev_from and p_prev_to) as prev_clicks,
+ sum(impressions) filter (where date between p_prev_from and p_prev_to) as prev_impressions
+ from public.gsc_query_stats
+ where brand_id = p_brand_id and date between p_prev_from and p_cur_to
+ group by query
+ order by sum(impressions) filter (where date between p_cur_from and p_cur_to) desc nulls last
+ limit 500
+ ) x
+$$;
+
+-- ─── AI landing pages: analytics and the tracking snippet, per page ─────────
+
+create or replace function public.ae_ai_traffic_pages(
+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date
+) returns jsonb
+language sql stable
+as $$
+ with ga as (
+ select landing_page as page,
+ sum(sessions) filter (where date between p_cur_from and p_cur_to) as cur_sessions,
+ sum(sessions) filter (where date between p_prev_from and p_prev_to) as prev_sessions,
+ sum(engaged_sessions) filter (where date between p_cur_from and p_cur_to) as cur_engaged,
+ sum(key_events) filter (where date between p_cur_from and p_cur_to) as cur_key_events,
+ sum(key_events) filter (where date between p_prev_from and p_prev_to) as prev_key_events
+ from public.ga_ai_traffic_stats
+ where brand_id = p_brand_id and date between p_prev_from and p_cur_to
+ group by landing_page
+ ),
+ snippet as (
+ select url as page,
+ count(*) filter (where created_at::date between p_cur_from and p_cur_to) as cur_sessions,
+ count(*) filter (where created_at::date between p_prev_from and p_prev_to) as prev_sessions
+ from public.ai_traffic_logs
+ where brand_id = p_brand_id and created_at >= p_prev_from
+ group by url
+ )
+ select jsonb_build_object(
+ 'analytics', (select coalesce(jsonb_agg(row_to_json(g)), '[]'::jsonb) from (select * from ga order by cur_sessions desc nulls last limit 300) g),
+ 'snippet', (select coalesce(jsonb_agg(row_to_json(s)), '[]'::jsonb) from (select * from snippet order by cur_sessions desc nulls last limit 300) s)
+ )
+$$;
+
+-- Service-role only.
+revoke all on function public.ae_prompt_stats(uuid, date, date, date, date) from public, anon, authenticated;
+revoke all on function public.ae_competitor_prompt_stats(uuid, date, date, date, date) from public, anon, authenticated;
+revoke all on function public.ae_dimension_stats(uuid, date, date, date, date) from public, anon, authenticated;
+revoke all on function public.ae_citation_sources(uuid, timestamptz) from public, anon, authenticated;
+revoke all on function public.ae_owned_citations(uuid, timestamptz, timestamptz) from public, anon, authenticated;
+revoke all on function public.ae_fanout_gaps(uuid, timestamptz) from public, anon, authenticated;
+revoke all on function public.ae_gsc_queries(uuid, date, date, date, date) from public, anon, authenticated;
+revoke all on function public.ae_ai_traffic_pages(uuid, date, date, date, date) from public, anon, authenticated;
+
+grant execute on function public.ae_prompt_stats(uuid, date, date, date, date) to service_role;
+grant execute on function public.ae_competitor_prompt_stats(uuid, date, date, date, date) to service_role;
+grant execute on function public.ae_dimension_stats(uuid, date, date, date, date) to service_role;
+grant execute on function public.ae_citation_sources(uuid, timestamptz) to service_role;
+grant execute on function public.ae_owned_citations(uuid, timestamptz, timestamptz) to service_role;
+grant execute on function public.ae_fanout_gaps(uuid, timestamptz) to service_role;
+grant execute on function public.ae_gsc_queries(uuid, date, date, date, date) to service_role;
+grant execute on function public.ae_ai_traffic_pages(uuid, date, date, date, date) to service_role;
+
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00092_action_engine_owned_citations_fast.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Replaces ae_owned_citations from 00091, which took 6.1s on the largest
+-- brand: it joined every citation of the last fortnight to its URL (≈480k
+-- rows) and only then asked which were owned. This counts per URL id first,
+-- straight off the (brand_id, created_at) covering index, and joins the few
+-- thousand distinct URLs afterwards. 0.95s on the same brand — well clear of
+-- the 8s statement timeout that took the nightly pass down twice (#829, #834).
+
+create or replace function public.ae_owned_citations(
+ p_brand_id uuid, p_cur_from timestamptz, p_prev_from timestamptz
+) returns jsonb
+language sql stable
+as $$
+ with owned as (
+ select regexp_replace(lower(domain), '^www\.', '') as d
+ from public.brand_domains where brand_id = p_brand_id
+ ),
+ per_url as materialized (
+ select url_id,
+ count(*) filter (where created_at >= p_cur_from) as cur_citations,
+ count(*) filter (where created_at < p_cur_from) as prev_citations
+ from public.prompt_result_citations
+ where brand_id = p_brand_id and created_at >= p_prev_from
+ group by url_id
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select u.url, p.cur_citations, p.prev_citations
+ from per_url p
+ join public.citation_urls u on u.id = p.url_id
+ where exists (
+ select 1 from owned o
+ where regexp_replace(lower(u.domain), '^www\.', '') = o.d
+ or regexp_replace(lower(u.domain), '^www\.', '') like '%.' || o.d
+ )
+ order by p.cur_citations + p.prev_citations desc
+ limit 300
+ ) x
+$$;
+
+revoke all on function public.ae_owned_citations(uuid, timestamptz, timestamptz) from public, anon, authenticated;
+grant execute on function public.ae_owned_citations(uuid, timestamptz, timestamptz) to service_role;
+
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00093_task_modes_per_spec.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Task execution modes and permission levels, in the specification's terms.
+--
+-- Phase 5 (00088) stored a simplification: `mode` as manual/agent and
+-- `permission` as none/approval. The V1 Task Library specification defines
+-- four execution modes and three permission levels, and the difference is not
+-- cosmetic — SYSTEM work (a deterministic comparison) and HUMAN_OR_AGENT work
+-- (either may do it, depending on the tools connected) are both things the
+-- planner and the runner have to be able to say, and manual/agent cannot.
+--
+-- mode system | agent | human | human_or_agent
+-- permission read | write | execute
+--
+-- WRITE and EXECUTE require approval unless a workspace explicitly authorises
+-- autonomy; READ does not. That is the specification's default and what the
+-- runner enforces.
+--
+-- The constraints are dropped before the rows are rewritten: 00083 rewrote
+-- rows first and the old constraint rejected them, rolling the migration back.
+
+alter table public.action_tasks drop constraint if exists action_tasks_mode_check;
+alter table public.action_tasks drop constraint if exists action_tasks_permission_check;
+
+update public.action_tasks
+set mode = case mode when 'manual' then 'human' else mode end,
+ permission = case permission when 'none' then 'read' when 'approval' then 'execute' else permission end;
+
+alter table public.action_tasks alter column mode set default 'human';
+alter table public.action_tasks alter column permission set default 'read';
+
+alter table public.action_tasks
+ add constraint action_tasks_mode_check
+ check (mode in ('system', 'agent', 'human', 'human_or_agent'));
+
+alter table public.action_tasks
+ add constraint action_tasks_permission_check
+ check (permission in ('read', 'write', 'execute'));
+
+comment on column public.action_tasks.mode is
+ 'Who carries the task out: system (deterministic, by Ansvisor), agent, human, or human_or_agent.';
+comment on column public.action_tasks.permission is
+ 'read, write (modifies owned content) or execute (acts externally). write and execute require approval unless autonomy is authorised.';
+
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00094_task_modes_transition_window.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Keeps the old task vocabulary valid until the code that writes the new one
+-- is deployed.
+--
+-- 00093 moved `mode` and `permission` to the specification's terms and
+-- constrained them to those. The server that was live when it was applied
+-- still inserted `manual` / `none` / `approval`, and a rejected insert while
+-- raising an action throws the whole nightly pass — the failure #829 and #834
+-- were about. So both vocabularies are accepted for the transition.
+--
+-- A later migration drops the old values once the deploy that stops writing
+-- them has run for a night; existing rows were already rewritten by 00093.
+
+alter table public.action_tasks drop constraint if exists action_tasks_mode_check;
+alter table public.action_tasks drop constraint if exists action_tasks_permission_check;
+
+alter table public.action_tasks
+ add constraint action_tasks_mode_check
+ check (mode in ('system', 'agent', 'human', 'human_or_agent', 'manual'));
+
+alter table public.action_tasks
+ add constraint action_tasks_permission_check
+ check (permission in ('read', 'write', 'execute', 'none', 'approval'));
+
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00095_action_engine_citation_sources_fast.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Replaces ae_citation_sources from 00091.
+--
+-- It normalised every citation's domain — `regexp_replace` on ≈240k rows for
+-- the largest brand — before deduplicating. It ran in 2.4s alone and timed
+-- out under load during the first end-to-end run. Deduplicating on URL ids
+-- first and normalising the ≈50k distinct URLs once brings it to 1.6s on the
+-- same brand, and the detector retries a transient timeout on top.
+
+create or replace function public.ae_citation_sources(p_brand_id uuid, p_from timestamptz)
+returns jsonb
+language sql stable
+as $$
+ with owned as (
+ select regexp_replace(lower(domain), '^www\.', '') as d
+ from public.brand_domains where brand_id = p_brand_id
+ ),
+ r as materialized (
+ select id, prompt_id, coalesce(mention_count, 0) > 0 as bm,
+ coalesce(competitor_mentions @? '$[*] ? (@.mention_count > 0)', false) as cm
+ from public.prompt_results
+ where brand_id = p_brand_id and created_at >= p_from
+ ),
+ rd as materialized (
+ select distinct prc.prompt_result_id as rid, prc.url_id
+ from public.prompt_result_citations prc
+ where prc.brand_id = p_brand_id and prc.created_at >= p_from
+ ),
+ url_domain as materialized (
+ select ids.url_id, regexp_replace(lower(u.domain), '^www\.', '') as domain
+ from (select distinct url_id from rd) ids
+ join public.citation_urls u on u.id = ids.url_id
+ ),
+ dom as materialized (
+ select distinct rd.rid, ud.domain
+ from rd join url_domain ud on ud.url_id = rd.url_id
+ )
+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (
+ select dom.domain,
+ exists (select 1 from owned o where dom.domain = o.d or dom.domain like '%.' || o.d) as owned,
+ count(*) as results,
+ count(distinct r.prompt_id) as prompts,
+ count(*) filter (where r.bm) as with_brand,
+ count(*) filter (where r.cm and not r.bm) as competitor_only,
+ count(*) filter (where not r.bm) as without_brand
+ from dom join r on r.id = dom.rid
+ group by dom.domain
+ order by count(*) desc
+ limit 300
+ ) x
+$$;
+
+revoke all on function public.ae_citation_sources(uuid, timestamptz) from public, anon, authenticated;
+grant execute on function public.ae_citation_sources(uuid, timestamptz) to service_role;
+
diff --git a/web/messages/en.json b/web/messages/en.json
index caebb5550..131d5656a 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -282,7 +282,14 @@
"urls": "{count, plural, one {1 URL} other {# URLs}}",
"platform": "Platform",
"competitor": "Competitor",
- "allPrompts": "All prompts"
+ "allPrompts": "All prompts",
+ "pages": "{count, plural, one {# page} other {# pages}}",
+ "sources": "{count, plural, one {# source} other {# sources}}",
+ "queries": "{count, plural, one {# query} other {# queries}}",
+ "topics": "{count, plural, one {# topic} other {# topics}}",
+ "platforms": "{count, plural, one {# platform} other {# platforms}}",
+ "regions": "{count, plural, one {# region} other {# regions}}",
+ "competitors": "{count, plural, one {# competitor} other {# competitors}}"
},
"menu": {
"label": "Actions for this signal",
@@ -372,6 +379,204 @@
"competitor_citation_gap": {
"title": "A competitor is cited far more often",
"description": "{competitor} was cited in {theirs} answers; you were cited in {ours}."
+ },
+ "prompt_visibility_gap": {
+ "title": "Absent from {targets}",
+ "description": "Your brand does not appear in answers to these prompts."
+ },
+ "high_demand_gap": {
+ "title": "No visibility on {targets} with demand",
+ "description": "These prompts carry demand, and your brand is absent from their answers."
+ },
+ "uncovered_demand": {
+ "title": "Uncovered demand across {targets}",
+ "description": "Demand exists here, and no page of yours covers it."
+ },
+ "prompt_unmapped": {
+ "title": "No page for {targets}",
+ "description": "No page is mapped to these prompts, and none has been cited."
+ },
+ "content_underperforming": {
+ "title": "Pages not winning {targets}",
+ "description": "A page exists for these prompts, and your brand is still absent."
+ },
+ "lost_mentions": {
+ "title": "Mentions lost on {targets}",
+ "description": "Your brand was named in these answers and no longer is."
+ },
+ "high_value_prompt_lost": {
+ "title": "Lost presence on {targets} with demand",
+ "description": "You were visible on these high-demand prompts and no longer are."
+ },
+ "citation_at_risk": {
+ "title": "Citations thinning on {targets}",
+ "description": "Citations on these prompts fell below half their earlier rate."
+ },
+ "topic_gap": {
+ "title": "Partial coverage of {name}",
+ "description": "You appear on part of this topic’s prompts."
+ },
+ "topic_uncovered": {
+ "title": "Barely present in {name}",
+ "description": "You appear on few of this topic’s prompts."
+ },
+ "topic_slipping": {
+ "title": "Coverage slipping in {name}",
+ "description": "Your coverage of this topic is starting to fall."
+ },
+ "topic_drop": {
+ "title": "Coverage dropped in {name}",
+ "description": "Your coverage of this topic fell significantly."
+ },
+ "platform_slipping": {
+ "title": "Visibility slipping on {name}",
+ "description": "Your mention rate on this platform is starting to fall."
+ },
+ "platform_drop": {
+ "title": "Visibility dropped on {name}",
+ "description": "Your mention rate on this platform fell significantly."
+ },
+ "country_gap": {
+ "title": "Weak in {name}",
+ "description": "You are far less visible here than in your strongest region."
+ },
+ "competitor_leads": {
+ "title": "{name} is mentioned far more than you",
+ "description": "This competitor is named a multiple of your count."
+ },
+ "competitor_momentum": {
+ "title": "{name} is gaining fast",
+ "description": "This competitor’s mentions grew sharply against the week before."
+ },
+ "competitor_topic_lead": {
+ "title": "A competitor leads {name}",
+ "description": "Competitors appear on most of this topic’s prompts where you do not."
+ },
+ "competitor_high_value_lead": {
+ "title": "Competitors lead on {targets}",
+ "description": "Competitors appear on these high-demand prompts, and you do not."
+ },
+ "competitor_uncovered_topic": {
+ "title": "A competitor leads {name}, where you have no content",
+ "description": "Competitors hold this topic, and no page of yours covers it."
+ },
+ "authority_citation_gap": {
+ "title": "Rarely beside {name}",
+ "description": "This source is cited widely, and rarely in answers that name you."
+ },
+ "third_party_citation_gap": {
+ "title": "{name} could reference your pages",
+ "description": "This source is cited when answers discuss you, and does not reference your own pages."
+ },
+ "third_party_presence_gap": {
+ "title": "Absent from answers citing {name}",
+ "description": "Answers citing this source never name your brand."
+ },
+ "competitor_cited_source": {
+ "title": "{name} cites competitors, not you",
+ "description": "This source appears in answers naming competitors, and never in yours."
+ },
+ "competitor_winning_source": {
+ "title": "Competitors win {name}",
+ "description": "Competitors appear across several prompts citing this source; you never do."
+ },
+ "page_citation_slipping": {
+ "title": "Citations slipping on {targets}",
+ "description": "Your pages here are cited less than the week before."
+ },
+ "owned_page_citation_lost": {
+ "title": "Citations lost on {targets}",
+ "description": "Your pages here were cited and are now cited nowhere."
+ },
+ "fanout_gap": {
+ "title": "Absent from {targets}",
+ "description": "Engines search these follow-up queries, and your brand never appears."
+ },
+ "competitor_fanout_gap": {
+ "title": "Competitors win {targets}",
+ "description": "Competitors appear on these follow-up queries, and you do not."
+ },
+ "gsc_demand_gap": {
+ "title": "Search demand without AI visibility on {targets}",
+ "description": "These queries earn Google impressions, and the related prompts show no AI visibility."
+ },
+ "search_ai_misalignment": {
+ "title": "Top three in Google, invisible in AI for {targets}",
+ "description": "You rank near the top for these queries and do not appear in AI answers."
+ },
+ "gsc_low_ctr": {
+ "title": "Low click-through on {targets}",
+ "description": "These queries earn far fewer clicks than their position usually does."
+ },
+ "gsc_risk": {
+ "title": "AI visibility slipping on {targets} that earn clicks",
+ "description": "These queries bring organic clicks while their AI visibility falls."
+ },
+ "gsc_decline": {
+ "title": "Clicks falling on {targets}",
+ "description": "Search clicks on these queries fell significantly."
+ },
+ "ai_traffic_slipping": {
+ "title": "AI traffic slipping on {targets}",
+ "description": "AI-referred visits to these pages are starting to fall."
+ },
+ "ai_traffic_drop": {
+ "title": "AI traffic dropped across {targets}",
+ "description": "AI-referred visits fell significantly."
+ },
+ "ai_landing_page_winner": {
+ "title": "Strong AI conversions on {targets}",
+ "description": "These pages turn AI traffic into key events well above your site’s rate."
+ },
+ "ai_landing_underperforming": {
+ "title": "Weak engagement on {targets}",
+ "description": "AI visitors engage on these pages well below your site’s rate."
+ },
+ "converting_page_slipping": {
+ "title": "AI traffic slipping on {targets} that convert",
+ "description": "Pages with key events are losing AI-referred visits."
+ },
+ "cross_channel_risk": {
+ "title": "Search and AI traffic falling together",
+ "description": "Organic clicks and AI referrals both fell against the period before."
+ },
+ "visibility_traffic_loss": {
+ "title": "Visibility and AI traffic falling together",
+ "description": "AI visibility and AI-referred traffic fell in the same window. A correlation, not a proven cause."
+ },
+ "crawler_blocked": {
+ "title": "AI crawlers blocked on {targets}",
+ "description": "Site Audit found these pages closed to AI crawlers."
+ },
+ "structured_data_issue": {
+ "title": "Structured data issues on {targets}",
+ "description": "Structured data is missing or invalid on these pages."
+ },
+ "outdated_content": {
+ "title": "Outdated content on {targets}",
+ "description": "These pages fail Site Audit’s freshness checks."
+ },
+ "weak_entity": {
+ "title": "Weak entity signals on {targets}",
+ "description": "These pages fail brand-entity or entity-coverage checks."
+ },
+ "weak_internal_links": {
+ "title": "Weak internal linking on {targets}",
+ "description": "These pages fail the internal-linking check."
+ },
+ "content_gap": {
+ "title": "Content gaps on {targets}",
+ "description": "These pages do not cover the queries they target."
+ },
+ "targets": {
+ "prompts": "{count, plural, one {# prompt} other {# prompts}}",
+ "pages": "{count, plural, one {# page} other {# pages}}",
+ "sources": "{count, plural, one {# source} other {# sources}}",
+ "queries": "{count, plural, one {# query} other {# queries}}",
+ "topics": "{count, plural, one {# topic} other {# topics}}",
+ "platforms": "{count, plural, one {# platform} other {# platforms}}",
+ "regions": "{count, plural, one {# region} other {# regions}}",
+ "competitors": "{count, plural, one {# competitor} other {# competitors}}"
}
},
"actionCategories": {
@@ -439,7 +644,13 @@
"tags": {
"signals": "{count, plural, one {1 signal} other {# signals}}",
"prompts": "{count, plural, one {1 prompt} other {# prompts}}",
- "pages": "{count, plural, one {1 page} other {# pages}}"
+ "pages": "{count, plural, one {1 page} other {# pages}}",
+ "sources": "{count, plural, one {# source} other {# sources}}",
+ "queries": "{count, plural, one {# query} other {# queries}}",
+ "topics": "{count, plural, one {# topic} other {# topics}}",
+ "platforms": "{count, plural, one {# platform} other {# platforms}}",
+ "regions": "{count, plural, one {# region} other {# regions}}",
+ "competitors": "{count, plural, one {# competitor} other {# competitors}}"
},
"menu": {
"label": "Actions for this item"
@@ -505,52 +716,390 @@
},
"actionTexts": {
"recover_visibility": {
- "title": "Recover lost visibility and citations",
- "description": "Citations were lost across {prompts, plural, one {1 prompt} other {# prompts}}.",
- "descriptionWithDrop": "Visibility dropped from {from}% to {to}%; citations lost across {prompts, plural, one {1 prompt} other {# prompts}}.",
- "goal": "Recover and grow visibility and citations for the affected prompts."
+ "title": "Recover visibility across {targets}",
+ "titleGeneric": "Recover lost visibility",
+ "description": "Your AI visibility fell meaningfully.",
+ "goal": "Recover visibility to where it was."
},
"capture_ai_traffic": {
- "title": "Capture AI traffic for {pages, plural, one {1 high-value page} other {# high-value pages}}",
- "description": "Pages with strong business value receive no AI referrals.",
- "goal": "Make these pages visible and cited in AI answers so they start earning AI referrals."
+ "title": "Capture AI traffic for {targets}",
+ "titleGeneric": "Capture AI traffic for high-value pages",
+ "description": "These pages are visible or cited in AI answers but earn little AI-referred traffic.",
+ "goal": "Turn existing AI visibility on these pages into AI-referred visits."
},
"convert_mentions": {
- "title": "Convert mentions into citations",
- "description": "Your brand is mentioned but never cited in {prompts, plural, one {1 prompt} other {# prompts}}.",
+ "title": "Convert mentions into citations across {targets}",
+ "titleGeneric": "Convert mentions into citations",
+ "description": "AI answers name your brand here but do not cite your domain.",
"goal": "Give AI engines something of yours to cite where you are already part of the answer."
},
"fix_low_scores": {
- "title": "Fix low-scoring pages",
- "description": "{pages, plural, one {1 audited page scores} other {# audited pages score}} below 50/100 on AEO readiness.",
- "goal": "Bring the audited pages above the readiness bar."
+ "title": "Fix {targets} with low AI readiness",
+ "titleGeneric": "Fix low-scoring pages",
+ "description": "These pages score below the AI-readiness threshold in Site Audit.",
+ "goal": "Bring pages up to the standard AI engines cite."
},
"close_competitor_gap": {
- "title": "Close the gap with {name}",
- "titleMany": "Close the gap with competitors",
- "description": "Competitor visibility moved sharply against you across your tracked prompts.",
- "goal": "Regain the visibility position lost to competitors."
+ "title": "Close the visibility gap with {targets}",
+ "titleGeneric": "Close the visibility gap with competitors",
+ "description": "A competitor is mentioned well more often than you.",
+ "goal": "Close the gap."
},
"protect_visibility": {
- "title": "Protect visibility before it slips further",
- "description": "Visibility is falling from a strong position.",
- "descriptionWithDrop": "Visibility slipped from {from}% to {to}% — still strong, but heading down.",
- "goal": "Hold the position while it is still there, rather than recovering it later."
+ "title": "Protect visibility across {targets}",
+ "titleGeneric": "Protect your visibility",
+ "description": "A real visibility position is losing ground, before it becomes a collapse.",
+ "goal": "Hold the position while it still exists to hold."
},
"expand_platform_visibility": {
- "title": "Expand visibility on {platform}",
- "description": "You reach {bestRate}% of {best} answers but {rate}% on {platform} — the content ranks, this engine does not surface it.",
- "goal": "Close the gap between your strongest engine and your weakest."
+ "title": "Expand visibility on {targets}",
+ "titleGeneric": "Expand platform visibility",
+ "description": "You rank on some AI platforms and are weak on others. The content can rank; the platform differs.",
+ "goal": "Bring weaker platforms up to the level of your strongest."
},
"unknown": {
"description": "This action comes from a detection rule newer than this release of the app. Its tasks, evidence and measurement are complete — only the written description is missing.",
"goal": "Work through the tasks below; they carry what this action is for."
},
"close_citation_gap": {
- "title": "Close the citation gap",
- "description": "A competitor is cited far more often than you are.",
- "descriptionWithName": "{competitor} was cited in {theirs} answers to your {ours}.",
- "goal": "Earn citations from the sources answering these prompts."
+ "title": "Close the citation gap with {targets}",
+ "titleGeneric": "Close the citation gap",
+ "description": "A competitor is cited a multiple of your count.",
+ "goal": "Earn citations where competitors are winning them."
+ },
+ "expand_prompt_visibility": {
+ "title": "Expand visibility across {targets}",
+ "titleGeneric": "Expand prompt visibility",
+ "description": "Your brand is absent from answers to these tracked prompts.",
+ "goal": "Become visible in AI answers to these prompts."
+ },
+ "capture_high_demand_prompts": {
+ "title": "Capture demand across {targets}",
+ "titleGeneric": "Capture high-demand prompts",
+ "description": "These prompts carry real demand, and your brand does not appear in their answers.",
+ "goal": "Win visibility where the demand is highest."
+ },
+ "expand_topic_visibility": {
+ "title": "Expand visibility in {targets}",
+ "titleGeneric": "Expand topic visibility",
+ "description": "You appear on part of this topic’s prompts; the rest is uncovered.",
+ "goal": "Cover the topic’s missing prompts and subtopics."
+ },
+ "capture_fanout_opportunities": {
+ "title": "Capture fan-out opportunities across {targets}",
+ "titleGeneric": "Capture query fan-out opportunities",
+ "description": "AI engines search these follow-up queries while answering your prompts, and your brand never appears for them.",
+ "goal": "Cover the queries engines research on the way to their answers."
+ },
+ "increase_authority_citations": {
+ "title": "Increase citations from {targets}",
+ "titleGeneric": "Increase authority citations",
+ "description": "These sources are cited widely in your prompts’ answers, and rarely alongside your brand.",
+ "goal": "Earn citations from the sources AI engines already trust in your space."
+ },
+ "expand_country_visibility": {
+ "title": "Expand AI visibility in {targets}",
+ "titleGeneric": "Expand country visibility",
+ "description": "You perform well in one tracked region and poorly in another.",
+ "goal": "Close the visibility gap between regions."
+ },
+ "strengthen_emerging_content": {
+ "title": "Strengthen momentum across {targets}",
+ "titleGeneric": "Strengthen emerging content",
+ "description": "Visibility is improving on these prompts but has not reached its potential.",
+ "goal": "Build on content that is starting to win."
+ },
+ "expand_brand_associations": {
+ "title": "Strengthen brand associations across {targets}",
+ "titleGeneric": "Expand brand associations",
+ "description": "Your brand is under-associated with the topics or attributes you want to own.",
+ "goal": "Be named in answers about the topics you want to own."
+ },
+ "convert_search_demand": {
+ "title": "Expand AI visibility for {targets} already driving search demand",
+ "titleGeneric": "Convert search demand into AI visibility",
+ "description": "These queries earn impressions in Google, and the related AI prompts show no visibility.",
+ "goal": "Carry your search demand into AI answers."
+ },
+ "expand_organic_pages": {
+ "title": "Expand AI visibility for {targets} performing in search",
+ "titleGeneric": "Expand high-performing organic pages into AI",
+ "description": "Pages that perform in organic search have weak AI presence.",
+ "goal": "Make your best organic pages visible in AI answers."
+ },
+ "scale_ai_landing_pages": {
+ "title": "Scale {targets} driving high-quality AI traffic",
+ "titleGeneric": "Scale proven AI landing pages",
+ "description": "These AI landing pages convert well above your site’s rate.",
+ "goal": "Expand what already turns AI traffic into outcomes."
+ },
+ "create_content_for_demand": {
+ "title": "Create content for {targets} with uncovered demand",
+ "titleGeneric": "Create content for uncovered demand",
+ "description": "These prompts carry demand, and no page of yours covers them.",
+ "goal": "Create the content these prompts are asking for."
+ },
+ "create_content_for_topics": {
+ "title": "Create content to cover {targets}",
+ "titleGeneric": "Create content for topic gaps",
+ "description": "You barely appear in this topic, and new content is needed rather than edits.",
+ "goal": "Build coverage for a topic you are missing."
+ },
+ "optimize_content_for_ai": {
+ "title": "Optimize pages for {targets}",
+ "titleGeneric": "Optimize content for AI visibility",
+ "description": "A page is mapped to these prompts, and your brand is still not visible on them.",
+ "goal": "Make existing pages good enough to be cited."
+ },
+ "earn_third_party_presence": {
+ "title": "Build brand presence across {targets}",
+ "titleGeneric": "Earn third-party brand presence",
+ "description": "AI answers cite these sources, and your brand never appears in those answers.",
+ "goal": "Get included on the sources AI engines use."
+ },
+ "earn_third_party_citations": {
+ "title": "Target {targets} for citations of your pages",
+ "titleGeneric": "Earn third-party citations",
+ "description": "These sources are cited when answers discuss your brand, and could reference your own pages.",
+ "goal": "Turn third-party mentions into references to your assets."
+ },
+ "protect_valuable_citations": {
+ "title": "Protect citations on {targets}",
+ "titleGeneric": "Protect valuable citations",
+ "description": "Citations on these prompts are thinning.",
+ "goal": "Keep the citations you have."
+ },
+ "protect_ai_traffic_pages": {
+ "title": "Protect AI traffic across {targets}",
+ "titleGeneric": "Protect AI traffic pages",
+ "description": "These pages are beginning to lose AI-referred traffic.",
+ "goal": "Keep AI traffic on your valuable pages."
+ },
+ "defend_competitor_gains": {
+ "title": "Defend your position against {targets}",
+ "titleGeneric": "Defend against competitor gains",
+ "description": "A competitor is gaining fast while you still hold your position.",
+ "goal": "Keep your lead."
+ },
+ "protect_topic_leadership": {
+ "title": "Protect leadership in {targets}",
+ "titleGeneric": "Protect topic leadership",
+ "description": "Coverage of a topic you lead is starting to decline.",
+ "goal": "Keep your share of the topic."
+ },
+ "protect_high_performing_content": {
+ "title": "Protect {targets} that AI engines cite",
+ "titleGeneric": "Protect high-performing content",
+ "description": "Your pages that were cited often are now cited less.",
+ "goal": "Keep your best pages cited."
+ },
+ "protect_platform_visibility": {
+ "title": "Protect visibility on {targets}",
+ "titleGeneric": "Protect platform visibility",
+ "description": "Visibility on this AI platform is beginning to decline.",
+ "goal": "Hold your position on the platform."
+ },
+ "protect_organic_on_ai_pages": {
+ "title": "Protect organic traffic across {targets}",
+ "titleGeneric": "Protect organic traffic on AI-exposed pages",
+ "description": "These queries earn organic clicks while their AI visibility slips.",
+ "goal": "Protect search traffic as AI answers change."
+ },
+ "protect_search_and_ai_assets": {
+ "title": "Protect pages driving search and AI traffic",
+ "titleGeneric": "Protect search and AI traffic assets",
+ "description": "Organic clicks and AI referrals are falling together.",
+ "goal": "Protect the pages that carry both channels."
+ },
+ "protect_converting_ai_pages": {
+ "title": "Protect {targets} that convert AI traffic",
+ "titleGeneric": "Protect high-converting AI landing pages",
+ "description": "AI landing pages with key events are losing traffic.",
+ "goal": "Keep the traffic that converts."
+ },
+ "recover_lost_citations": {
+ "title": "Recover lost citations on {targets}",
+ "titleGeneric": "Recover lost citations",
+ "description": "Citations you held consistently are gone.",
+ "goal": "Win back the citations you lost."
+ },
+ "recover_ai_traffic": {
+ "title": "Recover AI traffic across {targets}",
+ "titleGeneric": "Recover AI traffic",
+ "description": "AI-referred traffic fell significantly.",
+ "goal": "Bring AI traffic back."
+ },
+ "recover_lost_mentions": {
+ "title": "Recover lost mentions across {targets}",
+ "titleGeneric": "Recover lost mentions",
+ "description": "Your brand disappeared from prompts where it was mentioned.",
+ "goal": "Be named again where you were."
+ },
+ "recover_topic_visibility": {
+ "title": "Recover visibility in {targets}",
+ "titleGeneric": "Recover topic visibility",
+ "description": "Coverage of this topic fell significantly.",
+ "goal": "Recover your share of the topic."
+ },
+ "recover_platform_visibility": {
+ "title": "Recover visibility on {targets}",
+ "titleGeneric": "Recover platform visibility",
+ "description": "Visibility on this AI platform fell significantly.",
+ "goal": "Recover your position on the platform."
+ },
+ "recover_after_competitor_gains": {
+ "title": "Recover ground lost to {targets}",
+ "titleGeneric": "Recover after competitor gains",
+ "description": "A competitor passed you while you lost ground.",
+ "goal": "Take back the position."
+ },
+ "recover_cited_pages": {
+ "title": "Recover citations for {targets}",
+ "titleGeneric": "Recover previously cited pages",
+ "description": "Your pages that were cited are now cited nowhere.",
+ "goal": "Get these pages cited again."
+ },
+ "recover_high_value_prompts": {
+ "title": "Recover coverage across {targets}",
+ "titleGeneric": "Recover high-value prompt coverage",
+ "description": "You lost presence on prompts that carry real demand.",
+ "goal": "Recover the prompts that matter most."
+ },
+ "recover_search_performance": {
+ "title": "Recover search performance across {targets}",
+ "titleGeneric": "Recover search performance on AI-relevant pages",
+ "description": "Clicks fell on search queries tied to your tracked prompts.",
+ "goal": "Recover search performance while keeping AI visibility stable."
+ },
+ "recover_traffic_after_visibility_loss": {
+ "title": "Recover traffic across {targets} after visibility loss",
+ "titleGeneric": "Recover traffic after AI visibility loss",
+ "description": "AI visibility and AI-referred traffic fell in the same window. This is a correlation, not a proven cause.",
+ "goal": "Recover both visibility and the traffic that came with it."
+ },
+ "fix_crawler_access": {
+ "title": "Fix AI crawler access on {targets}",
+ "titleGeneric": "Fix AI crawler accessibility",
+ "description": "AI crawlers are blocked from these pages.",
+ "goal": "Let AI engines read your pages."
+ },
+ "fix_structured_data": {
+ "title": "Fix structured data on {targets}",
+ "titleGeneric": "Fix structured data issues",
+ "description": "Structured data is missing or invalid on these pages.",
+ "goal": "Describe your pages in a form engines understand."
+ },
+ "fix_content_gaps": {
+ "title": "Fix content gaps on {targets}",
+ "titleGeneric": "Fix content gaps",
+ "description": "These pages do not cover the queries they target.",
+ "goal": "Cover what the queries ask for."
+ },
+ "fix_outdated_content": {
+ "title": "Update {targets} that look outdated",
+ "titleGeneric": "Fix outdated content",
+ "description": "These pages fail freshness checks.",
+ "goal": "Keep content current enough to be cited."
+ },
+ "fix_entity_signals": {
+ "title": "Strengthen entity signals on {targets}",
+ "titleGeneric": "Fix weak entity signals",
+ "description": "These pages fail brand-entity or entity-coverage checks.",
+ "goal": "Make your brand unmistakable to AI engines."
+ },
+ "fix_broken_citation_targets": {
+ "title": "Fix broken citation targets on {targets}",
+ "titleGeneric": "Fix broken citation targets",
+ "description": "Your pages that AI answers cite are unavailable.",
+ "goal": "Keep cited pages reachable."
+ },
+ "fix_brand_inconsistency": {
+ "title": "Fix inconsistent brand information",
+ "titleGeneric": "Fix inconsistent brand information",
+ "description": "AI answers contradict each other about your brand.",
+ "goal": "Give engines one consistent account of your brand."
+ },
+ "fix_underperforming_ai_landing_pages": {
+ "title": "Improve {targets} that underperform for AI traffic",
+ "titleGeneric": "Fix underperforming AI landing pages",
+ "description": "AI traffic arrives on these pages and engages well below your site’s rate.",
+ "goal": "Make AI visits count."
+ },
+ "fix_internal_connectivity": {
+ "title": "Improve internal links across {targets}",
+ "titleGeneric": "Fix internal content connectivity",
+ "description": "These pages fail the internal-linking check.",
+ "goal": "Connect your content so engines follow it."
+ },
+ "fix_prompt_content_coverage": {
+ "title": "Fix content coverage for {targets}",
+ "titleGeneric": "Fix prompt-to-content coverage",
+ "description": "No page of yours is mapped to these prompts, and none has been cited.",
+ "goal": "Give every important prompt a page."
+ },
+ "improve_low_ctr_pages": {
+ "title": "Improve click-through on {targets}",
+ "titleGeneric": "Improve high-impression, low-CTR pages",
+ "description": "These queries earn far fewer clicks than their position usually does.",
+ "goal": "Turn impressions into visits while keeping AI visibility."
+ },
+ "align_search_and_ai_content": {
+ "title": "Align {targets} with AI demand",
+ "titleGeneric": "Fix search-to-AI content misalignment",
+ "description": "You rank in Google’s top three for these queries and are invisible in AI answers.",
+ "goal": "Carry search strength into AI answers."
+ },
+ "capture_competitor_cited_sources": {
+ "title": "Target {targets} citing competitors but not you",
+ "titleGeneric": "Capture competitor-cited sources",
+ "description": "These sources are cited where competitors appear and you do not.",
+ "goal": "Earn citations from sources that already reference your competitors."
+ },
+ "close_topic_coverage_gap": {
+ "title": "Close the coverage gap in {targets}",
+ "titleGeneric": "Close topic coverage gap",
+ "description": "A competitor holds a topic where you have pages but no presence.",
+ "goal": "Win back the topic."
+ },
+ "compete_on_high_value_prompts": {
+ "title": "Compete on {targets} where a competitor leads",
+ "titleGeneric": "Compete on high-value prompts",
+ "description": "A competitor appears on high-demand prompts where you are absent.",
+ "goal": "Win the prompts that matter most."
+ },
+ "capture_competitor_fanouts": {
+ "title": "Capture competitor-winning fan-outs across {targets}",
+ "titleGeneric": "Capture competitor query fan-outs",
+ "description": "Competitors appear on these follow-up queries and you do not.",
+ "goal": "Cover the research engines do on the way to an answer."
+ },
+ "respond_to_competitor_momentum": {
+ "title": "Respond to growth from {targets}",
+ "titleGeneric": "Respond to competitor momentum",
+ "description": "A competitor’s mentions are growing fast.",
+ "goal": "Answer the trend before it becomes a gap."
+ },
+ "earn_competitor_source_presence": {
+ "title": "Build presence across {targets} competitors win",
+ "titleGeneric": "Earn presence on competitor-winning sources",
+ "description": "Competitors win these sources across several prompts, and you never appear.",
+ "goal": "Get included where competitors are."
+ },
+ "create_content_for_competitor_gaps": {
+ "title": "Create content for {targets} where a competitor leads",
+ "titleGeneric": "Create content to close competitor gaps",
+ "description": "A competitor leads a topic you have no content for.",
+ "goal": "Create the content to compete."
+ },
+ "targets": {
+ "prompts": "{count, plural, one {# prompt} other {# prompts}}",
+ "pages": "{count, plural, one {# page} other {# pages}}",
+ "sources": "{count, plural, one {# source} other {# sources}}",
+ "queries": "{count, plural, one {# query} other {# queries}}",
+ "topics": "{count, plural, one {# topic} other {# topics}}",
+ "platforms": "{count, plural, one {# platform} other {# platforms}}",
+ "regions": "{count, plural, one {# region} other {# regions}}",
+ "competitors": "{count, plural, one {# competitor} other {# competitors}}"
}
},
"actionTasks": {
@@ -560,7 +1109,7 @@
"internal_links": "Strengthen internal linking to affected pages",
"validate": "Validate across AI platforms",
"review_pages": "Review the affected high-value pages",
- "optimize_content": "Optimize content for AI answer inclusion",
+ "optimize_content": "Optimize the content",
"identify_prompts": "Identify the prompts mentioning you without citation",
"create_citable_content": "Create or improve citable source content",
"strengthen_sources": "Strengthen the pages AI engines could cite",
@@ -584,7 +1133,140 @@
"analyze_competitor_target": "Analyze what {competitor} gained visibility with",
"measure_traffic_impact": "Measure what the drop cost in AI referral sessions",
"competitor_pressure": "Identify which competitors are gaining the ground you are losing",
- "page_readiness": "Check the affected pages against their audit findings"
+ "page_readiness": "Check the affected pages against their audit findings",
+ "analyze_ai_responses": "Analyze AI responses",
+ "analyze_ai_responses_target": "Analyze AI responses for {targets}",
+ "analyze_visibility_change": "Analyze the visibility change",
+ "analyze_visibility_change_target": "Analyze the visibility change across {targets}",
+ "analyze_platform_gap": "Compare visibility by AI platform",
+ "analyze_platform_gap_target": "Compare visibility across {targets}",
+ "analyze_country_gap": "Compare visibility by country",
+ "analyze_country_gap_target": "Compare visibility across {targets}",
+ "analyze_topic_gap": "Identify missing and declining topic clusters",
+ "analyze_topic_gap_target": "Identify missing clusters in {targets}",
+ "analyze_prompt_gap": "Inspect prompt-level presence",
+ "analyze_prompt_gap_target": "Inspect presence on {targets}",
+ "analyze_fanout_gap": "Inspect query fan-out coverage",
+ "analyze_fanout_gap_target": "Inspect coverage of {targets}",
+ "analyze_mention_context": "Inspect the contexts you are mentioned in",
+ "analyze_mention_context_target": "Inspect mention contexts across {targets}",
+ "analyze_citations": "Analyze citation sources",
+ "analyze_citations_target": "Analyze citations across {targets}",
+ "analyze_competitor_visibility": "Compare competitor visibility",
+ "analyze_competitor_visibility_target": "Compare competitor visibility across {targets}",
+ "analyze_competitor_citations": "Compare competitor citation sources",
+ "analyze_competitor_citations_target": "Compare competitor citations across {targets}",
+ "analyze_competitor_content": "Compare competitor content and coverage",
+ "analyze_competitor_content_target": "Compare competitor coverage across {targets}",
+ "analyze_ai_traffic": "Inspect AI-referred visits",
+ "analyze_ai_traffic_target": "Inspect AI-referred visits to {targets}",
+ "analyze_gsc_demand": "Inspect Search Console queries",
+ "analyze_gsc_demand_target": "Inspect Search Console demand for {targets}",
+ "analyze_gsc_ctr": "Find high-impression, low-CTR queries",
+ "analyze_gsc_ctr_target": "Inspect click-through on {targets}",
+ "analyze_ga4_outcomes": "Inspect engagement and key events",
+ "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_entity_signals": "Audit entity consistency and coverage",
+ "analyze_entity_signals_target": "Audit entity signals on {targets}",
+ "analyze_internal_links": "Inspect internal linking",
+ "analyze_internal_links_target": "Inspect internal linking around {targets}",
+ "analyze_third_party_sources": "Inspect relevant third-party sources",
+ "analyze_third_party_sources_target": "Inspect {targets}",
+ "cluster_prompts": "Cluster the prompts into coherent groups",
+ "cluster_prompts_target": "Cluster {targets} into coherent groups",
+ "map_prompts_to_content": "Map prompts to your pages",
+ "map_prompts_to_content_target": "Map {targets} to your pages",
+ "map_queries_to_prompts": "Map search queries to tracked prompts",
+ "map_queries_to_prompts_target": "Map {targets} to tracked prompts",
+ "identify_target_pages": "Identify the pages to work on",
+ "identify_target_pages_target": "Identify the pages behind {targets}",
+ "identify_content_gaps": "Identify missing sections, topics and questions",
+ "identify_content_gaps_target": "Identify content gaps across {targets}",
+ "identify_new_content_need": "Confirm where no adequate page exists",
+ "identify_new_content_need_target": "Confirm which of {targets} need new content",
+ "identify_citation_gaps": "Identify missing citation opportunities",
+ "identify_citation_gaps_target": "Identify citation gaps across {targets}",
+ "identify_target_sources": "Select the sources to pursue",
+ "identify_target_sources_target": "Select which of {targets} to pursue",
+ "identify_inclusion_path": "Find a legitimate path to inclusion",
+ "identify_inclusion_path_target": "Find a legitimate path onto {targets}",
+ "prioritize_targets": "Prioritize targets by impact",
+ "prioritize_targets_target": "Prioritize {targets} by impact",
+ "define_validation_baseline": "Record the baseline to measure against",
+ "define_validation_baseline_target": "Record the baseline for {targets}",
+ "create_content_brief": "Create a content brief",
+ "create_content_brief_target": "Create content briefs for {targets}",
+ "create_content_draft": "Create a content draft",
+ "create_content_draft_target": "Draft content for {targets}",
+ "optimize_content_target": "Optimize content for {targets}",
+ "refresh_content": "Refresh outdated content",
+ "refresh_content_target": "Refresh content for {targets}",
+ "strengthen_reference_asset": "Make your pages more citable",
+ "strengthen_reference_asset_target": "Make pages more citable for {targets}",
+ "strengthen_entity_content": "Strengthen how your brand is described",
+ "strengthen_entity_content_target": "Strengthen brand descriptions for {targets}",
+ "add_internal_links": "Add internal links",
+ "add_internal_links_target": "Add internal links around {targets}",
+ "improve_cta_path": "Improve the page path and calls to action",
+ "improve_cta_path_target": "Improve paths and calls to action on {targets}",
+ "publish_content": "Publish the approved content",
+ "publish_content_target": "Publish content for {targets}",
+ "fix_crawler_access": "Fix crawler access directives",
+ "fix_crawler_access_target": "Fix crawler access on {targets}",
+ "fix_structured_data": "Add or correct structured data",
+ "fix_structured_data_target": "Fix structured data on {targets}",
+ "fix_broken_target": "Repair the broken page or redirect",
+ "fix_broken_target_target": "Repair {targets}",
+ "fix_technical_issue": "Resolve the audit issues",
+ "fix_technical_issue_target": "Resolve audit issues on {targets}",
+ "validate_technical_fix": "Re-check the technical fix",
+ "validate_technical_fix_target": "Re-audit {targets}",
+ "prepare_outreach": "Prepare outreach",
+ "prepare_outreach_target": "Prepare outreach for {targets}",
+ "execute_outreach": "Send the approved outreach",
+ "execute_outreach_target": "Send approved outreach to {targets}",
+ "prepare_contribution": "Prepare a contribution",
+ "prepare_contribution_target": "Prepare contributions for {targets}",
+ "track_third_party_status": "Track placement status",
+ "track_third_party_status_target": "Track placement on {targets}",
+ "validate_third_party_presence": "Verify your brand now appears",
+ "validate_third_party_presence_target": "Verify you appear on {targets}",
+ "validate_third_party_citation": "Verify the citation is live",
+ "validate_third_party_citation_target": "Verify citations from {targets}",
+ "validate_ai_visibility": "Validate AI visibility",
+ "validate_ai_visibility_target": "Validate AI visibility across {targets}",
+ "validate_mentions": "Validate mentions",
+ "validate_mentions_target": "Validate mentions across {targets}",
+ "validate_citations": "Validate citations",
+ "validate_citations_target": "Validate citations across {targets}",
+ "validate_topic_sov": "Validate topic share of voice",
+ "validate_topic_sov_target": "Validate share of voice in {targets}",
+ "validate_platform_visibility": "Validate platform visibility",
+ "validate_platform_visibility_target": "Validate visibility on {targets}",
+ "validate_country_visibility": "Validate country visibility",
+ "validate_country_visibility_target": "Validate visibility in {targets}",
+ "validate_ai_traffic": "Validate AI-referred traffic",
+ "validate_ai_traffic_target": "Validate AI traffic to {targets}",
+ "validate_gsc": "Validate Search Console performance",
+ "validate_gsc_target": "Validate Search Console performance for {targets}",
+ "validate_ga4": "Validate engagement and key events",
+ "validate_ga4_target": "Validate outcomes on {targets}",
+ "validate_competitive_gap": "Validate the competitive gap",
+ "validate_competitive_gap_target": "Validate the gap with {targets}",
+ "measure_action_outcome": "Measure the outcome",
+ "measure_action_outcome_target": "Measure the outcome across {targets}",
+ "targets": {
+ "prompts": "{count, plural, one {# prompt} other {# prompts}}",
+ "pages": "{count, plural, one {# page} other {# pages}}",
+ "sources": "{count, plural, one {# source} other {# sources}}",
+ "queries": "{count, plural, one {# query} other {# queries}}",
+ "topics": "{count, plural, one {# topic} other {# topics}}",
+ "platforms": "{count, plural, one {# platform} other {# platforms}}",
+ "regions": "{count, plural, one {# region} other {# regions}}",
+ "competitors": "{count, plural, one {# competitor} other {# competitors}}"
+ }
},
"taskStatus": {
"todo": "To Do",
diff --git a/web/src/components/action-center/action-table.tsx b/web/src/components/action-center/action-table.tsx
index 0437c8f68..2f69e82ea 100644
--- a/web/src/components/action-center/action-table.tsx
+++ b/web/src/components/action-center/action-table.tsx
@@ -32,7 +32,8 @@ import { cn } from '@/lib/utils';
type IconComponent = React.ComponentType<{ className?: string }>;
-const KIND_ICONS: Record<ActionKind, IconComponent> = {
+/** Icons for the original eight kinds; everything else takes its family's. */
+const KIND_ICONS: Partial<Record<ActionKind, IconComponent>> = {
recover_visibility: BarChart3,
protect_visibility: ShieldCheck,
expand_platform_visibility: Layers,
diff --git a/web/src/components/action-center/signal-drawer.tsx b/web/src/components/action-center/signal-drawer.tsx
index 53ceb7d81..4bc1b0359 100644
--- a/web/src/components/action-center/signal-drawer.tsx
+++ b/web/src/components/action-center/signal-drawer.tsx
@@ -17,7 +17,7 @@ import type { Signal } from '@/lib/actions/signals';
import { SIGNAL_KINDS, type SignalStatus } from '@/lib/signals/registry';
import { signalAffected, signalTexts } from '@/lib/signals/display';
import { isKpiKey } from '@/lib/kpis/registry';
-import { ImpactDots, SIGNAL_ICONS, SignalStatusBadge, SourceList } from './signal-table';
+import { ImpactDots, SignalKindIcon, SignalStatusBadge, SourceList } from './signal-table';
/**
* Signal detail: the evidence view. Deliberately light in v1 — identity,
@@ -70,7 +70,7 @@ export function SignalDrawer({
</div>
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-muted/40">
- <HeaderIcon kind={signal.kind} />
+ <SignalKindIcon kind={signal.kind} category={signal.category} />
</div>
<div className="min-w-0">
<SheetTitle>{texts.title}</SheetTitle>
@@ -215,11 +215,6 @@ export function SignalDrawer({
);
}
-function HeaderIcon({ kind }: { kind: Signal['kind'] }) {
- const Icon = SIGNAL_ICONS[kind];
- return <Icon className="h-4 w-4 text-muted-foreground" />;
-}
-
function DetailItem({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div>
diff --git a/web/src/components/action-center/signal-table.tsx b/web/src/components/action-center/signal-table.tsx
index a09723f6d..1db45bc08 100644
--- a/web/src/components/action-center/signal-table.tsx
+++ b/web/src/components/action-center/signal-table.tsx
@@ -21,6 +21,7 @@ import {
X,
Layers,
Quote,
+ Wrench,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import {
@@ -40,6 +41,7 @@ import {
import type { Signal } from '@/lib/actions/signals';
import {
SIGNAL_KINDS,
+ type SignalCategory,
type SignalImpact,
type SignalKind,
type SignalSource,
@@ -49,7 +51,11 @@ import { signalAffected, signalTexts } from '@/lib/signals/display';
import { formatRelative } from '@/lib/format-relative';
import { cn } from '@/lib/utils';
-export const SIGNAL_ICONS: Record<SignalKind, React.ComponentType<{ className?: string }>> = {
+/** Icons for the original kinds. The library's forty-seven take their
+ * category's — a traffic finding reads as traffic whichever detector wrote it. */
+export const SIGNAL_ICONS: Partial<
+ Record<SignalKind, React.ComponentType<{ className?: string }>>
+> = {
sharp_drop: TrendingDown,
visibility_slipping: TrendingDown,
platform_gap: Layers,
@@ -140,9 +146,27 @@ function detectedLabel(iso: string, tCommon: ReturnType<typeof useTranslations>)
return formatRelative(iso, tCommon);
}
-function KindIcon({ kind }: { kind: SignalKind }) {
- const Icon = SIGNAL_ICONS[kind];
- return <Icon className="h-4 w-4 text-muted-foreground" />;
+/** What a kind without its own icon falls back to. */
+const SIGNAL_CATEGORY_ICONS: Record<SignalCategory, React.ComponentType<{ className?: string }>> = {
+ visibility: TrendingDown,
+ citation: Quote,
+ mention: MessageSquare,
+ traffic: MousePointerClick,
+ technical: Wrench,
+ competitor: Swords,
+};
+
+export function SignalKindIcon({
+ kind,
+ category,
+ className = 'h-4 w-4 text-muted-foreground',
+}: {
+ kind: SignalKind;
+ category: SignalCategory;
+ className?: string;
+}) {
+ const Icon = SIGNAL_ICONS[kind] ?? SIGNAL_CATEGORY_ICONS[category] ?? BarChart3;
+ return <Icon className={className} />;
}
export function SignalTable({
@@ -189,7 +213,7 @@ export function SignalTable({
<TableCell className="max-w-[360px]">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-muted/40">
- <KindIcon kind={signal.kind} />
+ <SignalKindIcon kind={signal.kind} category={signal.category} />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-medium">{texts.title}</p>
diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.ts
index 6bbd7810f..0c5a8a8b9 100644
--- a/web/src/lib/action-center/display.test.ts
+++ b/web/src/lib/action-center/display.test.ts
@@ -15,10 +15,14 @@ const t = (key: string, values?: Record<string, string | number>) => {
.reduce<unknown>((node, part) => (node as Record<string, unknown> | undefined)?.[part], scope);
if (typeof value !== 'string') throw new Error(`missing message: ${key}`);
// Enough ICU to prove the value reached the message; next-intl does the
- // real formatting at runtime.
- return value.replace(/\{\s*(\w+)\s*\}/g, (match, name) =>
- values && name in values ? String(values[name]) : match,
- );
+ // real formatting at runtime. Plurals collapse to their `other` branch.
+ return value
+ .replace(/\{(\w+), plural, one \{[^}]*\} other \{([^}]*)\}\}/g, (_m, name, other) =>
+ String(other).replace('#', String(values?.[name] ?? '')),
+ )
+ .replace(/\{\s*(\w+)\s*\}/g, (match, name) =>
+ values && name in values ? String(values[name]) : match,
+ );
};
const action = (over: Partial<ActionItem>) =>
@@ -36,6 +40,31 @@ describe('actionTexts', () => {
expect(() => actionGoal(kind, t)).not.toThrow();
});
+ it('holds copy for all sixty-two definitions', () => {
+ expect(ACTION_KINDS).toHaveLength(62);
+ });
+
+ /**
+ * The specification's title rule: "Recover 7 lost citations", never
+ * "Recover citations". Every definition's title names its targets.
+ */
+ it.each(ACTION_KINDS)('%s names its targets in the title', (kind) => {
+ const texts = actionTexts(
+ action({ kind, payload: { targetCount: 7, targetEntity: 'prompts' } }),
+ t,
+ );
+ if (messages.actionCenter.actionTexts[kind].title.includes('{targets}')) {
+ expect(texts.title).toContain('7 prompts');
+ }
+ });
+
+ /** An action raised before the library has no targets on its payload, and
+ * must not read "0 prompts". */
+ it('falls back to a title without a count', () => {
+ const texts = actionTexts(action({ kind: 'recover_lost_citations', payload: {} }), t);
+ expect(texts.title).toBe(messages.actionCenter.actionTexts.recover_lost_citations.titleGeneric);
+ });
+
/**
* The server's definition registry grows on its own release cycle, so the
* web will meet kinds it has never heard of. Hiding them was the old
@@ -62,6 +91,19 @@ describe('humanizeKind', () => {
});
describe('taskText', () => {
+ it('names what a library task acts on', () => {
+ expect(
+ taskText(
+ {
+ taskKey: 'analyze_citations',
+ title: null,
+ titleParams: { count: 11, entity: 'sources' },
+ },
+ t,
+ ),
+ ).toBe('Analyze citations across 11 sources');
+ });
+
/** Nothing about a planned task's text is stored — only which message it
* is and what it names — so the plan survives translation. */
it('renders the target variant when the planner resolved one', () => {
diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.ts
index e26388b4b..ab9ea6177 100644
--- a/web/src/lib/action-center/display.ts
+++ b/web/src/lib/action-center/display.ts
@@ -35,93 +35,42 @@ export function humanizeKind(kind: string): string {
return words.charAt(0).toUpperCase() + words.slice(1);
}
+/**
+ * "11 prompts", "6 sources" — how many of what an action is about.
+ *
+ * Every payload carries `targetEntity` and `targetCount` (server
+ * definitions/_helpers.js). An action raised before the library existed has
+ * neither, and gets its title without a count rather than "0 prompts".
+ */
+export function targetLabel(payload: Record<string, unknown>, t: Translator): string {
+ const count = num(payload, 'targetCount');
+ const entity = str(payload, 'targetEntity');
+ return count > 0 && entity ? t(`targets.${entity}`, { count }) : '';
+}
+
+/**
+ * An action's title and description.
+ *
+ * One path for all sixty-two definitions: the specification asks for titles
+ * that name their targets — "Recover 7 lost citations", never "Recover
+ * citations" — and every definition's payload now says what its targets are.
+ * A kind this build has no copy for is still shown, from its id: the server's
+ * registry grows on its own release cycle, and a row nobody can read beats a
+ * row nobody sees.
+ */
export function actionTexts(
- action: ActionItem,
+ action: Pick<ActionItem, 'kind' | 'payload'>,
t: Translator,
): { title: string; description: string } {
- const p = action.payload;
- const kind = action.kind;
- if (!isActionKind(kind)) {
- return {
- title: humanizeKind(kind),
- description: t('unknown.description'),
- };
- }
- switch (kind) {
- case 'recover_visibility': {
- const hasDrop = p.dropFrom !== undefined && p.dropFrom !== null;
- return {
- title: t('recover_visibility.title'),
- description: hasDrop
- ? t('recover_visibility.descriptionWithDrop', {
- from: num(p, 'dropFrom'),
- to: num(p, 'dropTo'),
- prompts: num(p, 'promptCount'),
- })
- : t('recover_visibility.description', { prompts: num(p, 'promptCount') }),
- };
- }
- case 'protect_visibility': {
- const hasDrop = p.dropFrom !== undefined && p.dropFrom !== null;
- return {
- title: t('protect_visibility.title'),
- description: hasDrop
- ? t('protect_visibility.descriptionWithDrop', {
- from: num(p, 'dropFrom'),
- to: num(p, 'dropTo'),
- })
- : t('protect_visibility.description'),
- };
- }
- case 'capture_ai_traffic':
- return {
- title: t('capture_ai_traffic.title', { pages: num(p, 'pageCount') }),
- description: t('capture_ai_traffic.description'),
- };
- case 'expand_platform_visibility':
- return {
- title: t('expand_platform_visibility.title', { platform: str(p, 'platform') }),
- description: t('expand_platform_visibility.description', {
- platform: str(p, 'platform'),
- best: str(p, 'bestPlatform'),
- bestRate: num(p, 'dropFrom'),
- rate: num(p, 'dropTo'),
- }),
- };
- case 'close_citation_gap': {
- const names = Array.isArray(p.competitorNames) ? (p.competitorNames as string[]) : [];
- return {
- title: t('close_citation_gap.title'),
- description: names[0]
- ? t('close_citation_gap.descriptionWithName', {
- competitor: names[0],
- theirs: num(p, 'competitorCitations'),
- ours: num(p, 'citationCount'),
- })
- : t('close_citation_gap.description'),
- };
- }
- case 'convert_mentions':
- return {
- title: t('convert_mentions.title'),
- description: t('convert_mentions.description', { prompts: num(p, 'promptCount') }),
- };
- case 'fix_low_scores':
- return {
- title: t('fix_low_scores.title'),
- description: t('fix_low_scores.description', { pages: num(p, 'pageCount') }),
- };
- case 'close_competitor_gap': {
- const names = Array.isArray(p.competitorNames) ? (p.competitorNames as string[]) : [];
- return {
- title:
- names.length === 1
- ? t('close_competitor_gap.title', { name: names[0] })
- : t('close_competitor_gap.titleMany'),
- description: t('close_competitor_gap.description'),
- };
- }
+ const p = action.payload ?? {};
+ if (!isActionKind(action.kind)) {
+ return { title: humanizeKind(action.kind), description: t('unknown.description') };
}
+ const targets = targetLabel(p, t);
+ return {
+ title: targets ? t(`${action.kind}.title`, { targets }) : t(`${action.kind}.titleGeneric`),
+ description: t(`${action.kind}.description`),
+ };
}
/**
@@ -155,38 +104,10 @@ export function actionGoal(kind: string, t: Translator): string {
/** Compact evidence chips under the title: signal count plus the kind's own
* count (pages, prompts, competitors). */
export function actionContextTags(action: ActionItem, t: Translator): string[] {
- const p = action.payload;
const tags = [t('tags.signals', { count: action.signalCount })];
- if (!isActionKind(action.kind)) return tags;
- switch (action.kind) {
- case 'recover_visibility':
- if (num(p, 'promptCount') > 0) tags.push(t('tags.prompts', { count: num(p, 'promptCount') }));
- break;
- case 'protect_visibility':
- break;
- case 'expand_platform_visibility':
- tags.push(str(p, 'platform'));
- break;
- case 'close_citation_gap': {
- const names = Array.isArray(p.competitorNames) ? (p.competitorNames as string[]) : [];
- if (names[0]) tags.push(names[0]);
- break;
- }
- case 'capture_ai_traffic':
- tags.push(t('tags.pages', { count: num(p, 'pageCount') }));
- break;
- case 'convert_mentions':
- tags.push(t('tags.prompts', { count: num(p, 'promptCount') }));
- break;
- case 'fix_low_scores':
- tags.push(t('tags.pages', { count: num(p, 'pageCount') }));
- break;
- case 'close_competitor_gap': {
- const names = Array.isArray(p.competitorNames) ? (p.competitorNames as string[]) : [];
- if (names[0]) tags.push(names[0]);
- break;
- }
- }
+ const count = num(action.payload ?? {}, 'targetCount');
+ const entity = str(action.payload ?? {}, 'targetEntity');
+ if (count > 0 && entity) tags.push(t(`tags.${entity}`, { count }));
return tags;
}
@@ -234,11 +155,14 @@ export function taskText(
if (title) return title;
if (!task.taskKey) return '';
- // A planned task that knows what it is about carries the values as
- // parameters and is rendered from the `_target` variant of its message —
- // "Compare gemini-web coverage against chatgpt-web" rather than "Compare
- // platform coverage". No parameters means no target was resolvable, and
- // the plain message is the honest one.
- const params = task.titleParams ?? {};
+ // A planned task that knows what it acts on carries the values as
+ // parameters and is rendered from the `_target` variant of its message:
+ // "Analyze citations across 11 sources" rather than "Analyze citations".
+ // Library tasks name a count and an entity, rendered here in the reader's
+ // language; the original tasks name their own fields.
+ const params = { ...(task.titleParams ?? {}) };
+ if (params.count && params.entity) {
+ params.targets = t(`targets.${params.entity}`, { count: Number(params.count) });
+ }
return Object.keys(params).length > 0 ? t(`${task.taskKey}_target`, params) : t(task.taskKey);
}
diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.ts
index ecb7b8580..a7649eae3 100644
--- a/web/src/lib/action-center/registry.ts
+++ b/web/src/lib/action-center/registry.ts
@@ -36,16 +36,70 @@ export type ActionOutcome =
| 'declined'
| 'not_measurable';
-/** A kind this build has copy and an icon for. */
+/** A kind this build has copy for — the V1 library's sixty-two definitions. */
export type ActionKind =
- | 'recover_visibility'
- | 'protect_visibility'
- | 'expand_platform_visibility'
- | 'close_citation_gap'
| 'capture_ai_traffic'
| 'convert_mentions'
+ | 'expand_prompt_visibility'
+ | 'capture_high_demand_prompts'
+ | 'expand_topic_visibility'
+ | 'capture_fanout_opportunities'
+ | 'increase_authority_citations'
+ | 'expand_platform_visibility'
+ | 'expand_country_visibility'
+ | 'strengthen_emerging_content'
+ | 'expand_brand_associations'
+ | 'convert_search_demand'
+ | 'expand_organic_pages'
+ | 'scale_ai_landing_pages'
+ | 'create_content_for_demand'
+ | 'create_content_for_topics'
+ | 'optimize_content_for_ai'
+ | 'earn_third_party_presence'
+ | 'earn_third_party_citations'
+ | 'protect_visibility'
+ | 'protect_valuable_citations'
+ | 'protect_ai_traffic_pages'
+ | 'defend_competitor_gains'
+ | 'protect_topic_leadership'
+ | 'protect_high_performing_content'
+ | 'protect_platform_visibility'
+ | 'protect_organic_on_ai_pages'
+ | 'protect_search_and_ai_assets'
+ | 'protect_converting_ai_pages'
+ | 'recover_visibility'
+ | 'recover_lost_citations'
+ | 'recover_ai_traffic'
+ | 'recover_lost_mentions'
+ | 'recover_topic_visibility'
+ | 'recover_platform_visibility'
+ | 'recover_after_competitor_gains'
+ | 'recover_cited_pages'
+ | 'recover_high_value_prompts'
+ | 'recover_search_performance'
+ | 'recover_traffic_after_visibility_loss'
| 'fix_low_scores'
- | 'close_competitor_gap';
+ | 'fix_crawler_access'
+ | 'fix_structured_data'
+ | 'fix_content_gaps'
+ | 'fix_outdated_content'
+ | 'fix_entity_signals'
+ | 'fix_broken_citation_targets'
+ | 'fix_brand_inconsistency'
+ | 'fix_underperforming_ai_landing_pages'
+ | 'fix_internal_connectivity'
+ | 'fix_prompt_content_coverage'
+ | 'improve_low_ctr_pages'
+ | 'align_search_and_ai_content'
+ | 'close_competitor_gap'
+ | 'close_citation_gap'
+ | 'capture_competitor_cited_sources'
+ | 'close_topic_coverage_gap'
+ | 'compete_on_high_value_prompts'
+ | 'capture_competitor_fanouts'
+ | 'respond_to_competitor_momentum'
+ | 'earn_competitor_source_presence'
+ | 'create_content_for_competitor_gaps';
export type TaskStatus =
| 'todo'
@@ -97,14 +151,68 @@ export const TASK_STATUSES: readonly TaskStatus[] = [
export const UNCOUNTED_TASK_STATUSES: readonly TaskStatus[] = ['skipped', 'failed'];
export const ACTION_KINDS: readonly ActionKind[] = [
- 'recover_visibility',
- 'protect_visibility',
- 'expand_platform_visibility',
- 'close_citation_gap',
'capture_ai_traffic',
'convert_mentions',
+ 'expand_prompt_visibility',
+ 'capture_high_demand_prompts',
+ 'expand_topic_visibility',
+ 'capture_fanout_opportunities',
+ 'increase_authority_citations',
+ 'expand_platform_visibility',
+ 'expand_country_visibility',
+ 'strengthen_emerging_content',
+ 'expand_brand_associations',
+ 'convert_search_demand',
+ 'expand_organic_pages',
+ 'scale_ai_landing_pages',
+ 'create_content_for_demand',
+ 'create_content_for_topics',
+ 'optimize_content_for_ai',
+ 'earn_third_party_presence',
+ 'earn_third_party_citations',
+ 'protect_visibility',
+ 'protect_valuable_citations',
+ 'protect_ai_traffic_pages',
+ 'defend_competitor_gains',
+ 'protect_topic_leadership',
+ 'protect_high_performing_content',
+ 'protect_platform_visibility',
+ 'protect_organic_on_ai_pages',
+ 'protect_search_and_ai_assets',
+ 'protect_converting_ai_pages',
+ 'recover_visibility',
+ 'recover_lost_citations',
+ 'recover_ai_traffic',
+ 'recover_lost_mentions',
+ 'recover_topic_visibility',
+ 'recover_platform_visibility',
+ 'recover_after_competitor_gains',
+ 'recover_cited_pages',
+ 'recover_high_value_prompts',
+ 'recover_search_performance',
+ 'recover_traffic_after_visibility_loss',
'fix_low_scores',
+ 'fix_crawler_access',
+ 'fix_structured_data',
+ 'fix_content_gaps',
+ 'fix_outdated_content',
+ 'fix_entity_signals',
+ 'fix_broken_citation_targets',
+ 'fix_brand_inconsistency',
+ 'fix_underperforming_ai_landing_pages',
+ 'fix_internal_connectivity',
+ 'fix_prompt_content_coverage',
+ 'improve_low_ctr_pages',
+ 'align_search_and_ai_content',
'close_competitor_gap',
+ 'close_citation_gap',
+ 'capture_competitor_cited_sources',
+ 'close_topic_coverage_gap',
+ 'compete_on_high_value_prompts',
+ 'capture_competitor_fanouts',
+ 'respond_to_competitor_momentum',
+ 'earn_competitor_source_presence',
+ 'create_content_for_competitor_gaps',
];
/**
diff --git a/web/src/lib/signals/display.ts b/web/src/lib/signals/display.ts
index 3de143e89..875cfe385 100644
--- a/web/src/lib/signals/display.ts
+++ b/web/src/lib/signals/display.ts
@@ -1,4 +1,5 @@
import type { Signal } from '@/lib/actions/signals';
+import { isLibrarySignalKind } from '@/lib/signals/registry';
/**
* Composes the display strings a signal row shows from `kind` + `payload`.
@@ -14,7 +15,31 @@ function str(payload: Record<string, unknown>, key: string): string {
return typeof value === 'string' ? value : String(value ?? '');
}
+/**
+ * A library signal's copy: what it is about, named from its targets.
+ *
+ * The V1 library's detectors all write the same shape — an entity and a list
+ * of targets — so their copy needs two values: how many ("11 prompts") for a
+ * finding about a group, and which one ("gemini-web", a topic, a domain) for a
+ * finding about a single thing.
+ */
+function librarySignalTexts(signal: Signal, t: Translator): { title: string; description: string } {
+ const p = signal.payload ?? {};
+ const targets = Array.isArray(p.targets) ? (p.targets as Array<{ label?: string }>) : [];
+ const entity = str(p, 'entity');
+ const count = entity === '' ? 0 : Math.max(targets.length, Number(signal.currentValue ?? 0));
+ const values = {
+ targets: entity ? t(`targets.${entity}`, { count }) : '',
+ name: targets[0]?.label ?? '',
+ };
+ return {
+ title: t(`${signal.kind}.title`, values),
+ description: t(`${signal.kind}.description`, values),
+ };
+}
+
export function signalTexts(signal: Signal, t: Translator): { title: string; description: string } {
+ if (isLibrarySignalKind(signal.kind)) return librarySignalTexts(signal, t);
const p = signal.payload;
const values = ((): Record<string, string | number> => {
switch (signal.kind) {
@@ -80,6 +105,17 @@ export function signalAffected(
t: Translator,
): { label: string; detail: string | null } {
const p = signal.payload;
+ if (isLibrarySignalKind(signal.kind)) {
+ // The count for a group, the thing itself for a single finding.
+ const targets = Array.isArray(p.targets) ? (p.targets as Array<{ label?: string }>) : [];
+ const entity = str(p, 'entity');
+ const count = Math.max(targets.length, Number(signal.currentValue ?? 0));
+ if (targets.length === 1) return { label: targets[0]?.label ?? '', detail: null };
+ return {
+ label: entity ? t(`affected.${entity}`, { count }) : '',
+ detail: targets[0]?.label ?? null,
+ };
+ }
switch (signal.kind) {
case 'sharp_drop':
case 'visibility_slipping':
diff --git a/web/src/lib/signals/library-kinds.ts b/web/src/lib/signals/library-kinds.ts
new file mode 100644
index 000000000..7412fcc64
--- /dev/null
+++ b/web/src/lib/signals/library-kinds.ts
@@ -0,0 +1,58 @@
+/**
+ * The signal kinds the V1 definition library's detectors write (#818).
+ *
+ * Generated alongside server/src/lib/signals/library/kinds.js; the state word
+ * each shows in the Type column, and whether its change arrow is good news.
+ */
+
+export const LIBRARY_SIGNAL_KINDS = {
+ prompt_visibility_gap: { stateKey: 'gap', positive: false },
+ high_demand_gap: { stateKey: 'gap', positive: false },
+ uncovered_demand: { stateKey: 'opportunity', positive: false },
+ prompt_unmapped: { stateKey: 'gap', positive: false },
+ content_underperforming: { stateKey: 'gap', positive: false },
+ lost_mentions: { stateKey: 'lost', positive: false },
+ high_value_prompt_lost: { stateKey: 'lost', positive: false },
+ citation_at_risk: { stateKey: 'slipping', positive: false },
+ topic_gap: { stateKey: 'gap', positive: false },
+ topic_uncovered: { stateKey: 'gap', positive: false },
+ topic_slipping: { stateKey: 'slipping', positive: false },
+ topic_drop: { stateKey: 'dropped', positive: false },
+ platform_slipping: { stateKey: 'slipping', positive: false },
+ platform_drop: { stateKey: 'dropped', positive: false },
+ country_gap: { stateKey: 'gap', positive: false },
+ competitor_leads: { stateKey: 'gap', positive: false },
+ competitor_momentum: { stateKey: 'gain', positive: false },
+ competitor_topic_lead: { stateKey: 'gap', positive: false },
+ competitor_high_value_lead: { stateKey: 'gap', positive: false },
+ competitor_uncovered_topic: { stateKey: 'gap', positive: false },
+ authority_citation_gap: { stateKey: 'gap', positive: false },
+ third_party_citation_gap: { stateKey: 'opportunity', positive: false },
+ third_party_presence_gap: { stateKey: 'gap', positive: false },
+ competitor_cited_source: { stateKey: 'gap', positive: false },
+ competitor_winning_source: { stateKey: 'gap', positive: false },
+ page_citation_slipping: { stateKey: 'slipping', positive: false },
+ owned_page_citation_lost: { stateKey: 'lost', positive: false },
+ fanout_gap: { stateKey: 'opportunity', positive: false },
+ competitor_fanout_gap: { stateKey: 'gap', positive: false },
+ gsc_demand_gap: { stateKey: 'gap', positive: false },
+ search_ai_misalignment: { stateKey: 'gap', positive: false },
+ gsc_low_ctr: { stateKey: 'issue', positive: false },
+ gsc_risk: { stateKey: 'slipping', positive: false },
+ gsc_decline: { stateKey: 'dropped', positive: false },
+ ai_traffic_slipping: { stateKey: 'slipping', positive: false },
+ ai_traffic_drop: { stateKey: 'dropped', positive: false },
+ ai_landing_page_winner: { stateKey: 'opportunity', positive: true },
+ ai_landing_underperforming: { stateKey: 'issue', positive: false },
+ converting_page_slipping: { stateKey: 'slipping', positive: false },
+ cross_channel_risk: { stateKey: 'dropped', positive: false },
+ visibility_traffic_loss: { stateKey: 'dropped', positive: false },
+ crawler_blocked: { stateKey: 'issue', positive: false },
+ structured_data_issue: { stateKey: 'issue', positive: false },
+ outdated_content: { stateKey: 'issue', positive: false },
+ weak_entity: { stateKey: 'issue', positive: false },
+ weak_internal_links: { stateKey: 'issue', positive: false },
+ content_gap: { stateKey: 'issue', positive: false },
+} as const;
+
+export type LibrarySignalKind = keyof typeof LIBRARY_SIGNAL_KINDS;
diff --git a/web/src/lib/signals/registry.ts b/web/src/lib/signals/registry.ts
index 6dc10b0bb..9b95cf8ae 100644
--- a/web/src/lib/signals/registry.ts
+++ b/web/src/lib/signals/registry.ts
@@ -1,3 +1,5 @@
+import { LIBRARY_SIGNAL_KINDS, type LibrarySignalKind } from './library-kinds';
+
/**
* The signal registry — static product knowledge about every detector kind
* the Signals page can render. The database stores what gets filtered and
@@ -23,7 +25,8 @@ export type SignalImpact = 'high' | 'medium' | 'low';
export type SignalStatus = 'new' | 'acknowledged' | 'resolved' | 'dismissed';
-export type SignalKind =
+/** The original detectors' kinds, each with its own display copy. */
+export type BaseSignalKind =
| 'sharp_drop'
| 'visibility_slipping'
| 'platform_gap'
@@ -39,6 +42,9 @@ export type SignalKind =
| 'uncited_mentions'
| 'audit_low_score';
+/** Every kind a signal row can carry: the originals and the V1 library's. */
+export type SignalKind = BaseSignalKind | LibrarySignalKind;
+
export const SIGNAL_CATEGORIES: readonly SignalCategory[] = [
'visibility',
'citation',
@@ -81,7 +87,7 @@ export interface SignalKindMeta {
positive: boolean;
}
-export const SIGNAL_KINDS: Record<SignalKind, SignalKindMeta> = {
+const BASE_SIGNAL_KINDS: Record<BaseSignalKind, SignalKindMeta> = {
sharp_drop: { kind: 'sharp_drop', stateKey: 'dropped', positive: false },
visibility_slipping: { kind: 'visibility_slipping', stateKey: 'slipping', positive: false },
platform_gap: { kind: 'platform_gap', stateKey: 'gap', positive: false },
@@ -98,6 +104,18 @@ export const SIGNAL_KINDS: Record<SignalKind, SignalKindMeta> = {
audit_low_score: { kind: 'audit_low_score', stateKey: 'issue', positive: false },
};
+export const SIGNAL_KINDS: Record<SignalKind, SignalKindMeta> = {
+ ...BASE_SIGNAL_KINDS,
+ ...(Object.fromEntries(
+ Object.entries(LIBRARY_SIGNAL_KINDS).map(([kind, meta]) => [kind, { kind, ...meta }]),
+ ) as Record<LibrarySignalKind, SignalKindMeta>),
+};
+
+/** A library kind: its copy is generic over targets rather than per-field. */
+export function isLibrarySignalKind(kind: string): kind is LibrarySignalKind {
+ return kind in LIBRARY_SIGNAL_KINDS;
+}
+
export function isSignalKind(value: string): value is SignalKind {
return value in SIGNAL_KINDS;
}