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(insights): add the Opportunities card with relevance and Track (#1046)

Cihan4be87eaacdb9
diff --git a/server/src/config/plans.js b/server/src/config/plans.js
index 9484beff0..e4a8a8099 100644
--- a/server/src/config/plans.js
+++ b/server/src/config/plans.js
@@ -16,6 +16,7 @@ export const PLANS = {
maxVolumeAnalyses: -1,
maxBriefGenerations: -1,
improveMonthlyBudgetUsd: -1,
+ relevanceMonthlyBudgetUsd: -1,
maxOpportunitiesPerMonth: -1,
maxOpportunitiesPerRequest: 5,
maxSiteAudits: -1,
@@ -50,6 +51,8 @@ export const PLANS = {
maxVolumeAnalyses: 4,
maxBriefGenerations: 10,
improveMonthlyBudgetUsd: 0,
+ // 0.1% of the $49 price, spent rating suggestions' relevance (VIS-011).
+ relevanceMonthlyBudgetUsd: 0.049,
maxOpportunitiesPerMonth: 10,
maxOpportunitiesPerRequest: 3,
maxSiteAudits: 100,
@@ -85,6 +88,8 @@ export const PLANS = {
maxBriefGenerations: 50,
// 1% of the $249 price, spent on Improve model calls (PROMPT-003).
improveMonthlyBudgetUsd: 2.49,
+ // 0.1% of the $249 price, spent rating suggestions' relevance (VIS-011).
+ relevanceMonthlyBudgetUsd: 0.249,
maxOpportunitiesPerMonth: 50,
maxOpportunitiesPerRequest: 5,
maxSiteAudits: 500,
@@ -125,6 +130,9 @@ export const PLANS = {
// 1% of the $499 floor. plan_overrides.contractMonthlyUsd raises it to 1%
// of the contract; an explicit plan_overrides.improveMonthlyBudgetUsd wins.
improveMonthlyBudgetUsd: 4.99,
+ // 0.1% of the $499 floor, raised to 0.1% of contractMonthlyUsd; an
+ // explicit plan_overrides.relevanceMonthlyBudgetUsd wins.
+ relevanceMonthlyBudgetUsd: 0.499,
maxOpportunitiesPerMonth: -1,
maxOpportunitiesPerRequest: 5,
maxSiteAudits: -1,
diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.js
index 9b7831fb1..ba617f925 100644
--- a/server/src/lib/plan-guard.js
+++ b/server/src/lib/plan-guard.js
@@ -13,6 +13,7 @@ import {
medianCost,
typicalCostUsd,
} from './improve-cost.js';
+import { RELEVANCE_BUDGET_SHARE } from './suggestion-relevance.js';
export class PlanLimitError extends Error {
constructor(message, statusCode = 403) {
@@ -29,7 +30,9 @@ export class PlanLimitError extends Error {
* `contractMonthlyUsd` is the contract's monthly value, entered when the deal
* is signed. It sets the Improve budget to the same 1% share of the contract
* the other plans get of their price (never below the plan default), unless
- * `improveMonthlyBudgetUsd` is set explicitly, which wins.
+ * `improveMonthlyBudgetUsd` is set explicitly, which wins. The relevance
+ * budget (VIS-011) follows the same rule at 0.1%, rounded down so it never
+ * passes the share.
*/
export function applyPlanOverrides(plan, org) {
if (
@@ -47,6 +50,12 @@ export function applyPlanOverrides(plan, org) {
Math.round(usd * IMPROVE_BUDGET_SHARE * 100) / 100,
);
}
+ if (overrides.relevanceMonthlyBudgetUsd === undefined && Number.isFinite(usd) && usd > 0) {
+ limits.relevanceMonthlyBudgetUsd = Math.max(
+ plan.limits.relevanceMonthlyBudgetUsd ?? 0,
+ Math.floor(usd * RELEVANCE_BUDGET_SHARE * 1e6) / 1e6,
+ );
+ }
return { ...plan, limits };
}
return plan;
@@ -336,6 +345,50 @@ export async function enforceImproveQuota(orgId, modelId) {
return quota;
}
+/**
+ * Suggestion-relevance allowance (VIS-011): a monthly USD budget per
+ * organization, 0.1% of the plan price (plan.limits.relevanceMonthlyBudgetUsd),
+ * separate from Improve's. Reserves a refresh's worst case (`costUsd`)
+ * before it rates, atomically per organization
+ * (reserve_suggestion_relevance), so concurrent refreshes can't overshoot.
+ * Returns { unlimited, id }: id is the usage row to settle once the model
+ * answers (settleRelevanceUsage), or null when what's left can't cover it.
+ */
+export async function reserveRelevanceAllowance(orgId, { brandId, modelId, costUsd }) {
+ const plan = await resolveOrgPlanByOrgId(orgId);
+ const budget = plan.limits.relevanceMonthlyBudgetUsd ?? -1;
+ if (budget === -1) return { unlimited: true, id: null };
+
+ const { data, error } = await supabaseAdmin.rpc('reserve_suggestion_relevance', {
+ p_organization_id: orgId,
+ p_brand_id: brandId,
+ p_model: modelId,
+ p_since: (await quotaPeriodStart(orgId)).toISOString(),
+ p_budget: budget,
+ p_cost: costUsd,
+ });
+ if (error) throw new Error(error.message);
+ return { unlimited: false, id: data ?? null };
+}
+
+/**
+ * Lowers a reservation to what the refresh's attempts cost, with the call's
+ * own tokens to check the estimate against. A failed update leaves the
+ * worst case charged: the budget errs high, never low.
+ */
+export async function settleRelevanceUsage(id, { attempts, costUsd, usage }) {
+ const { error } = await supabaseAdmin
+ .from('suggestion_relevance_usage')
+ .update({
+ attempts,
+ cost_usd: costUsd,
+ input_tokens: usage?.inputTokens ?? null,
+ output_tokens: usage?.outputTokens ?? null,
+ })
+ .eq('id', id);
+ if (error) throw new Error(error.message);
+}
+
async function countOpportunityUsage(orgId, since) {
const { count } = await supabaseAdmin
.from('opportunity_usage')
diff --git a/server/src/lib/plan-guard.test.js b/server/src/lib/plan-guard.test.js
index 4065b84a6..53fe2f7c4 100644
--- a/server/src/lib/plan-guard.test.js
+++ b/server/src/lib/plan-guard.test.js
@@ -76,3 +76,40 @@ describe('applyPlanOverrides — Improve budget from the contract value', () =>
expect(budget({ contractMonthlyUsd: 'n/a' })).toBe(4.99);
});
});
+
+describe('applyPlanOverrides — relevance allowance from the contract value', () => {
+ const enterprise = {
+ id: 'enterprise',
+ name: 'Enterprise',
+ limits: { maxPrompts: -1, improveMonthlyBudgetUsd: 4.99, relevanceMonthlyBudgetUsd: 0.499 },
+ };
+ const limits = (plan_overrides) =>
+ applyPlanOverrides(enterprise, { plan: 'enterprise', plan_overrides }).limits;
+
+ it('is 0.1% of the monthly contract, rounded down', () => {
+ expect(limits({ contractMonthlyUsd: 1000 }).relevanceMonthlyBudgetUsd).toBe(1);
+ expect(limits({ contractMonthlyUsd: 1234.5678 }).relevanceMonthlyBudgetUsd).toBe(1.234567);
+ });
+
+ it('never drops below the plan default, and an explicit value wins', () => {
+ expect(limits({ contractMonthlyUsd: 300 }).relevanceMonthlyBudgetUsd).toBe(0.499);
+ expect(
+ limits({ contractMonthlyUsd: 2000, relevanceMonthlyBudgetUsd: 0.5 })
+ .relevanceMonthlyBudgetUsd,
+ ).toBe(0.5);
+ });
+
+ it('leaves the Improve budget at its own 1%', () => {
+ expect(limits({ contractMonthlyUsd: 1000 }).improveMonthlyBudgetUsd).toBe(10);
+ });
+});
+
+describe('relevance allowance per plan', () => {
+ it('is 0.1% of each plan price, unlimited on self-hosted', async () => {
+ const { PLANS } = await import('../config/plans.js');
+ expect(PLANS.starter.limits.relevanceMonthlyBudgetUsd).toBe(0.049);
+ expect(PLANS.growth.limits.relevanceMonthlyBudgetUsd).toBe(0.249);
+ expect(PLANS.enterprise.limits.relevanceMonthlyBudgetUsd).toBe(0.499);
+ expect(PLANS.self_hosted.limits.relevanceMonthlyBudgetUsd).toBe(-1);
+ });
+});
diff --git a/server/src/lib/relevance-allowance.test.js b/server/src/lib/relevance-allowance.test.js
new file mode 100644
index 000000000..ae9c706c8
--- /dev/null
+++ b/server/src/lib/relevance-allowance.test.js
@@ -0,0 +1,129 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// The suggestion-relevance allowance (VIS-011) in plan-guard.js: 0.1% of the
+// plan price a month, reserved atomically before a refresh rates and settled
+// to what it cost after.
+
+const rpc = vi.fn();
+const tables = {};
+let updates = [];
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ rpc: (...a) => rpc(...a),
+ from: (table) => tables[table](),
+ },
+}));
+
+const { reserveRelevanceAllowance, settleRelevanceUsage } = await import('./plan-guard.js');
+
+/** A query builder that resolves to `result` however it is chained. */
+function chain(result) {
+ const b = {
+ select: () => b,
+ eq: () => b,
+ update: (row) => {
+ updates.push(row);
+ return b;
+ },
+ single: () => Promise.resolve(result),
+ maybeSingle: () => Promise.resolve(result),
+ then: (resolve) => resolve(result),
+ };
+ return b;
+}
+
+function org(plan) {
+ tables.organizations = () =>
+ chain({
+ data: {
+ plan,
+ subscription_status: 'active',
+ subscription_ends_at: '2026-11-12T00:00:00.000Z',
+ plan_overrides: null,
+ },
+ });
+}
+
+beforeEach(() => {
+ process.env.IS_CLOUD = 'true';
+ rpc.mockReset();
+ updates = [];
+ // Inside the subscription period that renews on the 12th.
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-20T00:00:00.000Z'));
+});
+
+afterEach(() => {
+ delete process.env.IS_CLOUD;
+ vi.useRealTimers();
+});
+
+describe('reserveRelevanceAllowance', () => {
+ it('reserves the cost against 0.1% of the plan price for the period', async () => {
+ org('starter');
+ rpc.mockResolvedValue({ data: 'r1', error: null });
+
+ const reservation = await reserveRelevanceAllowance('o1', {
+ brandId: 'b1',
+ modelId: 'google/gemini-3-flash-preview',
+ costUsd: 0.0047,
+ });
+
+ expect(reservation).toEqual({ unlimited: false, id: 'r1' });
+ expect(rpc).toHaveBeenCalledWith('reserve_suggestion_relevance', {
+ p_organization_id: 'o1',
+ p_brand_id: 'b1',
+ p_model: 'google/gemini-3-flash-preview',
+ p_since: '2026-10-12T00:00:00.000Z',
+ p_budget: 0.049,
+ p_cost: 0.0047,
+ });
+ });
+
+ it('gives no id when what is left can’t cover it', async () => {
+ org('growth');
+ rpc.mockResolvedValue({ data: null, error: null });
+ expect(await reserveRelevanceAllowance('o1', { costUsd: 1 })).toEqual({
+ unlimited: false,
+ id: null,
+ });
+ });
+
+ it('reserves nothing when self-hosted', async () => {
+ delete process.env.IS_CLOUD;
+ expect(await reserveRelevanceAllowance('o1', { costUsd: 1 })).toEqual({
+ unlimited: true,
+ id: null,
+ });
+ expect(rpc).not.toHaveBeenCalled();
+ });
+
+ it('throws when the reservation fails, so the caller can skip rating', async () => {
+ org('starter');
+ rpc.mockResolvedValue({ data: null, error: { message: 'lock timeout' } });
+ await expect(reserveRelevanceAllowance('o1', { costUsd: 0.001 })).rejects.toThrow(
+ 'lock timeout',
+ );
+ });
+});
+
+describe('settleRelevanceUsage', () => {
+ it('lowers the row to what the attempts cost, with the call’s tokens', async () => {
+ tables.suggestion_relevance_usage = () => chain({ error: null });
+ await settleRelevanceUsage('r1', {
+ attempts: 1,
+ costUsd: 0.0016,
+ usage: { inputTokens: 5000, outputTokens: 2400 },
+ });
+ expect(updates).toEqual([
+ { attempts: 1, cost_usd: 0.0016, input_tokens: 5000, output_tokens: 2400 },
+ ]);
+ });
+
+ it('throws when the update fails, leaving the worst case charged', async () => {
+ tables.suggestion_relevance_usage = () => chain({ error: { message: 'denied' } });
+ await expect(settleRelevanceUsage('r1', { attempts: 3, costUsd: 0.0047 })).rejects.toThrow(
+ 'denied',
+ );
+ });
+});
diff --git a/server/src/lib/suggestion-relevance.js b/server/src/lib/suggestion-relevance.js
new file mode 100644
index 000000000..ee5242bda
--- /dev/null
+++ b/server/src/lib/suggestion-relevance.js
@@ -0,0 +1,46 @@
+import { generationCostUsd } from './improve-cost.js';
+
+/**
+ * How relevant a suggested prompt is to the brand (VIS-011). The refresh's
+ * model rates each suggestion 0–10 in the same answer that writes it: a whole
+ * number is a few output tokens per suggestion, where a second call to judge
+ * the list would cost about as much as the refresh itself. Stored 0–1, the
+ * scale of the Insights Opportunities card's 0.6 threshold.
+ */
+export const RELEVANCE_SCALE = 10;
+
+/**
+ * Share of the plan price that rating relevance may add to suggestion
+ * refreshes each month (plan.limits.relevanceMonthlyBudgetUsd).
+ */
+export const RELEVANCE_BUDGET_SHARE = 0.001;
+
+/**
+ * What rating adds to one refresh attempt, rounded up so the budget is
+ * charged at least what was spent: the rule and the schema field in the
+ * input (~85 tokens); per suggestion in the output, `"relevance": 10,`
+ * (~5 tokens) and the model's reasoning about it, which thinking models such
+ * as Gemini 3 Flash bill as output (allowed ~15). The usage rows keep each
+ * call's real tokens to check this against.
+ */
+export const RATING_TOKENS = { input: 120, perSuggestion: 20 };
+
+/**
+ * The model's rating as stored: rounded to a whole step and clamped, so an
+ * out-of-range rating caps instead of failing the whole generated batch.
+ * Null when the model gave none.
+ */
+export function toRelevance(rating) {
+ if (rating === null || rating === undefined || rating === '') return null;
+ const n = Number(rating);
+ if (!Number.isFinite(n)) return null;
+ return Math.min(RELEVANCE_SCALE, Math.max(0, Math.round(n))) / RELEVANCE_SCALE;
+}
+
+/** USD that rating adds to a refresh of `attempts` model calls. */
+export function ratingCostUsd(modelId, { suggestions, attempts }) {
+ return generationCostUsd(modelId, {
+ inputTokens: RATING_TOKENS.input * attempts,
+ outputTokens: RATING_TOKENS.perSuggestion * suggestions * attempts,
+ });
+}
diff --git a/server/src/lib/suggestion-relevance.test.js b/server/src/lib/suggestion-relevance.test.js
new file mode 100644
index 000000000..4f274c0d9
--- /dev/null
+++ b/server/src/lib/suggestion-relevance.test.js
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+import { RATING_TOKENS, ratingCostUsd, toRelevance } from './suggestion-relevance.js';
+
+describe('toRelevance', () => {
+ it('stores the 0–10 rating on a 0–1 scale', () => {
+ expect([0, 6, 8, 10].map(toRelevance)).toEqual([0, 0.6, 0.8, 1]);
+ });
+
+ it('rounds a fractional rating to a whole step', () => {
+ expect(toRelevance(7.4)).toBe(0.7);
+ expect(toRelevance(5.5)).toBe(0.6);
+ });
+
+ it('caps an out-of-range rating instead of rejecting it', () => {
+ expect(toRelevance(14)).toBe(1);
+ expect(toRelevance(-2)).toBe(0);
+ });
+
+ it('is null when the model gave no rating', () => {
+ expect([undefined, null, '', 'high', Number.NaN].map(toRelevance)).toEqual([
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ });
+});
+
+describe('ratingCostUsd', () => {
+ it('charges the rule once and the field per suggestion, for every attempt', () => {
+ // Gemini 3 Flash: $0.50 in, $3 out per million tokens.
+ const one = (RATING_TOKENS.input * 0.5 + 25 * RATING_TOKENS.perSuggestion * 3) / 1e6;
+ const model = 'google/gemini-3-flash-preview';
+ expect(ratingCostUsd(model, { suggestions: 25, attempts: 1 })).toBeCloseTo(one, 12);
+ expect(ratingCostUsd(model, { suggestions: 25, attempts: 3 })).toBeCloseTo(3 * one, 12);
+ });
+
+ it('leaves a Starter month room for about 30 refreshes', () => {
+ const model = 'google/gemini-3-flash-preview';
+ const once = ratingCostUsd(model, { suggestions: 25, attempts: 1 });
+ const worstCase = ratingCostUsd(model, { suggestions: 25, attempts: 3 });
+ // 0.1% of $49: ~30 refreshes, and still 10 if every one retried twice.
+ expect(Math.floor(0.049 / once)).toBeGreaterThanOrEqual(30);
+ expect(Math.floor(0.049 / worstCase)).toBeGreaterThanOrEqual(10);
+ });
+});
diff --git a/server/src/routes/prompts-suggestions-refresh.test.js b/server/src/routes/prompts-suggestions-refresh.test.js
new file mode 100644
index 000000000..81505fde2
--- /dev/null
+++ b/server/src/routes/prompts-suggestions-refresh.test.js
@@ -0,0 +1,229 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * POST /api/prompts/suggestions/:brandId/refresh with relevance (VIS-011).
+ * Rating rides along in the same model call only once its worst case is
+ * reserved against the org's monthly allowance (0.1% of the plan price), and
+ * the reservation is then settled to every attempt made, so the month can't
+ * pass the budget.
+ */
+
+const reserveRelevanceAllowance = vi.fn();
+const settleRelevanceUsage = vi.fn();
+const generateObject = vi.fn();
+let db;
+
+function table(name) {
+ let op = 'select';
+ let row = null;
+ const result = (single = false) => {
+ if (op === 'insert') {
+ db.inserts.push({ table: name, row });
+ return { data: name === 'prompt_suggestions' ? row : null, error: null };
+ }
+ if (op === 'delete') return { data: null, error: null };
+ if (name === 'brands') {
+ const brand = { id: 'b1', name: 'Acme', language: 'en', organization_id: 'o1' };
+ return { data: brand, error: null };
+ }
+ if (name === 'profiles') return { data: { organization_id: 'o1' }, error: null };
+ // The topic lookup for each suggestion finds one; the topic list is empty.
+ if (name === 'topics') return { data: single ? { id: 't1' } : [], error: null };
+ return { data: [], error: null };
+ };
+ const chain = new Proxy(
+ {},
+ {
+ get: (_t, prop) => {
+ if (prop === 'then') {
+ return (resolve, reject) => Promise.resolve(result()).then(resolve, reject);
+ }
+ if (prop === 'single' || prop === 'maybeSingle') return async () => result(true);
+ if (prop === 'insert') {
+ return (r) => {
+ op = 'insert';
+ row = r;
+ return chain;
+ };
+ }
+ if (prop === 'delete') {
+ return () => {
+ op = 'delete';
+ return chain;
+ };
+ }
+ return () => chain;
+ },
+ },
+ );
+ return chain;
+}
+
+vi.mock('../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));
+vi.mock('../lib/plan-guard.js', () => ({
+ PlanLimitError: class extends Error {},
+ enforceFeature: vi.fn(),
+ enforceImproveQuota: vi.fn(),
+ getImproveQuotaStatus: vi.fn(),
+ requireFeature: () => (req, res, next) => next(),
+ reserveRelevanceAllowance,
+ settleRelevanceUsage,
+}));
+vi.mock('ai', () => ({ generateObject, NoObjectGeneratedError: class extends Error {} }));
+vi.mock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn(() => 'model') }));
+vi.mock('../lib/gsc-suggestions.js', () => ({ getGscSuggestionCandidates: async () => [] }));
+vi.mock('../lib/ga-suggestions.js', () => ({ getGaSuggestionCandidates: async () => [] }));
+// Retries without the real backoff delay.
+vi.mock('../lib/retry.js', () => ({
+ withRetry: async (fn, { attempts }) => {
+ let last;
+ for (let i = 0; i < attempts; i += 1) {
+ try {
+ return await fn();
+ } catch (err) {
+ last = err;
+ }
+ }
+ throw last;
+ },
+}));
+
+const { ratingCostUsd } = await import('../lib/suggestion-relevance.js');
+const { default: router } = await import('./prompts.js');
+
+const MODEL = 'google/gemini-3-flash-preview';
+const suggestion = (i, extra = {}) => ({
+ text: `how do teams track brand visibility in ai answers ${i}`,
+ topic: 'AI visibility',
+ reason: 'Competitors are already cited for this question in AI answers.',
+ estVolume: 1000 + i,
+ ...extra,
+});
+const answer = (extra) => ({
+ object: { suggestions: Array.from({ length: 15 }, (_, i) => suggestion(i, extra)) },
+ usage: { inputTokens: 5000, outputTokens: 2400 },
+});
+
+let server;
+let baseUrl;
+const modelEnv = process.env.PROMPT_SUGGESTION_MODEL;
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ delete process.env.PROMPT_SUGGESTION_MODEL;
+ db = { inserts: [] };
+ reserveRelevanceAllowance.mockResolvedValue({ unlimited: false, id: 'r1' });
+ settleRelevanceUsage.mockResolvedValue();
+ generateObject.mockResolvedValue(answer({ relevance: 8 }));
+
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.user = { id: 'u1' };
+ req.log = { error: vi.fn(), info: vi.fn() };
+ next();
+ });
+ app.use('/api/prompts', router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/api/prompts`;
+});
+
+afterEach(async () => {
+ await new Promise((resolve) => server.close(resolve));
+ if (modelEnv === undefined) delete process.env.PROMPT_SUGGESTION_MODEL;
+ else process.env.PROMPT_SUGGESTION_MODEL = modelEnv;
+});
+
+const refresh = () => fetch(`${baseUrl}/suggestions/b1/refresh`, { method: 'POST' });
+const insertsInto = (name) => db.inserts.filter((i) => i.table === name).map((i) => i.row);
+const askedForRelevance = (call = 0) => {
+ const { schema, system } = generateObject.mock.calls[call][0];
+ return {
+ schema: 'relevance' in schema.shape.suggestions.element.shape,
+ rule: /- relevance:/.test(system),
+ };
+};
+
+describe('suggestion refresh relevance', () => {
+ it('reserves the worst case, rates in the same call, then settles to what it cost', async () => {
+ const res = await refresh();
+
+ expect(res.status).toBe(200);
+ expect(generateObject).toHaveBeenCalledTimes(1);
+ expect(askedForRelevance()).toEqual({ schema: true, rule: true });
+ expect(reserveRelevanceAllowance).toHaveBeenCalledWith('o1', {
+ brandId: 'b1',
+ modelId: MODEL,
+ costUsd: ratingCostUsd(MODEL, { suggestions: 25, attempts: 3 }),
+ });
+
+ const [rows] = insertsInto('prompt_suggestions');
+ expect(rows.every((r) => r.relevance === 0.8)).toBe(true);
+ expect(settleRelevanceUsage).toHaveBeenCalledWith('r1', {
+ attempts: 1,
+ usage: { inputTokens: 5000, outputTokens: 2400 },
+ costUsd: ratingCostUsd(MODEL, { suggestions: 25, attempts: 1 }),
+ });
+ });
+
+ it('leaves relevance out when the allowance can’t cover a refresh', async () => {
+ reserveRelevanceAllowance.mockResolvedValue({ unlimited: false, id: null });
+ generateObject.mockResolvedValue(answer());
+
+ expect((await refresh()).status).toBe(200);
+ expect(askedForRelevance()).toEqual({ schema: false, rule: false });
+ const [rows] = insertsInto('prompt_suggestions');
+ expect(rows.every((r) => r.relevance === null)).toBe(true);
+ expect(settleRelevanceUsage).not.toHaveBeenCalled();
+ });
+
+ it('rates nothing when the allowance can’t be reserved', async () => {
+ reserveRelevanceAllowance.mockRejectedValue(new Error('db down'));
+ generateObject.mockResolvedValue(answer());
+
+ expect((await refresh()).status).toBe(200);
+ expect(askedForRelevance()).toEqual({ schema: false, rule: false });
+ expect(settleRelevanceUsage).not.toHaveBeenCalled();
+ });
+
+ it('rates without charging anything on an unlimited plan', async () => {
+ reserveRelevanceAllowance.mockResolvedValue({ unlimited: true, id: null });
+
+ expect((await refresh()).status).toBe(200);
+ expect(askedForRelevance()).toEqual({ schema: true, rule: true });
+ expect(settleRelevanceUsage).not.toHaveBeenCalled();
+ });
+
+ it('settles every attempt, a failed one too', async () => {
+ generateObject
+ .mockRejectedValueOnce(new Error('No object generated'))
+ .mockResolvedValueOnce(answer({ relevance: 7 }));
+
+ expect((await refresh()).status).toBe(200);
+ expect(settleRelevanceUsage).toHaveBeenCalledWith('r1', {
+ attempts: 2,
+ usage: { inputTokens: 5000, outputTokens: 2400 },
+ costUsd: ratingCostUsd(MODEL, { suggestions: 25, attempts: 2 }),
+ });
+ });
+
+ it('settles the attempts of a refresh that failed outright', async () => {
+ generateObject.mockRejectedValue(new Error('No object generated'));
+
+ expect((await refresh()).status).toBe(500);
+ expect(generateObject).toHaveBeenCalledTimes(3);
+ expect(settleRelevanceUsage).toHaveBeenCalledWith('r1', {
+ attempts: 3,
+ usage: undefined,
+ costUsd: ratingCostUsd(MODEL, { suggestions: 25, attempts: 3 }),
+ });
+ });
+
+ it('still answers when settling fails, leaving the worst case charged', async () => {
+ settleRelevanceUsage.mockRejectedValue(new Error('db down'));
+ expect((await refresh()).status).toBe(200);
+ });
+});
diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.js
index 5fa6d8d94..823afec10 100644
--- a/server/src/routes/prompts.js
+++ b/server/src/routes/prompts.js
@@ -11,10 +11,13 @@ import {
enforceImproveQuota,
getImproveQuotaStatus,
requireFeature,
+ reserveRelevanceAllowance,
+ settleRelevanceUsage,
} from '../lib/plan-guard.js';
import { withRetry } from '../lib/retry.js';
import { getGscSuggestionCandidates } from '../lib/gsc-suggestions.js';
import { getGaSuggestionCandidates } from '../lib/ga-suggestions.js';
+import { RELEVANCE_SCALE, ratingCostUsd, toRelevance } from '../lib/suggestion-relevance.js';
import {
ACTIONABLE_STATES,
IMPROVE_PLATFORM_LABELS,
@@ -209,9 +212,70 @@ const newSuggestionSchema = z.object({
.max(SUGGESTIONS_PER_REFRESH),
});
+// Relevance (VIS-011), asked for while the org's monthly allowance covers it.
+// No bounds, for the same reason as estVolume: toRelevance clamps at the insert.
+const ratedSuggestionSchema = z.object({
+ suggestions: z
+ .array(
+ newSuggestionSchema.shape.suggestions.element.extend({
+ relevance: z
+ .number()
+ .describe(
+ `How closely this prompt fits what the brand offers and who it serves, 0-${RELEVANCE_SCALE}`,
+ ),
+ }),
+ )
+ .min(MIN_SUGGESTIONS)
+ .max(SUGGESTIONS_PER_REFRESH),
+});
+
const SUGGESTION_TTL_HOURS = 48;
-async function generateSuggestions(brandId) {
+/** Model calls one refresh may make (withRetry's attempts). */
+const REFRESH_ATTEMPTS = 3;
+
+/**
+ * Reserves rating for this refresh (VIS-011): its worst case, every retry,
+ * against the org's monthly allowance. Null when that doesn't fit or the
+ * allowance can't be read: the refresh then leaves relevance out rather than
+ * risk the budget.
+ */
+async function reserveRating(orgId, brandId, modelId, log) {
+ try {
+ const reservation = await reserveRelevanceAllowance(orgId, {
+ brandId,
+ modelId,
+ costUsd: ratingCostUsd(modelId, {
+ suggestions: SUGGESTIONS_PER_REFRESH,
+ attempts: REFRESH_ATTEMPTS,
+ }),
+ });
+ return reservation.unlimited || reservation.id ? reservation : null;
+ } catch (err) {
+ log.error({ err }, 'suggestion relevance allowance error');
+ return null;
+ }
+}
+
+/**
+ * Lowers the reservation to what rating added to the attempts made, failed
+ * ones included. A failure is logged, not thrown: the suggestions the user
+ * asked for still go out, and the worst case stays charged.
+ */
+async function settleRating(log, reservation, { modelId, attempts, usage }) {
+ if (!reservation.id) return;
+ try {
+ await settleRelevanceUsage(reservation.id, {
+ attempts,
+ usage,
+ costUsd: ratingCostUsd(modelId, { suggestions: SUGGESTIONS_PER_REFRESH, attempts }),
+ });
+ } catch (err) {
+ log.error({ err }, 'suggestion relevance usage settle error');
+ }
+}
+
+async function generateSuggestions(brandId, { orgId, log }) {
const ctx = await loadSuggestionContext(brandId);
const langName = getLanguageName(ctx.brand.language);
const currentYear = new Date().getFullYear();
@@ -229,6 +293,11 @@ async function generateSuggestions(brandId) {
// brands that have neither.
const gaCandidates = await getGaSuggestionCandidates(brandId, ctx.existingPromptTexts);
+ const promptModel = process.env.PROMPT_SUGGESTION_MODEL || 'google/gemini-3-flash-preview';
+ const aiModel = resolveModel(promptModel);
+ const reservation = await reserveRating(orgId, brandId, promptModel, log);
+ const rate = reservation !== null;
+
const system = `You are an AEO (Answer Engine Optimization) strategist. You suggest NEW search prompts a brand should track in AI engines (ChatGPT, Perplexity, Gemini, Claude). Current year: ${currentYear}.
RULES:
@@ -239,7 +308,12 @@ RULES:
- Pick prompts where the brand could realistically appear AND where its competitors are already getting cited.
- Volume bias: prioritize prompt ideas that resemble (in topic and intent) the HIGH-volume prompts already tracked. Avoid suggesting prompts close in topic to LOW-volume ones unless there is a strong competitor gap.
- estVolume must be a realistic monthly AI search volume; calibrate it against the volume samples shown — do not output flat round numbers like 1000 for everything.
-- Reasons must be concrete: cite the gap, the trend, or the competitor activity. Avoid generic platitudes.
+- Reasons must be concrete: cite the gap, the trend, or the competitor activity. Avoid generic platitudes.${
+ rate
+ ? `
+- relevance: a whole number 0-${RELEVANCE_SCALE}. ${RELEVANCE_SCALE} = the brand's core offering, 6 = adjacent but a realistic fit, below 6 = off its business. Be strict.`
+ : ''
+ }
- Diversity: mix comparison, how-to, best-of, recommendation, and problem-solving intents.${
gscCandidates.length
? `
@@ -308,25 +382,30 @@ ${gaCandidates
Suggest the next ${SUGGESTIONS_PER_REFRESH} prompts this brand should start tracking, with topic, reason and a calibrated monthly AI search volume (estVolume).`;
- const promptModel = process.env.PROMPT_SUGGESTION_MODEL || 'google/gemini-3-flash-preview';
- const aiModel = resolveModel(promptModel);
-
// #379 pattern — bounded retry: generateObject throws "No object generated:
// response did not match schema" when the model misses a constraint (short
// reason, <6 items, non-integer estVolume, …); a fresh sample usually
// passes, so one miss must not fail the whole refresh.
- const { object } = await withRetry(
- () =>
- generateObject({
- model: aiModel,
- schema: newSuggestionSchema,
- system,
- prompt: userPrompt,
- }),
- { attempts: 3, baseDelayMs: 500, label: 'suggestion-refresh' },
- );
-
- return { suggestions: object.suggestions, gscCandidates, gaCandidates };
+ let attempts = 0;
+ let usage;
+ try {
+ const { object, usage: callUsage } = await withRetry(
+ () => {
+ attempts += 1;
+ return generateObject({
+ model: aiModel,
+ schema: rate ? ratedSuggestionSchema : newSuggestionSchema,
+ system,
+ prompt: userPrompt,
+ });
+ },
+ { attempts: REFRESH_ATTEMPTS, baseDelayMs: 500, label: 'suggestion-refresh' },
+ );
+ usage = callUsage;
+ return { suggestions: object.suggestions, gscCandidates, gaCandidates };
+ } finally {
+ if (rate) await settleRating(log, reservation, { modelId: promptModel, attempts, usage });
+ }
}
async function findOrCreateTopic(brandId, topicName) {
@@ -353,9 +432,10 @@ router.post(
requireFeature('prompt_suggestions'),
async (req, res) => {
try {
- await assertBrandAccess(req.params.brandId, req.user.id);
+ const { brand } = await assertBrandAccess(req.params.brandId, req.user.id);
const { suggestions, gscCandidates, gaCandidates } = await generateSuggestions(
req.params.brandId,
+ { orgId: brand.organization_id, log: req.log },
);
await supabaseAdmin
@@ -397,6 +477,7 @@ router.post(
// Sanity clamp replacing the removed schema ceiling — one absurd
// estimate must cap out, not reject the whole generated batch.
est_volume: Math.min(s.estVolume, 10_000_000),
+ relevance: toRelevance(s.relevance),
source: candidate ? 'gsc' : gaCandidate ? 'ga' : 'llm',
source_data: candidate
? {
diff --git a/supabase/migrations/00138_prompt_suggestion_relevance.sql b/supabase/migrations/00138_prompt_suggestion_relevance.sql
new file mode 100644
index 000000000..059f9d675
--- /dev/null
+++ b/supabase/migrations/00138_prompt_suggestion_relevance.sql
@@ -0,0 +1,92 @@
+-- Relevance of a prompt suggestion to the brand (VIS-011).
+--
+-- The Insights Opportunities card ranks suggestions by relevance × demand ×
+-- gap and hides any under a fixed 0.6 (Visibility spec v2). The refresh's
+-- model already writes each suggestion; relevance is one more field of that
+-- same answer, stored 0–1. Rows generated before this, or once the month's
+-- allowance below is spent, stay null, and the card doesn't list a suggestion
+-- it can't place against the threshold.
+alter table public.prompt_suggestions
+ add column if not exists relevance real
+ constraint prompt_suggestions_relevance_check
+ check (relevance is null or (relevance >= 0 and relevance <= 1));
+
+-- Monthly relevance allowance: one row per refresh that rated relevance,
+-- charged an upper estimate of what rating added to it (a full list, for
+-- every attempt), summed per organization over the subscription period
+-- against plan.limits.relevanceMonthlyBudgetUsd, 0.1% of the plan price
+-- (Starter $0.049, Growth $0.249, Enterprise $0.499 or 0.1% of
+-- plan_overrides.contractMonthlyUsd). A refresh rates only once its worst
+-- case is reserved below, so the month never passes it. Separate from the
+-- Improve budget (prompt_improve_usage, 00120). The call's own token counts
+-- are kept to check the estimate against. Self-hosted isn't limited and
+-- records nothing.
+
+create table if not exists public.suggestion_relevance_usage (
+ id uuid primary key default gen_random_uuid(),
+ organization_id uuid not null references public.organizations(id) on delete cascade,
+ brand_id uuid references public.brands(id) on delete set null,
+ model text,
+ attempts integer not null default 1,
+ input_tokens integer,
+ output_tokens integer,
+ cost_usd numeric(12, 6) not null default 0,
+ used_at timestamptz not null default now()
+);
+
+create index if not exists suggestion_relevance_usage_org_used_idx
+ on public.suggestion_relevance_usage (organization_id, used_at);
+
+-- Service-role only, no policy (as prompt_improve_usage).
+alter table public.suggestion_relevance_usage enable row level security;
+
+grant all on table public.suggestion_relevance_usage to service_role;
+
+-- Reserves a refresh's worst case (p_cost) in one transaction, under a
+-- per-organization lock, so two refreshes running at once (several brands of
+-- one org, or a double click) can never take the organization past
+-- p_budget. Returns the usage row id, or null when what's left can't cover
+-- it; the caller then refreshes without rating, and once the model answers
+-- lowers the row to what the attempts it made cost.
+create or replace function public.reserve_suggestion_relevance(
+ p_organization_id uuid,
+ p_brand_id uuid,
+ p_model text,
+ p_since timestamptz,
+ p_budget numeric,
+ p_cost numeric
+)
+returns uuid
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_spent numeric;
+ v_id uuid;
+begin
+ perform pg_advisory_xact_lock(hashtext('suggestion_relevance:' || p_organization_id::text));
+
+ select coalesce(sum(cost_usd), 0) into v_spent
+ from public.suggestion_relevance_usage
+ where organization_id = p_organization_id
+ and used_at >= p_since;
+
+ if v_spent + p_cost > p_budget then
+ return null;
+ end if;
+
+ insert into public.suggestion_relevance_usage (organization_id, brand_id, model, cost_usd)
+ values (p_organization_id, p_brand_id, p_model, p_cost)
+ returning id into v_id;
+ return v_id;
+end;
+$$;
+
+revoke all on function public.reserve_suggestion_relevance(uuid, uuid, text, timestamptz, numeric, numeric)
+ from public, anon, authenticated;
+grant execute on function public.reserve_suggestion_relevance(uuid, uuid, text, timestamptz, numeric, numeric)
+ to service_role;
+
+comment on function public.reserve_suggestion_relevance(uuid, uuid, text, timestamptz, numeric, numeric) is
+ 'Atomically reserves a suggestion refresh''s worst-case relevance cost against the organization''s monthly allowance (VIS-011). Returns the suggestion_relevance_usage id, or null when it does not fit.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 1069c4d62..8b3c0216b 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -16999,6 +16999,102 @@ grant execute on function public.insights_topic_competitors_daily(
comment on function public.insights_topic_competitors_daily(uuid, date, date, text[], text) is
'Insights "Topics vs competitors" (VIS-010, 00137): per active topic, the brand''s Visibility components over the topic''s prompts and each live competitor''s components over the same answers, from the prompt-grain rollups. complete=false until they are backfilled (00130).';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00138_prompt_suggestion_relevance.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Relevance of a prompt suggestion to the brand (VIS-011).
+--
+-- The Insights Opportunities card ranks suggestions by relevance × demand ×
+-- gap and hides any under a fixed 0.6 (Visibility spec v2). The refresh's
+-- model already writes each suggestion; relevance is one more field of that
+-- same answer, stored 0–1. Rows generated before this, or once the month's
+-- allowance below is spent, stay null, and the card doesn't list a suggestion
+-- it can't place against the threshold.
+alter table public.prompt_suggestions
+ add column if not exists relevance real
+ constraint prompt_suggestions_relevance_check
+ check (relevance is null or (relevance >= 0 and relevance <= 1));
+
+-- Monthly relevance allowance: one row per refresh that rated relevance,
+-- charged an upper estimate of what rating added to it (a full list, for
+-- every attempt), summed per organization over the subscription period
+-- against plan.limits.relevanceMonthlyBudgetUsd, 0.1% of the plan price
+-- (Starter $0.049, Growth $0.249, Enterprise $0.499 or 0.1% of
+-- plan_overrides.contractMonthlyUsd). A refresh rates only once its worst
+-- case is reserved below, so the month never passes it. Separate from the
+-- Improve budget (prompt_improve_usage, 00120). The call's own token counts
+-- are kept to check the estimate against. Self-hosted isn't limited and
+-- records nothing.
+
+create table if not exists public.suggestion_relevance_usage (
+ id uuid primary key default gen_random_uuid(),
+ organization_id uuid not null references public.organizations(id) on delete cascade,
+ brand_id uuid references public.brands(id) on delete set null,
+ model text,
+ attempts integer not null default 1,
+ input_tokens integer,
+ output_tokens integer,
+ cost_usd numeric(12, 6) not null default 0,
+ used_at timestamptz not null default now()
+);
+
+create index if not exists suggestion_relevance_usage_org_used_idx
+ on public.suggestion_relevance_usage (organization_id, used_at);
+
+-- Service-role only, no policy (as prompt_improve_usage).
+alter table public.suggestion_relevance_usage enable row level security;
+
+grant all on table public.suggestion_relevance_usage to service_role;
+
+-- Reserves a refresh's worst case (p_cost) in one transaction, under a
+-- per-organization lock, so two refreshes running at once (several brands of
+-- one org, or a double click) can never take the organization past
+-- p_budget. Returns the usage row id, or null when what's left can't cover
+-- it; the caller then refreshes without rating, and once the model answers
+-- lowers the row to what the attempts it made cost.
+create or replace function public.reserve_suggestion_relevance(
+ p_organization_id uuid,
+ p_brand_id uuid,
+ p_model text,
+ p_since timestamptz,
+ p_budget numeric,
+ p_cost numeric
+)
+returns uuid
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_spent numeric;
+ v_id uuid;
+begin
+ perform pg_advisory_xact_lock(hashtext('suggestion_relevance:' || p_organization_id::text));
+
+ select coalesce(sum(cost_usd), 0) into v_spent
+ from public.suggestion_relevance_usage
+ where organization_id = p_organization_id
+ and used_at >= p_since;
+
+ if v_spent + p_cost > p_budget then
+ return null;
+ end if;
+
+ insert into public.suggestion_relevance_usage (organization_id, brand_id, model, cost_usd)
+ values (p_organization_id, p_brand_id, p_model, p_cost)
+ returning id into v_id;
+ return v_id;
+end;
+$$;
+
+revoke all on function public.reserve_suggestion_relevance(uuid, uuid, text, timestamptz, numeric, numeric)
+ from public, anon, authenticated;
+grant execute on function public.reserve_suggestion_relevance(uuid, uuid, text, timestamptz, numeric, numeric)
+ to service_role;
+
+comment on function public.reserve_suggestion_relevance(uuid, uuid, text, timestamptz, numeric, numeric) is
+ 'Atomically reserves a suggestion refresh''s worst-case relevance cost against the organization''s monthly allowance (VIS-011). Returns the suggestion_relevance_usage id, or null when it does not fit.';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00147_insights_same_prompts_definer.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/messages/en.json b/web/messages/en.json
index f63bbc499..91cb793a4 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1843,6 +1843,34 @@
"sendFailed": "Couldn't send to the Action Center.",
"openAction": "Open",
"gapChanged": "The gap changed since the page loaded. Refresh to see the latest."
+ },
+ "opportunities": {
+ "title": "Opportunities",
+ "seeAll": "See all",
+ "listLabel": "What to track next",
+ "topicKind": "Topic",
+ "promptKind": "Prompt",
+ "prompts": "{count, plural, one {# prompt} other {# prompts}}",
+ "volume": "~{volume}/mo",
+ "notTracked": "not tracked",
+ "competitorLeads": "{name} leads",
+ "leaderScore": "leader {score}",
+ "youLead": "you lead",
+ "track": "Track",
+ "trackCount": "Track {count}",
+ "trackHint": "Start tracking this prompt",
+ "trackCountHint": "Start tracking the {count} prompts suggested for {topic}",
+ "planFull": "Your plan's prompt locations are full",
+ "tracked": "Now tracking {count, plural, one {# prompt} other {# prompts}}",
+ "trackedPartly": "Tracked {tracked} of {total}: your plan's prompt locations are full.",
+ "trackFailed": "Couldn't track the suggestions.",
+ "openPrompts": "Open",
+ "empty": "No prompt suggestions yet. Generate ideas to see what to track next.",
+ "unrated": "These suggestions aren't rated for fit yet. New suggestions are rated when they refresh, within a monthly allowance on your plan.",
+ "noneRelevant": "No suggestion fits your brand closely enough right now. Refresh for new ideas.",
+ "allTracked": "You're tracking every suggestion that fits. Refresh suggestions for more ideas.",
+ "alreadyHandled": "These suggestions were already accepted or dismissed.",
+ "openSuggestions": "Open suggestions"
}
},
"topics": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx
new file mode 100644
index 000000000..6a8f37cd4
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx
@@ -0,0 +1,209 @@
+'use client';
+
+import { useMemo, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { ArrowRight, Loader2, MessageCircle, Tag } from 'lucide-react';
+import { toast } from 'sonner';
+import { Link, useRouter } from '@/i18n/navigation';
+import { Button } from '@/components/ui/button';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { formatCompactNumber } from '@/lib/format';
+import { trackSuggestions } from '@/lib/actions/prompt-suggestions';
+import {
+ opportunities,
+ topicStandings,
+ type Opportunity,
+ type OpportunitySuggestion,
+} from '@/lib/insights-opportunities';
+import type { TopicCompetitors } from '@/lib/insights-topics';
+
+/** Items shown, as in the mockup; "See all" opens the rest. */
+const VISIBLE_ITEMS = 4;
+
+const SUGGESTIONS_HREF = '/dashboard/prompts/suggestions';
+
+/**
+ * Opportunities (VIS-011), as in the v2 mockup: what to track next, from the
+ * stored prompt suggestions. A topic item tracks all its suggested prompts
+ * (Track 23), a prompt item the one. Both stay within the plan's prompt
+ * locations: the server checks every prompt and stops when they're full.
+ */
+export function Opportunities({
+ suggestions,
+ trackedTopicIds,
+ topics,
+ entities,
+ slotsLeft,
+ onTracked,
+ className,
+}: {
+ suggestions: OpportunitySuggestion[];
+ trackedTopicIds: string[] | null;
+ /** The heat map's data, for who leads each topic; null where it isn't loaded. */
+ topics: TopicCompetitors[] | null;
+ /** The trend's brands, for the names of the competitors leading topics. */
+ entities: { key: string; name: string; isOwnBrand: boolean }[] | null;
+ /** Prompt locations left on the plan; null when unlimited. */
+ slotsLeft: number | null;
+ onTracked: (count: number) => void;
+ className?: string;
+}) {
+ const t = useTranslations('insights.opportunities');
+ const router = useRouter();
+ const [trackedIds, setTrackedIds] = useState<ReadonlySet<string>>(new Set());
+ const [busy, setBusy] = useState<string | null>(null);
+
+ const result = useMemo(() => {
+ const names = Object.fromEntries(
+ (entities ?? []).filter((e) => !e.isOwnBrand).map((e) => [e.key, e.name]),
+ );
+ return opportunities(
+ suggestions.filter((s) => !trackedIds.has(s.id)),
+ topicStandings(topics, names, trackedTopicIds && new Set(trackedTopicIds)),
+ );
+ }, [suggestions, trackedIds, topics, entities, trackedTopicIds]);
+ const planFull = slotsLeft !== null && slotsLeft <= 0;
+
+ const track = async (item: Opportunity) => {
+ setBusy(item.key);
+ try {
+ const {
+ trackedIds: done,
+ skippedIds,
+ error,
+ code,
+ } = await trackSuggestions(item.suggestionIds);
+ // Skipped ones were accepted or dismissed elsewhere: they leave the list too.
+ if (done.length + skippedIds.length > 0) {
+ setTrackedIds((prev) => new Set([...prev, ...done, ...skippedIds]));
+ }
+ if (done.length > 0) onTracked(done.length);
+ const open = { label: t('openPrompts'), onClick: () => router.push('/dashboard/prompts') };
+ if (!error && done.length === 0) {
+ toast.info(t('alreadyHandled'));
+ } else if (!error) {
+ toast.success(t('tracked', { count: done.length }), { action: open });
+ } else if (code === 'plan_limit' && done.length > 0) {
+ toast.warning(
+ t('trackedPartly', { tracked: done.length, total: item.suggestionIds.length }),
+ { action: open },
+ );
+ } else if (code === 'plan_limit') {
+ toast.error(t('planFull'));
+ } else {
+ toast.error(t('trackFailed'), { description: error });
+ }
+ } catch {
+ toast.error(t('trackFailed'));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const meta = (item: Opportunity): string => {
+ const volume = t('volume', { volume: formatCompactNumber(item.volume) });
+ if (item.kind === 'prompt') return [volume, t('notTracked')].join(' · ');
+ const s = item.standing;
+ const standing =
+ s.kind === 'competitor'
+ ? s.name
+ ? t('competitorLeads', { name: s.name })
+ : t('leaderScore', { score: s.score.toFixed(1) })
+ : s.kind === 'you'
+ ? t('youLead')
+ : s.kind === 'notTracked'
+ ? t('notTracked')
+ : null;
+ return [t('prompts', { count: item.suggestionIds.length }), volume, standing]
+ .filter(Boolean)
+ .join(' · ');
+ };
+
+ return (
+ <Card className={className}>
+ <CardHeader className="pb-2">
+ <div className="flex items-center justify-between gap-2">
+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>
+ {result.status === 'ready' && (
+ <Link
+ href={SUGGESTIONS_HREF}
+ className="shrink-0 text-xs font-medium text-primary underline-offset-2 hover:underline"
+ >
+ {t('seeAll')}
+ </Link>
+ )}
+ </div>
+ </CardHeader>
+ <CardContent>
+ {result.status === 'ready' ? (
+ <ul className="divide-y" aria-label={t('listLabel')}>
+ {result.items.slice(0, VISIBLE_ITEMS).map((item) => {
+ const isTopic = item.kind === 'topic';
+ const Icon = isTopic ? Tag : MessageCircle;
+ const count = item.suggestionIds.length;
+ return (
+ <li
+ key={item.key}
+ className="flex items-center gap-2.5 py-2.5 first:pt-0 last:pb-0"
+ >
+ <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">
+ <Icon className="h-3.5 w-3.5" aria-hidden />
+ <span className="sr-only">{isTopic ? t('topicKind') : t('promptKind')}</span>
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium" title={item.title}>
+ {item.title}
+ </span>
+ <span className="block truncate text-xs text-muted-foreground">
+ {meta(item)}
+ </span>
+ </span>
+ {/* The hint sits on a wrapper: a disabled button shows no tooltip. */}
+ <span
+ className="shrink-0"
+ title={
+ planFull
+ ? t('planFull')
+ : isTopic
+ ? t('trackCountHint', { count, topic: item.title })
+ : t('trackHint')
+ }
+ >
+ <Button
+ size="sm"
+ className="h-7 gap-1.5 px-2.5 text-xs"
+ disabled={planFull || busy !== null}
+ onClick={() => track(item)}
+ >
+ {/* Track N adds one prompt at a time, so a big topic takes a moment. */}
+ {busy === item.key && (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
+ )}
+ {isTopic ? t('trackCount', { count }) : t('track')}
+ </Button>
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <div className="flex flex-col items-center justify-center gap-2 py-6 text-center">
+ <p className="max-w-xs text-xs text-muted-foreground">
+ {/* Tracking the last item empties the list: that's done, not "nothing fits". */}
+ {result.status === 'noneRelevant' && trackedIds.size > 0
+ ? t('allTracked')
+ : t(result.status)}
+ </p>
+ <Link
+ href={SUGGESTIONS_HREF}
+ className="inline-flex items-center gap-1 text-xs font-medium text-primary underline-offset-2 hover:underline"
+ >
+ {t('openSuggestions')}
+ <ArrowRight className="h-3.5 w-3.5" aria-hidden />
+ </Link>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index ce5df7972..afcb9eb0f 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -22,7 +22,7 @@ import {
type TrackedPromptsKpi,
type CompetitorComparisonData,
type ShareOfVoiceData,
- type InsightsRecommendations,
+ type InsightsOpportunities,
type TrackingJobStatus,
type BreakdownFilters,
type BreakdownMetric,
@@ -37,7 +37,7 @@ import {
DateRangeFilter,
type DateRangePreset,
} from '@/components/filters/date-range-filter';
-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { buttonVariants } from '@/components/ui/button-variants';
@@ -46,7 +46,6 @@ import {
BarChart3,
CalendarX2,
Play,
- TrendingUp,
Loader2,
FlaskConical,
Users,
@@ -54,9 +53,6 @@ import {
ArrowRight,
Download,
FileText,
- Lightbulb,
- Sparkles,
- Tag,
} from 'lucide-react';
import {
Select,
@@ -68,7 +64,6 @@ import {
import { cn } from '@/lib/utils';
import { getAIProviderDisplayName, resolveAIProvider } from '@/components/ai-provider-avatar';
import { usePlanContext } from '@/components/providers/plan-provider';
-import { formatCompactNumber } from '@/lib/format';
import { toast } from 'sonner';
import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';
import type { PromptComparison } from '@/lib/insights-same-prompts';
@@ -82,6 +77,7 @@ import { Leaderboard } from './_leaderboard';
import { TrendCard } from './_trend-card';
import { trendLines, type TrendMarkerData } from '@/lib/insights-trend';
import { TopicHeatmap } from './_topic-heatmap';
+import { Opportunities } from './_opportunities';
import type { TopicCompetitors } from '@/lib/insights-topics';
import { WhyChanged } from './_why-changed';
import type { WhyChanged as WhyChangedData } from '@/lib/insights-drivers';
@@ -560,138 +556,6 @@ function NoDataForPeriod({ datePreset, onReset }: { datePreset: DatePreset; onRe
);
}
-// ─── Recommendations ──────────────────────────────────────────────────────────
-
-/** Teaser targets. Topic suggestions live on the Topics page (#463) — its
- * card expands + scrolls itself for this hash; the prompt-suggestions card
- * lives on the Prompts page's default All Prompts tab and does the same. */
-const TOPIC_OPPORTUNITIES_HREF = '/dashboard/topics#topic-opportunities';
-const PROMPT_OPPORTUNITIES_HREF = '/dashboard/prompts?tab=all&view=suggestions';
-
-function RecommendationCard({
- title,
- icon: Icon,
- href,
- emptyText,
- children,
- isEmpty,
-}: {
- title: string;
- icon: React.ElementType;
- href: string;
- emptyText: string;
- children: React.ReactNode;
- isEmpty: boolean;
-}) {
- return (
- <Card>
- <CardHeader className="pb-2">
- <div className="flex items-center justify-between gap-3">
- <CardTitle className="flex items-center gap-2 text-sm font-medium">
- <Icon className="h-4 w-4 text-primary" />
- {title}
- </CardTitle>
- {!isEmpty && (
- <Link
- href={href}
- className="shrink-0 text-xs font-medium text-primary underline-offset-2 hover:underline"
- >
- See all
- </Link>
- )}
- </div>
- </CardHeader>
- <CardContent>
- {isEmpty ? (
- <div className="flex flex-col items-center justify-center py-6 text-center gap-2">
- <p className="text-xs text-muted-foreground max-w-xs">{emptyText}</p>
- <Link
- href={href}
- className="text-xs font-medium text-primary underline-offset-2 hover:underline"
- >
- Generate ideas →
- </Link>
- </div>
- ) : (
- children
- )}
- </CardContent>
- </Card>
- );
-}
-
-/**
- * The "so what, what next?" row (#459) filling the space freed by the removed
- * results tree (#458). Reads only stored data assembled server-side inside
- * getInsightsData — no extra client round trip, no LLM call. Deliberately
- * outside the date-filter contract: no delta badges, own section heading
- * (see #457 for why period-scoped and account-scoped numbers must not mix).
- */
-function RecommendationsSection({ data }: { data: InsightsRecommendations }) {
- return (
- <div className="space-y-3">
- <div>
- <h2 className="flex items-center gap-2 text-sm font-semibold">
- <Lightbulb className="h-4 w-4 text-primary" />
- Recommendations
- </h2>
- <p className="text-xs text-muted-foreground mt-0.5">
- Ideas from your stored analyses — independent of the date filters above.
- </p>
- </div>
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
- <RecommendationCard
- title="Topic Opportunities"
- icon={Tag}
- href={TOPIC_OPPORTUNITIES_HREF}
- isEmpty={data.topics.length === 0}
- emptyText="No topic clusters yet. Analyze your prompt volumes to surface the themes with the most AI search demand."
- >
- <ul className="divide-y">
- {data.topics.map((t) => (
- <li key={t.keyword} className="flex items-center gap-3 py-2 first:pt-0 last:pb-0">
- <p className="flex-1 min-w-0 truncate text-sm">{t.keyword}</p>
- <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
- {t.promptCount} prompt{t.promptCount !== 1 ? 's' : ''}
- </span>
- <Badge variant="outline" className="shrink-0 gap-1 text-xs tabular-nums">
- <TrendingUp className="h-3 w-3" />~{formatCompactNumber(t.estimatedAiVolume)}/mo
- </Badge>
- </li>
- ))}
- </ul>
- </RecommendationCard>
- <RecommendationCard
- title="Prompt Opportunities"
- icon={Sparkles}
- href={PROMPT_OPPORTUNITIES_HREF}
- isEmpty={data.prompts.length === 0}
- emptyText="No prompt suggestions stored yet. Generate AI prompt ideas based on your brand and competitor citations."
- >
- <ul className="divide-y">
- {data.prompts.map((p) => (
- <li key={p.id} className="flex items-center gap-3 py-2 first:pt-0 last:pb-0">
- <p className="flex-1 min-w-0 truncate text-sm">{p.text}</p>
- {p.topicName && (
- <Badge variant="outline" className="hidden sm:inline-flex shrink-0 gap-1 text-xs">
- <Tag className="h-3 w-3" />
- {p.topicName}
- </Badge>
- )}
- {p.estVolume != null && p.estVolume > 0 && (
- <Badge variant="outline" className="shrink-0 gap-1 text-xs tabular-nums">
- <TrendingUp className="h-3 w-3" />~{formatCompactNumber(p.estVolume)}/mo
- </Badge>
- )}
- </li>
- ))}
- </ul>
- </RecommendationCard>
- </div>
- </div>
- );
-}
-
// ─── Tracking Progress ────────────────────────────────────────────────────────
import { saveTrackingJob, loadTrackingJob, clearTrackingJob } from '@/lib/tracking-job-store';
@@ -850,7 +714,7 @@ export default function InsightsPage() {
const [competitorData, setCompetitorData] = useState<CompetitorComparisonData | null>(null);
const [rateTrend, setRateTrend] = useState<VisibilityRateTrendData | null>(null);
const [sovData, setSovData] = useState<ShareOfVoiceData | null>(null);
- const [recommendations, setRecommendations] = useState<InsightsRecommendations | null>(null);
+ const [opportunities, setOpportunities] = useState<InsightsOpportunities | null>(null);
const [comparison, setComparison] = useState<PromptComparison | null>(null);
const [coverage, setCoverage] = useState<CoverageKpi | null>(null);
const [kpiSeries, setKpiSeries] = useState<KpiSeriesDay[] | null>(null);
@@ -944,7 +808,7 @@ export default function InsightsPage() {
setTrackedPrompts(insights.trackedPrompts);
setCompetitorData(insights.competitors.brands.length > 1 ? insights.competitors : null);
setSovData(insights.sov.byPlatform.length > 0 ? insights.sov : null);
- setRecommendations(insights.recommendations);
+ setOpportunities(insights.opportunities);
setComparison(insights.comparison);
setCoverage(insights.coverage);
setKpiSeries(insights.kpiSeries);
@@ -1497,8 +1361,25 @@ export default function InsightsPage() {
/>
)}
- {/* Recommendations (#459) — stored data, not period-scoped */}
- {recommendations && <RecommendationsSection data={recommendations} />}
+ {/* Opportunities (VIS-011), under the map: stored suggestions, not period-scoped. */}
+ {opportunities && (
+ <Opportunities
+ suggestions={opportunities.suggestions}
+ trackedTopicIds={opportunities.trackedTopicIds}
+ topics={topicCompetitors}
+ entities={rateTrend?.entities ?? null}
+ slotsLeft={
+ !trackedPrompts || trackedPrompts.quotaLimit < 0
+ ? null
+ : Math.max(0, trackedPrompts.quotaLimit - trackedPrompts.quotaUsed)
+ }
+ onTracked={(count) =>
+ setTrackedPrompts(
+ (current) => current && { ...current, quotaUsed: current.quotaUsed + count },
+ )
+ }
+ />
+ )}
</>
)}
</div>
diff --git a/web/src/config/plans.ts b/web/src/config/plans.ts
index 3a7f44449..0236fea0b 100644
--- a/web/src/config/plans.ts
+++ b/web/src/config/plans.ts
@@ -50,6 +50,12 @@ export interface PlanLimits {
* -1 = unlimited (self-host).
*/
improveMonthlyBudgetUsd: number;
+ /**
+ * Monthly USD budget for rating prompt suggestions' relevance (VIS-011),
+ * the cost Insights Opportunities adds to a suggestion refresh: 0.1% of
+ * the plan price, enforced on the server. -1 = unlimited (self-host).
+ */
+ relevanceMonthlyBudgetUsd: number;
/**
* New content opportunities per month (CONTENT-001), counted separately
* from briefs. -1 = unlimited. Enterprise is -1 by default and set per
@@ -103,6 +109,7 @@ export const PLANS: Record<PlanId, Plan> = {
maxVolumeAnalyses: -1,
maxBriefGenerations: -1,
improveMonthlyBudgetUsd: -1,
+ relevanceMonthlyBudgetUsd: -1,
maxOpportunitiesPerMonth: -1,
maxOpportunitiesPerRequest: 5,
maxSiteAudits: -1,
@@ -141,6 +148,8 @@ export const PLANS: Record<PlanId, Plan> = {
maxVolumeAnalyses: 4,
maxBriefGenerations: 10,
improveMonthlyBudgetUsd: 0,
+ // 0.1% of the $49 price, spent rating suggestions' relevance (VIS-011).
+ relevanceMonthlyBudgetUsd: 0.049,
maxOpportunitiesPerMonth: 10,
maxOpportunitiesPerRequest: 3,
maxSiteAudits: 100,
@@ -183,6 +192,8 @@ export const PLANS: Record<PlanId, Plan> = {
maxBriefGenerations: 50,
// 1% of the $249 price, spent on Improve model calls (PROMPT-003).
improveMonthlyBudgetUsd: 2.49,
+ // 0.1% of the $249 price, spent rating suggestions' relevance (VIS-011).
+ relevanceMonthlyBudgetUsd: 0.249,
maxOpportunitiesPerMonth: 50,
maxOpportunitiesPerRequest: 5,
maxSiteAudits: 500,
@@ -225,6 +236,9 @@ export const PLANS: Record<PlanId, Plan> = {
// 1% of the $499 floor. plan_overrides.contractMonthlyUsd raises it to 1%
// of the contract; an explicit plan_overrides.improveMonthlyBudgetUsd wins.
improveMonthlyBudgetUsd: 4.99,
+ // 0.1% of the $499 floor, raised to 0.1% of contractMonthlyUsd; an
+ // explicit plan_overrides.relevanceMonthlyBudgetUsd wins.
+ relevanceMonthlyBudgetUsd: 0.499,
maxOpportunitiesPerMonth: -1,
maxOpportunitiesPerRequest: 5,
maxSiteAudits: -1,
diff --git a/web/src/lib/actions/prompt-suggestions.test.ts b/web/src/lib/actions/prompt-suggestions.test.ts
new file mode 100644
index 000000000..b04ce7c8b
--- /dev/null
+++ b/web/src/lib/actions/prompt-suggestions.test.ts
@@ -0,0 +1,118 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * trackSuggestions (VIS-011): an Opportunities topic's "Track N". Each
+ * prompt is added through the single Track's addPromptToSet, so the plan
+ * check holds per prompt, and the run stops where the plan's prompt
+ * locations run out; suggestions handled elsewhere are skipped.
+ */
+
+let slotsLeft = Infinity;
+let added: string[] = [];
+/** Suggestions still 'new'; others were accepted or dismissed elsewhere. */
+let open: Set<string>;
+let reads: string[] = [];
+
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));
+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://server' }));
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ auth: { getSession: async () => ({ data: { session: { access_token: 't' } } }) },
+ from: (table: string) => {
+ reads.push(table);
+ let ids: string[] = [];
+ const suggestion = (id: string) => ({
+ id,
+ brand_id: 'b1',
+ suggested_text: `prompt ${id}`,
+ topic_name: 'GEO tools',
+ });
+ const row = () =>
+ table === 'prompt_sets' ? { id: 'ps1' } : { platforms: ['chatgpt-web'], models: [] };
+ const chain = {
+ select: () => chain,
+ in: (_col: string, val: string[]) => {
+ ids = val;
+ return chain;
+ },
+ eq: () => chain,
+ order: () => chain,
+ limit: () => chain,
+ maybeSingle: async () => ({ data: row(), error: null }),
+ then: (resolve: (r: unknown) => void) =>
+ resolve({ data: ids.filter((id) => open.has(id)).map(suggestion), error: null }),
+ };
+ return chain;
+ },
+ })),
+}));
+
+vi.mock('@/lib/actions/prompt', () => ({
+ addPromptToSet: vi.fn(async ({ text }: { text: string }) => {
+ if (slotsLeft <= 0) {
+ return { error: 'Your plan’s prompt locations are full.', code: 'plan_limit' };
+ }
+ slotsLeft -= 1;
+ added.push(text);
+ return { prompt: { id: `p-${added.length}` } };
+ }),
+}));
+
+const fetchMock = vi.fn(async () => new Response('{}', { status: 200 }));
+vi.stubGlobal('fetch', fetchMock);
+
+const { trackSuggestions } = await import('./prompt-suggestions');
+
+beforeEach(() => {
+ slotsLeft = Infinity;
+ added = [];
+ reads = [];
+ open = new Set(['s1', 's2', 's3', 's4']);
+ fetchMock.mockClear();
+});
+
+describe('trackSuggestions', () => {
+ it('tracks each suggestion in order and marks it added', async () => {
+ expect(await trackSuggestions(['s1', 's2', 's3'])).toEqual({
+ trackedIds: ['s1', 's2', 's3'],
+ skippedIds: [],
+ });
+ expect(added).toEqual(['prompt s1', 'prompt s2', 'prompt s3']);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ // The suggestions, the prompt set and its defaults are read once, not per prompt.
+ expect(reads).toEqual(['prompt_suggestions', 'prompt_sets', 'prompts']);
+ });
+
+ it('stops where the plan’s prompt locations run out', async () => {
+ slotsLeft = 2;
+ expect(await trackSuggestions(['s1', 's2', 's3', 's4'])).toEqual({
+ trackedIds: ['s1', 's2'],
+ skippedIds: [],
+ error: 'Your plan’s prompt locations are full.',
+ code: 'plan_limit',
+ });
+ expect(added).toHaveLength(2);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('skips suggestions accepted or dismissed elsewhere and tracks the rest', async () => {
+ open.delete('s1');
+ expect(await trackSuggestions(['s1', 's2', 's3'])).toEqual({
+ trackedIds: ['s2', 's3'],
+ skippedIds: ['s1'],
+ });
+ });
+
+ it('tracks a repeated id once', async () => {
+ expect((await trackSuggestions(['s1', 's1'])).trackedIds).toEqual(['s1']);
+ });
+
+ it('refuses an empty or oversized list before adding anything', async () => {
+ const many = Array.from({ length: 26 }, (_, i) => `s${i}`);
+ expect((await trackSuggestions([])).trackedIds).toEqual([]);
+ expect((await trackSuggestions(many)).error).toBeDefined();
+ expect((await trackSuggestions('s1' as unknown as string[])).error).toBeDefined();
+ expect(added).toEqual([]);
+ });
+});
diff --git a/web/src/lib/actions/prompt-suggestions.ts b/web/src/lib/actions/prompt-suggestions.ts
index 4ef87d067..27acac5d6 100644
--- a/web/src/lib/actions/prompt-suggestions.ts
+++ b/web/src/lib/actions/prompt-suggestions.ts
@@ -18,6 +18,8 @@ export interface PromptSuggestion {
topicId: string | null;
reason: string | null;
estVolume: number | null;
+ /** 0–1, how closely it fits the brand (VIS-011); null before 00138. */
+ relevance: number | null;
source: PromptSuggestionSource;
sourceData: SuggestionSourceData | null;
status: 'new' | 'added' | 'dismissed';
@@ -33,6 +35,7 @@ interface SuggestionRow {
topic_id: string | null;
reason: string | null;
est_volume: number | null;
+ relevance?: number | null;
source: PromptSuggestionSource;
source_data: SuggestionSourceData | null;
status: 'new' | 'added' | 'dismissed';
@@ -49,6 +52,7 @@ function mapRow(row: SuggestionRow): PromptSuggestion {
topicId: row.topic_id,
reason: row.reason,
estVolume: row.est_volume,
+ relevance: row.relevance ?? null,
source: row.source,
sourceData: row.source_data ?? null,
status: row.status,
@@ -118,29 +122,23 @@ export async function dismissSuggestion(suggestionId: string): Promise<{ success
return res.json();
}
-export type AcceptSuggestionResult = { promptId: string } | { error: string };
+export type AcceptSuggestionResult = { promptId: string } | { error: string; code?: 'plan_limit' };
-export async function acceptSuggestion(
- suggestionId: string,
- options?: { platforms?: string[]; models?: string[] },
-): Promise<AcceptSuggestionResult> {
- const session = await getSession();
- const supabase = await createClient();
-
- const { data: row, error: rowErr } = await supabase
- .from('prompt_suggestions')
- .select('id, brand_id, suggested_text, topic_name')
- .eq('id', suggestionId)
- .eq('status', 'new')
- .single();
- if (rowErr || !row) {
- return { error: 'Suggestion not found or already processed' };
- }
+type ServerClient = Awaited<ReturnType<typeof createClient>>;
+/**
+ * Where an accepted suggestion goes: the brand's first prompt set, with the
+ * platforms and models of its newest active prompt unless the caller picks.
+ */
+async function promptTarget(
+ supabase: ServerClient,
+ brandId: string,
+ options?: { platforms?: string[]; models?: string[] },
+): Promise<{ promptSetId: string; platforms: string[]; models: string[] } | { error: string }> {
const { data: ps, error: psErr } = await supabase
.from('prompt_sets')
.select('id')
- .eq('brand_id', row.brand_id)
+ .eq('brand_id', brandId)
.order('created_at', { ascending: true })
.limit(1)
.maybeSingle();
@@ -164,31 +162,125 @@ export async function acceptSuggestion(
: ['chatgpt-web']);
const models =
options?.models ?? (Array.isArray(defaults?.models) ? (defaults!.models as string[]) : []);
+ return { promptSetId: ps.id, platforms, models };
+}
- const result = await addPromptToSet({
- promptSetId: ps.id,
- text: row.suggested_text,
- category: row.topic_name ?? undefined,
- platforms,
- models,
- });
- if ('error' in result) {
- return { error: result.error };
- }
- const created = result.prompt;
-
+/** Marks the suggestion added on the server; a failure is logged, not returned. */
+async function ackAccepted(accessToken: string, suggestionId: string, promptId: string) {
const ack = await fetch(`${AEO_SERVER_URL}/api/prompts/suggestions/${suggestionId}/accept`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
- Authorization: `Bearer ${session.access_token}`,
+ Authorization: `Bearer ${accessToken}`,
},
- body: JSON.stringify({ promptId: created.id }),
+ body: JSON.stringify({ promptId }),
});
if (!ack.ok) {
console.error('[prompt-suggestions] accept ack failed:', await ack.text().catch(() => ''));
}
+}
+export async function acceptSuggestion(
+ suggestionId: string,
+ options?: { platforms?: string[]; models?: string[] },
+): Promise<AcceptSuggestionResult> {
+ const session = await getSession();
+ const supabase = await createClient();
+
+ const { data: row, error: rowErr } = await supabase
+ .from('prompt_suggestions')
+ .select('id, brand_id, suggested_text, topic_name')
+ .eq('id', suggestionId)
+ .eq('status', 'new')
+ .single();
+ if (rowErr || !row) {
+ return { error: 'Suggestion not found or already processed' };
+ }
+
+ const target = await promptTarget(supabase, row.brand_id, options);
+ if ('error' in target) return target;
+
+ const result = await addPromptToSet({
+ ...target,
+ text: row.suggested_text,
+ category: row.topic_name ?? undefined,
+ });
+ if ('error' in result) {
+ return { error: result.error, code: result.code };
+ }
+
+ await ackAccepted(session.access_token, suggestionId, result.prompt.id);
revalidatePath('/dashboard/prompts');
- return { promptId: created.id };
+ return { promptId: result.prompt.id };
+}
+
+export interface TrackSuggestionsResult {
+ /** Tracked, in the order given. */
+ trackedIds: string[];
+ /** Already accepted or dismissed elsewhere: skipped, nothing to track. */
+ skippedIds: string[];
+ /** Why the rest weren't; `code` 'plan_limit' when the plan's prompt locations ran out. */
+ error?: string;
+ code?: 'plan_limit';
+}
+
+/** More than an Opportunities item can hold: a refresh makes 25 suggestions. */
+const MAX_TRACK_AT_ONCE = 25;
+
+/**
+ * Track suggestions together: an Opportunities topic's "Track N" (VIS-011).
+ * The suggestions and where they go are read once; then each prompt is added
+ * on its own through addPromptToSet, so each passes the same plan check as a
+ * single Track, and the run stops at the first one that fails: the plan's
+ * prompt locations are full, or the rest can't be added either. Suggestions
+ * already accepted or dismissed elsewhere are skipped, not a failure.
+ */
+export async function trackSuggestions(suggestionIds: string[]): Promise<TrackSuggestionsResult> {
+ const ids = Array.isArray(suggestionIds)
+ ? [...new Set(suggestionIds.filter((id) => typeof id === 'string'))]
+ : [];
+ if (ids.length === 0 || ids.length > MAX_TRACK_AT_ONCE) {
+ return { trackedIds: [], skippedIds: [], error: 'Pick between 1 and 25 suggestions.' };
+ }
+
+ const session = await getSession();
+ const supabase = await createClient();
+ const { data: rows, error: rowsErr } = await supabase
+ .from('prompt_suggestions')
+ .select('id, brand_id, suggested_text, topic_name')
+ .in('id', ids)
+ .eq('status', 'new');
+ if (rowsErr) return { trackedIds: [], skippedIds: [], error: rowsErr.message };
+
+ const byId = new Map((rows ?? []).map((r) => [r.id as string, r]));
+ const skippedIds = ids.filter((id) => !byId.has(id));
+ const brandIds = new Set((rows ?? []).map((r) => r.brand_id as string));
+ if (brandIds.size === 0) return { trackedIds: [], skippedIds };
+ if (brandIds.size > 1) {
+ return { trackedIds: [], skippedIds, error: 'Track suggestions of one brand at a time.' };
+ }
+
+ const target = await promptTarget(supabase, [...brandIds][0]);
+ if ('error' in target) return { trackedIds: [], skippedIds, error: target.error };
+
+ const added: { id: string; promptId: string }[] = [];
+ let failure: { error: string; code?: 'plan_limit' } | undefined;
+ for (const id of ids) {
+ const row = byId.get(id);
+ if (!row) continue;
+ const result = await addPromptToSet({
+ ...target,
+ text: row.suggested_text as string,
+ category: (row.topic_name as string | null) ?? undefined,
+ });
+ if ('error' in result) {
+ failure = { error: result.error, code: result.code };
+ break;
+ }
+ added.push({ id, promptId: result.prompt.id });
+ }
+
+ await Promise.all(added.map((a) => ackAccepted(session.access_token, a.id, a.promptId)));
+ if (added.length > 0) revalidatePath('/dashboard/prompts');
+ return { trackedIds: added.map((a) => a.id), skippedIds, ...failure };
}
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index 4bca3129d..1fd3e7491 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -41,13 +41,12 @@ import { normalizeCitationUrl } from '@/lib/citations/normalize';
import { getTopicById } from '@/lib/actions/topic';
import { getOrgPlan } from '@/lib/guards/plan-guard';
import { getOrgLocationUsage } from '@/lib/prompt-locations';
-import { getPromptVolumes } from '@/lib/actions/volumes';
import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';
-import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';
import { percentageChange } from '@/lib/metrics';
import { parseChangeDrivers, whyChanged, type WhyChanged } from '@/lib/insights-drivers';
import { parseTrendMarkers, type TrendMarkerData } from '@/lib/insights-trend';
import { parseTopicCompetitors, type TopicCompetitors } from '@/lib/insights-topics';
+import type { OpportunitySuggestion } from '@/lib/insights-opportunities';
import {
parsePlatformRows,
platformChanges,
@@ -631,60 +630,55 @@ async function getInsightsFilterOptions(brandId: string): Promise<InsightsFilter
};
}
-export interface TopicOpportunity {
- keyword: string;
- estimatedAiVolume: number;
- promptCount: number;
+export interface InsightsOpportunities {
+ suggestions: OpportunitySuggestion[];
+ /** The suggestions' topics with at least one active tracked prompt; null when unknown. */
+ trackedTopicIds: string[] | null;
}
-export interface PromptOpportunity {
- id: string;
- text: string;
- topicName?: string;
- estVolume?: number;
-}
-
-export interface InsightsRecommendations {
- topics: TopicOpportunity[];
- prompts: PromptOpportunity[];
-}
-
-/** Items per Recommendations teaser card on the Insights page (#459). */
-const RECOMMENDATION_ITEM_LIMIT = 5;
+/** PostgREST's default row cap: a read that fills it may have been cut short. */
+const TRACKED_TOPIC_ROWS = 1000;
/**
- * Teaser data for the Insights Recommendations row (#459): the top stored
- * similar-topic clusters and prompt suggestions. Both are bounded reads of
- * already-persisted data — generation only ever happens from the Prompts
- * page's explicit refresh actions, never from the Insights load path.
- * Each read degrades independently to an empty list on failure so a hiccup
- * here can never take the Insights page down with it.
+ * The Opportunities card's data (VIS-011): the stored prompt suggestions and
+ * which of their topics you already track. A bounded read of persisted data:
+ * suggestions are only ever generated by the Prompts page's explicit refresh,
+ * never from the Insights load path. A failure degrades to an empty card so
+ * it can never take the Insights page down with it.
*/
-async function getInsightsRecommendations(brandId: string): Promise<InsightsRecommendations> {
- const [topics, prompts] = await Promise.all([
- getPromptVolumes(brandId)
- .then(({ volumes }) =>
- aggregatePromptVolumeClusters(volumes)
- .slice(0, RECOMMENDATION_ITEM_LIMIT)
- .map((c) => ({
- keyword: c.keyword,
- estimatedAiVolume: c.estimatedAiVolume,
- promptCount: c.prompts.length,
- })),
- )
- .catch(() => [] as TopicOpportunity[]),
- getPromptSuggestions(brandId)
- .then(({ suggestions }) =>
- suggestions.slice(0, RECOMMENDATION_ITEM_LIMIT).map((s) => ({
- id: s.id,
- text: s.suggestedText,
- topicName: s.topicName ?? undefined,
- estVolume: s.estVolume ?? undefined,
- })),
- )
- .catch(() => [] as PromptOpportunity[]),
- ]);
- return { topics, prompts };
+async function getInsightsOpportunities(brandId: string): Promise<InsightsOpportunities> {
+ try {
+ const { suggestions } = await getPromptSuggestions(brandId);
+ const topicIds = [...new Set(suggestions.flatMap((s) => (s.topicId ? [s.topicId] : [])))];
+ let trackedTopicIds: string[] | null = [];
+ if (topicIds.length > 0) {
+ const supabase = await dbClient();
+ const { data, error } = await supabase
+ .from('prompts')
+ .select('topic_id')
+ .in('topic_id', topicIds)
+ .eq('is_active', true)
+ .limit(TRACKED_TOPIC_ROWS);
+ // Unknown, not "none": a failed or cut-off read would call tracked topics untracked.
+ trackedTopicIds =
+ error || (data?.length ?? 0) >= TRACKED_TOPIC_ROWS
+ ? null
+ : [...new Set((data ?? []).map((r) => r.topic_id as string))];
+ }
+ return {
+ suggestions: suggestions.map((s) => ({
+ id: s.id,
+ text: s.suggestedText,
+ topicId: s.topicId,
+ topicName: s.topicName,
+ estVolume: s.estVolume,
+ relevance: s.relevance,
+ })),
+ trackedTopicIds,
+ };
+ } catch {
+ return { suggestions: [], trackedTopicIds: [] };
+ }
}
/**
@@ -714,7 +708,7 @@ export interface InsightsData {
sov: ShareOfVoiceData;
trackedPrompts: TrackedPromptsKpi;
filterOptions: InsightsFilterOptions;
- recommendations: InsightsRecommendations;
+ opportunities: InsightsOpportunities;
hasAnyData: boolean;
/** The visibility-rate chart for the same window; null when its read failed. */
trend: VisibilityRateTrendData | null;
@@ -1343,12 +1337,12 @@ export async function getInsightsData(
})
: loadWindowedInsights(brandId, filterOpts, { strict: false });
- // Quota (tracked prompts), recommendations and the unfiltered check depend
+ // Quota (tracked prompts), opportunities and the unfiltered check depend
// on the caller's org and session, so they are read live on every open.
- const [windowed, trackedPrompts, recommendations, unfilteredHasData] = await Promise.all([
+ const [windowed, trackedPrompts, opportunities, unfilteredHasData] = await Promise.all([
windowedRead,
getTrackedPromptsKpi(brandId, filterOpts),
- getInsightsRecommendations(brandId),
+ getInsightsOpportunities(brandId),
opts.checkUnfiltered ? brandHasResults(brandId) : Promise.resolve(null),
]);
@@ -1360,7 +1354,7 @@ export async function getInsightsData(
return {
...windowed,
trackedPrompts,
- recommendations,
+ opportunities,
hasAnyData,
trackingWindow,
};
diff --git a/web/src/lib/insights-opportunities.test.ts b/web/src/lib/insights-opportunities.test.ts
new file mode 100644
index 000000000..aba502d91
--- /dev/null
+++ b/web/src/lib/insights-opportunities.test.ts
@@ -0,0 +1,190 @@
+import { describe, expect, it } from 'vitest';
+import type { TopicCompetitors } from './insights-topics';
+import {
+ gapWeight,
+ opportunities,
+ RELEVANCE_THRESHOLD,
+ topicStandings,
+ type OpportunityStanding,
+ type OpportunitySuggestion,
+} from './insights-opportunities';
+
+const suggestion = (
+ id: string,
+ over: Partial<OpportunitySuggestion> = {},
+): OpportunitySuggestion => ({
+ id,
+ text: `prompt ${id}`,
+ topicId: null,
+ topicName: null,
+ estVolume: 1000,
+ relevance: 0.8,
+ ...over,
+});
+
+const unknown = (): OpportunityStanding => ({ kind: 'unknown' });
+
+const comps = (mentions: number) => ({
+ mentionAnswers: mentions,
+ citationAnswers: 0,
+ sumInvPosition: 0,
+ positionCount: 0,
+});
+
+const topic = (
+ topicId: string,
+ answers: number,
+ you: number,
+ competitors: Record<string, number>,
+): TopicCompetitors => ({
+ topicId,
+ name: topicId,
+ prompts: 3,
+ answers,
+ brand: comps(you),
+ competitors: Object.fromEntries(Object.entries(competitors).map(([id, m]) => [id, comps(m)])),
+});
+
+describe('opportunities', () => {
+ it('groups suggestions sharing a topic into one item, a lone one stays a prompt', () => {
+ const result = opportunities(
+ [
+ suggestion('a', { topicId: 't1', topicName: 'GEO tools', estVolume: 30_000 }),
+ suggestion('b', { topicId: 't1', topicName: 'GEO tools', estVolume: 62_000 }),
+ suggestion('c', { topicId: 't2', topicName: 'Pricing', estVolume: 38_400 }),
+ ],
+ unknown,
+ );
+
+ expect(result).toEqual({
+ status: 'ready',
+ items: [
+ expect.objectContaining({
+ kind: 'topic',
+ title: 'GEO tools',
+ volume: 92_000,
+ // Track adds the biggest first, so a plan that fills up keeps those.
+ suggestionIds: ['b', 'a'],
+ }),
+ expect.objectContaining({
+ kind: 'prompt',
+ title: 'prompt c',
+ volume: 38_400,
+ suggestionIds: ['c'],
+ }),
+ ],
+ });
+ });
+
+ it('never lists a suggestion under the relevance threshold', () => {
+ const result = opportunities(
+ [
+ suggestion('a', { topicId: 't1', topicName: 'GEO tools', relevance: 0.9 }),
+ suggestion('b', { topicId: 't1', topicName: 'GEO tools', relevance: 0.5 }),
+ suggestion('c', { relevance: RELEVANCE_THRESHOLD }),
+ suggestion('d', { relevance: 0.59 }),
+ ],
+ unknown,
+ );
+
+ // 'b' doesn't count toward its topic, so 'a' is a prompt on its own.
+ expect(result.status === 'ready' && result.items.map((i) => [i.kind, i.suggestionIds])).toEqual(
+ [
+ ['prompt', ['a']],
+ ['prompt', ['c']],
+ ],
+ );
+ });
+
+ it('ranks by relevance × demand × gap', () => {
+ const standings: Record<string, OpportunityStanding> = {
+ behind: { kind: 'competitor', name: 'Peec AI', score: 44, gap: 30 },
+ lead: { kind: 'you' },
+ };
+ const result = opportunities(
+ [
+ // 0.8 × 10k × 1.3 = 10.4k
+ suggestion('behind', { topicId: 'behind', estVolume: 10_000 }),
+ // 0.8 × 12k = 9.6k
+ suggestion('plain', { topicId: 'plain', estVolume: 12_000 }),
+ // 0.8 × 20k × 0.5 = 8k
+ suggestion('lead', { topicId: 'lead', estVolume: 20_000 }),
+ // 1.0 × 9k = 9k
+ suggestion('apt', { topicId: 'apt', estVolume: 9_000, relevance: 1 }),
+ ],
+ (id) => standings[id ?? ''] ?? { kind: 'unknown' },
+ );
+
+ expect(result.status === 'ready' && result.items.map((i) => i.key)).toEqual([
+ 'behind',
+ 'plain',
+ 'apt',
+ 'lead',
+ ]);
+ });
+
+ it('tells apart no suggestions, unrated ones and none relevant', () => {
+ expect(opportunities([], unknown)).toEqual({ status: 'empty' });
+ expect(opportunities([suggestion('a', { relevance: null })], unknown)).toEqual({
+ status: 'unrated',
+ });
+ expect(opportunities([suggestion('a', { relevance: 0.3 })], unknown)).toEqual({
+ status: 'noneRelevant',
+ });
+ });
+
+ it('groups by topic name when a suggestion has no topic id', () => {
+ const result = opportunities(
+ [suggestion('a', { topicName: 'GEO tools' }), suggestion('b', { topicName: 'geo tools ' })],
+ unknown,
+ );
+ expect(result.status === 'ready' && result.items).toEqual([
+ expect.objectContaining({ kind: 'topic', title: 'GEO tools', topicId: null }),
+ ]);
+ });
+});
+
+describe('topicStandings', () => {
+ const names = { c1: 'Peec AI' };
+
+ it('reads the leader over every competitor, not only the trend’s', () => {
+ // 0.6 × 20% = 12.0 for you, 0.6 × 60% = 36.0 for Peec AI.
+ const standingOf = topicStandings([topic('t1', 100, 20, { c1: 60 })], names, new Set(['t1']));
+ expect(standingOf('t1')).toEqual({ kind: 'competitor', name: 'Peec AI', score: 36, gap: 24 });
+ });
+
+ it('knows when you lead', () => {
+ const standingOf = topicStandings([topic('t1', 100, 60, { c1: 20 })], names, new Set(['t1']));
+ expect(standingOf('t1')).toEqual({ kind: 'you' });
+ });
+
+ it('leaves the leader unnamed when the name is not known', () => {
+ const standingOf = topicStandings([topic('t1', 100, 20, { c9: 60 })], names, new Set(['t1']));
+ expect(standingOf('t1')).toMatchObject({ kind: 'competitor', name: null, score: 36 });
+ });
+
+ it('calls a topic with no tracked prompts not tracked', () => {
+ const standingOf = topicStandings([], names, new Set());
+ expect(standingOf('new-topic')).toEqual({ kind: 'notTracked' });
+ });
+
+ it('does not guess for a tracked topic with too few answers or no map', () => {
+ expect(topicStandings([topic('t1', 12, 1, { c1: 9 })], names, new Set(['t1']))('t1')).toEqual({
+ kind: 'unknown',
+ });
+ expect(topicStandings(null, names, new Set(['t1']))('t1')).toEqual({ kind: 'unknown' });
+ expect(topicStandings(null, names, new Set())(null)).toEqual({ kind: 'unknown' });
+ });
+
+ it('calls nothing untracked when which topics you track is unknown', () => {
+ expect(topicStandings([], names, null)('new-topic')).toEqual({ kind: 'unknown' });
+ });
+});
+
+describe('gapWeight', () => {
+ it('weighs a competitor’s lead up, yours down', () => {
+ expect(gapWeight({ kind: 'competitor', name: null, score: 44, gap: 25 })).toBe(1.25);
+ expect(gapWeight({ kind: 'you' })).toBe(0.5);
+ expect(gapWeight({ kind: 'notTracked' })).toBe(1);
+ });
+});
diff --git a/web/src/lib/insights-opportunities.ts b/web/src/lib/insights-opportunities.ts
new file mode 100644
index 000000000..defe63d1c
--- /dev/null
+++ b/web/src/lib/insights-opportunities.ts
@@ -0,0 +1,147 @@
+import { topicHeatmap, type TopicCompetitors } from '@/lib/insights-topics';
+
+/**
+ * Opportunities (VIS-011), as in the v2 mockup: what to track next, from the
+ * stored prompt suggestions. Suggestions sharing a topic make one topic item
+ * ("23 prompts · ~186k/mo", Track 23), a lone one a prompt item ("~38.4k/mo
+ * · not tracked", Track). Ranked by relevance × demand × gap; a suggestion
+ * under the relevance threshold is never listed, and relevance is never shown.
+ */
+
+/** Spec v2 decision: fixed, not a per-brand setting. */
+export const RELEVANCE_THRESHOLD = 0.6;
+
+export interface OpportunitySuggestion {
+ id: string;
+ text: string;
+ topicId: string | null;
+ topicName: string | null;
+ estVolume: number | null;
+ /** 0–1; null on suggestions generated before they were rated (00138). */
+ relevance: number | null;
+}
+
+/**
+ * Where you stand in an item's topic: a competitor leads it or you do (on
+ * 20+ answers, as the heat map reads it), none of your prompts track it yet,
+ * or it's tracked but not measured in this view.
+ */
+export type OpportunityStanding =
+ | { kind: 'competitor'; name: string | null; score: number; gap: number }
+ | { kind: 'you' }
+ | { kind: 'notTracked' }
+ | { kind: 'unknown' };
+
+export interface Opportunity {
+ kind: 'topic' | 'prompt';
+ key: string;
+ /** The topic's name, or the prompt's text. */
+ title: string;
+ topicId: string | null;
+ /** What Track adds, highest volume first. */
+ suggestionIds: string[];
+ /** Monthly AI search volume: the prompt's, or the sum of the topic's. */
+ volume: number;
+ standing: OpportunityStanding;
+}
+
+export type OpportunitiesResult =
+ | { status: 'ready'; items: Opportunity[] }
+ /** No suggestions stored. */
+ | { status: 'empty' }
+ /** Stored, but generated before suggestions were rated. */
+ | { status: 'unrated' }
+ /** Rated, and none clears the threshold. */
+ | { status: 'noneRelevant' };
+
+/**
+ * Each topic's standing, read from the heat map's data over every live
+ * competitor (not only the trend's). `topics` is null where the map isn't
+ * loaded (24h, a topic selected, rollups not backfilled): a tracked topic is
+ * then 'unknown', never a guess. `trackedTopicIds` is null when which topics
+ * you track isn't known: no topic is called untracked then.
+ */
+export function topicStandings(
+ topics: TopicCompetitors[] | null,
+ competitorNames: Record<string, string>,
+ trackedTopicIds: ReadonlySet<string> | null,
+): (topicId: string | null) => OpportunityStanding {
+ const ids = [...new Set((topics ?? []).flatMap((t) => Object.keys(t.competitors)))];
+ const rows = new Map(
+ topics ? topicHeatmap(topics, ['you', ...ids]).map((row) => [row.topicId, row]) : [],
+ );
+
+ return (topicId) => {
+ if (!topicId) return { kind: 'unknown' };
+ const row = rows.get(topicId);
+ if (row?.status === 'lead') return { kind: 'you' };
+ if (row?.status === 'behind') {
+ return {
+ kind: 'competitor',
+ name: competitorNames[row.leader] ?? null,
+ score: Math.max(...row.scores),
+ gap: -row.gap!,
+ };
+ }
+ return row || !trackedTopicIds || trackedTopicIds.has(topicId)
+ ? { kind: 'unknown' }
+ : { kind: 'notTracked' };
+ };
+}
+
+/**
+ * The gap in "relevance × demand × gap": a topic a competitor leads weighs
+ * more the further ahead they are (a 25-point lead is 1.25×), one you lead
+ * weighs half, and one not measured as is.
+ */
+export function gapWeight(standing: OpportunityStanding): number {
+ if (standing.kind === 'competitor') return 1 + standing.gap / 100;
+ if (standing.kind === 'you') return 0.5;
+ return 1;
+}
+
+const groupKey = (s: OpportunitySuggestion) =>
+ s.topicId ?? (s.topicName?.trim() ? `name:${s.topicName.trim().toLowerCase()}` : `id:${s.id}`);
+
+/** The card's items, best first. */
+export function opportunities(
+ suggestions: OpportunitySuggestion[],
+ standingOf: (topicId: string | null) => OpportunityStanding,
+): OpportunitiesResult {
+ if (suggestions.length === 0) return { status: 'empty' };
+ const rated = suggestions.filter((s) => s.relevance !== null);
+ if (rated.length === 0) return { status: 'unrated' };
+ const relevant = rated.filter((s) => s.relevance! >= RELEVANCE_THRESHOLD);
+ if (relevant.length === 0) return { status: 'noneRelevant' };
+
+ const groups = new Map<string, OpportunitySuggestion[]>();
+ for (const s of relevant) {
+ const key = groupKey(s);
+ groups.set(key, [...(groups.get(key) ?? []), s]);
+ }
+
+ const ranked = [...groups].map(([key, members]) => {
+ const sorted = [...members].sort((a, b) => (b.estVolume ?? 0) - (a.estVolume ?? 0));
+ const topicId = sorted[0].topicId;
+ const isTopic = sorted.length > 1;
+ const standing = standingOf(topicId);
+ const volume = sorted.reduce((sum, s) => sum + (s.estVolume ?? 0), 0);
+ const relevance = sorted.reduce((sum, s) => sum + s.relevance!, 0) / sorted.length;
+ const item: Opportunity = {
+ kind: isTopic ? 'topic' : 'prompt',
+ key,
+ title: isTopic ? (sorted.find((s) => s.topicName)?.topicName ?? '') : sorted[0].text,
+ topicId,
+ suggestionIds: sorted.map((s) => s.id),
+ volume,
+ standing,
+ };
+ return { item, relevance, rank: relevance * volume * gapWeight(standing) };
+ });
+
+ ranked.sort(
+ (a, b) =>
+ b.rank - a.rank || b.relevance - a.relevance || a.item.title.localeCompare(b.item.title),
+ );
+ return { status: 'ready', items: ranked.map((r) => r.item) };
+}