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(content): generate one opportunity per prompt cluster (#930)

Gökhan Geyik41382a8e824b
diff --git a/server/src/lib/open-opportunities.js b/server/src/lib/open-opportunities.js
index 5ea21b011..4e950a8c0 100644
--- a/server/src/lib/open-opportunities.js
+++ b/server/src/lib/open-opportunities.js
@@ -3,18 +3,19 @@ import supabaseAdmin from '../config/supabase.js';
const PAGE = 1000;
/**
- * A brand's open (status 'new') opportunities, as { prompt_id, title }. Paged:
- * a large brand holds more than PostgREST's 1,000-row default, and a short
- * read would undercount the per-prompt cap.
+ * A brand's cluster opportunities, every status, as { id, title, status,
+ * cluster_id, related_cluster_ids, opportunity_score }. Paged: a large brand
+ * can hold more than PostgREST's 1,000-row default, and a short read would
+ * let a covered cluster be suggested again.
*/
-export async function loadOpenOpportunities(brandId) {
+export async function loadClusterOpportunities(brandId) {
const rows = [];
for (let from = 0; ; from += PAGE) {
const { data, error } = await supabaseAdmin
.from('content_opportunities')
- .select('prompt_id, title')
+ .select('id, title, status, cluster_id, related_cluster_ids, opportunity_score')
.eq('brand_id', brandId)
- .eq('status', 'new')
+ .not('cluster_id', 'is', null)
.order('id')
.range(from, from + PAGE - 1);
if (error) throw new Error(error.message);
diff --git a/server/src/lib/opportunity-generator.js b/server/src/lib/opportunity-generator.js
index 995f74795..8eeccdaaa 100644
--- a/server/src/lib/opportunity-generator.js
+++ b/server/src/lib/opportunity-generator.js
@@ -1,6 +1,11 @@
/**
- * Standalone opportunity generation function used by the tracking worker.
- * Calls the content generate endpoint logic directly without HTTP.
+ * Content opportunity generation, per prompt cluster (#857).
+ *
+ * Shared by the nightly run after each tracking cycle and the queued job
+ * behind the Generate button. Each run takes the highest-scoring clusters
+ * that have no opportunity yet and asks the model to write one opportunity
+ * per cluster. A cluster that needs the same content as an existing
+ * opportunity in another topic is merged into it instead.
*/
import { generateObject } from 'ai';
@@ -11,245 +16,293 @@ import supabaseAdmin from '../config/supabase.js';
import { selectInChunks } from './chunked-in.js';
import { logger } from './logger.js';
import {
- ALREADY_SUGGESTED_RULE,
- OPPORTUNITIES_PER_RUN,
- OPPORTUNITY_COUNT_RULE,
- alreadySuggested,
- belowOpenCap,
- openCountsByPrompt,
- openTitlesByPrompt,
- opportunityKey,
- relatedCandidate,
+ OPPORTUNITY_WINDOW_DAYS,
+ clusterMetrics,
+ coveredClusterIds,
+ opportunityScore,
+ pickClusters,
+ scoreComponents,
} from './opportunity-limits.js';
-import { loadOpenOpportunities } from './open-opportunities.js';
-
-const opportunitySchema = z.object({
- opportunities: z
- .array(
- z.object({
- title: z
- .string()
- .describe(
- 'A specific, actionable content recommendation. Never reference prompts by their bracketed index like [0] or "Prompt 3" — name the topic or paraphrase the prompt text instead.',
- ),
- description: z
- .string()
- .describe(
- 'A 1-2 sentence explanation of why this action matters, referencing specific metrics. Never reference prompts by their bracketed index like [0] or "Prompt 3" — name the topic or paraphrase the prompt text instead.',
- ),
- type: z.enum(['owned', 'earned']),
- impact: z.enum(['high', 'medium', 'low']),
- relatedPromptIndex: z.number(),
- }),
- )
- .min(1)
- .max(OPPORTUNITIES_PER_RUN),
-});
+import { loadClusterOpportunities } from './open-opportunities.js';
+import { loadClusters } from './prompt-clusters.js';
+
+/** Existing opportunities shown to the model for the cross-topic check. */
+const EXISTING_SHOWN = 60;
+/** Included fan-out queries kept on an opportunity, most searched first. */
+const QUERIES_KEPT = 15;
+const PROMPTS_SHOWN = 12;
+
+const SYSTEM_PROMPT = `You are an AEO content strategist. Each cluster below is a group of prompts that one piece of content can answer. Write one content opportunity per cluster.
-const SYSTEM_PROMPT = `You are an AEO content strategist. Given a brand's AI visibility data, generate specific, actionable content recommendations.
Rules:
-- Each recommendation must be concrete and actionable.
-- Reference specific data points: volumes, visibility scores, competitor gaps.
-- Focus on content that will improve the brand's visibility in AI-generated answers.
-- Categorize as "owned" or "earned".
-${OPPORTUNITY_COUNT_RULE}
-${ALREADY_SUGGESTED_RULE}
-- The bracketed [N] indexes in the prompt data exist ONLY for the relatedPromptIndex field. NEVER mention an index like "[0]" or "Prompt 3" in titles or descriptions — refer to the prompt by quoting or paraphrasing its actual text/topic instead.`;
-
-function computeScore(volume, visibility, competitorGap, intent) {
- const weights = {
- comparison: 1.0,
- 'best-top': 0.95,
- 'vs-review': 0.9,
- recommendation: 0.85,
- 'how-to': 0.75,
- 'problem-solving': 0.7,
- 'what-is': 0.6,
- other: 0.5,
+- One opportunity per cluster, for the content that answers all of its prompts. Name the need, not a single prompt.
+- Be concrete and actionable, and reference the data: volume, visibility, the strongest competitor's visibility, competitors.
+- Categorize as "owned" (content the brand controls) or "earned" (third-party content, PR, reviews).
+- Existing opportunities from other topics are listed. If a cluster needs the same content as one of them — the same user need and the same piece of content — set sameAs to its bracketed E index. Otherwise set sameAs to null. Sharing words or a topic is not enough.
+- Write for the brand's marketing team: do not use the words "cluster" or "prompt" in titles or descriptions.
+- Refer to clusters and existing opportunities only through clusterIndex and sameAs. Never mention a bracketed index in a title or description.`;
+
+function buildSchema(count) {
+ return z.object({
+ opportunities: z
+ .array(
+ z.object({
+ clusterIndex: z.number().describe('The bracketed index of the cluster'),
+ sameAs: z
+ .number()
+ .nullable()
+ .describe('The E index of an existing opportunity needing the same content, or null'),
+ title: z.string().describe('A specific, actionable content recommendation'),
+ description: z
+ .string()
+ .describe('1-2 sentences on why it matters, referencing the metrics'),
+ type: z.enum(['owned', 'earned']),
+ impact: z.enum(['high', 'medium', 'low']),
+ }),
+ )
+ .max(count),
+ });
+}
+
+/** Everything the opportunity carries about its cluster(s), for the detail page and the brief. */
+function sourceData({ clusters, topicName, metrics, components, queries }) {
+ const [primary, ...related] = clusters;
+ return {
+ promptText: metrics.representative?.text,
+ clusterLabel: primary.label,
+ topicName: topicName(primary),
+ relatedTopics: related.map(topicName),
+ prompts: clusters.flatMap((c) => c.promptTexts),
+ estAiVolume: metrics.demand,
+ visibilityScore: metrics.visibility,
+ topCompetitorVisibility: metrics.topCompetitorVisibility,
+ competitorGap: metrics.competitorGap,
+ intent: metrics.intent,
+ keywords: metrics.keywords,
+ competitorsCited: metrics.competitorsCited,
+ queries,
+ scoreComponents: components,
+ windowDays: OPPORTUNITY_WINDOW_DAYS,
};
- const nv = Math.min(volume / 50000, 1);
- const vg = (100 - (visibility || 0)) / 100;
- const cg = Math.min((competitorGap || 0) / 100, 1);
- const iw = weights[intent] || 0.5;
- return Math.round(Math.min(nv * 40 + vg * 30 + cg * 20 + iw * 10, 100) * 100) / 100;
}
-export async function generateContentOpportunities(brandId) {
- logger.info({ brandId }, '[opportunities] generating');
+/** Included/excluded counts and the most searched included queries across clusters. */
+function basketSummary(clusterIds, basketRows) {
+ const rows = basketRows.filter((r) => clusterIds.includes(r.cluster_id));
+ const times = new Map();
+ for (const r of rows)
+ if (r.included) times.set(r.query, (times.get(r.query) || 0) + r.times_searched);
+ return {
+ included: new Set(rows.filter((r) => r.included).map((r) => r.query)).size,
+ excluded: new Set(rows.filter((r) => !r.included).map((r) => r.query)).size,
+ top: [...times]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, QUERIES_KEPT)
+ .map(([query, timesSearched]) => ({ query, timesSearched })),
+ };
+}
+
+async function loadPromptTexts(promptIds) {
+ const { data, error } = await selectInChunks(promptIds, (chunk) =>
+ supabaseAdmin.from('prompts').select('id, text').in('id', chunk),
+ );
+ if (error) throw new Error(error.message);
+ return data || [];
+}
+
+/**
+ * @param {string} brandId
+ * @param {{ model?: string, onProgress?: (p: {phase: string, message: string}) => void }} [opts]
+ * @returns {Promise<{ generated: number, merged: number }>}
+ */
+export async function generateContentOpportunities(brandId, { model, onProgress } = {}) {
+ onProgress?.({ phase: 'collecting_data', message: 'Fetching clusters and metrics...' });
const { data: brand } = await supabaseAdmin
.from('brands')
- .select('id, name, description, industry, language')
+ .select('id, name, industry, language')
.eq('id', brandId)
.single();
- if (!brand) return;
-
- const langName = getLanguageName(brand.language);
-
- const { data: domains } = await supabaseAdmin
- .from('brand_domains')
- .select('domain')
- .eq('brand_id', brandId);
-
- const { data: promptSets } = await supabaseAdmin
- .from('prompt_sets')
- .select('id')
- .eq('brand_id', brandId);
- if (!promptSets?.length) return;
-
- const setIds = promptSets.map((ps) => ps.id);
- const { data: prompts } = await supabaseAdmin
- .from('prompts')
- .select('id, text, category')
- .in('prompt_set_id', setIds)
- .eq('is_active', true);
- if (!prompts?.length) return;
-
- const promptIds = prompts.map((p) => p.id);
-
- // Both prompt-keyed filters are chunked: a large brand puts hundreds of
- // uuids in one query string, which is the request size the edge starts
- // rejecting (see lib/chunked-in.js). Grouping below still works, because a
- // prompt's rows all come from the same chunk and keep their order.
- const [volRes, resRes, compRes] = await Promise.all([
- selectInChunks(promptIds, (chunk) =>
- supabaseAdmin.from('prompt_volumes').select('*').in('prompt_id', chunk),
- ),
- selectInChunks(promptIds, (chunk) =>
+ if (!brand) return { generated: 0, merged: 0 };
+
+ const clusters = await loadClusters(brandId);
+ if (!clusters.length) return { generated: 0, merged: 0 };
+
+ const since = new Date(Date.now() - OPPORTUNITY_WINDOW_DAYS * 86_400_000)
+ .toISOString()
+ .slice(0, 10);
+ const memberIds = clusters.flatMap((c) => c.prompt_ids);
+ const [prompts, volumes, metricsRes, topicsRes, domainsRes, existing] = await Promise.all([
+ loadPromptTexts(memberIds),
+ selectInChunks(memberIds, (chunk) =>
supabaseAdmin
- .from('prompt_results')
- .select('prompt_id, visibility_score, competitor_mentions')
- .in('prompt_id', chunk)
- .order('created_at', { ascending: false }),
+ .from('prompt_volumes')
+ .select('prompt_id, est_ai_volume, intent, keywords')
+ .in('prompt_id', chunk),
),
- supabaseAdmin.from('competitors').select('name').eq('brand_id', brandId),
+ supabaseAdmin.rpc('brand_prompt_opportunity_metrics', { p_brand_id: brandId, p_since: since }),
+ supabaseAdmin.from('topics').select('id, name').eq('brand_id', brandId),
+ supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brandId),
+ loadClusterOpportunities(brandId),
]);
+ if (volumes.error) throw new Error(volumes.error.message);
+ if (metricsRes.error) throw new Error(metricsRes.error.message);
- const volMap = {};
- for (const v of volRes.data || []) volMap[v.prompt_id] = v;
-
- const resMap = {};
- for (const r of resRes.data || []) {
- if (!resMap[r.prompt_id]) resMap[r.prompt_id] = [];
- resMap[r.prompt_id].push(r);
+ const byPrompt = new Map(prompts.map((p) => [p.id, { text: p.text }]));
+ for (const v of volumes.data || []) {
+ if (byPrompt.has(v.prompt_id)) byPrompt.get(v.prompt_id).volume = v;
+ }
+ for (const m of metricsRes.data || []) {
+ if (byPrompt.has(m.prompt_id)) byPrompt.get(m.prompt_id).metrics = m;
}
- const testedPrompts = prompts.filter((p) => (resMap[p.id] || []).length > 0);
- if (!testedPrompts.length) return;
-
- // Open opportunities, read before choosing candidates: prompts already at
- // the cap are skipped, and the rest show the model what they already hold.
- const existing = await loadOpenOpportunities(brandId);
- const openCounts = openCountsByPrompt(existing);
- const openTitles = openTitlesByPrompt(existing);
-
- const ranked = testedPrompts
- .map((p) => {
- const vol = volMap[p.id];
- const res = resMap[p.id] || [];
- const avgVis = res.length
- ? Math.round(res.reduce((s, r) => s + r.visibility_score, 0) / res.length)
- : 0;
- const compMentions = {};
- for (const r of res) {
- const cms =
- typeof r.competitor_mentions === 'string'
- ? JSON.parse(r.competitor_mentions)
- : r.competitor_mentions;
- for (const cm of cms || [])
- compMentions[cm.name] = (compMentions[cm.name] || 0) + (cm.visibility_score || 0);
- }
- const cg = Object.values(compMentions).length
- ? Math.round(
- Object.values(compMentions).reduce((a, b) => a + b, 0) /
- Object.values(compMentions).length,
- ) - avgVis
- : 0;
-
- return {
- promptId: p.id,
- text: p.text,
- category: p.category || 'unknown',
- estAiVolume: vol?.est_ai_volume || 0,
- intent: vol?.intent || 'other',
- keywords: vol?.keywords || [],
- avgVisibility: avgVis,
- competitorGap: cg,
- competitorsCited: Object.keys(compMentions),
- score: computeScore(vol?.est_ai_volume || 0, avgVis, cg, vol?.intent || 'other'),
- };
- })
- .sort((a, b) => b.score - a.score);
- // Capped prompts drop out before the cut, so their slots go to the next
- // prompts down instead of to another rewording of the same idea.
- const scored = belowOpenCap(ranked, openCounts).slice(0, 25);
-
- if (!scored.length) {
+ const topicNames = new Map((topicsRes.data || []).map((t) => [t.id, t.name]));
+ const topicName = (c) => (c.topic_id ? topicNames.get(c.topic_id) || null : null);
+ const clusterById = new Map(
+ clusters.map((c) => [
+ c.id,
+ {
+ ...c,
+ promptTexts: c.prompt_ids.map((id) => byPrompt.get(id)?.text).filter(Boolean),
+ },
+ ]),
+ );
+
+ const measure = (clusterIds) => {
+ const metrics = clusterMetrics(
+ clusterIds.flatMap((id) => clusterById.get(id)?.prompt_ids || []),
+ byPrompt,
+ );
+ const components = scoreComponents(metrics);
+ return { metrics, components, score: opportunityScore(components) };
+ };
+
+ const candidates = clusters.map((c) => ({ id: c.id, ...measure([c.id]) }));
+ const picked = pickClusters(candidates, coveredClusterIds(existing));
+ if (!picked.length) {
logger.info(
- { brandId, openOpportunities: existing.length },
- '[opportunities] every candidate prompt is at its open cap — nothing generated',
+ { brandId, clusters: clusters.length, opportunities: existing.length },
+ '[opportunities] every cluster with answers already has an opportunity',
);
- return;
+ return { generated: 0, merged: 0 };
}
- const promptLine = (p, i) =>
- `[${i}] "${p.text}" | Intent: ${p.intent} | AI Vol: ${p.estAiVolume}/mo | Vis: ${p.avgVisibility}% | Gap: ${p.competitorGap}%${alreadySuggested(openTitles.get(p.promptId))}`;
+ const { data: basketRows, error: basketErr } = await supabaseAdmin
+ .from('prompt_cluster_queries')
+ .select('cluster_id, query, times_searched, included')
+ .in(
+ 'cluster_id',
+ picked.map((c) => c.id),
+ );
+ if (basketErr) throw new Error(basketErr.message);
+
+ const shown = existing
+ .filter((o) => o.status !== 'dismissed' && clusterById.has(o.cluster_id))
+ .sort((a, b) => b.opportunity_score - a.opportunity_score)
+ .slice(0, EXISTING_SHOWN);
+
+ const clusterLine = (cand, i) => {
+ const c = clusterById.get(cand.id);
+ const m = cand.metrics;
+ const basket = basketSummary([c.id], basketRows || []);
+ return `[${i}] ${c.label} (topic: ${topicName(c) || 'none'})
+Need: ${c.primary_intent}
+Prompts:
+${c.promptTexts
+ .slice(0, PROMPTS_SHOWN)
+ .map((t) => `- ${t}`)
+ .join('\n')}
+Searches AI engines ran for these prompts: ${basket.top.map((q) => q.query).join('; ') || 'none recorded'}
+Est. AI volume: ${m.demand}/mo | Brand visibility: ${m.visibility}% | Strongest competitor: ${m.topCompetitorVisibility}% | Competitors visible: ${m.competitorsCited.join(', ') || 'none'}`;
+ };
const userPrompt = `Brand: ${brand.name}
Industry: ${brand.industry || 'Not specified'}
-Domain: ${(domains || []).map((d) => d.domain).join(', ') || 'N/A'}
-Competitors: ${(compRes.data || []).map((c) => c.name).join(', ') || 'None'}
+Domain: ${(domainsRes.data || []).map((d) => d.domain).join(', ') || 'N/A'}
-Prompt Data:
-${scored.map(promptLine).join('\n')}
+Clusters (highest opportunity first):
+${picked.map(clusterLine).join('\n\n')}
-Generate actionable content opportunities.
+Existing opportunities in other topics:
+${shown.map((o, i) => `[E${i}] ${o.title} (topic: ${topicName(clusterById.get(o.cluster_id)) || 'none'})`).join('\n') || 'none'}
-IMPORTANT: Write every opportunity title and description in ${langName}.`;
+Write every title and description in ${getLanguageName(brand.language)}.`;
+ onProgress?.({ phase: 'analyzing', message: 'Generating opportunities with AI...' });
const { object } = await generateObject({
- model: resolveModel(),
- schema: opportunitySchema,
+ model: resolveModel(model),
+ schema: buildSchema(picked.length),
system: SYSTEM_PROMPT,
prompt: userPrompt,
});
- // Exact repeats are still caught here, as the last guard behind the cap and
- // the already-suggested list.
- const seen = new Set(existing.map((o) => opportunityKey(o.prompt_id, o.title)));
-
- const rows = object.opportunities
- .map((opp) => ({ rel: relatedCandidate(scored, opp.relatedPromptIndex), opp }))
- .filter(({ rel, opp }) => {
- if (!rel) return false;
- const key = opportunityKey(rel.promptId, opp.title);
- if (seen.has(key)) return false;
- seen.add(key);
- return true;
- })
- .map(({ rel, opp }) => ({
+ onProgress?.({ phase: 'saving', message: 'Saving opportunities...' });
+ const done = new Set();
+ const inserts = [];
+ let merged = 0;
+
+ for (const opp of object.opportunities) {
+ const cand = picked[opp.clusterIndex];
+ if (!Number.isInteger(opp.clusterIndex) || !cand || done.has(cand.id)) continue;
+ done.add(cand.id);
+
+ const target = Number.isInteger(opp.sameAs) ? shown[opp.sameAs] : null;
+ if (target) {
+ // Related clusters deleted by a re-clustering since are dropped here.
+ const ids = [target.cluster_id, ...(target.related_cluster_ids || []), cand.id].filter((id) =>
+ clusterById.has(id),
+ );
+ const { metrics, components, score } = measure(ids);
+ const { error } = await supabaseAdmin
+ .from('content_opportunities')
+ .update({
+ related_cluster_ids: ids.slice(1),
+ opportunity_score: score,
+ source_data: sourceData({
+ clusters: ids.map((id) => clusterById.get(id)),
+ topicName,
+ metrics,
+ components,
+ queries: basketSummary(ids, basketRows || []),
+ }),
+ updated_at: new Date().toISOString(),
+ })
+ .eq('id', target.id);
+ if (error) throw new Error(error.message);
+ // A later cluster in this run may name the same target.
+ target.related_cluster_ids = ids.slice(1);
+ merged += 1;
+ continue;
+ }
+
+ const c = clusterById.get(cand.id);
+ inserts.push({
brand_id: brandId,
- prompt_id: rel.promptId,
+ cluster_id: c.id,
+ prompt_id: cand.metrics.representative?.id ?? null,
title: opp.title,
description: opp.description,
type: opp.type,
impact: opp.impact,
- opportunity_score: rel.score,
+ opportunity_score: cand.score,
status: 'new',
- source_data: {
- promptText: rel.text,
- estAiVolume: rel.estAiVolume,
- visibilityScore: rel.avgVisibility,
- competitorGap: rel.competitorGap,
- intent: rel.intent,
- keywords: rel.keywords,
- competitorsCited: rel.competitorsCited,
- },
- }));
+ source_data: sourceData({
+ clusters: [c],
+ topicName,
+ metrics: cand.metrics,
+ components: cand.components,
+ queries: basketSummary([c.id], basketRows || []),
+ }),
+ });
+ }
- if (rows.length > 0) await supabaseAdmin.from('content_opportunities').insert(rows);
+ if (inserts.length) {
+ const { error } = await supabaseAdmin.from('content_opportunities').insert(inserts);
+ if (error) throw new Error(error.message);
+ }
logger.info(
- { brandId, generated: rows.length, alreadyPending: existing.length },
- '[opportunities] generated new opportunities',
+ { brandId, generated: inserts.length, merged, clusters: clusters.length },
+ '[opportunities] generated',
);
+ return { generated: inserts.length, merged };
}
diff --git a/server/src/lib/opportunity-limits.js b/server/src/lib/opportunity-limits.js
index a9141870e..484b5e1d8 100644
--- a/server/src/lib/opportunity-limits.js
+++ b/server/src/lib/opportunity-limits.js
@@ -1,84 +1,140 @@
/**
- * How many content opportunities one generation run may produce.
+ * How content opportunities are counted, ranked and scored (#857).
*
- * The two generators — the automatic one fired after each tracking cycle and
- * the queued one behind the Generate button — used to carry this rule as a
- * hand-written sentence and a schema ceiling apiece, and had already drifted
- * apart in wording. They share it from here so the button and the nightly run
- * cannot disagree about how many a brand gets.
- *
- * Three, not the five-to-fifteen it was: the model reliably landed near ten,
- * which is more than anyone works through in a day. Generation appends
- * nightly, so anything the reader does not act on accumulates — a short list
- * that gets read beats a long one that gets scrolled past.
+ * Opportunities are generated per prompt cluster: a group of prompts in one
+ * topic that a single piece of content can answer (lib/prompt-clusters.js).
+ * A cluster's figures are built from its member prompts, and the score keeps
+ * its components so the detail page can say why it is what it is.
*/
-export const OPPORTUNITIES_PER_RUN = 3;
/**
- * The count instruction, worded for a model that must now choose.
- *
- * At ten the ranking barely mattered; the good ones arrived alongside the
- * filler. At three there is no room for filler, so the instruction has to say
- * that the slots go to the highest-impact opportunities in the data rather
- * than to whichever the model composes first. The prompt data is already
- * ordered by score, which is what "provided" refers to.
+ * Opportunities one generation run may produce. A short list that gets read
+ * beats a long one that gets scrolled past, and generation runs nightly, so
+ * three a night reaches every cluster over time.
*/
-export const OPPORTUNITY_COUNT_RULE = `- Generate exactly ${OPPORTUNITIES_PER_RUN} opportunities: the ${OPPORTUNITIES_PER_RUN} highest-impact ones supported by the data provided, not the first ${OPPORTUNITIES_PER_RUN} that come to mind. Weigh volume, the visibility gap and the competitor gap together when choosing which ${OPPORTUNITIES_PER_RUN} to keep, and drop anything you would have ranked below them.`;
+export const OPPORTUNITIES_PER_RUN = 3;
+
+/** Window the cluster metrics are measured over. */
+export const OPPORTUNITY_WINDOW_DAYS = 30;
/**
- * Open (status 'new') opportunities a prompt may hold before the nightly run
- * skips it (#837). Prompts are ranked by a deterministic score, so without a
- * cap the same top prompts win every night and pile up rewordings of one idea
- * — one prompt had collected 38 open opportunities over 32 nights.
+ * Estimated monthly AI volume at which the demand component tops out. The
+ * scale is logarithmic: a cluster adds up its prompts' volumes, and on a
+ * linear scale with the old per-prompt ceiling of 50,000 most clusters sat
+ * at 100 and demand stopped telling them apart. 1,000 scores 50, 10,000
+ * scores 67, 150,000 scores 86.
*/
-export const MAX_OPEN_PER_PROMPT = 3;
+const DEMAND_CEILING = 1_000_000;
-/** Open opportunity count per prompt id, from rows carrying `prompt_id`. */
-export function openCountsByPrompt(rows) {
- const counts = new Map();
- for (const r of rows || []) {
- if (r.prompt_id) counts.set(r.prompt_id, (counts.get(r.prompt_id) || 0) + 1);
- }
- return counts;
-}
+const INTENT_WEIGHTS = {
+ comparison: 1.0,
+ 'best-top': 0.95,
+ 'vs-review': 0.9,
+ recommendation: 0.85,
+ 'how-to': 0.75,
+ 'problem-solving': 0.7,
+ 'what-is': 0.6,
+ other: 0.5,
+};
-/** Candidates whose prompt still has room for another open opportunity. */
-export function belowOpenCap(candidates, counts) {
- return candidates.filter((c) => (counts.get(c.promptId) || 0) < MAX_OPEN_PER_PROMPT);
+/** Score weights per component, out of 100. */
+export const SCORE_WEIGHTS = { demand: 40, visibilityGap: 30, competitorGap: 20, intent: 10 };
+
+const round1 = (n) => Math.round(n * 10) / 10;
+
+function mostFrequent(values, limit) {
+ const counts = new Map();
+ for (const v of values) counts.set(v, (counts.get(v) || 0) + 1);
+ return [...counts]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, limit)
+ .map(([v]) => v);
}
/**
- * The candidate an opportunity's relatedPromptIndex points at, or null when
- * the model returned an index outside the list. Such an opportunity is
- * dropped: falling back to the first candidate attached it to the prompt that
- * was already the most crowded.
+ * A cluster's figures from its member prompts.
+ *
+ * Demand adds up: one piece of content answers every member. Visibility and
+ * the strongest competitor's visibility are averaged over the members that
+ * have answers in the window, weighted by how many engine-days each has.
+ *
+ * @param {string[]} promptIds - the cluster's members
+ * @param {Map<string, {text: string, volume?: object, metrics?: object}>} prompts
*/
-export function relatedCandidate(candidates, index) {
- return Number.isInteger(index) && index >= 0 && index < candidates.length
- ? candidates[index]
- : null;
+export function clusterMetrics(promptIds, prompts) {
+ const members = promptIds.map((id) => ({ id, ...prompts.get(id) })).filter((m) => m.text);
+ const tested = members.filter((m) => m.metrics?.cells > 0);
+ const cells = tested.reduce((s, m) => s + m.metrics.cells, 0);
+ const weighted = (key) =>
+ cells ? tested.reduce((s, m) => s + m.metrics[key] * m.metrics.cells, 0) / cells : 0;
+
+ const volume = (m) => m.volume?.est_ai_volume || 0;
+ const visibility = round1(weighted('visibility'));
+ const topCompetitorVisibility = round1(weighted('top_competitor_visibility'));
+ const representative = [...(tested.length ? tested : members)].sort(
+ (a, b) => volume(b) - volume(a),
+ )[0];
+
+ return {
+ tested: tested.length,
+ demand: members.reduce((s, m) => s + volume(m), 0),
+ visibility,
+ topCompetitorVisibility,
+ competitorGap: round1(topCompetitorVisibility - visibility),
+ intent:
+ mostFrequent(
+ members.map((m) => m.volume?.intent || 'other'),
+ 1,
+ )[0] || 'other',
+ keywords: mostFrequent(
+ members.flatMap((m) => m.volume?.keywords || []),
+ 8,
+ ),
+ competitorsCited: mostFrequent(
+ tested.flatMap((m) => m.metrics.competitors || []),
+ 5,
+ ),
+ representative: representative ? { id: representative.id, text: representative.text } : null,
+ };
}
-/** The instruction that goes with the "Already suggested" lists in the prompt data. */
-export const ALREADY_SUGGESTED_RULE = `- Some prompts list opportunities "Already suggested" for them. Do not repeat or reword those: suggest a genuinely different piece of content for that prompt, or choose another prompt.`;
+/** Each score component on a 0–100 scale. */
+export function scoreComponents({ demand, visibility, competitorGap, intent }) {
+ return {
+ demand: round1(Math.min(Math.log10(1 + demand) / Math.log10(1 + DEMAND_CEILING), 1) * 100),
+ visibilityGap: round1(100 - visibility),
+ competitorGap: round1(Math.min(Math.max(competitorGap, 0), 100)),
+ intent: round1((INTENT_WEIGHTS[intent] || INTENT_WEIGHTS.other) * 100),
+ };
+}
-/** Open opportunity titles per prompt id, from rows carrying `prompt_id` and `title`. */
-export function openTitlesByPrompt(rows) {
- const titles = new Map();
- for (const r of rows || []) {
- if (!r.prompt_id || !r.title) continue;
- if (!titles.has(r.prompt_id)) titles.set(r.prompt_id, []);
- titles.get(r.prompt_id).push(r.title);
- }
- return titles;
+/** The weighted total of the components, 0–100. */
+export function opportunityScore(components) {
+ const total = Object.entries(SCORE_WEIGHTS).reduce(
+ (s, [key, weight]) => s + (components[key] * weight) / 100,
+ 0,
+ );
+ return Math.round(total * 100) / 100;
}
-/** The prompt-data suffix listing what a prompt already holds, or '' if nothing. */
-export function alreadySuggested(titles) {
- return titles?.length ? ` | Already suggested: ${titles.map((t) => `"${t}"`).join('; ')}` : '';
+/**
+ * Clusters that already have an opportunity, as its own cluster or a merged
+ * one. Any status counts: a cluster gets one opportunity, and a dismissed one
+ * is not suggested again in other words.
+ */
+export function coveredClusterIds(rows) {
+ const ids = new Set();
+ for (const r of rows || []) {
+ if (r.cluster_id) ids.add(r.cluster_id);
+ for (const id of r.related_cluster_ids || []) ids.add(id);
+ }
+ return ids;
}
-/** Duplicate key: the same prompt and the same title, ignoring case and outer spaces. */
-export function opportunityKey(promptId, title) {
- return `${promptId}::${(title || '').toLowerCase().trim()}`;
+/** The highest-scoring clusters with answers and no opportunity yet. */
+export function pickClusters(candidates, covered, count = OPPORTUNITIES_PER_RUN) {
+ return candidates
+ .filter((c) => c.metrics.tested > 0 && !covered.has(c.id))
+ .sort((a, b) => b.score - a.score)
+ .slice(0, count);
}
diff --git a/server/src/lib/opportunity-limits.test.js b/server/src/lib/opportunity-limits.test.js
index a1276e413..f375d1bea 100644
--- a/server/src/lib/opportunity-limits.test.js
+++ b/server/src/lib/opportunity-limits.test.js
@@ -2,132 +2,128 @@ import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import {
- MAX_OPEN_PER_PROMPT,
OPPORTUNITIES_PER_RUN,
- OPPORTUNITY_COUNT_RULE,
- alreadySuggested,
- belowOpenCap,
- openCountsByPrompt,
- openTitlesByPrompt,
- opportunityKey,
- relatedCandidate,
+ SCORE_WEIGHTS,
+ clusterMetrics,
+ coveredClusterIds,
+ opportunityScore,
+ pickClusters,
+ scoreComponents,
} from './opportunity-limits.js';
-/**
- * The count rule is shared because it was duplicated (#730).
- *
- * Two generators produce opportunities — the automatic one after each tracking
- * cycle and the queued one behind the Generate button — and each used to carry
- * its own copy of the sentence and its own schema ceiling. They had already
- * drifted in wording. These tests fail if a number is hand-written back into
- * either file, which is the only way they can disagree again.
- */
-
const source = (relative) =>
readFileSync(fileURLToPath(new URL(relative, import.meta.url)), 'utf8');
-const GENERATORS = [
- ['automatic (tracking cycle)', './opportunity-generator.js'],
- ['queued (Generate button)', '../workers/content-worker.js'],
-];
+const prompts = new Map([
+ [
+ 'a',
+ {
+ text: 'best tools for x',
+ volume: { est_ai_volume: 3000, intent: 'best-top', keywords: ['x tools', 'x software'] },
+ metrics: { cells: 30, visibility: 10, top_competitor_visibility: 60, competitors: ['Rival'] },
+ },
+ ],
+ [
+ 'b',
+ {
+ text: 'top x software',
+ volume: { est_ai_volume: 1000, intent: 'best-top', keywords: ['x software'] },
+ metrics: {
+ cells: 10,
+ visibility: 50,
+ top_competitor_visibility: 40,
+ competitors: ['Rival', 'Other'],
+ },
+ },
+ ],
+ // Tracked but not answered in the window: adds demand, not visibility.
+ ['c', { text: 'how to pick x', volume: { est_ai_volume: 500, intent: 'how-to', keywords: [] } }],
+]);
-describe('opportunity count', () => {
- it('asks for three', () => {
- expect(OPPORTUNITIES_PER_RUN).toBe(3);
+describe('clusterMetrics', () => {
+ it('adds demand and weights visibility by engine-days', () => {
+ const m = clusterMetrics(['a', 'b', 'c', 'gone'], prompts);
+ expect(m.tested).toBe(2);
+ expect(m.demand).toBe(4500);
+ // (10×30 + 50×10) / 40 and (60×30 + 40×10) / 40
+ expect(m.visibility).toBe(20);
+ expect(m.topCompetitorVisibility).toBe(55);
+ expect(m.competitorGap).toBe(35);
+ expect(m.intent).toBe('best-top');
+ expect(m.keywords[0]).toBe('x software');
+ expect(m.competitorsCited).toEqual(['Rival', 'Other']);
+ expect(m.representative).toEqual({ id: 'a', text: 'best tools for x' });
});
- it('states the count and that the slots go to the highest-impact findings', () => {
- expect(OPPORTUNITY_COUNT_RULE).toContain(String(OPPORTUNITIES_PER_RUN));
- expect(OPPORTUNITY_COUNT_RULE).toMatch(/highest-impact/i);
+ it('reports a cluster with no answers as untested', () => {
+ const m = clusterMetrics(['c'], prompts);
+ expect(m.tested).toBe(0);
+ expect(m.visibility).toBe(0);
+ expect(m.representative).toEqual({ id: 'c', text: 'how to pick x' });
});
-
- for (const [label, path] of GENERATORS) {
- it(`the ${label} generator takes its ceiling from the shared constant`, () => {
- const code = source(path);
- expect(code).toContain('OPPORTUNITIES_PER_RUN');
- expect(code).toContain('.max(OPPORTUNITIES_PER_RUN)');
- // A literal ceiling here is how the two drifted apart before.
- expect(code).not.toMatch(/\.max\(\d+\)/);
- });
-
- it(`the ${label} generator takes its count instruction from the shared rule`, () => {
- const code = source(path);
- expect(code).toContain('${OPPORTUNITY_COUNT_RULE}');
- expect(code).not.toMatch(/Generate (between )?\d+/);
- });
-
- it(`the ${label} generator drops an out-of-range prompt index`, () => {
- const code = source(path);
- expect(code).toContain('relatedCandidate(');
- // The old fallback attached the opportunity to the top candidate.
- expect(code).not.toMatch(/relatedPromptIndex\]\s*\|\|/);
- });
- }
});
-describe('open-opportunity cap (#837)', () => {
- it('counts open opportunities per prompt', () => {
- const counts = openCountsByPrompt([
- { prompt_id: 'a' },
- { prompt_id: 'a' },
- { prompt_id: 'b' },
- { prompt_id: null },
- ]);
- expect(counts.get('a')).toBe(2);
- expect(counts.get('b')).toBe(1);
- expect(counts.size).toBe(2);
+describe('score', () => {
+ it('scales each component to 0–100', () => {
+ expect(
+ scoreComponents({ demand: 2_000_000, visibility: 20, competitorGap: -5, intent: 'how-to' }),
+ ).toEqual({ demand: 100, visibilityGap: 80, competitorGap: 0, intent: 75 });
});
- it('keeps prompts under the cap and drops prompts at it', () => {
- const counts = new Map([
- ['full', MAX_OPEN_PER_PROMPT],
- ['partly', MAX_OPEN_PER_PROMPT - 1],
- ]);
- const kept = belowOpenCap(
- [{ promptId: 'full' }, { promptId: 'partly' }, { promptId: 'fresh' }],
- counts,
- );
- expect(kept.map((c) => c.promptId)).toEqual(['partly', 'fresh']);
+ it('puts demand on a log scale so large clusters still differ', () => {
+ const demand = (d) =>
+ scoreComponents({ demand: d, visibility: 0, competitorGap: 0, intent: 'other' }).demand;
+ expect(demand(0)).toBe(0);
+ expect(demand(1000)).toBe(50);
+ expect(demand(10000)).toBe(66.7);
+ expect(demand(150000)).toBeLessThan(demand(1_000_000));
});
- it('resolves an in-range index and drops anything else', () => {
- const candidates = [{ promptId: 'a' }, { promptId: 'b' }];
- expect(relatedCandidate(candidates, 1)).toEqual({ promptId: 'b' });
- expect(relatedCandidate(candidates, 2)).toBeNull();
- expect(relatedCandidate(candidates, -1)).toBeNull();
- expect(relatedCandidate(candidates, 0.5)).toBeNull();
- expect(relatedCandidate(candidates, undefined)).toBeNull();
+ it('weights the components into the total', () => {
+ expect(Object.values(SCORE_WEIGHTS).reduce((a, b) => a + b, 0)).toBe(100);
+ expect(opportunityScore({ demand: 100, visibilityGap: 80, competitorGap: 0, intent: 75 })).toBe(
+ 71.5,
+ );
});
+});
- it('lists open titles per prompt and renders them for the prompt data', () => {
- const titles = openTitlesByPrompt([
- { prompt_id: 'a', title: 'Guide' },
- { prompt_id: 'a', title: 'Checklist' },
- { prompt_id: 'b', title: null },
+describe('cluster selection', () => {
+ it('counts both own and merged clusters as covered', () => {
+ const covered = coveredClusterIds([
+ { cluster_id: 'c1', related_cluster_ids: ['c2'] },
+ { cluster_id: 'c3', related_cluster_ids: [] },
]);
- expect(titles.get('a')).toEqual(['Guide', 'Checklist']);
- expect(titles.has('b')).toBe(false);
- expect(alreadySuggested(titles.get('a'))).toBe(' | Already suggested: "Guide"; "Checklist"');
- expect(alreadySuggested(undefined)).toBe('');
+ expect([...covered].sort()).toEqual(['c1', 'c2', 'c3']);
});
- it('keys duplicates by prompt and title, ignoring case and outer spaces', () => {
- expect(opportunityKey('p', ' Guide ')).toBe(opportunityKey('p', 'guide'));
- expect(opportunityKey('p', 'Guide')).not.toBe(opportunityKey('q', 'Guide'));
+ it('takes the best uncovered clusters that have answers', () => {
+ const cand = (id, score, tested = 1) => ({ id, score, metrics: { tested } });
+ const picked = pickClusters(
+ [
+ cand('low', 10),
+ cand('covered', 90),
+ cand('untested', 80, 0),
+ cand('high', 70),
+ cand('mid', 40),
+ ],
+ new Set(['covered']),
+ 2,
+ );
+ expect(picked.map((c) => c.id)).toEqual(['high', 'mid']);
});
+});
- for (const [label, path] of GENERATORS) {
- it(`the ${label} generator applies the cap and shows the model what is open`, () => {
- const code = source(path);
- expect(code).toContain('loadOpenOpportunities(');
- expect(code).toContain('belowOpenCap(');
- expect(code).toContain('${ALREADY_SUGGESTED_RULE}');
- expect(code).toContain('opportunityKey(');
- });
- }
-
- it('the Generate button adds to the open list instead of deleting it (#63)', () => {
+describe('generators', () => {
+ it('the Generate button runs the shared per-cluster generator', () => {
const code = source('../workers/content-worker.js');
+ expect(code).toContain('generateContentOpportunities(');
+ expect(code).toContain('refreshPromptClusters(');
+ // It adds to the list instead of replacing it (#63).
expect(code).not.toMatch(/\.delete\(\)/);
});
+
+ it('runs at most the shared count per run', () => {
+ expect(OPPORTUNITIES_PER_RUN).toBe(3);
+ expect(source('./opportunity-generator.js')).toContain('pickClusters(');
+ });
});
diff --git a/server/src/lib/prompt-clusters.js b/server/src/lib/prompt-clusters.js
index 4e6da3415..d1170ac34 100644
--- a/server/src/lib/prompt-clusters.js
+++ b/server/src/lib/prompt-clusters.js
@@ -241,7 +241,8 @@ Write every reason in ${getLanguageName(brand.language)}.`,
// ─── Reads and writes ────────────────────────────────────────────────────────
-async function loadClusters(brandId) {
+/** A brand's clusters with their member prompt ids. */
+export async function loadClusters(brandId) {
const { data: clusters, error } = await supabaseAdmin
.from('prompt_clusters')
.select('id, topic_id, label, primary_intent')
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index 8cbc350f7..ea0181419 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -27,6 +27,7 @@ function mapOpportunityRow(row) {
id: row.id,
brandId: row.brand_id,
promptId: row.prompt_id,
+ clusterId: row.cluster_id ?? null,
title: row.title,
description: row.description,
type: row.type,
@@ -808,6 +809,17 @@ export async function generateBriefForOpportunity(opportunityId, { force = false
const sourceData = opportunity.source_data || {};
+ // A cluster opportunity (#857) answers several prompts: the brief treats
+ // them as the questions the piece must answer, and the searches AI engines
+ // ran for them as the related searches to cover.
+ const clusterContext = sourceData.prompts?.length
+ ? `
+Questions this content must answer (the cluster's prompts):
+${sourceData.prompts.map((p) => `- ${p}`).join('\n')}
+Searches AI engines ran while answering them: ${(sourceData.queries?.top || []).map((q) => q.query).join('; ') || 'none recorded'}
+`
+ : '';
+
const userPrompt = `Brand: ${brand?.name || 'Unknown'}
Industry: ${brand?.industry || 'Not specified'}
Description: ${brand?.description || 'N/A'}
@@ -822,7 +834,7 @@ Opportunity:
- Score: ${opportunity.opportunity_score}
Related Prompt: "${promptText}"
-Intent: ${sourceData.intent || 'unknown'}
+${clusterContext}Intent: ${sourceData.intent || 'unknown'}
Est. AI Volume: ${sourceData.estAiVolume || 0}/mo
Current Visibility: ${sourceData.visibilityScore || 0}%
Competitor Gap: ${sourceData.competitorGap || 0}%
@@ -954,6 +966,65 @@ router.post('/:id/brief', async (req, res) => {
* GET /api/content/:id
* Get a single opportunity by ID.
*/
+router.get('/:id/basket', async (req, res) => {
+ try {
+ const opp = await assertOpportunityAccess(req.params.id, req.user.id);
+ const clusterIds = [opp.cluster_id, ...(opp.related_cluster_ids || [])].filter(Boolean);
+ if (!clusterIds.length) return res.json({ clusters: [], queries: [] });
+
+ const [clustersRes, membersRes, queriesRes] = await Promise.all([
+ supabaseAdmin
+ .from('prompt_clusters')
+ .select('id, label, primary_intent, topics(name)')
+ .in('id', clusterIds),
+ supabaseAdmin
+ .from('prompt_cluster_members')
+ .select('cluster_id, prompts(id, text)')
+ .in('cluster_id', clusterIds),
+ supabaseAdmin
+ .from('prompt_cluster_queries')
+ .select('query, times_searched, included, reason')
+ .in('cluster_id', clusterIds),
+ ]);
+ const failed = clustersRes.error || membersRes.error || queriesRes.error;
+ if (failed) throw new Error(failed.message);
+
+ // A query searched for several of the opportunity's clusters is listed once.
+ const queries = new Map();
+ for (const q of queriesRes.data || []) {
+ const prior = queries.get(q.query);
+ queries.set(q.query, {
+ query: q.query,
+ timesSearched: (prior?.timesSearched || 0) + q.times_searched,
+ included: prior?.included || false || q.included,
+ reason: prior?.included ? prior.reason : q.reason,
+ });
+ }
+
+ return res.json({
+ clusters: clusterIds
+ .map((id) => (clustersRes.data || []).find((c) => c.id === id))
+ .filter(Boolean)
+ .map((c) => ({
+ id: c.id,
+ label: c.label,
+ need: c.primary_intent,
+ topicName: c.topics?.name ?? null,
+ prompts: (membersRes.data || [])
+ .filter((m) => m.cluster_id === c.id && m.prompts)
+ .map((m) => ({ id: m.prompts.id, text: m.prompts.text })),
+ })),
+ queries: [...queries.values()].sort((a, b) => b.timesSearched - a.timesSearched),
+ });
+ } catch (error) {
+ req.log.error({ err: error }, 'get opportunity basket error');
+ return res.status(error.status || 500).json({
+ error: 'Failed to get opportunity basket',
+ details: error.message,
+ });
+ }
+});
+
router.get('/:id', async (req, res) => {
try {
const { id } = req.params;
diff --git a/server/src/workers/content-worker.js b/server/src/workers/content-worker.js
index aa5ccf363..33244f2ee 100644
--- a/server/src/workers/content-worker.js
+++ b/server/src/workers/content-worker.js
@@ -3,319 +3,31 @@
* Moves the LLM-based generation out of the HTTP request path.
*/
-import { generateObject } from 'ai';
-import { z } from 'zod';
-import { resolveModel } from '../lib/ai-provider.js';
-import { getLanguageName } from '../lib/languages.js';
-import supabaseAdmin from '../config/supabase.js';
-import { selectInChunks } from '../lib/chunked-in.js';
import logger from '../lib/logger.js';
-import {
- ALREADY_SUGGESTED_RULE,
- OPPORTUNITIES_PER_RUN,
- OPPORTUNITY_COUNT_RULE,
- alreadySuggested,
- belowOpenCap,
- openCountsByPrompt,
- openTitlesByPrompt,
- opportunityKey,
- relatedCandidate,
-} from '../lib/opportunity-limits.js';
-import { loadOpenOpportunities } from '../lib/open-opportunities.js';
-
-const opportunitySchema = z.object({
- opportunities: z
- .array(
- z.object({
- title: z
- .string()
- .describe(
- 'A specific, actionable content recommendation backed by the data provided. Never reference prompts by their bracketed index like [0] or "Prompt 3" — name the topic or paraphrase the prompt text instead.',
- ),
- description: z
- .string()
- .describe(
- 'A 1-2 sentence explanation of why this action matters, referencing specific metrics. Never reference prompts by their bracketed index like [0] or "Prompt 3" — name the topic or paraphrase the prompt text instead.',
- ),
- type: z
- .enum(['owned', 'earned'])
- .describe(
- 'owned = content the brand controls (blog, landing page); earned = external content (PR, guest post, review)',
- ),
- impact: z
- .enum(['high', 'medium', 'low'])
- .describe('Expected impact on AI visibility based on volume and gap'),
- relatedPromptIndex: z
- .number()
- .describe('0-based index of the prompt in the input array this opportunity relates to'),
- }),
- )
- .min(1)
- .max(OPPORTUNITIES_PER_RUN),
-});
-
-const OPPORTUNITY_SYSTEM_PROMPT = `You are an AEO (Answer Engine Optimization) content strategist. Given a brand's AI visibility data — including prompt tracking results, search volumes, and competitor mentions — generate specific, actionable content recommendations.
-
-Rules:
-- Each recommendation must be concrete and actionable (e.g. "Create a comprehensive comparison page for X" not "Improve your content").
-- Reference specific data points: volumes, visibility scores, competitor gaps.
-- Focus on content that will improve the brand's visibility in AI-generated answers.
-- Categorize as "owned" (blog posts, landing pages, FAQ pages the brand controls) or "earned" (guest posts, PR, review sites).
-- Set impact based on: volume × (100 - current visibility) × competitor gap.
-${OPPORTUNITY_COUNT_RULE}
-- Do NOT repeat the same recommendation in different wording.
-${ALREADY_SUGGESTED_RULE}
-- The bracketed [N] indexes in the prompt data exist ONLY for the relatedPromptIndex field. NEVER mention an index like "[0]" or "Prompt 3" in titles or descriptions — refer to the prompt by quoting or paraphrasing its actual text/topic instead.`;
-
-function computeOpportunityScore(volume, visibility, competitorGap, intent) {
- const intentWeights = {
- comparison: 1.0,
- 'best-top': 0.95,
- 'vs-review': 0.9,
- recommendation: 0.85,
- 'how-to': 0.75,
- 'problem-solving': 0.7,
- 'what-is': 0.6,
- other: 0.5,
- };
-
- const maxVolume = 50000;
- const normalizedVolume = Math.min(volume / maxVolume, 1);
- const visibilityGap = (100 - (visibility || 0)) / 100;
- const normalizedCompGap = Math.min((competitorGap || 0) / 100, 1);
- const intentWeight = intentWeights[intent] || 0.5;
-
- const score =
- normalizedVolume * 40 + visibilityGap * 30 + normalizedCompGap * 20 + intentWeight * 10;
-
- return Math.round(Math.min(score, 100) * 100) / 100;
-}
+import { generateContentOpportunities } from '../lib/opportunity-generator.js';
+import { refreshPromptClusters } from '../lib/prompt-clusters.js';
/**
- * Core logic: collect brand data, generate opportunities via LLM, save them.
- * @param {{ brandId: string, model?: string, job?: { progress: function, signal?: AbortSignal } }} opts
+ * The Generate button runs the same per-cluster generation as the nightly
+ * run. Clusters are refreshed first: a brand whose prompts changed since its
+ * last tracking cycle, or that has never been clustered, would otherwise get
+ * nothing or work from stale groups. The button adds to the existing list
+ * (#63); a cluster that already has an opportunity is skipped.
+ *
+ * @param {{ brandId: string, model?: string, job: { progress: function } }} opts
*/
export async function processContentJob({ brandId, model, job }) {
- job.progress({ phase: 'collecting_data', message: 'Fetching brand and prompt data...' });
-
- const { data: brand } = await supabaseAdmin
- .from('brands')
- .select('id, name, description, industry, organization_id, language')
- .eq('id', brandId)
- .single();
-
- if (!brand) throw new Error(`Brand not found: ${brandId}`);
- const langName = getLanguageName(brand.language);
-
- const { data: domains } = await supabaseAdmin
- .from('brand_domains')
- .select('domain')
- .eq('brand_id', brandId);
-
- const { data: promptSets } = await supabaseAdmin
- .from('prompt_sets')
- .select('id')
- .eq('brand_id', brandId);
-
- if (!promptSets?.length) {
- throw new Error('No prompt sets found. Add prompts first.');
- }
-
- const setIds = promptSets.map((ps) => ps.id);
-
- const { data: prompts } = await supabaseAdmin
- .from('prompts')
- .select('id, text, category')
- .in('prompt_set_id', setIds)
- .eq('is_active', true);
-
- if (!prompts?.length) {
- throw new Error('No active prompts found.');
- }
-
- const promptIds = prompts.map((p) => p.id);
-
- // Chunked for the same reason as the volumes route: hundreds of prompt
- // uuids in one query string is the request size the edge starts rejecting
- // (see lib/chunked-in.js). A prompt's rows stay together in one chunk, so
- // the per-prompt ordering the maps below rely on is unchanged.
- const [volumeResult, resultResult, competitorResult] = await Promise.all([
- selectInChunks(promptIds, (chunk) =>
- supabaseAdmin.from('prompt_volumes').select('*').in('prompt_id', chunk),
- ),
- selectInChunks(promptIds, (chunk) =>
- supabaseAdmin
- .from('prompt_results')
- .select(
- 'prompt_id, visibility_score, mention_count, citation_count, sentiment, competitor_mentions',
- )
- .in('prompt_id', chunk)
- .order('created_at', { ascending: false }),
- ),
- supabaseAdmin.from('competitors').select('id, name, domain').eq('brand_id', brandId),
- ]);
-
- const volumes = volumeResult.data || [];
- const results = resultResult.data || [];
- const competitors = competitorResult.data || [];
-
- const volumeMap = {};
- for (const v of volumes) volumeMap[v.prompt_id] = v;
-
- const resultMap = {};
- for (const r of results) {
- if (!resultMap[r.prompt_id]) resultMap[r.prompt_id] = [];
- resultMap[r.prompt_id].push(r);
- }
-
- const testedPrompts = prompts.filter((p) => (resultMap[p.id] || []).length > 0);
- if (!testedPrompts.length) {
- return { generated: 0 };
+ job.progress({ phase: 'collecting_data', message: 'Grouping prompts into clusters...' });
+ try {
+ await refreshPromptClusters(brandId);
+ } catch (err) {
+ logger.error({ err, brandId }, 'prompt cluster refresh failed before generation');
}
- const promptDataForLLM = testedPrompts.map((p, idx) => {
- const vol = volumeMap[p.id];
- const res = resultMap[p.id] || [];
-
- const avgVisibility =
- res.length > 0 ? Math.round(res.reduce((s, r) => s + r.visibility_score, 0) / res.length) : 0;
-
- const competitorMentions = {};
- for (const r of res) {
- if (r.competitor_mentions) {
- const mentions =
- typeof r.competitor_mentions === 'string'
- ? JSON.parse(r.competitor_mentions)
- : r.competitor_mentions;
- for (const cm of mentions || []) {
- competitorMentions[cm.name] =
- (competitorMentions[cm.name] || 0) + (cm.visibility_score || 0);
- }
- }
- }
-
- return {
- index: idx,
- promptId: p.id,
- text: p.text,
- category: p.category || 'unknown',
- estAiVolume: vol?.est_ai_volume || 0,
- intent: vol?.intent || 'other',
- keywords: vol?.keywords || [],
- avgVisibility,
- totalResults: res.length,
- competitorsCited: Object.keys(competitorMentions),
- competitorGap:
- Object.values(competitorMentions).length > 0
- ? Math.round(
- Object.values(competitorMentions).reduce((a, b) => a + b, 0) /
- Object.values(competitorMentions).length,
- ) - avgVisibility
- : 0,
- };
+ const result = await generateContentOpportunities(brandId, {
+ model,
+ onProgress: (p) => job.progress(p),
});
-
- // The button adds to the open list, as the nightly run does (#63), rather
- // than replacing it: prompts at the cap are skipped and the rest show the
- // model what they already hold.
- const existing = await loadOpenOpportunities(brandId);
- const openCounts = openCountsByPrompt(existing);
- const openTitles = openTitlesByPrompt(existing);
-
- const ranked = promptDataForLLM
- .map((p) => ({
- ...p,
- score: computeOpportunityScore(p.estAiVolume, p.avgVisibility, p.competitorGap, p.intent),
- }))
- .sort((a, b) => b.score - a.score);
- const scoredPrompts = belowOpenCap(ranked, openCounts).slice(0, 25);
-
- if (scoredPrompts.length === 0) {
- logger.info(
- { brandId, openOpportunities: existing.length },
- 'every candidate prompt is at its open cap — nothing generated',
- );
- return { generated: 0 };
- }
-
- job.progress({ phase: 'analyzing', message: 'Generating opportunities with AI...' });
-
- const userPrompt = `Brand: ${brand.name}
-Industry: ${brand.industry || 'Not specified'}
-Domain: ${(domains || []).map((d) => d.domain).join(', ') || 'N/A'}
-Competitors: ${competitors.map((c) => c.name).join(', ') || 'None tracked'}
-
-Prompt Data (sorted by opportunity score, highest first):
-${scoredPrompts
- .map(
- (p, i) =>
- `[${i}] "${p.text}" | Category: ${p.category} | Intent: ${p.intent} | Est. AI Volume: ${p.estAiVolume}/mo | Visibility: ${p.avgVisibility}% | Competitor Gap: ${p.competitorGap > 0 ? '+' + p.competitorGap : p.competitorGap}% | Competitors Cited: ${p.competitorsCited.join(', ') || 'none'} | Keywords: ${p.keywords.join(', ')}${alreadySuggested(openTitles.get(p.promptId))}`,
- )
- .join('\n')}
-
-Generate actionable content opportunities based on this data. Reference specific numbers and competitors where relevant.
-
-IMPORTANT: Write every opportunity title and description in ${langName}.`;
-
- const aiModel = resolveModel(model);
-
- const { object } = await generateObject({
- model: aiModel,
- schema: opportunitySchema,
- system: OPPORTUNITY_SYSTEM_PROMPT,
- prompt: userPrompt,
- });
-
- job.progress({ phase: 'saving', message: 'Saving opportunities...' });
-
- const seen = new Set(existing.map((o) => opportunityKey(o.prompt_id, o.title)));
-
- const rows = object.opportunities.flatMap((opp) => {
- const relatedPrompt = relatedCandidate(scoredPrompts, opp.relatedPromptIndex);
- if (!relatedPrompt) return [];
- const key = opportunityKey(relatedPrompt.promptId, opp.title);
- if (seen.has(key)) return [];
- seen.add(key);
- const score = computeOpportunityScore(
- relatedPrompt.estAiVolume,
- relatedPrompt.avgVisibility,
- relatedPrompt.competitorGap,
- relatedPrompt.intent,
- );
-
- return [
- {
- brand_id: brandId,
- prompt_id: relatedPrompt.promptId,
- title: opp.title,
- description: opp.description,
- type: opp.type,
- impact: opp.impact,
- opportunity_score: score,
- status: 'new',
- source_data: {
- promptText: relatedPrompt.text,
- estAiVolume: relatedPrompt.estAiVolume,
- visibilityScore: relatedPrompt.avgVisibility,
- competitorGap: relatedPrompt.competitorGap,
- intent: relatedPrompt.intent,
- keywords: relatedPrompt.keywords,
- competitorsCited: relatedPrompt.competitorsCited,
- },
- },
- ];
- });
-
- const { error: insertErr } =
- rows.length > 0
- ? await supabaseAdmin.from('content_opportunities').insert(rows)
- : { error: null };
-
- if (insertErr) {
- throw new Error(insertErr.message);
- }
-
- logger.info({ brandId, generated: rows.length }, 'content opportunities generated');
-
- return { generated: rows.length };
+ logger.info({ brandId, ...result }, 'content opportunities generated');
+ return result;
}
diff --git a/supabase/migrations/00102_cluster_opportunities.sql b/supabase/migrations/00102_cluster_opportunities.sql
new file mode 100644
index 000000000..9a009e884
--- /dev/null
+++ b/supabase/migrations/00102_cluster_opportunities.sql
@@ -0,0 +1,69 @@
+-- Content opportunities per prompt cluster (#857).
+--
+-- An opportunity now belongs to a prompt cluster (00101) instead of a single
+-- prompt. cluster_id is the cluster it was generated for. related_cluster_ids
+-- holds clusters in other topics found to need the same content: they are
+-- merged into the existing opportunity instead of getting a near-copy of it.
+-- prompt_id stays, set to the cluster's highest-volume prompt, so the prompt
+-- filter, webhooks and briefs keep working until they move to clusters.
+--
+-- Rows from before this change keep cluster_id null.
+
+alter table public.content_opportunities
+ add column cluster_id uuid references public.prompt_clusters(id) on delete set null,
+ add column related_cluster_ids uuid[] not null default '{}';
+
+create index idx_co_cluster_id on public.content_opportunities (cluster_id);
+
+-- Per-prompt visibility for ranking clusters, read from the Insights rollups
+-- (00066) rather than prompt_results: on the largest brand the same figures
+-- from raw answers take about 50 s, from the rollups under one second.
+--
+-- Both rates are shares of the prompt's engine-days in the window: the
+-- brand's is the share where it was mentioned or cited, a competitor's the
+-- share where it was visible. top_competitor_visibility is the strongest
+-- live competitor's rate, and competitors lists up to five, strongest first.
+create or replace function public.brand_prompt_opportunity_metrics(
+ p_brand_id uuid,
+ p_since date
+)
+returns jsonb
+language sql
+stable
+set search_path = public
+as $$
+ with cells as (
+ select prompt_id,
+ count(*) as cells,
+ count(*) filter (where has_mention or has_citation) as visible
+ from insights_prompt_daily
+ where brand_id = p_brand_id and day >= p_since
+ group by prompt_id
+ ),
+ comp as (
+ select d.prompt_id, c.name, count(*) as visible
+ from insights_competitor_prompt_daily d
+ join competitors c on c.id::text = d.competitor_id and c.brand_id = p_brand_id
+ where d.brand_id = p_brand_id and d.day >= p_since
+ group by d.prompt_id, c.name
+ ),
+ top as (
+ select prompt_id,
+ max(visible) as visible,
+ (array_agg(name order by visible desc, name))[1:5] as names
+ from comp
+ group by prompt_id
+ )
+ select coalesce(jsonb_agg(jsonb_build_object(
+ 'prompt_id', c.prompt_id,
+ 'cells', c.cells,
+ 'visibility', round(100.0 * c.visible / c.cells, 1),
+ 'top_competitor_visibility', round(100.0 * coalesce(t.visible, 0) / c.cells, 1),
+ 'competitors', coalesce(to_jsonb(t.names), '[]'::jsonb)
+ )), '[]'::jsonb)
+ from cells c
+ left join top t on t.prompt_id = c.prompt_id;
+$$;
+
+revoke all on function public.brand_prompt_opportunity_metrics(uuid, date) from public, anon, authenticated;
+grant execute on function public.brand_prompt_opportunity_metrics(uuid, date) to service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 5e1d9bbc8..35001b26b 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -11965,3 +11965,76 @@ grant execute on function public.brand_prompt_fanout_queries(uuid, timestamptz,
comment on table public.prompt_clusters is 'Groups of prompts in one topic (or the no-topic scope) that share one intent; the unit content opportunities are generated for (#857).';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00102_cluster_opportunities.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Content opportunities per prompt cluster (#857).
+--
+-- An opportunity now belongs to a prompt cluster (00101) instead of a single
+-- prompt. cluster_id is the cluster it was generated for. related_cluster_ids
+-- holds clusters in other topics found to need the same content: they are
+-- merged into the existing opportunity instead of getting a near-copy of it.
+-- prompt_id stays, set to the cluster's highest-volume prompt, so the prompt
+-- filter, webhooks and briefs keep working until they move to clusters.
+--
+-- Rows from before this change keep cluster_id null.
+
+alter table public.content_opportunities
+ add column cluster_id uuid references public.prompt_clusters(id) on delete set null,
+ add column related_cluster_ids uuid[] not null default '{}';
+
+create index idx_co_cluster_id on public.content_opportunities (cluster_id);
+
+-- Per-prompt visibility for ranking clusters, read from the Insights rollups
+-- (00066) rather than prompt_results: on the largest brand the same figures
+-- from raw answers take about 50 s, from the rollups under one second.
+--
+-- Both rates are shares of the prompt's engine-days in the window: the
+-- brand's is the share where it was mentioned or cited, a competitor's the
+-- share where it was visible. top_competitor_visibility is the strongest
+-- live competitor's rate, and competitors lists up to five, strongest first.
+create or replace function public.brand_prompt_opportunity_metrics(
+ p_brand_id uuid,
+ p_since date
+)
+returns jsonb
+language sql
+stable
+set search_path = public
+as $$
+ with cells as (
+ select prompt_id,
+ count(*) as cells,
+ count(*) filter (where has_mention or has_citation) as visible
+ from insights_prompt_daily
+ where brand_id = p_brand_id and day >= p_since
+ group by prompt_id
+ ),
+ comp as (
+ select d.prompt_id, c.name, count(*) as visible
+ from insights_competitor_prompt_daily d
+ join competitors c on c.id::text = d.competitor_id and c.brand_id = p_brand_id
+ where d.brand_id = p_brand_id and d.day >= p_since
+ group by d.prompt_id, c.name
+ ),
+ top as (
+ select prompt_id,
+ max(visible) as visible,
+ (array_agg(name order by visible desc, name))[1:5] as names
+ from comp
+ group by prompt_id
+ )
+ select coalesce(jsonb_agg(jsonb_build_object(
+ 'prompt_id', c.prompt_id,
+ 'cells', c.cells,
+ 'visibility', round(100.0 * c.visible / c.cells, 1),
+ 'top_competitor_visibility', round(100.0 * coalesce(t.visible, 0) / c.cells, 1),
+ 'competitors', coalesce(to_jsonb(t.names), '[]'::jsonb)
+ )), '[]'::jsonb)
+ from cells c
+ left join top t on t.prompt_id = c.prompt_id;
+$$;
+
+revoke all on function public.brand_prompt_opportunity_metrics(uuid, date) from public, anon, authenticated;
+grant execute on function public.brand_prompt_opportunity_metrics(uuid, date) to service_role;
+
diff --git a/web/messages/en.json b/web/messages/en.json
index a10a73013..818a907b1 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1693,7 +1693,22 @@
"webhookStatus": "Webhook Status",
"notSentYet": "Not sent to any workflow yet.",
"sentAt": "Sent at {date}",
- "webhookResponse": "Webhook Response"
+ "webhookResponse": "Webhook Response",
+ "topCompetitor": "Strongest Competitor",
+ "basketTitle": "Opportunity Basket",
+ "basketSummary": "{prompts, plural, one {# prompt} other {# prompts}} · {included} searches included · {excluded} excluded",
+ "basketIncluded": "Searches AI engines ran for these prompts",
+ "basketShowExcluded": "Show {count} excluded searches",
+ "basketHideExcluded": "Hide excluded searches",
+ "scoreTitle": "Why This Score",
+ "scoreWeight": "{weight}% of score",
+ "scoreWindow": "Measured over the last {days} days.",
+ "score": {
+ "demand": "Demand",
+ "visibilityGap": "Visibility gap",
+ "competitorGap": "Competitor gap",
+ "intent": "Intent"
+ }
},
"webhook": {
"title": "Webhook Settings",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
index 74fbc20b8..c0dcc3a66 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx
@@ -35,6 +35,7 @@ import {
} from '@/lib/actions/content';
import type { ContentBrief, ContentOpportunity } from '@/types';
import { getPromptFanout, type FanoutSubQuery } from '@/lib/actions/fanout';
+import { OpportunityBasketCard, ScoreBreakdown } from '@/components/content/opportunity-basket';
import { toast } from 'sonner';
const IMPACT_COLORS: Record<string, string> = {
@@ -103,7 +104,8 @@ export default function ContentDetailPage() {
.then((opp) => {
setOpportunity(opp);
if (opp.brief) setBrief(opp.brief);
- if (opp.brandId && opp.promptId) {
+ // A cluster opportunity shows its whole basket instead (#857).
+ if (opp.brandId && opp.promptId && !opp.clusterId) {
getPromptFanout(opp.brandId, opp.promptId)
.then((d) => setFanoutQueries(d.subQueries))
.catch(() => setFanoutQueries([]));
@@ -265,13 +267,22 @@ export default function ContentDetailPage() {
</span>
</div>
+ {opportunity.clusterId && (
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
+ <div className="lg:col-span-2">
+ <OpportunityBasketCard opportunityId={opportunity.id} />
+ </div>
+ <ScoreBreakdown sourceData={sd} />
+ </div>
+ )}
+
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">{t('detail.sourceData')}</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
- {sd.promptText && (
+ {sd.promptText && !opportunity.clusterId && (
<StatCard icon={Search} label={t('detail.relatedPrompt')} value={sd.promptText} />
)}
@@ -297,6 +308,13 @@ export default function ContentDetailPage() {
value={`${sd.competitorGap > 0 ? '+' : ''}${Math.round(sd.competitorGap)}%`}
/>
)}
+ {sd.topCompetitorVisibility !== undefined && (
+ <StatCard
+ icon={Users}
+ label={t('detail.topCompetitor')}
+ value={`${Math.round(sd.topCompetitorVisibility)}%`}
+ />
+ )}
{sd.intent && (
<StatCard
icon={Tag}
diff --git a/web/src/components/content/opportunity-basket.tsx b/web/src/components/content/opportunity-basket.tsx
new file mode 100644
index 000000000..c8b169860
--- /dev/null
+++ b/web/src/components/content/opportunity-basket.tsx
@@ -0,0 +1,176 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Layers, Search } from 'lucide-react';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import { getOpportunityBasket } from '@/lib/actions/content';
+import type { ContentOpportunitySourceData, OpportunityBasket } from '@/types';
+
+const SCORE_PARTS = [
+ ['demand', 40],
+ ['visibilityGap', 30],
+ ['competitorGap', 20],
+ ['intent', 10],
+] as const;
+
+/** Why a cluster opportunity scored what it did: each component and its weight. */
+export function ScoreBreakdown({ sourceData }: { sourceData: ContentOpportunitySourceData }) {
+ const t = useTranslations('content.detail');
+ const parts = sourceData.scoreComponents;
+ if (!parts) return null;
+
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">{t('scoreTitle')}</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-2.5">
+ {SCORE_PARTS.map(([key, weight]) => (
+ <div key={key} className="space-y-1">
+ <div className="flex items-center justify-between text-xs">
+ <span>{t(`score.${key}`)}</span>
+ <span className="tabular-nums text-muted-foreground">
+ {Math.round(parts[key])} · {t('scoreWeight', { weight })}
+ </span>
+ </div>
+ <div className="h-1.5 rounded-full bg-muted">
+ <div
+ className="h-1.5 rounded-full bg-primary"
+ style={{ width: `${Math.min(Math.max(parts[key], 0), 100)}%` }}
+ />
+ </div>
+ </div>
+ ))}
+ {sourceData.windowDays && (
+ <p className="text-[11px] text-muted-foreground">
+ {t('scoreWindow', { days: sourceData.windowDays })}
+ </p>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
+
+/**
+ * The prompts a cluster opportunity answers and the searches AI engines ran
+ * for them, included and excluded, read live from the cluster.
+ */
+export function OpportunityBasketCard({ opportunityId }: { opportunityId: string }) {
+ const t = useTranslations('content.detail');
+ const [basket, setBasket] = useState<OpportunityBasket | null>(null);
+ const [failed, setFailed] = useState(false);
+ const [showExcluded, setShowExcluded] = useState(false);
+
+ useEffect(() => {
+ getOpportunityBasket(opportunityId)
+ .then(setBasket)
+ .catch(() => setFailed(true));
+ }, [opportunityId]);
+
+ if (failed) return null;
+
+ const included = basket?.queries.filter((q) => q.included) ?? [];
+ const excluded = basket?.queries.filter((q) => !q.included) ?? [];
+ const promptCount = basket?.clusters.reduce((s, c) => s + c.prompts.length, 0) ?? 0;
+
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <Layers className="h-4 w-4 text-primary" />
+ <CardTitle className="text-sm font-medium">{t('basketTitle')}</CardTitle>
+ {basket && (
+ <span className="text-xs text-muted-foreground">
+ {t('basketSummary', {
+ prompts: promptCount,
+ included: included.length,
+ excluded: excluded.length,
+ })}
+ </span>
+ )}
+ </div>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {!basket ? (
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-1/2" />
+ <Skeleton className="h-16 w-full" />
+ </div>
+ ) : (
+ <>
+ {basket.clusters.map((c) => (
+ <div key={c.id} className="space-y-1.5">
+ <div className="flex flex-wrap items-center gap-2">
+ <p className="text-sm font-medium">{c.label}</p>
+ {c.topicName && (
+ <Badge variant="outline" className="text-[10px]">
+ {c.topicName}
+ </Badge>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground">{c.need}</p>
+ <ul className="space-y-1 text-xs">
+ {c.prompts.map((p) => (
+ <li key={p.id} className="flex gap-2">
+ <span className="text-muted-foreground">•</span>
+ <span>{p.text}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+
+ {included.length > 0 && (
+ <div>
+ <p className="text-xs text-muted-foreground mb-1.5">{t('basketIncluded')}</p>
+ <div className="flex flex-wrap gap-1">
+ {included.map((q) => (
+ <Badge
+ key={q.query}
+ variant="outline"
+ className="text-xs border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400 gap-1"
+ title={q.reason}
+ >
+ <Search className="h-2.5 w-2.5 shrink-0" />
+ {q.query}
+ <span className="opacity-60 tabular-nums">×{q.timesSearched}</span>
+ </Badge>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {excluded.length > 0 && (
+ <div className="space-y-1.5">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-2 text-xs"
+ onClick={() => setShowExcluded((v) => !v)}
+ >
+ {showExcluded
+ ? t('basketHideExcluded')
+ : t('basketShowExcluded', { count: excluded.length })}
+ </Button>
+ {showExcluded && (
+ <ul className="space-y-1 text-xs">
+ {excluded.map((q) => (
+ <li key={q.query}>
+ <span className="text-muted-foreground line-through">{q.query}</span>
+ {q.reason && <span className="text-muted-foreground"> — {q.reason}</span>}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ </>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.ts
index 08d0fec8e..544166f03 100644
--- a/web/src/lib/actions/content.ts
+++ b/web/src/lib/actions/content.ts
@@ -1,7 +1,7 @@
'use server';
import { createClient } from '@/lib/supabase/server';
-import type { ContentBrief, ContentOpportunity, WebhookConfig } from '@/types';
+import type { ContentBrief, ContentOpportunity, OpportunityBasket, WebhookConfig } from '@/types';
import { API_BASE_URL } from '@/config/api';
const AEO_SERVER_URL = API_BASE_URL;
@@ -166,6 +166,22 @@ export async function getOpportunity(id: string): Promise<ContentOpportunity> {
return res.json();
}
+export async function getOpportunityBasket(id: string): Promise<OpportunityBasket> {
+ const session = await getSession();
+
+ const res = await fetch(`${AEO_SERVER_URL}/api/content/${id}/basket`, {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.error || `Server error: ${res.status}`);
+ }
+
+ return res.json();
+}
+
export interface BriefQuota {
used: number;
limit: number;
diff --git a/web/src/types/index.ts b/web/src/types/index.ts
index 6b9da3ffa..90e8d8956 100644
--- a/web/src/types/index.ts
+++ b/web/src/types/index.ts
@@ -188,6 +188,35 @@ export interface ContentOpportunitySourceData {
intent?: string;
keywords?: string[];
competitorsCited?: string[];
+ // Cluster opportunities (#857).
+ clusterLabel?: string;
+ topicName?: string | null;
+ relatedTopics?: (string | null)[];
+ prompts?: string[];
+ topCompetitorVisibility?: number;
+ queries?: {
+ included: number;
+ excluded: number;
+ top: { query: string; timesSearched: number }[];
+ };
+ scoreComponents?: {
+ demand: number;
+ visibilityGap: number;
+ competitorGap: number;
+ intent: number;
+ };
+ windowDays?: number;
+}
+
+export interface OpportunityBasket {
+ clusters: {
+ id: string;
+ label: string;
+ need: string;
+ topicName: string | null;
+ prompts: { id: string; text: string }[];
+ }[];
+ queries: { query: string; timesSearched: number; included: boolean; reason: string }[];
}
export interface ContentBrief {
@@ -204,6 +233,7 @@ export interface ContentOpportunity {
id: string;
brandId: string;
promptId?: string;
+ clusterId?: string | null;
title: string;
description?: string;
type: ContentOpportunityType;