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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): read the opportunity list through prompt clusters (#932)
Gökhan Geyik50d8717954f5
diff --git a/server/src/lib/opportunity-generator.js b/server/src/lib/opportunity-generator.jsindex 8eeccdaaa..3cafb5a8c 100644--- a/server/src/lib/opportunity-generator.js+++ b/server/src/lib/opportunity-generator.js@@ -177,7 +177,7 @@ export async function generateContentOpportunities(brandId, { model, onProgressreturn { metrics, components, score: opportunityScore(components) };};- const candidates = clusters.map((c) => ({ id: c.id, ...measure([c.id]) }));+ const candidates = clusters.map((c) => ({ id: c.id, topicId: c.topic_id, ...measure([c.id]) }));const picked = pickClusters(candidates, coveredClusterIds(existing));if (!picked.length) {logger.info(diff --git a/server/src/lib/opportunity-limits.js b/server/src/lib/opportunity-limits.jsindex 484b5e1d8..3faf354e8 100644--- a/server/src/lib/opportunity-limits.js+++ b/server/src/lib/opportunity-limits.js@@ -131,10 +131,23 @@ export function coveredClusterIds(rows) {return ids;}-/** The highest-scoring clusters with answers and no opportunity yet. */+/**+ * The highest-scoring clusters with answers and no opportunity yet, at most+ * one per topic, so a run's few suggestions spread across the brand's topics+ * instead of all landing in its strongest one. The no-topic scope (null)+ * counts as one topic.+ */export function pickClusters(candidates, covered, count = OPPORTUNITIES_PER_RUN) {- return candidates+ const topics = new Set();+ const picked = [];+ for (const c of [...candidates].filter((c) => c.metrics.tested > 0 && !covered.has(c.id))- .sort((a, b) => b.score - a.score)- .slice(0, count);+ .sort((a, b) => b.score - a.score)) {+ const topic = c.topicId ?? null;+ if (topics.has(topic)) continue;+ topics.add(topic);+ picked.push(c);+ if (picked.length === count) break;+ }+ return picked;}diff --git a/server/src/lib/opportunity-limits.test.js b/server/src/lib/opportunity-limits.test.jsindex f375d1bea..9e1e13412 100644--- a/server/src/lib/opportunity-limits.test.js+++ b/server/src/lib/opportunity-limits.test.js@@ -97,7 +97,7 @@ describe('cluster selection', () => {});it('takes the best uncovered clusters that have answers', () => {- const cand = (id, score, tested = 1) => ({ id, score, metrics: { tested } });+ const cand = (id, score, tested = 1) => ({ id, score, topicId: id, metrics: { tested } });const picked = pickClusters([cand('low', 10),@@ -111,6 +111,21 @@ describe('cluster selection', () => {);expect(picked.map((c) => c.id)).toEqual(['high', 'mid']);});++ it('takes at most one cluster per topic, the no-topic scope included', () => {+ const cand = (id, score, topicId) => ({ id, score, topicId, metrics: { tested: 1 } });+ const picked = pickClusters(+ [+ cand('a1', 95, 'a'),+ cand('a2', 90, 'a'),+ cand('none1', 85, null),+ cand('none2', 80, null),+ cand('b1', 50, 'b'),+ ],+ new Set(),+ );+ expect(picked.map((c) => c.id)).toEqual(['a1', 'none1', 'b1']);+ });});describe('generators', () => {diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex ea0181419..07e966fd5 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -19,6 +19,7 @@ import {assertOpportunitiesAccess,assertOpportunityAccess,} from '../lib/access.js';+import { loadClusters } from '../lib/prompt-clusters.js';const router = Router();@@ -124,6 +125,37 @@ router.get('/job/:jobId', async (req, res) => {}});+/**+ * The cluster a filtered prompt belongs to, and the clusters of a filtered+ * topic, so the list can match opportunities through their clusters (#857).+ * Both are scoped to the brand, so ids from another brand match nothing.+ */+async function clusterScope(brandId, promptId, topicId) {+ const [memberRes, topicRes] = await Promise.all([+ promptId+ ? supabaseAdmin+ .from('prompt_cluster_members')+ .select('cluster_id, prompt_clusters!inner(brand_id)')+ .eq('prompt_id', promptId)+ .eq('prompt_clusters.brand_id', brandId)+ .maybeSingle()+ : { data: null },+ topicId+ ? supabaseAdmin+ .from('prompt_clusters')+ .select('id')+ .eq('brand_id', brandId)+ .eq('topic_id', topicId)+ : { data: [] },+ ]);+ if (memberRes.error) throw new Error(memberRes.error.message);+ if (topicRes.error) throw new Error(topicRes.error.message);+ return {+ promptCluster: memberRes.data?.cluster_id ?? null,+ topicClusters: (topicRes.data || []).map((c) => c.id),+ };+}+/*** GET /api/content/brand/:brandId* List opportunities for a brand with optional filters.@@ -138,18 +170,25 @@ router.get('/brand/:brandId', async (req, res) => {type,q,prompt_id: promptId,+ topic_id: topicId,limit = 50,offset = 0,sort = 'score',} = req.query;const search = q ? String(q).replace(/[,()]/g, ' ') : null;+ const { promptCluster, topicClusters } = await clusterScope(+ brandId,+ promptId ? String(promptId) : null,+ topicId ? String(topicId) : null,+ );const applyFilters = (query) => {let filteredQuery = query.eq('brand_id', brandId);- if (status) {- filteredQuery = filteredQuery.eq('status', status);- }+ // Archived opportunities (the per-prompt backlog, #857) show only when asked for.+ filteredQuery = status+ ? filteredQuery.eq('status', status)+ : filteredQuery.neq('status', 'archived');if (impact) {filteredQuery = filteredQuery.eq('impact', impact);@@ -159,8 +198,22 @@ router.get('/brand/:brandId', async (req, res) => {filteredQuery = filteredQuery.eq('type', type);}+ // A prompt matches its cluster's opportunities, own or merged, and any+ // older opportunity written for the prompt itself.if (promptId) {- filteredQuery = filteredQuery.eq('prompt_id', promptId);+ filteredQuery = promptCluster+ ? filteredQuery.or(+ `prompt_id.eq.${promptId},cluster_id.eq.${promptCluster},related_cluster_ids.cs.{${promptCluster}}`,+ )+ : filteredQuery.eq('prompt_id', promptId);+ }++ if (topicId) {+ filteredQuery = topicClusters.length+ ? filteredQuery.or(+ `cluster_id.in.(${topicClusters.join(',')}),related_cluster_ids.ov.{${topicClusters.join(',')}}`,+ )+ : filteredQuery.in('id', []);}if (q) {@@ -193,6 +246,7 @@ router.get('/brand/:brandId', async (req, res) => {p_type: type ? String(type) : null,p_q: search,p_prompt_id: promptId ? String(promptId) : null,+ p_topic_id: topicId ? String(topicId) : null,});const [{ data, error: dataError, count }, { data: aggregateData, error: aggregateError }] =@@ -210,6 +264,7 @@ router.get('/brand/:brandId', async (req, res) => {avg_score: 0,high_impact_count: 0,sent_count: 0,+ signal_count: 0,};return res.json({@@ -221,6 +276,7 @@ router.get('/brand/:brandId', async (req, res) => {avgScore: Math.round(Number(aggregates.avg_score) || 0),highImpactCount: Number(aggregates.high_impact_count) || 0,sentCount: Number(aggregates.sent_count) || 0,+ signalCount: Number(aggregates.signal_count) || 0,},});} catch (error) {@@ -235,9 +291,48 @@ router.get('/brand/:brandId', async (req, res) => {const FACET_PAGE_SIZE = 1000;+/**+ * A brand's listed (not archived) opportunities with the prompts each one+ * answers: its cluster's members, merged clusters included, or for an older+ * per-prompt opportunity its prompt_id (#857). Paged: PostgREST caps a+ * response at 1,000 rows and a large brand holds more opportunities.+ */+async function opportunityPrompts(brandId) {+ const opportunities = [];+ for (let from = 0; ; from += FACET_PAGE_SIZE) {+ const { data, error } = await supabaseAdmin+ .from('content_opportunities')+ .select('prompt_id, cluster_id, related_cluster_ids')+ .eq('brand_id', brandId)+ .neq('status', 'archived')+ .order('id')+ .range(from, from + FACET_PAGE_SIZE - 1);+ if (error) throw new Error(error.message);+ opportunities.push(...(data || []));+ if (!data || data.length < FACET_PAGE_SIZE) break;+ }++ const clusters = await loadClusters(brandId);+ const byCluster = new Map(clusters.map((c) => [c.id, c]));+ return {+ clusters: byCluster,+ rows: opportunities.map((o) => {+ const ids = [o.cluster_id, ...(o.related_cluster_ids || [])].filter((id) =>+ byCluster.has(id),+ );+ return {+ clusterIds: ids,+ promptIds: ids.length+ ? ids.flatMap((id) => byCluster.get(id).prompt_ids)+ : [o.prompt_id].filter(Boolean),+ };+ }),+ };+}+/*** GET /api/content/brand/:brandId/prompts- * The prompts this brand's opportunities belong to, with how many each has,+ * The prompts this brand's opportunities answer, with how many each has,* most first — the options for the Content page's prompt filter (#836).* Opportunities whose prompt was deleted are left out: there is nothing to* name them by.@@ -247,22 +342,10 @@ router.get('/brand/:brandId/prompts', async (req, res) => {const { brandId } = req.params;await assertBrandAccess(brandId, req.user.id);- // Paged: PostgREST caps a response at 1,000 rows and a large brand holds- // more opportunities than that.+ const { rows } = await opportunityPrompts(brandId);const counts = new Map();- for (let from = 0; ; from += FACET_PAGE_SIZE) {- const { data, error } = await supabaseAdmin- .from('content_opportunities')- .select('prompt_id')- .eq('brand_id', brandId)- .not('prompt_id', 'is', null)- .order('id')- .range(from, from + FACET_PAGE_SIZE - 1);- if (error) throw new Error(error.message);- for (const row of data || []) {- counts.set(row.prompt_id, (counts.get(row.prompt_id) || 0) + 1);- }- if (!data || data.length < FACET_PAGE_SIZE) break;+ for (const row of rows) {+ for (const id of new Set(row.promptIds)) counts.set(id, (counts.get(id) || 0) + 1);}const { data: prompts, error: promptError } = await selectInChunks(@@ -282,6 +365,41 @@ router.get('/brand/:brandId/prompts', async (req, res) => {}});+/**+ * GET /api/content/brand/:brandId/topics+ * The topics this brand's opportunities belong to, through their own or+ * merged clusters, with how many each has — the topic filter's options.+ */+router.get('/brand/:brandId/topics', async (req, res) => {+ try {+ const { brandId } = req.params;+ await assertBrandAccess(brandId, req.user.id);++ const { rows, clusters } = await opportunityPrompts(brandId);+ const counts = new Map();+ for (const row of rows) {+ const topics = new Set(row.clusterIds.map((id) => clusters.get(id).topic_id).filter(Boolean));+ for (const id of topics) counts.set(id, (counts.get(id) || 0) + 1);+ }++ const { data: topics, error } = await supabaseAdmin+ .from('topics')+ .select('id, name')+ .eq('brand_id', brandId);+ if (error) throw new Error(error.message);++ return res.json({+ topics: (topics || [])+ .filter((t) => counts.has(t.id))+ .map((t) => ({ topicId: t.id, name: t.name, count: counts.get(t.id) }))+ .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)),+ });+ } catch (error) {+ req.log.error({ err: error }, 'list opportunity topics error');+ return res.status(error.status || 500).json({ error: 'Failed to list opportunity topics' });+ }+});+/*** POST /api/content/bulk/status* Update the status of multiple opportunities at once.diff --git a/supabase/migrations/00103_cluster_opportunity_list.sql b/supabase/migrations/00103_cluster_opportunity_list.sqlnew file mode 100644index 000000000..5a5527c13--- /dev/null+++ b/supabase/migrations/00103_cluster_opportunity_list.sql@@ -0,0 +1,106 @@+-- The Content page reads opportunities through their clusters (#857).+--+-- 1. Archive the per-prompt backlog. Before 00102, opportunities were+-- generated per prompt and piled up: thousands of open ones across brands,+-- up to ~760 on one brand, almost none ever worked on. Cluster+-- opportunities would be lost among them. Untouched ones (status 'new', no+-- brief) move to 'archived', which the list and its summary hide unless+-- asked for. Nothing is deleted: setting one back to 'new' restores it.+-- Ones with a brief, or that moved past 'new', are left alone.+--+-- 2. content_opportunity_aggregates takes the list's new filters. A prompt+-- matches the opportunities of its cluster, not only the ones whose+-- prompt_id it is; a topic matches opportunities whose own or merged+-- clusters are in it. It also counts the brand's signals: the prompts+-- and fan-out queries its clusters were built from.++update public.content_opportunities+ set status = 'archived', updated_at = now()+ where cluster_id is null+ and status = 'new'+ and brief is null;++drop function if exists public.content_opportunity_aggregates(uuid, text, text, text, text, uuid);++create or replace function public.content_opportunity_aggregates(+ p_brand_id uuid,+ p_status text default null,+ p_impact text default null,+ p_type text default null,+ p_q text default null,+ p_prompt_id uuid default null,+ p_topic_id uuid default null+)+returns table (+ avg_score numeric,+ high_impact_count bigint,+ sent_count bigint,+ signal_count bigint+)+language sql+stable+security invoker+set search_path = public+as $$+ select+ coalesce(avg(co.opportunity_score), 0) as avg_score,+ count(*) filter (+ where co.impact = 'high'+ ) as high_impact_count,+ count(*) filter (+ where co.status in ('sent', 'in_progress', 'done')+ ) as sent_count,+ (+ select count(*)+ from prompt_cluster_members m+ join prompt_clusters pc on pc.id = m.cluster_id+ where pc.brand_id = p_brand_id+ ) + (+ select count(*)+ from prompt_cluster_queries q+ join prompt_clusters pc on pc.id = q.cluster_id+ where pc.brand_id = p_brand_id+ ) as signal_count+ from public.content_opportunities co+ where co.brand_id = p_brand_id+ and (+ (p_status is null and co.status <> 'archived')+ or co.status = p_status+ )+ and (p_impact is null or co.impact = p_impact)+ and (p_type is null or co.type = p_type)+ and (+ p_prompt_id is null+ or co.prompt_id = p_prompt_id+ or exists (+ select 1+ from prompt_cluster_members m+ where m.prompt_id = p_prompt_id+ and (m.cluster_id = co.cluster_id or m.cluster_id = any(co.related_cluster_ids))+ )+ )+ and (+ p_topic_id is null+ or exists (+ select 1+ from prompt_clusters pc+ where pc.topic_id = p_topic_id+ and (pc.id = co.cluster_id or pc.id = any(co.related_cluster_ids))+ )+ )+ and (+ p_q is null+ or co.title ilike '%' || p_q || '%'+ or co.description ilike '%' || p_q || '%'+ );+$$;++grant execute on function public.content_opportunity_aggregates(+ uuid,+ text,+ text,+ text,+ text,+ uuid,+ uuid+) to authenticated;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 35001b26b..50b63dd2c 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -12038,3 +12038,113 @@ $$;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;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00103_cluster_opportunity_list.sql+-- ─────────────────────────────────────────────────────────────────────────+-- The Content page reads opportunities through their clusters (#857).+--+-- 1. Archive the per-prompt backlog. Before 00102, opportunities were+-- generated per prompt and piled up: thousands of open ones across brands,+-- up to ~760 on one brand, almost none ever worked on. Cluster+-- opportunities would be lost among them. Untouched ones (status 'new', no+-- brief) move to 'archived', which the list and its summary hide unless+-- asked for. Nothing is deleted: setting one back to 'new' restores it.+-- Ones with a brief, or that moved past 'new', are left alone.+--+-- 2. content_opportunity_aggregates takes the list's new filters. A prompt+-- matches the opportunities of its cluster, not only the ones whose+-- prompt_id it is; a topic matches opportunities whose own or merged+-- clusters are in it. It also counts the brand's signals: the prompts+-- and fan-out queries its clusters were built from.++update public.content_opportunities+ set status = 'archived', updated_at = now()+ where cluster_id is null+ and status = 'new'+ and brief is null;++drop function if exists public.content_opportunity_aggregates(uuid, text, text, text, text, uuid);++create or replace function public.content_opportunity_aggregates(+ p_brand_id uuid,+ p_status text default null,+ p_impact text default null,+ p_type text default null,+ p_q text default null,+ p_prompt_id uuid default null,+ p_topic_id uuid default null+)+returns table (+ avg_score numeric,+ high_impact_count bigint,+ sent_count bigint,+ signal_count bigint+)+language sql+stable+security invoker+set search_path = public+as $$+ select+ coalesce(avg(co.opportunity_score), 0) as avg_score,+ count(*) filter (+ where co.impact = 'high'+ ) as high_impact_count,+ count(*) filter (+ where co.status in ('sent', 'in_progress', 'done')+ ) as sent_count,+ (+ select count(*)+ from prompt_cluster_members m+ join prompt_clusters pc on pc.id = m.cluster_id+ where pc.brand_id = p_brand_id+ ) + (+ select count(*)+ from prompt_cluster_queries q+ join prompt_clusters pc on pc.id = q.cluster_id+ where pc.brand_id = p_brand_id+ ) as signal_count+ from public.content_opportunities co+ where co.brand_id = p_brand_id+ and (+ (p_status is null and co.status <> 'archived')+ or co.status = p_status+ )+ and (p_impact is null or co.impact = p_impact)+ and (p_type is null or co.type = p_type)+ and (+ p_prompt_id is null+ or co.prompt_id = p_prompt_id+ or exists (+ select 1+ from prompt_cluster_members m+ where m.prompt_id = p_prompt_id+ and (m.cluster_id = co.cluster_id or m.cluster_id = any(co.related_cluster_ids))+ )+ )+ and (+ p_topic_id is null+ or exists (+ select 1+ from prompt_clusters pc+ where pc.topic_id = p_topic_id+ and (pc.id = co.cluster_id or pc.id = any(co.related_cluster_ids))+ )+ )+ and (+ p_q is null+ or co.title ilike '%' || p_q || '%'+ or co.description ilike '%' || p_q || '%'+ );+$$;++grant execute on function public.content_opportunity_aggregates(+ uuid,+ text,+ text,+ text,+ text,+ uuid,+ uuid+) to authenticated;+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 818a907b1..2b87bd7d0 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1634,7 +1634,8 @@"sent": "Sent to Workflow","in_progress": "In Progress","done": "Done",- "dismissed": "Dismissed"+ "dismissed": "Dismissed",+ "archived": "Archived"},"impact": {"high": "High",@@ -1653,12 +1654,14 @@"shown": "{count} shown","opportunities": "opportunities","outOf100": "out of 100",- "sentOrInProgress": "sent or in progress"+ "sentOrInProgress": "sent or in progress",+ "fromSignals": "from {count, plural, one {# signal} other {# signals}} analyzed"},"filters": {"allStatuses": "All Statuses","allImpacts": "All Impacts",- "allTypes": "All Types"+ "allTypes": "All Types",+ "allTopics": "All Topics"},"bulk": {"selected": "{count} selected",@@ -1750,7 +1753,10 @@"bulkDismissError": "Bulk dismiss failed","bulkDeleteError": "Bulk delete failed","briefGeneratedToast": "Content brief generated!",- "briefGenerateError": "Failed to generate brief"+ "briefGenerateError": "Failed to generate brief",+ "restore": "Restore",+ "restoredToast": "Restored to New",+ "restoreError": "Failed to restore the opportunity"},"traffic": {"title": "AI Traffic Analytics",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsxindex c0dcc3a66..511ccf7e6 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx@@ -22,6 +22,7 @@ import {Target,ListOrdered,Crown,+ RotateCcw,} from 'lucide-react';import { cn } from '@/lib/utils';import { Link } from '@/i18n/navigation';@@ -50,6 +51,7 @@ const STATUS_COLORS: Record<string, string> = {in_progress: 'border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400',done: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',dismissed: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400',+ archived: 'border-zinc-500/30 bg-zinc-500/5 text-zinc-500 dark:text-zinc-400',};const INTENT_LABELS: Record<string, string> = {@@ -166,6 +168,16 @@ export default function ContentDetailPage() {}};+ const handleRestore = async () => {+ try {+ await updateOpportunityStatus(id, 'new');+ setOpportunity(await getOpportunity(id));+ toast.success(t('restoredToast'));+ } catch {+ toast.error(t('restoreError'));+ }+ };+const handleGenerateBrief = async () => {setGeneratingBrief(true);try {@@ -220,6 +232,12 @@ export default function ContentDetailPage() {)}</div><div className="flex items-center gap-2">+ {opportunity.status === 'archived' && (+ <Button variant="outline" size="sm" onClick={handleRestore} className="gap-2">+ <RotateCcw className="h-4 w-4" />+ {t('restore')}+ </Button>+ )}{opportunity.status === 'new' && (<><Buttondiff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsxindex 216776150..e8a1d4703 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx@@ -65,7 +65,9 @@ import {getGenerationJobStatus,getOpportunities,getOpportunityPrompts,+ getOpportunityTopics,type OpportunityPrompt,+ type OpportunityTopic,updateOpportunityStatus,sendToWebhook,bulkSendToWebhook,@@ -126,6 +128,7 @@ const STATUS_COLORS: Record<string, string> = {in_progress: 'border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400',done: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',dismissed: 'border-zinc-500/30 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400',+ archived: 'border-zinc-500/30 bg-zinc-500/5 text-zinc-500 dark:text-zinc-400',};function KpiCard({@@ -188,6 +191,9 @@ export default function ContentPage() {const [urlRead, setUrlRead] = useState(false);// null until loaded for the current brand.const [promptOptions, setPromptOptions] = useState<OpportunityPrompt[] | null>(null);+ // Topic filter (#857): matches opportunities through their clusters.+ const [topicFilter, setTopicFilter] = useState('');+ const [topicOptions, setTopicOptions] = useState<OpportunityTopic[]>([]);const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());const [bulkSending, setBulkSending] = useState(false);@@ -199,6 +205,7 @@ export default function ContentPage() {avgScore: 0,highImpactCount: 0,sentCount: 0,+ signalCount: 0,});// Server-side paging (#610) — the list can hold far more than one page's@@ -206,7 +213,7 @@ export default function ContentPage() {// pager instead of the length of whatever page happens to be loaded.const pager = usePagination(total,- `${statusFilter}|${impactFilter}|${typeFilter}|${promptFilter}|${debouncedSearch}`,+ `${statusFilter}|${impactFilter}|${typeFilter}|${promptFilter}|${topicFilter}|${debouncedSearch}`,);const loadData = useCallback(@@ -219,6 +226,7 @@ export default function ContentPage() {avgScore: 0,highImpactCount: 0,sentCount: 0,+ signalCount: 0,});setLoading(false);return;@@ -232,6 +240,7 @@ export default function ContentPage() {if (impactFilter !== 'all') filters.impact = impactFilter;if (typeFilter !== 'all') filters.type = typeFilter;if (promptFilter) filters.promptId = promptFilter;+ if (topicFilter) filters.topicId = topicFilter;if (debouncedSearch.trim()) {filters.q = debouncedSearch.trim();}@@ -250,6 +259,7 @@ export default function ContentPage() {avgScore: 0,highImpactCount: 0,sentCount: 0,+ signalCount: 0,},);return data.total;@@ -270,6 +280,7 @@ export default function ContentPage() {impactFilter,typeFilter,promptFilter,+ topicFilter,pager.start,debouncedSearch,t,@@ -320,6 +331,20 @@ export default function ContentPage() {};}, [loadPromptOptions]);+ useEffect(() => {+ let cancelled = false;+ setTopicFilter('');+ setTopicOptions([]);+ if (!activeBrandId) return;+ getOpportunityTopics(activeBrandId)+ .then((options) => !cancelled && setTopicOptions(options))+ // Like the prompt filter, it just stays hidden without its options.+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, [activeBrandId]);+// A prompt id from another brand, or one whose prompt was deleted, would// filter to nothing while the picker shows "All prompts". Drop it.useEffect(() => {@@ -554,6 +579,7 @@ export default function ContentPage() {impactFilter !== 'all' ||typeFilter !== 'all' ||promptFilter !== '' ||+ topicFilter !== '' ||search.trim() !== '';const clearFilters = () => {@@ -561,6 +587,7 @@ export default function ContentPage() {setImpactFilter('all');setTypeFilter('all');selectPrompt('');+ setTopicFilter('');setSearch('');};@@ -646,7 +673,11 @@ export default function ContentPage() {title={t('kpi.total')}icon={Lightbulb}value={total}- sub={t('kpi.shown', { count: filtered.length })}+ sub={+ aggregates.signalCount > 0+ ? t('kpi.fromSignals', { count: aggregates.signalCount })+ : t('kpi.shown', { count: filtered.length })+ }/><KpiCardtitle={t('kpi.highImpact')}@@ -706,6 +737,7 @@ export default function ContentPage() {<SelectItem value="in_progress">{t('status.in_progress')}</SelectItem><SelectItem value="done">{t('status.done')}</SelectItem><SelectItem value="dismissed">{t('status.dismissed')}</SelectItem>+ <SelectItem value="archived">{t('status.archived')}</SelectItem></SelectContent></Select><Select value={impactFilter} onValueChange={(v) => v && setImpactFilter(v)}>@@ -735,6 +767,31 @@ export default function ContentPage() {<SelectItem value="earned">{t('type.earned')}</SelectItem></SelectContent></Select>+ {(topicOptions.length >= 2 || topicFilter !== '') && (+ <Select+ items={[+ { value: 'all', label: t('filters.allTopics') },+ ...topicOptions.map((o) => ({ value: o.topicId, label: o.name })),+ ]}+ value={topicFilter || 'all'}+ onValueChange={(v) => setTopicFilter(!v || v === 'all' ? '' : v)}+ >+ <SelectTrigger className="h-8 w-44 text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">{t('filters.allTopics')}</SelectItem>+ {topicOptions.map((o) => (+ <SelectItem key={o.topicId} value={o.topicId}>+ <span className="min-w-0 flex-1 truncate">{o.name}</span>+ <span className="ml-2 shrink-0 tabular-nums text-muted-foreground">+ {o.count}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}{showPromptFilter && (<Comboboxitems={promptItems}diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.tsindex 544166f03..dafeb488a 100644--- a/web/src/lib/actions/content.ts+++ b/web/src/lib/actions/content.ts@@ -84,6 +84,7 @@ export async function getOpportunities(q?: string;type?: string;promptId?: string;+ topicId?: string;limit?: number;offset?: number;sort?: string;@@ -95,6 +96,7 @@ export async function getOpportunities(avgScore: number;highImpactCount: number;sentCount: number;+ signalCount: number;};}> {const session = await getSession();@@ -105,6 +107,7 @@ export async function getOpportunities(if (filters?.q) params.set('q', filters.q);if (filters?.type) params.set('type', filters.type);if (filters?.promptId) params.set('prompt_id', filters.promptId);+ if (filters?.topicId) params.set('topic_id', filters.topicId);if (filters?.limit) params.set('limit', String(filters.limit));if (filters?.offset) params.set('offset', String(filters.offset));if (filters?.sort) params.set('sort', filters.sort);@@ -150,6 +153,29 @@ export async function getOpportunityPrompts(brandId: string): Promise<Opportunitreturn body.prompts;}+export interface OpportunityTopic {+ topicId: string;+ name: string;+ count: number;+}++export async function getOpportunityTopics(brandId: string): Promise<OpportunityTopic[]> {+ const session = await getSession();++ const res = await fetch(`${AEO_SERVER_URL}/api/content/brand/${brandId}/topics`, {+ 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}`);+ }++ const body = (await res.json()) as { topics: OpportunityTopic[] };+ return body.topics;+}+export async function getOpportunity(id: string): Promise<ContentOpportunity> {const session = await getSession();diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex d49771926..570d5d4fb 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -607,7 +607,7 @@ export interface ContentOpportunityRow {export interface ListContentOpportunitiesParams {brandId: string;- status?: 'new' | 'sent' | 'in_progress' | 'done' | 'dismissed';+ status?: 'new' | 'sent' | 'in_progress' | 'done' | 'dismissed' | 'archived';impact?: 'high' | 'medium' | 'low';type?: 'owned' | 'earned';limit?: number;@@ -640,7 +640,8 @@ export async function listContentOpportunitiesFor(.order('created_at', { ascending: false }).limit(limit);- if (params.status) query = query.eq('status', params.status);+ // The archived per-prompt backlog (#857) only when asked for by status.+ query = params.status ? query.eq('status', params.status) : query.neq('status', 'archived');if (params.impact) query = query.eq('impact', params.impact);if (params.type) query = query.eq('type', params.type);diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex a53910d62..ccc7766f3 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -267,9 +267,11 @@ export function createMcpServer(auth: McpAuthContext): McpServer {inputSchema: {brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),status: z- .enum(['new', 'sent', 'in_progress', 'done', 'dismissed'])+ .enum(['new', 'sent', 'in_progress', 'done', 'dismissed', 'archived']).optional()- .describe('Filter by progress status of the opportunity.'),+ .describe(+ 'Filter by progress status of the opportunity. Archived ones (an older per-prompt backlog) are left out unless asked for.',+ ),impact: z.enum(['high', 'medium', 'low']).optional()diff --git a/web/src/types/index.ts b/web/src/types/index.tsindex 90e8d8956..ca3f6c40e 100644--- a/web/src/types/index.ts+++ b/web/src/types/index.ts@@ -174,7 +174,13 @@ export interface PromptVolume {fetchedAt: string;}-export type ContentOpportunityStatus = 'new' | 'sent' | 'in_progress' | 'done' | 'dismissed';+export type ContentOpportunityStatus =+ | 'new'+ | 'sent'+ | 'in_progress'+ | 'done'+ | 'dismissed'+ | 'archived';export type ContentOpportunityImpact = 'high' | 'medium' | 'low';