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): decide create, optimize or expand from the site's pages (#939)
Gökhan Geyik824712d8ff61
diff --git a/server/src/lib/open-opportunities.js b/server/src/lib/open-opportunities.jsindex 4e950a8c0..4e3549508 100644--- a/server/src/lib/open-opportunities.js+++ b/server/src/lib/open-opportunities.js@@ -4,16 +4,18 @@ const PAGE = 1000;/*** A brand's cluster opportunities, every status, as { id, title, status,- * cluster_id, related_cluster_ids, opportunity_score }. Paged: a large brand- * can hold more than PostgREST's 1,000-row default, and a short read would- * let a covered cluster be suggested again.+ * cluster_id, related_cluster_ids, opportunity_score, targetPages }. Paged: a+ * large brand can hold more than PostgREST's 1,000-row default, and a short+ * read would let a covered cluster be suggested again.*/export async function loadClusterOpportunities(brandId) {const rows = [];for (let from = 0; ; from += PAGE) {const { data, error } = await supabaseAdmin.from('content_opportunities')- .select('id, title, status, cluster_id, related_cluster_ids, opportunity_score')+ .select(+ 'id, title, status, cluster_id, related_cluster_ids, opportunity_score, targetPages:source_data->targetPages',+ ).eq('brand_id', brandId).not('cluster_id', 'is', null).order('id')diff --git a/server/src/lib/opportunity-generator.js b/server/src/lib/opportunity-generator.jsindex 3cafb5a8c..0025f012d 100644--- a/server/src/lib/opportunity-generator.js+++ b/server/src/lib/opportunity-generator.js@@ -25,9 +25,16 @@ import {} from './opportunity-limits.js';import { loadClusterOpportunities } from './open-opportunities.js';import { loadClusters } from './prompt-clusters.js';+import { DECISIONS, candidatePages, resolveDecision } from './page-matching.js';/** Existing opportunities shown to the model for the cross-topic check. */const EXISTING_SHOWN = 60;+/**+ * Clusters an opportunity may absorb from other topics. Past this it stops+ * being offered as a merge target: one opportunity that keeps absorbing+ * neighbouring needs turns into a catch-all no single page can answer.+ */+export const MAX_MERGED_CLUSTERS = 3;/** Included fan-out queries kept on an opportunity, most searched first. */const QUERIES_KEPT = 15;const PROMPTS_SHOWN = 12;@@ -38,7 +45,15 @@ Rules:- One opportunity per cluster, for the content that answers all of its prompts. Name the need, not a single prompt.- Be concrete and actionable, and reference the data: volume, visibility, the strongest competitor's visibility, competitors.- Categorize as "owned" (content the brand controls) or "earned" (third-party content, PR, reviews).-- Existing opportunities from other topics are listed. If a cluster needs the same content as one of them — the same user need and the same piece of content — set sameAs to its bracketed E index. Otherwise set sameAs to null. Sharing words or a topic is not enough.+- Existing opportunities from other topics are listed. If a cluster needs the same content as one of them — the same user need and the same piece of content, answering the cluster's prompts without becoming a different page — set sameAs to its bracketed E index. Otherwise set sameAs to null. Sharing words, a topic or a product category is not enough.+- Decide what the content is, given the brand's pages listed under each cluster:+ - create: no listed page answers this need. Write a new page.+ - optimize: a listed page already targets this need. Make it the answer AI engines pick: structure, evidence, direct answers, FAQ.+ - expand: a listed page covers part of the need. Add the angles it misses.+ - refresh: a listed page covers the need but is out of date (old year, old last-modified date, stale facts).+ - consolidate: two or more listed pages are each mainly about this same need, close to duplicates, and split its signals. Merge them into one. Pages of different kinds (a head-to-head comparison and a general list, a glossary entry and a guide) are not duplicates: pick the page closest to the need and expand or optimize it instead.+ - defend: the brand is already visible for this need and a listed page answers it. Keep it ahead of competitors.+ Set pageIndexes to the bracketed P indexes of the pages the decision is about, and leave it empty for create. The title should say what to do with which page, for example "Expand the AI rank tracker comparison with Google AI Overviews coverage".- Write for the brand's marketing team: do not use the words "cluster" or "prompt" in titles or descriptions.- Refer to clusters and existing opportunities only through clusterIndex and sameAs. Never mention a bracketed index in a title or description.`;@@ -58,6 +73,10 @@ function buildSchema(count) {.describe('1-2 sentences on why it matters, referencing the metrics'),type: z.enum(['owned', 'earned']),impact: z.enum(['high', 'medium', 'low']),+ decision: z.enum(DECISIONS),+ pageIndexes: z+ .array(z.number())+ .describe('The P indexes of the existing pages the decision is about'),}),).max(count),@@ -132,20 +151,31 @@ export async function generateContentOpportunities(brandId, { model, onProgress.toISOString().slice(0, 10);const memberIds = clusters.flatMap((c) => c.prompt_ids);- const [prompts, volumes, metricsRes, topicsRes, domainsRes, existing] = await Promise.all([- loadPromptTexts(memberIds),- selectInChunks(memberIds, (chunk) =>+ const [prompts, volumes, metricsRes, topicsRes, domainsRes, existing, pagesRes] =+ await Promise.all([+ loadPromptTexts(memberIds),+ selectInChunks(memberIds, (chunk) =>+ supabaseAdmin+ .from('prompt_volumes')+ .select('prompt_id, est_ai_volume, intent, keywords')+ .in('prompt_id', chunk),+ ),+ supabaseAdmin.rpc('brand_prompt_opportunity_metrics', {+ p_brand_id: brandId,+ p_since: since,+ }),+ supabaseAdmin.from('topics').select('id, name').eq('brand_id', brandId),+ supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brandId),+ loadClusterOpportunities(brandId),+ // Pages that answered when last read; a 404 is not a page to work on.supabaseAdmin- .from('prompt_volumes')- .select('prompt_id, est_ai_volume, intent, keywords')- .in('prompt_id', chunk),- ),- supabaseAdmin.rpc('brand_prompt_opportunity_metrics', { p_brand_id: brandId, p_since: since }),- supabaseAdmin.from('topics').select('id, name').eq('brand_id', brandId),- supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brandId),- loadClusterOpportunities(brandId),- ]);+ .from('site_pages')+ .select('url, title, h1, description, lastmod, ai_citations, ga_sessions')+ .eq('brand_id', brandId)+ .eq('fetch_status', 200),+ ]);if (volumes.error) throw new Error(volumes.error.message);+ if (pagesRes.error) throw new Error(pagesRes.error.message);if (metricsRes.error) throw new Error(metricsRes.error.message);const byPrompt = new Map(prompts.map((p) => [p.id, { text: p.text }]));@@ -197,14 +227,32 @@ export async function generateContentOpportunities(brandId, { model, onProgressif (basketErr) throw new Error(basketErr.message);const shown = existing- .filter((o) => o.status !== 'dismissed' && clusterById.has(o.cluster_id))+ .filter(+ (o) =>+ o.status !== 'dismissed' &&+ clusterById.has(o.cluster_id) &&+ (o.related_cluster_ids || []).length < MAX_MERGED_CLUSTERS,+ ).sort((a, b) => b.opportunity_score - a.opportunity_score).slice(0, EXISTING_SHOWN);+ // Each cluster's candidate pages, by the words its need shares with them.+ const pagesFor = new Map(+ picked.map((cand) => {+ const c = clusterById.get(cand.id);+ const basket = basketSummary([c.id], basketRows || []);+ const need = [c.label, c.primary_intent, ...c.promptTexts, ...basket.top.map((q) => q.query)];+ return [cand.id, candidatePages(need.join(' '), pagesRes.data || [])];+ }),+ );+ const pageLine = (p, i) =>+ `[P${i}] ${p.title || p.h1 || p.url} — ${p.url} | AI citations (30d): ${p.ai_citations} | GA sessions (30d): ${p.ga_sessions} | Last modified: ${p.lastmod ? p.lastmod.slice(0, 10) : 'unknown'}`;+const clusterLine = (cand, i) => {const c = clusterById.get(cand.id);const m = cand.metrics;const basket = basketSummary([c.id], basketRows || []);+ const pages = pagesFor.get(cand.id);return `[${i}] ${c.label} (topic: ${topicName(c) || 'none'})Need: ${c.primary_intent}Prompts:@@ -213,7 +261,9 @@ ${c.promptTexts.map((t) => `- ${t}`).join('\n')}Searches AI engines ran for these prompts: ${basket.top.map((q) => q.query).join('; ') || 'none recorded'}-Est. AI volume: ${m.demand}/mo | Brand visibility: ${m.visibility}% | Strongest competitor: ${m.topCompetitorVisibility}% | Competitors visible: ${m.competitorsCited.join(', ') || 'none'}`;+Est. AI volume: ${m.demand}/mo | Brand visibility: ${m.visibility}% | Strongest competitor: ${m.topCompetitorVisibility}% | Competitors visible: ${m.competitorsCited.join(', ') || 'none'}+Brand pages that may cover this need:+${pages.map(pageLine).join('\n') || 'none found'}`;};const userPrompt = `Brand: ${brand.name}@@ -258,13 +308,17 @@ Write every title and description in ${getLanguageName(brand.language)}.`;.update({related_cluster_ids: ids.slice(1),opportunity_score: score,- source_data: sourceData({- clusters: ids.map((id) => clusterById.get(id)),- topicName,- metrics,- components,- queries: basketSummary(ids, basketRows || []),- }),+ source_data: {+ ...sourceData({+ clusters: ids.map((id) => clusterById.get(id)),+ topicName,+ metrics,+ components,+ queries: basketSummary(ids, basketRows || []),+ }),+ // The decision and its pages stay as first made.+ ...(target.targetPages ? { targetPages: target.targetPages } : {}),+ },updated_at: new Date().toISOString(),}).eq('id', target.id);@@ -276,6 +330,11 @@ Write every title and description in ${getLanguageName(brand.language)}.`;}const c = clusterById.get(cand.id);+ const { decision, pages } = resolveDecision(+ opp.decision,+ opp.pageIndexes,+ pagesFor.get(cand.id),+ );inserts.push({brand_id: brandId,cluster_id: c.id,@@ -286,13 +345,23 @@ Write every title and description in ${getLanguageName(brand.language)}.`;impact: opp.impact,opportunity_score: cand.score,status: 'new',- source_data: sourceData({- clusters: [c],- topicName,- metrics: cand.metrics,- components: cand.components,- queries: basketSummary([c.id], basketRows || []),- }),+ decision,+ source_data: {+ ...sourceData({+ clusters: [c],+ topicName,+ metrics: cand.metrics,+ components: cand.components,+ queries: basketSummary([c.id], basketRows || []),+ }),+ targetPages: pages.map((p) => ({+ url: p.url,+ title: p.title || p.h1 || null,+ aiCitations: p.ai_citations,+ gaSessions: p.ga_sessions,+ lastmod: p.lastmod,+ })),+ },});}diff --git a/server/src/lib/page-matching.js b/server/src/lib/page-matching.jsnew file mode 100644index 000000000..082bc9343--- /dev/null+++ b/server/src/lib/page-matching.js@@ -0,0 +1,100 @@+/**+ * Which of a brand's existing pages (lib/site-pages.js) might already cover a+ * cluster's need, and what to do about it (#857, Phase 2).+ *+ * Matching is lexical and cheap: it only narrows 500 pages down to a handful+ * of candidates. The model then reads those candidates next to the cluster+ * and makes the call — create, optimize, expand, refresh, consolidate or+ * defend — so a near-miss here costs nothing worse than a candidate it+ * ignores.+ */++/** Candidate pages shown to the model per cluster. */+export const CANDIDATES_PER_CLUSTER = 8;++export const DECISIONS = ['create', 'optimize', 'expand', 'refresh', 'consolidate', 'defend'];++const STOPWORDS = new Set(+ (+ 'the and for with what which who how why when where are was were can could should would ' ++ 'does did best top your you our their this that these those from into about than then ' ++ 'them they its has have had not but all any more most some such only also very just ' ++ 'use using used get make way ways vs versus guide list 2024 2025 2026 2027'+ ).split(' '),+);++/** Lower-cased word tokens worth matching on: three letters or more, no filler words. */+export function tokens(text) {+ const out = [];+ for (const raw of String(text ?? '')+ .toLowerCase()+ .match(/[\p{L}\p{N}]+/gu) || []) {+ if (raw.length < 3 || STOPWORDS.has(raw)) continue;+ // A plain plural matches its singular: "tools" and "tool".+ out.push(raw.length > 4 && raw.endsWith('s') && !raw.endsWith('ss') ? raw.slice(0, -1) : raw);+ }+ return out;+}++const slugText = (url) => {+ try {+ return new URL(url).pathname.replace(/[-_/]+/g, ' ');+ } catch {+ return '';+ }+};++/**+ * The pages most likely to cover a need, best first. A page scores the rarer+ * words it shares with the need, twice as much for words in its title, first+ * heading or URL as for words only in its description. At least two shared+ * words are required, so one common word cannot pull a page in.+ *+ * @param {string} needText - the cluster's label, need, prompts and searches+ * @param {{url: string, title?: string, h1?: string, description?: string}[]} pages+ */+export function candidatePages(needText, pages, limit = CANDIDATES_PER_CLUSTER) {+ const indexed = pages.map((p) => ({+ page: p,+ strong: new Set(tokens(`${p.title || ''} ${p.h1 || ''} ${slugText(p.url)}`)),+ weak: new Set(tokens(p.description)),+ }));+ const df = new Map();+ for (const { strong, weak } of indexed) {+ for (const t of new Set([...strong, ...weak])) df.set(t, (df.get(t) || 0) + 1);+ }++ const need = new Set(tokens(needText));+ const n = indexed.length;+ return indexed+ .map(({ page, strong, weak }) => {+ let score = 0;+ let shared = 0;+ for (const t of need) {+ const weight = strong.has(t) ? 2 : weak.has(t) ? 1 : 0;+ if (!weight) continue;+ shared += 1;+ score += weight * Math.log(1 + n / df.get(t));+ }+ return { page, score, shared };+ })+ .filter((c) => c.shared >= 2)+ .sort((a, b) => b.score - a.score)+ .slice(0, limit)+ .map((c) => c.page);+}++/**+ * The model's decision, held to what it can stand on: every decision other+ * than create needs an existing page, and consolidate needs two. Pages are+ * resolved from the candidate indexes, out-of-range ones dropped.+ */+export function resolveDecision(decision, pageIndexes, candidates) {+ const pages = [...new Set(pageIndexes || [])]+ .filter((i) => Number.isInteger(i) && i >= 0 && i < candidates.length)+ .map((i) => candidates[i]);+ const valid = DECISIONS.includes(decision) ? decision : 'create';+ if (valid === 'create' || !pages.length) return { decision: 'create', pages: [] };+ if (valid === 'consolidate' && pages.length < 2) return { decision: 'optimize', pages };+ return { decision: valid, pages };+}diff --git a/server/src/lib/page-matching.test.js b/server/src/lib/page-matching.test.jsnew file mode 100644index 000000000..295692eda--- /dev/null+++ b/server/src/lib/page-matching.test.js@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest';+import { candidatePages, resolveDecision, tokens } from './page-matching.js';++describe('tokens', () => {+ it('keeps meaningful words, folds plain plurals and handles any script', () => {+ expect(tokens('The BEST AI rank trackers for 2026')).toEqual(['rank', 'tracker']);+ expect(tokens('Yapay zekâ görünürlüğü araçları')).toEqual([+ 'yapay',+ 'zekâ',+ 'görünürlüğü',+ 'araçları',+ ]);+ expect(tokens('class process')).toEqual(['class', 'process']);+ });+});++describe('candidatePages', () => {+ const pages = [+ {+ url: 'https://example.com/blog/best-ai-rank-tracker-tools',+ title: 'Best AI Rank Tracker Tools',+ description: 'Compare rank trackers for AI search.',+ },+ {+ url: 'https://example.com/blog/google-ai-overviews-tracking',+ title: 'How to Track Google AI Overviews',+ description: 'Monitor rankings in AI Overviews.',+ },+ { url: 'https://example.com/pricing', title: 'Pricing', description: 'Plans for every team.' },+ {+ url: 'https://example.com/blog/rank',+ title: 'Rank',+ description: 'A page that shares one word.',+ },+ ];++ it('ranks pages by the rarer words they share with the need', () => {+ const found = candidatePages('Which AI rank tracker tools are most accurate?', pages);+ expect(found.map((p) => p.url)).toEqual([+ 'https://example.com/blog/best-ai-rank-tracker-tools',+ ]);+ });++ it('needs two shared words, so one common word does not pull a page in', () => {+ expect(candidatePages('pricing', pages)).toEqual([]);+ });++ it('keeps at most the limit', () => {+ expect(candidatePages('track rank google overviews tracker tools', pages, 1)).toHaveLength(1);+ });+});++describe('resolveDecision', () => {+ const candidates = [{ url: 'a' }, { url: 'b' }];++ it('keeps a decision its pages support', () => {+ expect(resolveDecision('expand', [1, 1, 9], candidates)).toEqual({+ decision: 'expand',+ pages: [{ url: 'b' }],+ });+ expect(resolveDecision('consolidate', [0, 1], candidates).decision).toBe('consolidate');+ });++ it('falls back when the pages are missing', () => {+ expect(resolveDecision('optimize', [], candidates)).toEqual({ decision: 'create', pages: [] });+ expect(resolveDecision('consolidate', [0], candidates).decision).toBe('optimize');+ expect(resolveDecision('create', [0], candidates)).toEqual({ decision: 'create', pages: [] });+ expect(resolveDecision('rewrite', [0], candidates).decision).toBe('create');+ });+});diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex 07e966fd5..04d2a30b8 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -29,6 +29,7 @@ function mapOpportunityRow(row) {brandId: row.brand_id,promptId: row.prompt_id,clusterId: row.cluster_id ?? null,+ decision: row.decision ?? null,title: row.title,description: row.description,type: row.type,@@ -930,6 +931,19 @@ export async function generateBriefForOpportunity(opportunityId, { force = false// A cluster opportunity (#857) answers several prompts: the brief treats// them as the questions the piece must answer, and the searches AI engines// ran for them as the related searches to cover.+ // What to do with the brand's existing pages (#857, Phase 2): the brief+ // works on the named page instead of drafting a new one beside it.+ const targetPages = sourceData.targetPages || [];+ const decisionContext =+ opportunity.decision && opportunity.decision !== 'create' && targetPages.length+ ? `+Decision: ${opportunity.decision} the existing page${targetPages.length > 1 ? 's' : ''} below rather than writing a new one.+${targetPages.map((p) => `- ${p.title || p.url} (${p.url})`).join('\n')}+`+ : opportunity.decision === 'create'+ ? '\nDecision: create a new page; the site has none for this need.\n'+ : '';+const clusterContext = sourceData.prompts?.length? `Questions this content must answer (the cluster's prompts):@@ -952,7 +966,7 @@ Opportunity:- Score: ${opportunity.opportunity_score}Related Prompt: "${promptText}"-${clusterContext}Intent: ${sourceData.intent || 'unknown'}+${clusterContext}${decisionContext}Intent: ${sourceData.intent || 'unknown'}Est. AI Volume: ${sourceData.estAiVolume || 0}/moCurrent Visibility: ${sourceData.visibilityScore || 0}%Competitor Gap: ${sourceData.competitorGap || 0}%diff --git a/supabase/migrations/00105_opportunity_decision.sql b/supabase/migrations/00105_opportunity_decision.sqlnew file mode 100644index 000000000..f2b117ecf--- /dev/null+++ b/supabase/migrations/00105_opportunity_decision.sql@@ -0,0 +1,10 @@+-- What a content opportunity asks for, given the brand's existing pages+-- (#857, Phase 2): write a new page, or work on one the site already has.+--+-- Decided at generation from the site page inventory (00104). The pages it+-- refers to are kept in source_data.targetPages. Opportunities from before+-- this keep decision null.++alter table public.content_opportunities+ add column decision text+ check (decision in ('create', 'optimize', 'expand', 'refresh', 'consolidate', 'defend'));diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 0781f03df..4f3a8cc7b 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -12228,3 +12228,17 @@ $$;revoke all on function public.brand_landing_page_sessions(uuid, date, integer) from public, anon, authenticated;grant execute on function public.brand_landing_page_sessions(uuid, date, integer) to service_role;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00105_opportunity_decision.sql+-- ─────────────────────────────────────────────────────────────────────────+-- What a content opportunity asks for, given the brand's existing pages+-- (#857, Phase 2): write a new page, or work on one the site already has.+--+-- Decided at generation from the site page inventory (00104). The pages it+-- refers to are kept in source_data.targetPages. Opportunities from before+-- this keep decision null.++alter table public.content_opportunities+ add column decision text+ check (decision in ('create', 'optimize', 'expand', 'refresh', 'consolidate', 'defend'));+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 2b87bd7d0..e71c56331 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1711,7 +1711,9 @@"visibilityGap": "Visibility gap","competitorGap": "Competitor gap","intent": "Intent"- }+ },+ "targetTitle": "Your Site",+ "targetStats": "{citations, plural, one {# AI citation} other {# AI citations}} · {sessions, plural, one {# session} other {# sessions}} in the last 30 days"},"webhook": {"title": "Webhook Settings",@@ -1756,7 +1758,23 @@"briefGenerateError": "Failed to generate brief","restore": "Restore","restoredToast": "Restored to New",- "restoreError": "Failed to restore the opportunity"+ "restoreError": "Failed to restore the opportunity",+ "decision": {+ "create": "Create",+ "optimize": "Optimize",+ "expand": "Expand",+ "refresh": "Refresh",+ "consolidate": "Consolidate",+ "defend": "Defend"+ },+ "decisionHint": {+ "create": "No page on your site answers this yet. Write a new one.",+ "optimize": "A page on your site already targets this. Make it the answer AI engines pick.",+ "expand": "A page on your site covers part of this. Add the angles it misses.",+ "refresh": "A page on your site covers this but is out of date. Update it.",+ "consolidate": "Several pages on your site target this and split its signals. Merge them into one.",+ "defend": "You are already visible here. Keep this page ahead of competitors."+ }},"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 511ccf7e6..0dc418117 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/[id]/page.tsx@@ -36,7 +36,11 @@ import {} from '@/lib/actions/content';import type { ContentBrief, ContentOpportunity } from '@/types';import { getPromptFanout, type FanoutSubQuery } from '@/lib/actions/fanout';-import { OpportunityBasketCard, ScoreBreakdown } from '@/components/content/opportunity-basket';+import {+ OpportunityBasketCard,+ ScoreBreakdown,+ TargetPagesCard,+} from '@/components/content/opportunity-basket';import { toast } from 'sonner';const IMPACT_COLORS: Record<string, string> = {@@ -287,7 +291,10 @@ export default function ContentDetailPage() {{opportunity.clusterId && (<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">- <div className="lg:col-span-2">+ <div className="space-y-4 lg:col-span-2">+ {opportunity.decision && (+ <TargetPagesCard decision={opportunity.decision} sourceData={sd} />+ )}<OpportunityBasketCard opportunityId={opportunity.id} /></div><ScoreBreakdown sourceData={sd} />diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsxindex e8a1d4703..96cf90c13 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx@@ -990,9 +990,16 @@ export default function ContentPage() {</Link></TableCell><TableCell className="text-center">- <Badge variant="outline" className="text-xs">- {t(`type.${opp.type}` as 'type.owned' | 'type.earned')}- </Badge>+ <div className="flex flex-col items-center gap-1">+ <Badge variant="outline" className="text-xs">+ {t(`type.${opp.type}` as 'type.owned' | 'type.earned')}+ </Badge>+ {opp.decision && (+ <Badge variant="secondary" className="text-[10px]">+ {t(`decision.${opp.decision}`)}+ </Badge>+ )}+ </div></TableCell><TableCell className="text-center"><Badgediff --git a/web/src/components/content/opportunity-basket.tsx b/web/src/components/content/opportunity-basket.tsxindex c8b169860..8619cd962 100644--- a/web/src/components/content/opportunity-basket.tsx+++ b/web/src/components/content/opportunity-basket.tsx@@ -2,13 +2,17 @@import { useEffect, useState } from 'react';import { useTranslations } from 'next-intl';-import { Layers, Search } from 'lucide-react';+import { ExternalLink, FileText, Layers, Search } from 'lucide-react';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';import { getOpportunityBasket } from '@/lib/actions/content';-import type { ContentOpportunitySourceData, OpportunityBasket } from '@/types';+import type {+ ContentOpportunityDecision,+ ContentOpportunitySourceData,+ OpportunityBasket,+} from '@/types';const SCORE_PARTS = [['demand', 40],@@ -174,3 +178,55 @@ export function OpportunityBasketCard({ opportunityId }: { opportunityId: string</Card>);}++/** The brand's existing pages an opportunity is about, and what to do with them. */+export function TargetPagesCard({+ decision,+ sourceData,+}: {+ decision: ContentOpportunityDecision;+ sourceData: ContentOpportunitySourceData;+}) {+ const t = useTranslations('content');+ const pages = sourceData.targetPages ?? [];++ return (+ <Card>+ <CardHeader className="pb-2">+ <div className="flex flex-wrap items-center gap-2">+ <FileText className="h-4 w-4 text-primary" />+ <CardTitle className="text-sm font-medium">{t('detail.targetTitle')}</CardTitle>+ <Badge variant="secondary" className="text-[10px]">+ {t(`decision.${decision}`)}+ </Badge>+ </div>+ <p className="text-xs text-muted-foreground">{t(`decisionHint.${decision}`)}</p>+ </CardHeader>+ {pages.length > 0 && (+ <CardContent className="space-y-2">+ {pages.map((p) => (+ <a+ key={p.url}+ href={p.url}+ target="_blank"+ rel="noreferrer"+ className="flex items-start justify-between gap-3 rounded-md border p-2.5 hover:bg-muted/50"+ >+ <div className="min-w-0">+ <p className="text-sm font-medium line-clamp-1">{p.title || p.url}</p>+ <p className="text-xs text-muted-foreground truncate">{p.url}</p>+ <p className="text-[11px] text-muted-foreground mt-0.5">+ {t('detail.targetStats', {+ citations: p.aiCitations,+ sessions: p.gaSessions,+ })}+ </p>+ </div>+ <ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground mt-1" />+ </a>+ ))}+ </CardContent>+ )}+ </Card>+ );+}diff --git a/web/src/types/index.ts b/web/src/types/index.tsindex ca3f6c40e..0a904e477 100644--- a/web/src/types/index.ts+++ b/web/src/types/index.ts@@ -186,6 +186,14 @@ export type ContentOpportunityImpact = 'high' | 'medium' | 'low';export type ContentOpportunityType = 'owned' | 'earned';+export type ContentOpportunityDecision =+ | 'create'+ | 'optimize'+ | 'expand'+ | 'refresh'+ | 'consolidate'+ | 'defend';+export interface ContentOpportunitySourceData {promptText?: string;estAiVolume?: number;@@ -212,6 +220,13 @@ export interface ContentOpportunitySourceData {intent: number;};windowDays?: number;+ targetPages?: {+ url: string;+ title: string | null;+ aiCitations: number;+ gaSessions: number;+ lastmod: string | null;+ }[];}export interface OpportunityBasket {@@ -240,6 +255,7 @@ export interface ContentOpportunity {brandId: string;promptId?: string;clusterId?: string | null;+ decision?: ContentOpportunityDecision | null;title: string;description?: string;type: ContentOpportunityType;