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): add the Content plan page (#1308)
Cihan33318dfa58c8
diff --git a/supabase/migrations/00220_content_plan_pages.sql b/supabase/migrations/00220_content_plan_pages.sqlnew file mode 100644index 000000000..7235f324b--- /dev/null+++ b/supabase/migrations/00220_content_plan_pages.sql@@ -0,0 +1,250 @@+-- ============================================================================+-- 00220: the brand's pages for the Content plan (Content Editor, CE-014)+-- ============================================================================+-- The Plan (spec v2 §4) answers what to work on first. Content Opportunities+-- name the new pages AI needs; this reads the brand's own pages, so the Plan+-- can tell which to optimize, which to protect and which compete:+--+-- * answers {cur, prev}: the brand's tracked answers in each window, the+-- denominator that makes the two windows comparable (a brand tracked+-- weekly, prompts added or removed);+-- * citations {cur, prev}: AI answers' citations of the page over the last+-- p_days whole UTC days to yesterday and the p_days before. Today is left+-- out: its runs land through the morning (UTC), so it would read short;+-- * platformsDown: the platforms citing it at a lower rate (citations per+-- answer of that platform) than before, the biggest drop first;+-- * aiVisits: AI-referred visits in the current window, by+-- ai_traffic_merged's rule (00176): the snippet's visits, and Analytics'+-- sessions on days the snippet has none;+-- * overlaps: how many of the brand's other pages are cited for at least+-- two of the same prompts in the current window (pages competing).+--+-- Citations come from the daily rollups (citation_url_daily, answers from+-- citation_result_daily), as ai_traffic_page_citations reads them, so the+-- cost follows the window and not the brand's history; ChatGPT Shopping is+-- left out, as there. Only the overlaps need each citation's prompt: raw+-- rows of the current window, for the chosen pages, through the covering+-- indexes (00207, 00209).+--+-- The 100 pages cited most over both windows. Security definer with an+-- organization check, as 00209; null outside the member's organization.++create or replace function public.content_plan_pages(+ p_brand_id uuid,+ p_days integer default 30+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+-- A cached generic plan can't see the brand's size (00207).+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_last date := (now() at time zone 'utc')::date - 1;+ v_cur_day date;+ v_prev_day date;+ v_cur timestamptz;+ v_until timestamptz;+ v_result jsonb;+begin+ if not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) and auth.role() is distinct from 'service_role' then+ return null;+ end if;+ if p_days not in (7, 30) then+ raise exception 'p_days must be 7 or 30';+ end if;++ v_cur_day := v_last - p_days + 1;+ v_prev_day := v_cur_day - p_days;+ v_cur := v_cur_day::timestamp at time zone 'utc';+ v_until := (v_last + 1)::timestamp at time zone 'utc';++ with own_domains as (+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain+ from public.brand_domains bd+ where bd.brand_id = p_brand_id+ ),+ own_urls as materialized (+ select cu.id, cu.url, cu.title, lower(public.normalize_page_path(cu.url)) as page_key+ from public.citation_urls cu+ where cu.domain in (select domain from own_domains)+ ),+ url_counts as materialized (+ select d.url_id, d.platform, d.day >= v_cur_day as is_cur, sum(d.citations)::bigint as n+ from public.citation_url_daily d+ where d.brand_id = p_brand_id+ and d.day >= v_prev_day+ and d.day <= v_last+ and d.url_id in (select id from own_urls)+ and d.platform is distinct from 'chatgpt-shopping'+ group by d.url_id, d.platform, d.day >= v_cur_day+ ),+ url_totals as (+ select+ u.page_key,+ u.url,+ u.title,+ coalesce(sum(c.n) filter (where c.is_cur), 0) as cur,+ coalesce(sum(c.n) filter (where not c.is_cur), 0) as prev+ from url_counts c+ join own_urls u on u.id = c.url_id+ group by u.page_key, u.url, u.title+ ),+ pages as materialized (+ select+ t.page_key,+ -- The address cited most often stands for the page.+ (array_agg(t.url order by t.cur + t.prev desc, t.url))[1] as page,+ max(t.title) as title,+ sum(t.cur)::bigint as cur,+ sum(t.prev)::bigint as prev+ from url_totals t+ group by t.page_key+ order by sum(t.cur + t.prev) desc, t.page_key+ limit 100+ ),+ answers as (+ select+ r.platform,+ coalesce(sum(r.answers) filter (where r.day >= v_cur_day), 0)::bigint as cur,+ coalesce(sum(r.answers) filter (where r.day < v_cur_day), 0)::bigint as prev+ from public.citation_result_daily r+ where r.brand_id = p_brand_id+ and r.day >= v_prev_day+ and r.day <= v_last+ and r.platform is distinct from 'chatgpt-shopping'+ group by r.platform+ ),+ per_platform as (+ select+ u.page_key,+ c.platform,+ coalesce(sum(c.n) filter (where c.is_cur), 0) as cur,+ coalesce(sum(c.n) filter (where not c.is_cur), 0) as prev+ from url_counts c+ join own_urls u on u.id = c.url_id+ where u.page_key in (select p.page_key from pages p)+ and c.platform is not null+ group by u.page_key, c.platform+ ),+ down as (+ -- A platform tracked in both windows, citing the page at a lower rate.+ select+ pp.page_key,+ array_agg(+ pp.platform+ order by pp.prev::numeric / a.prev - pp.cur::numeric / a.cur desc, pp.platform+ ) as platforms+ from per_platform pp+ join answers a on a.platform = pp.platform+ where a.prev > 0+ and a.cur > 0+ and pp.prev::numeric / a.prev > pp.cur::numeric / a.cur+ group by pp.page_key+ ),+ cur_answers as materialized (+ select pr.id, pr.prompt_id+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.created_at >= v_cur+ and pr.created_at < v_until+ and pr.platform is distinct from 'chatgpt-shopping'+ ),+ page_prompts as (+ select distinct u.page_key, a.prompt_id+ from public.prompt_result_citations prc+ join own_urls u on u.id = prc.url_id+ join cur_answers a on a.id = prc.prompt_result_id+ where prc.brand_id = p_brand_id+ and prc.created_at >= v_cur+ and prc.created_at < v_until+ and u.page_key in (select p.page_key from pages p)+ ),+ competing as (+ select a.page_key, b.page_key as other+ from page_prompts a+ join page_prompts b on b.prompt_id = a.prompt_id and b.page_key <> a.page_key+ group by a.page_key, b.page_key+ having count(*) >= 2+ ),+ page_overlaps as (+ select cm.page_key, count(*) as pages+ from competing cm+ group by cm.page_key+ ),+ snippet_days as (+ select distinct (l.created_at at time zone 'utc')::date as day+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= v_cur+ and l.created_at < v_until+ ),+ visits as (+ select lower(public.normalize_page_path(l.url)) as page_key, 1::bigint as n+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= v_cur+ and l.created_at < v_until+ union all+ select lower(public.normalize_page_path(g.landing_page)), g.sessions::bigint+ from public.ga_ai_traffic_stats g+ where g.brand_id = p_brand_id+ and g.sessions > 0+ -- A session without a landing page would read as the home page.+ and g.landing_page <> ''+ and g.date >= v_cur_day+ and g.date <= v_last+ and not exists (select 1 from snippet_days s where s.day = g.date)+ ),+ page_visits as (+ select v.page_key, sum(v.n) as visits+ from visits v+ where v.page_key in (select p.page_key from pages p)+ group by v.page_key+ )+ select jsonb_build_object(+ 'days', p_days,+ 'answers', (+ select jsonb_build_object(+ 'cur', coalesce(sum(a.cur), 0),+ 'prev', coalesce(sum(a.prev), 0)+ )+ from answers a+ ),+ 'pages', coalesce((+ select jsonb_agg(+ jsonb_build_object(+ 'page', p.page,+ 'title', p.title,+ 'citations', jsonb_build_object('cur', p.cur, 'prev', p.prev),+ 'platformsDown', coalesce(to_jsonb(d.platforms[1:3]), '[]'::jsonb),+ 'aiVisits', coalesce(pv.visits, 0),+ 'overlaps', coalesce(o.pages, 0)+ )+ order by p.cur + p.prev desc, p.page+ )+ from pages p+ left join down d on d.page_key = p.page_key+ left join page_overlaps o on o.page_key = p.page_key+ left join page_visits pv on pv.page_key = p.page_key+ ), '[]'::jsonb)+ )+ into v_result;++ return v_result;+end;+$$;++revoke all on function public.content_plan_pages(uuid, integer) from public, anon;+grant execute on function public.content_plan_pages(uuid, integer) to authenticated, service_role;++comment on function public.content_plan_pages(uuid, integer) is+ 'Content Editor (CE-014): the brand''s 100 most cited pages over the last N (7 or 30) whole UTC days to yesterday and the N before, from the daily rollups: citations, the brand''s answers in each window, platforms citing at a lower rate, AI visits and how many of its other pages compete for the same prompts. Security definer with an organization check.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 28d945bf4..0d8aef04e 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -30518,3 +30518,257 @@ beginend;$$;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00220_content_plan_pages.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00220: the brand's pages for the Content plan (Content Editor, CE-014)+-- ============================================================================+-- The Plan (spec v2 §4) answers what to work on first. Content Opportunities+-- name the new pages AI needs; this reads the brand's own pages, so the Plan+-- can tell which to optimize, which to protect and which compete:+--+-- * answers {cur, prev}: the brand's tracked answers in each window, the+-- denominator that makes the two windows comparable (a brand tracked+-- weekly, prompts added or removed);+-- * citations {cur, prev}: AI answers' citations of the page over the last+-- p_days whole UTC days to yesterday and the p_days before. Today is left+-- out: its runs land through the morning (UTC), so it would read short;+-- * platformsDown: the platforms citing it at a lower rate (citations per+-- answer of that platform) than before, the biggest drop first;+-- * aiVisits: AI-referred visits in the current window, by+-- ai_traffic_merged's rule (00176): the snippet's visits, and Analytics'+-- sessions on days the snippet has none;+-- * overlaps: how many of the brand's other pages are cited for at least+-- two of the same prompts in the current window (pages competing).+--+-- Citations come from the daily rollups (citation_url_daily, answers from+-- citation_result_daily), as ai_traffic_page_citations reads them, so the+-- cost follows the window and not the brand's history; ChatGPT Shopping is+-- left out, as there. Only the overlaps need each citation's prompt: raw+-- rows of the current window, for the chosen pages, through the covering+-- indexes (00207, 00209).+--+-- The 100 pages cited most over both windows. Security definer with an+-- organization check, as 00209; null outside the member's organization.++create or replace function public.content_plan_pages(+ p_brand_id uuid,+ p_days integer default 30+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+-- A cached generic plan can't see the brand's size (00207).+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_last date := (now() at time zone 'utc')::date - 1;+ v_cur_day date;+ v_prev_day date;+ v_cur timestamptz;+ v_until timestamptz;+ v_result jsonb;+begin+ if not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) and auth.role() is distinct from 'service_role' then+ return null;+ end if;+ if p_days not in (7, 30) then+ raise exception 'p_days must be 7 or 30';+ end if;++ v_cur_day := v_last - p_days + 1;+ v_prev_day := v_cur_day - p_days;+ v_cur := v_cur_day::timestamp at time zone 'utc';+ v_until := (v_last + 1)::timestamp at time zone 'utc';++ with own_domains as (+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain+ from public.brand_domains bd+ where bd.brand_id = p_brand_id+ ),+ own_urls as materialized (+ select cu.id, cu.url, cu.title, lower(public.normalize_page_path(cu.url)) as page_key+ from public.citation_urls cu+ where cu.domain in (select domain from own_domains)+ ),+ url_counts as materialized (+ select d.url_id, d.platform, d.day >= v_cur_day as is_cur, sum(d.citations)::bigint as n+ from public.citation_url_daily d+ where d.brand_id = p_brand_id+ and d.day >= v_prev_day+ and d.day <= v_last+ and d.url_id in (select id from own_urls)+ and d.platform is distinct from 'chatgpt-shopping'+ group by d.url_id, d.platform, d.day >= v_cur_day+ ),+ url_totals as (+ select+ u.page_key,+ u.url,+ u.title,+ coalesce(sum(c.n) filter (where c.is_cur), 0) as cur,+ coalesce(sum(c.n) filter (where not c.is_cur), 0) as prev+ from url_counts c+ join own_urls u on u.id = c.url_id+ group by u.page_key, u.url, u.title+ ),+ pages as materialized (+ select+ t.page_key,+ -- The address cited most often stands for the page.+ (array_agg(t.url order by t.cur + t.prev desc, t.url))[1] as page,+ max(t.title) as title,+ sum(t.cur)::bigint as cur,+ sum(t.prev)::bigint as prev+ from url_totals t+ group by t.page_key+ order by sum(t.cur + t.prev) desc, t.page_key+ limit 100+ ),+ answers as (+ select+ r.platform,+ coalesce(sum(r.answers) filter (where r.day >= v_cur_day), 0)::bigint as cur,+ coalesce(sum(r.answers) filter (where r.day < v_cur_day), 0)::bigint as prev+ from public.citation_result_daily r+ where r.brand_id = p_brand_id+ and r.day >= v_prev_day+ and r.day <= v_last+ and r.platform is distinct from 'chatgpt-shopping'+ group by r.platform+ ),+ per_platform as (+ select+ u.page_key,+ c.platform,+ coalesce(sum(c.n) filter (where c.is_cur), 0) as cur,+ coalesce(sum(c.n) filter (where not c.is_cur), 0) as prev+ from url_counts c+ join own_urls u on u.id = c.url_id+ where u.page_key in (select p.page_key from pages p)+ and c.platform is not null+ group by u.page_key, c.platform+ ),+ down as (+ -- A platform tracked in both windows, citing the page at a lower rate.+ select+ pp.page_key,+ array_agg(+ pp.platform+ order by pp.prev::numeric / a.prev - pp.cur::numeric / a.cur desc, pp.platform+ ) as platforms+ from per_platform pp+ join answers a on a.platform = pp.platform+ where a.prev > 0+ and a.cur > 0+ and pp.prev::numeric / a.prev > pp.cur::numeric / a.cur+ group by pp.page_key+ ),+ cur_answers as materialized (+ select pr.id, pr.prompt_id+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.created_at >= v_cur+ and pr.created_at < v_until+ and pr.platform is distinct from 'chatgpt-shopping'+ ),+ page_prompts as (+ select distinct u.page_key, a.prompt_id+ from public.prompt_result_citations prc+ join own_urls u on u.id = prc.url_id+ join cur_answers a on a.id = prc.prompt_result_id+ where prc.brand_id = p_brand_id+ and prc.created_at >= v_cur+ and prc.created_at < v_until+ and u.page_key in (select p.page_key from pages p)+ ),+ competing as (+ select a.page_key, b.page_key as other+ from page_prompts a+ join page_prompts b on b.prompt_id = a.prompt_id and b.page_key <> a.page_key+ group by a.page_key, b.page_key+ having count(*) >= 2+ ),+ page_overlaps as (+ select cm.page_key, count(*) as pages+ from competing cm+ group by cm.page_key+ ),+ snippet_days as (+ select distinct (l.created_at at time zone 'utc')::date as day+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= v_cur+ and l.created_at < v_until+ ),+ visits as (+ select lower(public.normalize_page_path(l.url)) as page_key, 1::bigint as n+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= v_cur+ and l.created_at < v_until+ union all+ select lower(public.normalize_page_path(g.landing_page)), g.sessions::bigint+ from public.ga_ai_traffic_stats g+ where g.brand_id = p_brand_id+ and g.sessions > 0+ -- A session without a landing page would read as the home page.+ and g.landing_page <> ''+ and g.date >= v_cur_day+ and g.date <= v_last+ and not exists (select 1 from snippet_days s where s.day = g.date)+ ),+ page_visits as (+ select v.page_key, sum(v.n) as visits+ from visits v+ where v.page_key in (select p.page_key from pages p)+ group by v.page_key+ )+ select jsonb_build_object(+ 'days', p_days,+ 'answers', (+ select jsonb_build_object(+ 'cur', coalesce(sum(a.cur), 0),+ 'prev', coalesce(sum(a.prev), 0)+ )+ from answers a+ ),+ 'pages', coalesce((+ select jsonb_agg(+ jsonb_build_object(+ 'page', p.page,+ 'title', p.title,+ 'citations', jsonb_build_object('cur', p.cur, 'prev', p.prev),+ 'platformsDown', coalesce(to_jsonb(d.platforms[1:3]), '[]'::jsonb),+ 'aiVisits', coalesce(pv.visits, 0),+ 'overlaps', coalesce(o.pages, 0)+ )+ order by p.cur + p.prev desc, p.page+ )+ from pages p+ left join down d on d.page_key = p.page_key+ left join page_overlaps o on o.page_key = p.page_key+ left join page_visits pv on pv.page_key = p.page_key+ ), '[]'::jsonb)+ )+ into v_result;++ return v_result;+end;+$$;++revoke all on function public.content_plan_pages(uuid, integer) from public, anon;+grant execute on function public.content_plan_pages(uuid, integer) to authenticated, service_role;++comment on function public.content_plan_pages(uuid, integer) is+ 'Content Editor (CE-014): the brand''s 100 most cited pages over the last N (7 or 30) whole UTC days to yesterday and the N before, from the daily rollups: citations, the brand''s answers in each window, platforms citing at a lower rate, AI visits and how many of its other pages compete for the same prompts. Security definer with an organization check.';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 8b58e6a73..0c5ec228e 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -74,6 +74,7 @@"promptsInsights": "Insights","contentOpportunities": "Opportunities","contentLibrary": "Library",+ "contentPlan": "Plan","toggleSubmenu": "Show or hide {label}"},"actionCenter": {@@ -3091,6 +3092,56 @@"openDetails": "Open topic details"},"contentEditor": {+ "plan": {+ "title": "Content plan",+ "description": "What to create, optimize or protect next.",+ "selectBrand": "Select a brand to see its content plan.",+ "period": "Period",+ "periods": "Last {days} days",+ "newContent": "New content",+ "cards": {+ "create": { "title": "Create", "hint": "New pages AI needs" },+ "optimize": { "title": "Optimize", "hint": "Pages losing ground" },+ "protect": { "title": "Protect", "hint": "Top pages · edit with care" },+ "overlaps": { "title": "Overlaps", "hint": "Pages competing for the same prompts" }+ },+ "listTitle": "Priority list",+ "ranked": "Ranked by impact · overlaps checked",+ "filtered": "Filtered · click the card again to clear",+ "columns": {+ "page": "Page",+ "action": "Action",+ "why": "Why · last {days} days",+ "who": "Who",+ "start": "Start"+ },+ "newPage": "New page",+ "overlap": "⚠ Overlap",+ "overlapHint": "{count, plural, one {# other page of yours is} other {# other pages of yours are}} cited for the same prompts",+ "actions": { "create": "Create", "optimize": "Optimize", "protect": "Protect" },+ "sources": {+ "opportunity": "Opportunity",+ "citations": "Citations",+ "protect": "Protect",+ "overlap": "Overlap"+ },+ "why": {+ "competitors": "{names} cited · you aren't",+ "competitorsVisibility": "{names} cited · you {visibility}%",+ "opportunity": "{count, plural, =0 {A page AI needs} one {Answers # prompt AI asks} other {Answers # prompts AI asks}}",+ "citationsDown": "Citations −{pct}%",+ "on": "on {platforms}",+ "top": "Top page · {citations, plural, one {{citationsText} citation} other {{citationsText} citations}} · {visits, plural, one {{visitsText} AI visit} other {{visitsText} AI visits}}",+ "overlap": "Competes with {count, plural, one {# of your pages} other {# of your pages}} for the same prompts"+ },+ "who": { "you": "You", "agent": "Agent", "team": "Teammate" },+ "start": { "create": "Create", "optimize": "Optimize", "protect": "View" },+ "openDraft": "Open draft",+ "empty": "Nothing to work on yet. New opportunities and your pages' AI citations show up here.",+ "emptyFiltered": "Nothing here for this period.",+ "loadError": "Couldn't load the content plan.",+ "retry": "Try again"+ },"agentState": {"writing": "Agent writing…","failed": "Agent failed"diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-table.tsxnew file mode 100644index 000000000..3be00d380--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-table.tsx@@ -0,0 +1,186 @@+'use client';++import { useFormatter, useTranslations } from 'next-intl';+import { Bot, User } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button-variants';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import { DRAFT_METHOD_BADGE, DRAFT_STATUS_BADGE } from '@/components/content/draft-badges';+import { contentEditorPath, isPageType } from '@/lib/content/drafts';+import { platformNames } from '@/lib/content/impact';+import { pagePath } from '@/lib/content/overlap';+import type { PlanAction, PlanPeriod, PlanRow, PlanWhy } from '@/lib/content/plan';+import { formatNumber } from '@/lib/format';+import { cn } from '@/lib/utils';++/** Create blue, Optimize amber (as the drafts' method), Protect green. */+export const PLAN_ACTION_BADGE: Record<PlanAction, string> = {+ create: DRAFT_METHOD_BADGE.create,+ optimize: DRAFT_METHOD_BADGE.optimize,+ protect: DRAFT_STATUS_BADGE.ready,+};++/**+ * The Plan's priority list (CE-014): rank, the page (a new one, or the+ * brand's own), the action, why for the period with where it comes from,+ * who is on it, and the button that starts it — or opens its draft.+ */+export function PlanTable({+ rows,+ days,+ onStart,+}: {+ rows: PlanRow[];+ days: PlanPeriod;+ onStart: (row: PlanRow) => void;+}) {+ const t = useTranslations('contentEditor.plan');+ const tTypes = useTranslations('contentEditor.pageTypes');++ return (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-10 pl-6">#</TableHead>+ <TableHead>{t('columns.page')}</TableHead>+ <TableHead>{t('columns.action')}</TableHead>+ <TableHead>{t('columns.why', { days })}</TableHead>+ {/* Wide windows only: the row's button says the same once a draft exists. */}+ <TableHead className="hidden xl:table-cell">{t('columns.who')}</TableHead>+ <TableHead className="pr-6">+ <span className="sr-only">{t('columns.start')}</span>+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.map((row, i) => (+ <TableRow key={row.key}>+ <TableCell className="pl-6 tabular-nums text-muted-foreground">{i + 1}</TableCell>+ <TableCell className="max-w-[260px]">+ <p className="truncate font-medium" title={row.title}>+ {row.title}+ </p>+ <p className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">+ {isPageType(row.pageType) && (+ <Badge variant="outline" className="shrink-0 font-normal">+ {tTypes(row.pageType)}+ </Badge>+ )}+ <span className="truncate" title={row.page ?? undefined}>+ {row.page ? pagePath(row.page) : t('newPage')}+ </span>+ {row.overlaps > 0 && (+ <span+ className="shrink-0 font-medium text-amber-700 dark:text-amber-400"+ title={t('overlapHint', { count: row.overlaps })}+ >+ {t('overlap')}+ </span>+ )}+ </p>+ </TableCell>+ <TableCell>+ <Badge variant="outline" className={PLAN_ACTION_BADGE[row.action]}>+ {t(`actions.${row.action}`)}+ </Badge>+ </TableCell>+ <TableCell className="min-w-[200px] max-w-[320px] whitespace-normal">+ <WhyText why={row.why} />+ <span className="ml-1.5 rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground">+ {t(`sources.${row.source}`)}+ </span>+ </TableCell>+ <TableCell className="hidden text-muted-foreground xl:table-cell">+ {row.draft ? (+ <span className="inline-flex items-center gap-1.5">+ {row.draft.author === 'agent' ? (+ <Bot aria-hidden className="h-3.5 w-3.5" />+ ) : (+ <User aria-hidden className="h-3.5 w-3.5" />+ )}+ {row.draft.author === 'agent'+ ? t('who.agent')+ : row.draft.isMine+ ? t('who.you')+ : t('who.team')}+ </span>+ ) : (+ '—'+ )}+ </TableCell>+ <TableCell className="pr-6 text-right">+ {row.draft ? (+ <Link+ href={contentEditorPath(row.draft.id)}+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }))}+ >+ {t('openDraft')}+ </Link>+ ) : (+ <Button+ size="sm"+ variant={row.action === 'protect' ? 'outline' : 'default'}+ onClick={() => onStart(row)}+ >+ {t(`start.${row.action}`)}+ </Button>+ )}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ );+}++function WhyText({ why }: { why: PlanWhy }) {+ const t = useTranslations('contentEditor.plan.why');+ const format = useFormatter();+ switch (why.kind) {+ case 'competitors':+ return (+ <span>+ {why.visibility === null+ ? t('competitors', { names: format.list(why.names) })+ : t('competitorsVisibility', {+ names: format.list(why.names),+ visibility: formatNumber(why.visibility),+ })}+ </span>+ );+ case 'opportunity':+ return <span>{t('opportunity', { count: why.prompts })}</span>;+ case 'citationsDown':+ return (+ <span>+ <span className="font-medium text-red-600 dark:text-red-400">+ {t('citationsDown', { pct: why.pct })}+ </span>+ {why.platforms.length > 0 &&+ ` ${t('on', { platforms: format.list(platformNames(why.platforms)) })}`}+ </span>+ );+ case 'top':+ return (+ <span>+ {t('top', {+ citations: why.citations,+ citationsText: formatNumber(why.citations),+ visits: why.aiVisits,+ visitsText: formatNumber(why.aiVisits),+ })}+ </span>+ );+ case 'overlap':+ return <span>{t('overlap', { count: why.pages })}</span>;+ }+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsxnew file mode 100644index 000000000..0b696cb56--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx@@ -0,0 +1,237 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../../messages/en.json';+import type { PlanOpportunity, PlanPage } from '@/lib/content/plan';+import ContentPlanPage from './page';++const getContentPlan = vi.fn();+vi.mock('@/lib/actions/content-plan', () => ({+ getContentPlan: (...args: unknown[]) => getContentPlan(...args),+}));+// New content is new-content-dialog.test.tsx's; here, what the Plan opens it on.+const dialog = vi.hoisted(() => ({ props: null as Record<string, unknown> | null }));+vi.mock('@/components/content/new-content-dialog', () => ({+ NewContentDialog: (props: Record<string, unknown>) => {+ dialog.props = props;+ return null;+ },+}));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+}));+const brandState = vi.hoisted(() => ({+ activeBrandId: 'brand-1' as string | null,+ brands: [{ id: 'brand-1', siteType: 'b2b' }],+}));+vi.mock('@/stores/use-brand-store', () => ({+ useBrandStore: (selector: (state: typeof brandState) => unknown) => selector(brandState),+}));++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const page = (path: string, over: Partial<PlanPage> = {}): PlanPage => ({+ page: `https://acme.example${path}`,+ title: null,+ citations: { cur: 2, prev: 2 },+ platformsDown: [],+ aiVisits: 0,+ overlaps: 0,+ ...over,+});+const opportunity: PlanOpportunity = {+ id: 'o1',+ title: 'Create an office coffee page',+ pageTitle: 'Office coffee subscriptions',+ decision: 'create',+ score: 74,+ targetPage: null,+ targetTitle: null,+ competitorsCited: ['Daily Grind Co.', 'Origin Box'],+ visibility: 6,+ prompts: 2,+};+const PLAN = {+ pages: [+ page('/guides/coffee-subscriptions', {+ title: 'Coffee subscriptions',+ citations: { cur: 3, prev: 10 },+ platformsDown: ['chatgpt-web', 'perplexity-web'],+ }),+ page('/guides/espresso', {+ title: 'Espresso guide',+ citations: { cur: 12, prev: 10 },+ aiVisits: 42,+ overlaps: 1,+ }),+ ],+ answers: { cur: 100, prev: 100 },+ opportunities: [opportunity],+ drafts: [],+};++let container: HTMLDivElement;+let root: Root;++async function renderPage() {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <ContentPlanPage />+ </NextIntlClientProvider>,+ );+ });+}++const button = (name: string) =>+ [...container.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.startsWith(name),+ )!;+const rowTexts = () =>+ [...container.querySelectorAll('tbody tr')].map((tr) =>+ [...tr.querySelectorAll('td')].slice(1, 4).map((td) => td.textContent),+ );++beforeEach(() => {+ brandState.activeBrandId = 'brand-1';+ window.history.replaceState(null, '', '/dashboard/content/plan');+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ getContentPlan.mockReset().mockResolvedValue(PLAN);+ dialog.props = null;+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('the Content plan', () => {+ it('counts the work and ranks it, with why for the period', async () => {+ await renderPage();+ expect(getContentPlan).toHaveBeenCalledWith('brand-1', 30);+ expect(button('Create').textContent).toBe('Create1New pages AI needs');+ expect(button('Optimize').textContent).toBe('Optimize1Pages losing ground');+ expect(button('Protect').textContent).toBe('Protect1Top pages · edit with care');+ expect(button('Overlaps').textContent).toBe('Overlaps1Pages competing for the same prompts');++ expect(rowTexts()).toEqual([+ [+ 'Office coffee subscriptionsNew page',+ 'Create',+ 'Daily Grind Co. and Origin Box cited · you 6%Opportunity',+ ],+ [+ 'Coffee subscriptionsGuide/guides/coffee-subscriptions',+ 'Optimize',+ 'Citations −70% on ChatGPT and PerplexityCitations',+ ],+ [+ 'Espresso guideGuide/guides/espresso⚠ Overlap',+ 'Protect',+ 'Top page · 12 citations · 42 AI visitsProtect',+ ],+ ]);+ expect(container.querySelector('thead')!.textContent).toContain('Why · last 30 days');+ });++ it('filters the list by a card, and clears it on a second click', async () => {+ await renderPage();+ await act(async () => button('Overlaps').click());+ expect(button('Overlaps').getAttribute('aria-pressed')).toBe('true');+ expect(rowTexts().map((r) => r[1])).toEqual(['Protect']);+ expect(container.textContent).toContain('Filtered · click the card again to clear');++ await act(async () => button('Overlaps').click());+ expect(rowTexts()).toHaveLength(3);+ });++ it('reads the other period, and keeps it in the URL', async () => {+ await renderPage();+ await act(async () => button('Last 7 days').click());+ expect(getContentPlan).toHaveBeenLastCalledWith('brand-1', 7);+ expect(window.location.search).toBe('?days=7');+ expect(container.querySelector('thead')!.textContent).toContain('Why · last 7 days');+ });++ it('opens on the period in the URL, read once', async () => {+ window.history.replaceState(null, '', '/dashboard/content/plan?days=7');+ await renderPage();+ expect(getContentPlan.mock.calls).toEqual([['brand-1', 7]]);+ });++ it('starts an opportunity for an existing page on that page', async () => {+ getContentPlan.mockResolvedValue({+ ...PLAN,+ pages: [],+ opportunities: [+ {+ ...opportunity,+ decision: 'optimize',+ targetPage: 'https://acme.example/pricing',+ targetTitle: 'Pricing',+ },+ ],+ });+ await renderPage();+ await act(async () => container.querySelector<HTMLButtonElement>('tbody tr button')!.click());+ expect(dialog.props).toMatchObject({+ preset: {+ kind: 'opportunity',+ id: 'o1',+ page: { url: 'https://acme.example/pricing', title: 'Pricing' },+ },+ });+ });++ it('starts a row in New content, or opens the draft already being written', async () => {+ getContentPlan.mockResolvedValue({+ ...PLAN,+ drafts: [+ {+ id: 'd1',+ author: 'agent',+ isMine: false,+ method: 'optimize',+ opportunityId: null,+ sourceUrl: 'https://acme.example/guides/espresso',+ },+ ],+ });+ await renderPage();+ const rows = container.querySelectorAll('tbody tr');++ await act(async () => rows[1].querySelector('button')!.click());+ expect(dialog.props).toMatchObject({+ open: true,+ preset: { kind: 'page', url: 'https://acme.example/guides/coffee-subscriptions' },+ });+ await act(async () => (dialog.props!.onOpenChange as (open: boolean) => void)(false));+ expect(dialog.props).toMatchObject({ open: false, preset: null });++ await act(async () => rows[0].querySelector('button')!.click());+ expect(dialog.props).toMatchObject({ preset: { kind: 'opportunity', id: 'o1', page: null } });++ expect(rows[2].textContent).toContain('Agent');+ expect(rows[2].querySelector('a')!.getAttribute('href')).toBe('/dashboard/content/editor/d1');+ });++ it('says so when the plan can’t be read, and tries again', async () => {+ getContentPlan.mockRejectedValueOnce(new Error('boom'));+ await renderPage();+ expect(container.textContent).toContain("Couldn't load the content plan.");+ await act(async () => button('Try again').click());+ expect(getContentPlan).toHaveBeenCalledTimes(2);+ expect(rowTexts()).toHaveLength(3);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsxnew file mode 100644index 000000000..47500c99a--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx@@ -0,0 +1,236 @@+'use client';++import { useEffect, useMemo, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Loader2, Plus } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Card, CardContent } from '@/components/ui/card';+import { NewContentDialog, type DialogPreset } from '@/components/content/new-content-dialog';+import { getContentPlan } from '@/lib/actions/content-plan';+import { siteTypeOf } from '@/lib/content/page-types';+import {+ PLAN_CARDS,+ PLAN_PERIODS,+ buildPlan,+ rowsFor,+ type PlanCard,+ type PlanPeriod,+ type PlanRow,+} from '@/lib/content/plan';+import { formatNumber } from '@/lib/format';+import { readUrlChoice, writeUrlParams } from '@/lib/url-state';+import { cn } from '@/lib/utils';+import { useBrandStore } from '@/stores/use-brand-store';+import { PlanTable } from './_plan-table';++type PlanRead = {+ brandId: string;+ days: PlanPeriod;+ data: Awaited<ReturnType<typeof getContentPlan>>;+ failed: boolean;+};++/** Each card's color, as its action's tag: Create blue, Optimize amber, Protect green, Overlaps red. */+const CARD_DOT: Record<PlanCard, string> = {+ create: 'bg-blue-600 dark:bg-blue-400',+ optimize: 'bg-amber-600 dark:bg-amber-400',+ protect: 'bg-green-600 dark:bg-green-400',+ overlaps: 'bg-red-600 dark:bg-red-400',+};++/**+ * The Content plan (Content Editor CE-014, spec v2 §4): what to create,+ * optimize or protect next, for the last 7 or 30 days. Four cards count the+ * work and filter the list; the list ranks it, and each row starts it in New+ * content (Start for an opportunity, an existing page read to optimize) or+ * opens the draft already being written. The period lives in the URL+ * (?days=7).+ */+export default function ContentPlanPage() {+ const t = useTranslations('contentEditor.plan');+ const activeBrandId = useBrandStore((s) => s.activeBrandId);+ const activeBrand = useBrandStore((s) => s.brands.find((b) => b.id === s.activeBrandId));+ const siteType = siteTypeOf(activeBrand ?? {});+ // Null until the URL is read, so ?days=7 reads 7 days once, not 30 first.+ const [days, setDays] = useState<PlanPeriod | null>(null);+ const [card, setCard] = useState<PlanCard | null>(null);+ const [read, setRead] = useState<PlanRead | null>(null);+ const [attempt, setAttempt] = useState(0);+ const [starting, setStarting] = useState(false);+ const [preset, setPreset] = useState<DialogPreset | null>(null);++ useEffect(() => {+ // eslint-disable-next-line react-hooks/set-state-in-effect -- one read of the URL after mount+ setDays(Number(readUrlChoice('days', ['7', '30'], '30')) as PlanPeriod);+ }, []);++ useEffect(() => {+ if (!activeBrandId || days === null) return;+ let cancelled = false;+ getContentPlan(activeBrandId, days)+ .then((data) => {+ // Null: the brand isn't the member's to read.+ if (!cancelled) setRead({ brandId: activeBrandId, days, data, failed: data === null });+ })+ .catch((err) => {+ console.error('Failed to load the content plan:', err);+ if (!cancelled) setRead({ brandId: activeBrandId, days, data: null, failed: true });+ });+ return () => {+ cancelled = true;+ };+ }, [activeBrandId, days, attempt]);++ // A read for another brand or period (just switched) counts as still loading.+ const current = read?.brandId === activeBrandId && read.days === days ? read : null;+ const plan = useMemo(+ () => (current?.data ? buildPlan({ ...current.data, siteType }) : null),+ [current, siteType],+ );++ const changeDays = (next: PlanPeriod) => {+ setDays(next);+ writeUrlParams({ days: String(next) }, { days: '30' });+ };++ const startRow = (row: PlanRow) => {+ setPreset(+ row.opportunityId+ ? {+ kind: 'opportunity',+ id: row.opportunityId,+ // An opportunity for an existing page starts on that page.+ page: row.page ? { url: row.page, title: row.title } : null,+ }+ : { kind: 'page', url: row.page! },+ );+ setStarting(true);+ };++ if (!activeBrandId) {+ return (+ <div className="flex min-h-[400px] items-center justify-center">+ <p className="text-muted-foreground">{t('selectBrand')}</p>+ </div>+ );+ }++ const rows = plan ? rowsFor(plan.rows, card) : [];++ return (+ <div className="space-y-6">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="text-sm text-muted-foreground">{t('description')}</p>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <div+ role="group"+ aria-label={t('period')}+ className="inline-flex rounded-lg border bg-muted/40 p-0.5"+ >+ {PLAN_PERIODS.map((value) => (+ <button+ key={value}+ type="button"+ aria-pressed={days === value}+ onClick={() => changeDays(value)}+ className={cn(+ 'rounded-md px-3 py-1 text-sm transition-colors',+ days === value+ ? 'bg-background font-medium shadow-sm'+ : 'text-muted-foreground hover:text-foreground',+ )}+ >+ {t('periods', { days: value })}+ </button>+ ))}+ </div>+ <Button+ className="gap-2"+ onClick={() => {+ setPreset(null);+ setStarting(true);+ }}+ >+ <Plus className="h-4 w-4" />+ {t('newContent')}+ </Button>+ </div>+ </div>+ <NewContentDialog+ open={starting}+ onOpenChange={(open) => {+ setStarting(open);+ if (!open) setPreset(null);+ }}+ brandId={activeBrandId}+ siteType={siteType}+ preset={preset}+ onSent={() => setAttempt((n) => n + 1)}+ />++ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">+ {PLAN_CARDS.map((value) => (+ <button+ key={value}+ type="button"+ aria-pressed={card === value}+ disabled={!plan}+ onClick={() => setCard((c) => (c === value ? null : value))}+ className={cn(+ 'rounded-xl border bg-card p-4 text-left transition-colors hover:bg-muted/40 disabled:cursor-default disabled:hover:bg-card',+ card === value && 'border-foreground ring-1 ring-inset ring-foreground',+ )}+ >+ <span className="flex items-center gap-2 text-sm font-medium">+ <span aria-hidden className={cn('h-2 w-2 rounded-full', CARD_DOT[value])} />+ {t(`cards.${value}.title`)}+ </span>+ <span className="mt-2 block text-2xl font-semibold tabular-nums">+ {plan ? formatNumber(plan.counts[value]) : '—'}+ </span>+ <span className="block text-xs text-muted-foreground">{t(`cards.${value}.hint`)}</span>+ </button>+ ))}+ </div>++ <div className="space-y-2">+ <div className="flex flex-wrap items-baseline justify-between gap-2">+ <h2 className="text-sm font-medium">{t('listTitle')}</h2>+ <p className="text-xs text-muted-foreground">{card ? t('filtered') : t('ranked')}</p>+ </div>+ <Card className="py-0">+ <CardContent className="px-0">+ {current?.failed ? (+ <div className="flex flex-col items-center gap-3 px-6 py-12 text-center">+ <p className="text-sm text-muted-foreground">{t('loadError')}</p>+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ setRead(null);+ setAttempt((n) => n + 1);+ }}+ >+ {t('retry')}+ </Button>+ </div>+ ) : !plan ? (+ <div className="flex items-center justify-center py-12" aria-busy="true">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />+ </div>+ ) : rows.length === 0 ? (+ <p className="px-6 py-12 text-center text-sm text-muted-foreground">+ {card ? t('emptyFiltered') : t('empty')}+ </p>+ ) : (+ <PlanTable rows={rows} days={current?.days ?? 30} onStart={startRow} />+ )}+ </CardContent>+ </Card>+ </div>+ </div>+ );+}diff --git a/web/src/components/content/new-content-dialog.test.tsx b/web/src/components/content/new-content-dialog.test.tsxindex 4fe3d4f7d..3aeeeed27 100644--- a/web/src/components/content/new-content-dialog.test.tsx+++ b/web/src/components/content/new-content-dialog.test.tsx@@ -4,7 +4,7 @@ import { NextIntlClientProvider } from 'next-intl';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../messages/en.json';import type { SiteType } from '@/lib/content/page-types';-import { NewContentDialog } from './new-content-dialog';+import { NewContentDialog, type DialogPreset } from './new-content-dialog';const getContentStartOptions = vi.fn();const createContentDraft = vi.fn();@@ -71,7 +71,7 @@ const OPTIONS = {let container: HTMLDivElement;let root: Root;-async function render(siteType: SiteType = 'b2b') {+async function render(siteType: SiteType = 'b2b', preset: DialogPreset | null = null) {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages}>@@ -81,6 +81,7 @@ async function render(siteType: SiteType = 'b2b') {brandId="b1"siteType={siteType}onSent={onSent}+ preset={preset}/></NextIntlClientProvider>,);@@ -262,6 +263,60 @@ describe('New content', () => {expect(button('Pick an opportunity')).toBeDefined();});+ describe('opened from the Content plan (CE-014)', () => {+ it('goes straight to Start for the opportunity', async () => {+ await render('b2b', { kind: 'opportunity', id: 'o2' });+ expect(document.body.textContent).toContain('Create: CRM for real estate teams');+ await click(button('Open editor'));+ expect(createContentDraft.mock.calls[0][1]).toMatchObject({+ method: 'create',+ title: 'CRM for real estate teams',+ source: { kind: 'opportunity', id: 'o2' },+ });+ });++ it('reads the page to optimize', async () => {+ importContentPage.mockResolvedValue({+ page: {+ url: 'https://northwind.example/pricing',+ title: 'Pricing',+ html: '<h1>Pricing</h1>',+ },+ });+ await render('b2b', { kind: 'page', url: 'https://northwind.example/pricing' });+ await act(async () => {});+ expect(importContentPage).toHaveBeenCalledWith('b1', 'https://northwind.example/pricing');+ expect(radio('Optimize content')!.getAttribute('aria-checked')).toBe('true');+ await click(button('Continue'));+ expect(document.body.textContent).toContain('Optimize: Pricing');+ });++ it('starts an opportunity for an existing page on that page, whatever the check recommends', async () => {+ // The check would recommend a new page: no page of the brand answers the prompts.+ getContentOverlap.mockResolvedValue({ totalPrompts: 2, pages: [] });+ await render('b2b', {+ kind: 'opportunity',+ id: 'o2',+ page: { url: 'https://northwind.example/pricing', title: 'Pricing' },+ });+ await act(async () => {});+ expect(document.body.textContent).toContain('Optimize: Pricing');+ await click(button('Open editor'));+ expect(createContentDraft.mock.calls[0][1]).toMatchObject({+ method: 'optimize',+ title: 'Pricing',+ source: { kind: 'opportunity', id: 'o2' },+ sourceUrl: 'https://northwind.example/pricing',+ });+ });++ it('leaves an opportunity no longer open to pick', async () => {+ await render('b2b', { kind: 'opportunity', id: 'gone' });+ expect(button('Continue')).toBeDefined();+ expect(document.body.textContent).toContain('Pick an opportunity');+ });+ });+describe('Optimize content › Page URL', () => {async function importUrl(url: string) {await render();diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsxindex 47f78bcac..415163c3a 100644--- a/web/src/components/content/new-content-dialog.tsx+++ b/web/src/components/content/new-content-dialog.tsx@@ -47,6 +47,7 @@ import {type DraftMethod,type DraftSource,type DraftStartOptions,+ type OverlapPage,type PageImportError,type PageType,} from '@/lib/content/drafts';@@ -112,6 +113,14 @@ interface StartChoice {choice: OverlapChoice;}+/**+ * What the dialog opens on, from the Content plan (CE-014): an opportunity+ * (for an existing page, Start optimizes that page), or a page to read.+ */+export type DialogPreset =+ | { kind: 'opportunity'; id: string; page?: { url: string; title: string | null } | null }+ | { kind: 'page'; url: string };+/** Who does the page (Start, CE-015): the person, the Content Agent, or the team. */type Who = 'me' | 'agent' | 'team';const WHO: Who[] = ['me', 'agent', 'team'];@@ -135,6 +144,7 @@ export function NewContentDialog({brandId,siteType,onSent,+ preset = null,}: {open: boolean;onOpenChange: (open: boolean) => void;@@ -142,6 +152,11 @@ export function NewContentDialog({siteType: SiteType;/** A draft was sent to the Action Center: the Library lists it. */onSent?: () => void;+ /**+ * What the Content plan (CE-014) opens it on: Start for an opportunity, or+ * an existing page read to optimize.+ */+ preset?: DialogPreset | null;}) {const t = useTranslations('contentEditor.newContent');const tTypes = useTranslations('contentEditor.pageTypes');@@ -187,6 +202,48 @@ export function NewContentDialog({};}, [open, brandId, attempt]);+ // From the Content plan: Start for its opportunity once the options are in+ // (one no longer open is left to pick), or its page read to optimize.+ const presetApplied = useRef(false);+ // The plan named the page to optimize: the overlap check doesn't replace it.+ const choiceGiven = useRef(false);+ useEffect(() => {+ if (!open || !preset || presetApplied.current) return;+ if (preset.kind === 'page') {+ presetApplied.current = true;+ setMethod('optimize');+ setFrom('url');+ setPageUrl(preset.url);+ void readPage(preset.url);+ return;+ }+ if (!options) return;+ presetApplied.current = true;+ const opportunity = options.opportunities.find((o) => o.id === preset.id);+ if (!opportunity) return;+ const item = {+ value: opportunity.id,+ label: opportunity.title,+ pageTitle: opportunity.pageTitle ?? undefined,+ };+ setKind('opportunity');+ setPicked(item);+ startFrom(+ item,+ 'opportunity',+ preset.page+ ? {+ url: preset.page.url,+ title: preset.page.title,+ promptsInCommon: 0,+ citations: 0,+ gscPosition: null,+ }+ : undefined,+ );+ // eslint-disable-next-line react-hooks/exhaustive-deps -- once per opening+ }, [open, preset, options]);+// Start checks the pages that already answer a new page's prompts. Content// brought to optimize has no prompts to check. A page type picked in Start// keeps the same source, so the check runs once per source.@@ -200,9 +257,11 @@ export function NewContentDialog({.then((overlap) => {if (cancelled) return;setOverlapRead({ key, overlap, failed: false });- // The recommended option is picked first.+ // The recommended option is picked first, unless the plan named the page.const recommended = adviseOverlap(overlap).options[0];- if (recommended) setStart((s) => (s ? withChoice(s, recommended.choice, siteType) : s));+ if (recommended && !choiceGiven.current) {+ setStart((s) => (s ? withChoice(s, recommended.choice, siteType) : s));+ }}).catch((err) => {console.error('Failed to check for overlapping pages:', err);@@ -214,6 +273,8 @@ export function NewContentDialog({}, [brandId, startSource, siteType, overlapAttempt]);const reset = () => {+ presetApplied.current = false;+ choiceGiven.current = false;setMethod('create');setKind('opportunity');setPicked(null);@@ -263,8 +324,7 @@ export function NewContentDialog({};/** A page of the brand's, read by its URL and cleaned like a paste. */- const readPage = async () => {- const address = pageUrl.trim();+ const readPage = async (address = pageUrl.trim()) => {if (!address) return;setReading(true);setUrlError(null);@@ -317,24 +377,34 @@ export function NewContentDialog({const canContinue =method === 'create' ? picked !== null : content !== null || (from === 'paste' && !!typed);+ /**+ * Start for a new page from what was picked: its title, and the page type+ * it reads as. With a page (an opportunity for an existing page, from the+ * plan), Start optimizes that page, and the overlap check leaves it chosen.+ */+ const startFrom = (item: PickerItem, from: SourceKind, page?: OverlapPage) => {+ const title = item.pageTitle ?? item.label;+ const type = startPageType({ title }, siteType);+ const newPageType = {+ pageType: type.pageType,+ detectedFrom: type.detected ? ('title' as const) : null,+ picked: false,+ };+ const next: StartChoice = {+ method: 'create',+ title,+ source: { kind: from, id: item.value },+ ...newPageType,+ newPageType,+ choice: { kind: 'create' },+ };+ choiceGiven.current = !!page;+ setStart(page ? withChoice(next, { kind: 'optimize', page }, siteType) : next);+ };+const toStart = () => {if (method === 'create') {- if (!picked) return;- const title = picked.pageTitle ?? picked.label;- const type = startPageType({ title }, siteType);- const newPageType = {- pageType: type.pageType,- detectedFrom: type.detected ? ('title' as const) : null,- picked: false,- };- setStart({- method,- title,- source: { kind, id: picked.value },- ...newPageType,- newPageType,- choice: { kind: 'create' },- });+ if (picked) startFrom(picked, kind);return;}const brought =diff --git a/web/src/components/layout/mobile-nav.tsx b/web/src/components/layout/mobile-nav.tsxindex 1283d18c8..8a61cdc1b 100644--- a/web/src/components/layout/mobile-nav.tsx+++ b/web/src/components/layout/mobile-nav.tsx@@ -165,13 +165,21 @@ export function MobileNav() {<Link key={child.href} href={child.href} onClick={() => setOpen(false)}><spanclassName={cn(- 'block rounded-md px-3 py-1.5 text-sm transition-colors',+ 'flex items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors',child.href === currentChild? 'font-medium text-primary': 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',)}>{getDashboardNavLabel(child.title, t, tBrands)}+ {child.badge && (+ <Badge+ variant="secondary"+ className="h-4 px-1.5 text-[10px] font-normal"+ >+ {child.badge}+ </Badge>+ )}</span></Link>))}diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsxindex 7e262f3e8..4e15edaaa 100644--- a/web/src/components/layout/sidebar.tsx+++ b/web/src/components/layout/sidebar.tsx@@ -454,6 +454,14 @@ export function Sidebar() {<span className="flex-1 truncate">{getDashboardNavLabel(child.title, t, tBrands)}</span>+ {child.badge && (+ <Badge+ variant="secondary"+ className="h-4 shrink-0 px-1.5 text-[10px] font-normal"+ >+ {child.badge}+ </Badge>+ )}{child.href.endsWith('/tracked') && trackedCount !== null && (<span className="text-[11px] tabular-nums text-muted-foreground">{trackedCount.toLocaleString()}diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.tsindex ff29db535..2aa3ffef3 100644--- a/web/src/config/dashboard.ts+++ b/web/src/config/dashboard.ts@@ -30,6 +30,8 @@ export interface NavChild {href: string;/** Other routes that belong to this entry, e.g. the editor to the Library. */activeFor?: string[];+ /** A short tag after the label, e.g. "New". */+ badge?: string;}export interface NavItem {@@ -83,15 +85,17 @@ export const dashboardNav: NavGroup[] = [icon: Sparkles,requiredFeature: 'ai_agent',},- // Content Editor (CE-001): a group, like Prompts. Opportunities is- // today's page and keeps /dashboard/content; the Library lists every- // page written or changed in Ansvisor.+ // Content Editor (CE-001): a group, like Prompts. The Plan says what to+ // do next (CE-014); Opportunities is today's page and keeps+ // /dashboard/content; the Library lists every page written or changed+ // in Ansvisor.{title: 'Content',href: '/dashboard/content',icon: FileText,requiredFeature: 'content_optimization',children: [+ { title: 'Plan', href: '/dashboard/content/plan', badge: 'New' },{ title: 'Opportunities', href: '/dashboard/content' },// A draft opens in the editor from the Library (CE-004).{diff --git a/web/src/lib/actions/content-plan.test.ts b/web/src/lib/actions/content-plan.test.tsnew file mode 100644index 000000000..521cb98f9--- /dev/null+++ b/web/src/lib/actions/content-plan.test.ts@@ -0,0 +1,149 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * What the Content plan (CE-014) reads: the brand's pages (00220), its open+ * opportunities for its own pages, and the drafts still being written.+ */++const BRAND = '33333333-3333-3333-3333-333333333333';++let reads: Record<string, unknown>;+let rpcResult: unknown;+let rpcCalls: [string, unknown][];+let filters: [string, string, string, unknown][];++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },+ rpc: async (name: string, args: unknown) => (+ rpcCalls.push([name, args]),+ { data: rpcResult, error: null }+ ),+ from: (table: string) => {+ const chain: Record<string, unknown> = {+ select: () => chain,+ eq: (col: string, v: unknown) => (filters.push([table, 'eq', col, v]), chain),+ in: (col: string, v: unknown) => (filters.push([table, 'in', col, v]), chain),+ order: () => chain,+ limit: () => chain,+ then: (resolve: (r: unknown) => void) => resolve({ data: reads[table] ?? [], error: null }),+ };+ return chain;+ },+ })),+}));++const { getContentPlan } = await import('./content-plan');++beforeEach(() => {+ reads = {};+ rpcResult = { days: 30, pages: [] };+ rpcCalls = [];+ filters = [];+});++describe('getContentPlan', () => {+ it('reads the pages, the open opportunities for own pages and the drafts being written', async () => {+ rpcResult = {+ days: 7,+ answers: { cur: 120, prev: 140 },+ pages: [+ {+ page: 'https://acme.example/guides/espresso',+ title: 'Espresso guide',+ citations: { cur: 4, prev: 9 },+ platformsDown: ['chatgpt-web'],+ aiVisits: 12,+ overlaps: 1,+ },+ ],+ };+ reads.content_opportunities = [+ {+ id: 'o1',+ title: 'Expand the espresso guide',+ decision: 'expand',+ opportunity_score: '81.10',+ brief: { suggestedTitle: ' The home espresso guide ' },+ source_data: {+ targetPages: [+ { url: '' },+ { url: 'https://acme.example/guides/espresso', title: 'The home espresso guide' },+ ],+ competitorsCited: ['Daily Grind Co.', '', 'Origin Box'],+ visibilityScore: 6,+ prompts: ['p1', 'p2'],+ },+ },+ ];+ reads.content_drafts = [+ {+ id: 'd1',+ author: 'agent',+ created_by: 'u1',+ method: 'create',+ opportunity_id: 'o2',+ source_url: null,+ },+ ];++ await expect(getContentPlan(BRAND, 7)).resolves.toEqual({+ pages: [+ {+ page: 'https://acme.example/guides/espresso',+ title: 'Espresso guide',+ citations: { cur: 4, prev: 9 },+ platformsDown: ['chatgpt-web'],+ aiVisits: 12,+ overlaps: 1,+ },+ ],+ answers: { cur: 120, prev: 140 },+ opportunities: [+ {+ id: 'o1',+ title: 'Expand the espresso guide',+ pageTitle: 'The home espresso guide',+ decision: 'expand',+ score: 81.1,+ targetPage: 'https://acme.example/guides/espresso',+ targetTitle: 'The home espresso guide',+ competitorsCited: ['Daily Grind Co.', 'Origin Box'],+ visibility: 6,+ prompts: 2,+ },+ ],+ drafts: [+ {+ id: 'd1',+ author: 'agent',+ isMine: true,+ method: 'create',+ opportunityId: 'o2',+ sourceUrl: null,+ },+ ],+ });+ expect(rpcCalls).toEqual([['content_plan_pages', { p_brand_id: BRAND, p_days: 7 }]]);+ expect(filters).toContainEqual(['content_opportunities', 'eq', 'type', 'owned']);+ expect(filters).toContainEqual([+ 'content_opportunities',+ 'in',+ 'status',+ ['new', 'reviewed', 'sent', 'in_progress'],+ ]);+ expect(filters).toContainEqual([+ 'content_drafts',+ 'in',+ 'status',+ ['draft', 'in_review', 'ready'],+ ]);+ });++ it('reads nothing of another organization’s brand, and refuses another period', async () => {+ rpcResult = null;+ await expect(getContentPlan(BRAND, 30)).resolves.toBeNull();+ await expect(getContentPlan(BRAND, 90 as 30)).rejects.toThrow('invalid');+ await expect(getContentPlan('nope', 30)).rejects.toThrow('invalid');+ });+});diff --git a/web/src/lib/actions/content-plan.ts b/web/src/lib/actions/content-plan.tsnew file mode 100644index 000000000..1d7c42bb7--- /dev/null+++ b/web/src/lib/actions/content-plan.ts@@ -0,0 +1,119 @@+'use server';++import { z } from 'zod';+import { createClient } from '@/lib/supabase/server';+import type { DraftMethod } from '@/lib/content/drafts';+import {+ PLAN_PERIODS,+ type PlanAnswers,+ type PlanDraft,+ type PlanOpportunity,+ type PlanPage,+ type PlanPeriod,+} from '@/lib/content/plan';++/**+ * What the Content plan (CE-014) is built from, read through the signed-in+ * member's session: the brand's pages as AI cites them (content_plan_pages,+ * 00220), its open opportunities for its own pages, and the drafts still+ * being written. lib/content/plan.ts ranks them.+ */++/** Open opportunities, as New content offers them. */+const OPEN_OPPORTUNITY_STATUSES = ['new', 'reviewed', 'sent', 'in_progress'];+const OPPORTUNITY_LIMIT = 200;+const DRAFT_LIMIT = 500;++const planInput = z.object({+ brandId: z.guid(),+ days: z.union(PLAN_PERIODS.map((d) => z.literal(d)) as [z.ZodLiteral<7>, z.ZodLiteral<30>]),+});++const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '');++export async function getContentPlan(+ brandId: string,+ days: PlanPeriod,+): Promise<{+ pages: PlanPage[];+ answers: PlanAnswers;+ opportunities: PlanOpportunity[];+ drafts: PlanDraft[];+} | null> {+ if (!planInput.safeParse({ brandId, days }).success) throw new Error('invalid');+ const supabase = await createClient();+ const [userRes, pagesRes, opportunitiesRes, draftsRes] = await Promise.all([+ supabase.auth.getUser(),+ supabase.rpc('content_plan_pages', { p_brand_id: brandId, p_days: days }),+ supabase+ .from('content_opportunities')+ .select('id, title, decision, opportunity_score, brief, source_data')+ .eq('brand_id', brandId)+ .eq('type', 'owned')+ .in('status', OPEN_OPPORTUNITY_STATUSES)+ .order('opportunity_score', { ascending: false })+ .limit(OPPORTUNITY_LIMIT),+ supabase+ .from('content_drafts')+ .select('id, author, created_by, method, opportunity_id, source_url')+ .eq('brand_id', brandId)+ .in('status', ['draft', 'in_review', 'ready'])+ .order('updated_at', { ascending: false })+ .limit(DRAFT_LIMIT),+ ]);+ if (pagesRes.error) throw new Error(pagesRes.error.message);+ if (opportunitiesRes.error) throw new Error(opportunitiesRes.error.message);+ if (draftsRes.error) throw new Error(draftsRes.error.message);+ // Null: not the member's brand.+ if (!pagesRes.data) return null;+ const me = userRes.data.user?.id ?? null;++ const read = pagesRes.data as unknown as { pages?: PlanPage[]; answers?: Partial<PlanAnswers> };+ const answers = {+ cur: Number(read.answers?.cur ?? 0),+ prev: Number(read.answers?.prev ?? 0),+ };+ const pages = (read.pages ?? []).map((p) => ({+ page: p.page,+ title: p.title ?? null,+ citations: { cur: Number(p.citations?.cur ?? 0), prev: Number(p.citations?.prev ?? 0) },+ platformsDown: Array.isArray(p.platformsDown) ? p.platformsDown : [],+ aiVisits: Number(p.aiVisits ?? 0),+ overlaps: Number(p.overlaps ?? 0),+ }));++ const opportunities = (opportunitiesRes.data ?? []).map((o): PlanOpportunity => {+ const sd = (o.source_data ?? {}) as Record<string, unknown>;+ const brief = (o.brief ?? null) as { suggestedTitle?: unknown } | null;+ const target = Array.isArray(sd.targetPages)+ ? (sd.targetPages as { url?: unknown; title?: unknown }[]).find((p) => text(p?.url))+ : undefined;+ return {+ id: o.id,+ title: o.title,+ pageTitle: text(brief?.suggestedTitle) || null,+ decision: o.decision,+ score: Number(o.opportunity_score ?? 0),+ targetPage: target ? text(target.url) : null,+ targetTitle: text(target?.title) || null,+ competitorsCited: Array.isArray(sd.competitorsCited)+ ? sd.competitorsCited.map(text).filter(Boolean).slice(0, 2)+ : [],+ visibility: typeof sd.visibilityScore === 'number' ? sd.visibilityScore : null,+ prompts: Array.isArray(sd.prompts) ? sd.prompts.length : 0,+ };+ });++ const drafts = (draftsRes.data ?? []).map(+ (d): PlanDraft => ({+ id: d.id,+ author: d.author === 'agent' ? 'agent' : 'user',+ isMine: me !== null && d.created_by === me,+ method: d.method as DraftMethod,+ opportunityId: d.opportunity_id,+ sourceUrl: d.source_url,+ }),+ );++ return { pages, answers, opportunities, drafts };+}diff --git a/web/src/lib/content/plan.test.ts b/web/src/lib/content/plan.test.tsnew file mode 100644index 000000000..de259847a--- /dev/null+++ b/web/src/lib/content/plan.test.ts@@ -0,0 +1,252 @@+import { describe, expect, it } from 'vitest';+import {+ MAX_ROWS,+ OVERLAP_SCORE,+ buildPlan,+ citationsDownScore,+ protectScore,+ rowsFor,+ type PlanAnswers,+ type PlanDraft,+ type PlanOpportunity,+ type PlanPage,+} from './plan';++/**+ * The Content plan (CE-014): opportunities and the brand's pages as one+ * ranked list of what to create, optimize or protect, without the same page+ * twice, with the drafts already being written.+ */++const page = (path: string, over: Partial<PlanPage> = {}): PlanPage => ({+ page: `https://acme.example${path}`,+ title: path.slice(1),+ citations: { cur: 2, prev: 2 },+ platformsDown: [],+ aiVisits: 0,+ overlaps: 0,+ ...over,+});+const opportunity = (id: string, over: Partial<PlanOpportunity> = {}): PlanOpportunity => ({+ id,+ title: `Opportunity ${id}`,+ pageTitle: null,+ decision: 'create',+ score: 70,+ targetPage: null,+ targetTitle: null,+ competitorsCited: [],+ visibility: null,+ prompts: 3,+ ...over,+});+const plan = (+ pages: PlanPage[],+ opportunities: PlanOpportunity[] = [],+ drafts: PlanDraft[] = [],+ answers: PlanAnswers = { cur: 100, prev: 100 },+) => buildPlan({ pages, answers, opportunities, drafts, siteType: 'b2b' });++describe('buildPlan', () => {+ it('creates a new page for an opportunity, named by its brief, with its evidence', () => {+ const { rows, counts } = plan(+ [],+ [+ opportunity('o1', {+ title: 'Create a pricing comparison',+ pageTitle: 'Northwind vs HubSpot',+ competitorsCited: ['HubSpot'],+ visibility: 6,+ score: 81.4,+ }),+ ],+ );+ expect(rows).toEqual([+ expect.objectContaining({+ action: 'create',+ title: 'Northwind vs HubSpot',+ page: null,+ pageType: 'comparison',+ why: { kind: 'competitors', names: ['HubSpot'], visibility: 6 },+ source: 'opportunity',+ score: 81,+ opportunityId: 'o1',+ draft: null,+ }),+ ]);+ expect(counts).toEqual({ create: 1, optimize: 0, protect: 0, overlaps: 0 });+ });++ it('optimizes a page losing citations, by how much it lost, with the platforms citing it less', () => {+ const { rows } = plan([+ page('/features/forecasting', {+ citations: { cur: 6, prev: 10 },+ platformsDown: ['chatgpt-web', 'perplexity-web'],+ }),+ // Down 10%: not losing ground.+ page('/features/email', { citations: { cur: 9, prev: 10 } }),+ // Too few to tell.+ page('/blog/note', { citations: { cur: 0, prev: 2 } }),+ ]);+ expect(rows).toHaveLength(2);+ expect(rows[0]).toMatchObject({+ action: 'optimize',+ page: 'https://acme.example/features/forecasting',+ why: { kind: 'citationsDown', pct: 40, platforms: ['chatgpt-web', 'perplexity-web'] },+ source: 'citations',+ score: citationsDownScore(40, 4),+ });+ expect(rows[1]).toMatchObject({ action: 'protect', title: 'features/email' });+ });++ it('compares citations per tracked answer, so fewer runs or prompts move no page', () => {+ const pages = [page('/features/forecasting', { citations: { cur: 5, prev: 10 } })];+ // Half the answers this period (a weekly brand before its run, prompts removed).+ expect(plan(pages, [], [], { cur: 50, prev: 100 }).rows[0]).toMatchObject({+ action: 'protect',+ });+ // The same answers: down 50%, 5 citations lost.+ expect(plan(pages).rows[0]).toMatchObject({+ why: { kind: 'citationsDown', pct: 50 },+ score: citationsDownScore(50, 5),+ });+ // Twice the answers and the same citations: down 50% per answer, 15 lost.+ expect(plan(pages, [], [], { cur: 200, prev: 100 }).rows[0]).toMatchObject({+ why: { kind: 'citationsDown', pct: 75 },+ score: citationsDownScore(75, 15),+ });+ // No answers before: nothing to compare with.+ expect(plan(pages, [], [], { cur: 100, prev: 0 }).rows[0]).toMatchObject({+ action: 'protect',+ });+ });++ it('ranks a drop by the citations lost more than by its share', () => {+ expect(citationsDownScore(41, 82)).toBeGreaterThan(citationsDownScore(100, 3));+ });++ it('keeps one row for a page an opportunity targets, with the period’s signal when it is losing', () => {+ const { rows } = plan(+ [page('/guides/espresso/', { citations: { cur: 2, prev: 8 }, overlaps: 2 })],+ [+ opportunity('o1', {+ title: 'Expand the espresso guide',+ decision: 'optimize',+ targetPage: 'https://www.acme.example/guides/espresso',+ targetTitle: 'The home espresso guide',+ score: 50,+ }),+ ],+ );+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ action: 'optimize',+ title: 'The home espresso guide',+ opportunityId: 'o1',+ source: 'citations',+ why: { kind: 'citationsDown', pct: 75 },+ overlaps: 2,+ score: citationsDownScore(75, 6),+ });+ });++ it('protects the five most cited pages, after the work to do', () => {+ const pages = [5, 6, 7, 8, 9, 30].map((cur, i) =>+ page(`/p${i}`, { citations: { cur, prev: cur }, aiVisits: 10 }),+ );+ const { rows, counts } = plan(pages, [opportunity('o1', { score: 61 })]);+ expect(counts.protect).toBe(5);+ expect(rows.map((r) => r.title)).toEqual(['Opportunity o1', 'p5', 'p4', 'p3', 'p2', 'p1']);+ expect(rows[1]).toMatchObject({+ why: { kind: 'top', citations: 30, aiVisits: 10 },+ score: protectScore(30),+ });+ });++ it('protects a page an opportunity says to defend', () => {+ const { rows } = plan(+ [],+ [+ opportunity('o1', {+ decision: 'defend',+ targetPage: 'https://acme.example/pricing',+ targetTitle: 'Pricing',+ }),+ ],+ );+ expect(rows[0]).toMatchObject({ action: 'protect', page: 'https://acme.example/pricing' });+ });++ it('lists a top page past the five protected when it competes with another', () => {+ const pages = [5, 6, 7, 8, 9, 30].map((cur, i) =>+ page(`/p${i}`, { citations: { cur, prev: cur }, overlaps: i === 0 ? 2 : 0 }),+ );+ const { rows, counts } = plan(pages);+ expect(counts.protect).toBe(5);+ expect(rows.find((r) => r.title === 'p0')).toMatchObject({+ action: 'optimize',+ why: { kind: 'overlap', pages: 2 },+ score: OVERLAP_SCORE,+ });+ });++ it('counts every row, and each card lists its own first rows', () => {+ const opportunities = Array.from({ length: 60 }, (_, i) =>+ opportunity(`o${i}`, { score: 99 - (i % 30) }),+ );+ const pages = [+ page('/top', { citations: { cur: 30, prev: 30 } }),+ page('/blog/a', { overlaps: 1 }),+ ];+ const { rows, counts } = plan(pages, opportunities);+ expect(counts).toEqual({ create: 60, optimize: 1, protect: 1, overlaps: 1 });+ expect(rowsFor(rows, null)).toHaveLength(MAX_ROWS);+ // Below the 50 opportunities on score, and still shown on their cards.+ expect(rowsFor(rows, 'protect').map((r) => r.title)).toEqual(['top']);+ expect(rowsFor(rows, 'overlaps').map((r) => r.title)).toEqual(['blog/a']);+ });++ it('lists a page that only competes with others, and counts every page competing', () => {+ const { rows, counts } = plan([+ page('/blog/espresso-basics', { overlaps: 1 }),+ page('/guides/espresso', { citations: { cur: 12, prev: 10 }, overlaps: 1 }),+ ]);+ // The work comes before protecting.+ expect(rows.map((r) => [r.action, r.why.kind])).toEqual([+ ['optimize', 'overlap'],+ ['protect', 'top'],+ ]);+ expect(counts.overlaps).toBe(2);+ expect(rowsFor(rows, 'overlaps')).toHaveLength(2);+ expect(rowsFor(rows, 'protect')).toHaveLength(1);+ expect(rowsFor(rows, null)).toHaveLength(2);+ });++ it('finds the draft being written for an opportunity or a page', () => {+ const drafts: PlanDraft[] = [+ {+ id: 'd1',+ author: 'agent',+ isMine: false,+ method: 'create',+ opportunityId: 'o1',+ sourceUrl: null,+ },+ {+ id: 'd2',+ author: 'user',+ isMine: true,+ method: 'optimize',+ opportunityId: null,+ sourceUrl: 'https://acme.example/features/forecasting/',+ },+ ];+ const { rows } = plan(+ [page('/features/forecasting', { citations: { cur: 1, prev: 9 } })],+ [opportunity('o1')],+ drafts,+ );+ // The opportunity (70) ranks over the page losing ground (1 of 9: 66).+ expect(rows.map((r) => r.draft?.id)).toEqual(['d1', 'd2']);+ });+});diff --git a/web/src/lib/content/plan.ts b/web/src/lib/content/plan.tsnew file mode 100644index 000000000..e9a6387d5--- /dev/null+++ b/web/src/lib/content/plan.ts@@ -0,0 +1,291 @@+/**+ * The Content plan (Content Editor CE-014, spec v2 §4): one ranked list of+ * what to create, optimize or protect next, built from the brand's open+ * Content Opportunities (new pages AI needs, pages to improve; tasks sent+ * from the Action Center become opportunities too) and its own pages as AI+ * cites them (content_plan_pages, 00220): pages losing citations, the top+ * pages, and pages competing for the same prompts. A page loses ground when+ * it is cited less per tracked answer than in the period before, so a week+ * with fewer runs, or prompts added or removed, moves no page.+ */++import { detectPageType, type SiteType } from './page-types';+import type { DraftMethod, PageType } from './drafts';+import { pageKey } from './sources';++export const PLAN_PERIODS = [7, 30] as const;+export type PlanPeriod = (typeof PLAN_PERIODS)[number];++export type PlanAction = 'create' | 'optimize' | 'protect';+/** The cards over the list, each a filter: the actions, and the pages competing. */+export const PLAN_CARDS = ['create', 'optimize', 'protect', 'overlaps'] as const;+export type PlanCard = (typeof PLAN_CARDS)[number];++/** The brand's tracked answers in each period: what makes their citations comparable. */+export interface PlanAnswers {+ cur: number;+ prev: number;+}++/** One of the brand's pages, as content_plan_pages (00220) reads it. */+export interface PlanPage {+ page: string;+ title: string | null;+ citations: { cur: number; prev: number };+ /** Platform keys citing it at a lower rate than before, the biggest drop first. */+ platformsDown: string[];+ aiVisits: number;+ /** The brand's other pages cited for two or more of the same prompts. */+ overlaps: number;+}++/** An open opportunity for one of the brand's own pages. */+export interface PlanOpportunity {+ id: string;+ title: string;+ /** The brief's suggested page title, when it has one. */+ pageTitle: string | null;+ decision: string | null;+ score: number;+ /** The page it works on, for an existing page, and that page's title. */+ targetPage: string | null;+ targetTitle: string | null;+ competitorsCited: string[];+ visibility: number | null;+ prompts: number;+}++/** A draft still being written, to open rather than start another. */+export interface PlanDraft {+ id: string;+ author: 'user' | 'agent';+ isMine: boolean;+ method: DraftMethod;+ opportunityId: string | null;+ sourceUrl: string | null;+}++/** Why a row is on the list, and where the signal comes from. */+export type PlanWhy =+ | { kind: 'competitors'; names: string[]; visibility: number | null }+ | { kind: 'opportunity'; prompts: number }+ | { kind: 'citationsDown'; pct: number; platforms: string[] }+ | { kind: 'top'; citations: number; aiVisits: number }+ | { kind: 'overlap'; pages: number };++export interface PlanRow {+ key: string;+ action: PlanAction;+ title: string;+ /** The page it works on; null for a new page. */+ page: string | null;+ pageType: PageType | null;+ why: PlanWhy;+ source: 'opportunity' | 'citations' | 'protect' | 'overlap';+ /** The brand's other pages competing with this one. */+ overlaps: number;+ score: number;+ opportunityId: string | null;+ draft: PlanDraft | null;+}++/**+ * A page losing this share of its citations per answer, from at least this+ * many citations, is losing ground.+ */+export const DROP_SHARE = 0.2;+export const MIN_PREV_CITATIONS = 3;+/** Top pages: cited at least this often, and not losing ground. */+export const MIN_TOP_CITATIONS = 5;+export const MAX_PROTECT = 5;+export const MAX_ROWS = 50;++/**+ * The rank of each kind of row, on the opportunities' 0–100 scale: an+ * opportunity keeps its own score; a page losing citations ranks by how much+ * it lost, the citations more than the share (40 + a fifth of the drop in+ * percent + up to 40 for the citations lost), so 200 → 118 outranks 3 → 0;+ * a page only competing with others, 45; a top page by how much it is cited+ * (20 + citations, at most 60), so protecting comes after the work to do.+ */+export function citationsDownScore(pct: number, lost: number): number {+ return Math.min(100, 40 + Math.round(pct / 5) + Math.min(40, lost));+}+export const OVERLAP_SCORE = 45;+export function protectScore(citations: number): number {+ return Math.min(60, 20 + citations);+}++const CREATE_DECISIONS = new Set(['create']);+/** An opportunity to defend a page the brand holds: protecting it, not optimizing. */+const PROTECT_DECISIONS = new Set(['defend']);++/**+ * Every row, ranked, and what each card counts: the list shows the first+ * MAX_ROWS of a card's rows (rowsFor), so a card never counts rows it can't+ * show.+ */+export function buildPlan({+ pages,+ answers,+ opportunities,+ drafts,+ siteType,+}: {+ pages: PlanPage[];+ answers: PlanAnswers;+ opportunities: PlanOpportunity[];+ drafts: PlanDraft[];+ siteType: SiteType;+}): { rows: PlanRow[]; counts: Record<PlanCard, number> } {+ const byPage = new Map<string, PlanPage>();+ for (const page of pages) {+ const key = pageKey(page.page);+ if (key && !byPage.has(key)) byPage.set(key, page);+ }+ const draftFor = (opportunityId: string | null, page: string | null): PlanDraft | null => {+ const key = page ? pageKey(page) : null;+ return (+ drafts.find(+ (d) =>+ (opportunityId && d.opportunityId === opportunityId) ||+ (key && d.method === 'optimize' && d.sourceUrl && pageKey(d.sourceUrl) === key),+ ) ?? null+ );+ };+ const typeOf = (title: string, page: string | null) =>+ detectPageType({ title, url: page ?? undefined }, siteType);++ const rows: PlanRow[] = [];+ const pagesTaken = new Set<string>();++ for (const o of opportunities) {+ const create = !o.decision || CREATE_DECISIONS.has(o.decision) || !o.targetPage;+ const key = o.targetPage ? pageKey(o.targetPage) : null;+ const page = key ? byPage.get(key) : undefined;+ // A new page by the title its brief suggests; an existing one by its own.+ const title = (create ? o.pageTitle : o.targetTitle) || o.title;+ const drop = page ? dropOf(page, answers) : null;+ rows.push({+ key: `opportunity:${o.id}`,+ action: create ? 'create' : PROTECT_DECISIONS.has(o.decision ?? '') ? 'protect' : 'optimize',+ title,+ page: create ? null : o.targetPage,+ pageType: typeOf(title, create ? null : o.targetPage),+ // The period's own signal, when the page is losing ground, says more.+ why:+ page && drop+ ? dropWhy(page, drop)+ : o.competitorsCited.length+ ? { kind: 'competitors', names: o.competitorsCited, visibility: o.visibility }+ : { kind: 'opportunity', prompts: o.prompts },+ source: drop ? 'citations' : 'opportunity',+ overlaps: page?.overlaps ?? 0,+ score: drop+ ? Math.max(o.score, citationsDownScore(drop.pct, drop.lost))+ : Math.round(o.score),+ opportunityId: o.id,+ draft: draftFor(o.id, create ? null : o.targetPage),+ });+ if (key && !create) pagesTaken.add(key);+ }++ const protect: PlanRow[] = [];+ for (const [key, page] of byPage) {+ if (pagesTaken.has(key)) continue;+ const title = page.title?.trim() || page.page;+ const base = {+ title,+ page: page.page,+ pageType: typeOf(title, page.page),+ overlaps: page.overlaps,+ opportunityId: null,+ draft: draftFor(null, page.page),+ };+ const drop = dropOf(page, answers);+ if (drop) {+ rows.push({+ ...base,+ key: `page:${key}`,+ action: 'optimize',+ why: dropWhy(page, drop),+ source: 'citations',+ score: citationsDownScore(drop.pct, drop.lost),+ });+ } else if (page.citations.cur >= MIN_TOP_CITATIONS) {+ protect.push({+ ...base,+ key: `page:${key}`,+ action: 'protect',+ why: { kind: 'top', citations: page.citations.cur, aiVisits: page.aiVisits },+ source: 'protect',+ score: protectScore(page.citations.cur),+ });+ } else if (page.overlaps > 0) {+ rows.push({+ ...base,+ key: `page:${key}`,+ action: 'optimize',+ why: { kind: 'overlap', pages: page.overlaps },+ source: 'overlap',+ score: OVERLAP_SCORE,+ });+ }+ }+ protect.sort((a, b) => b.score - a.score || a.title.localeCompare(b.title));+ rows.push(...protect.slice(0, MAX_PROTECT));+ // A top page past the five protected still gets its row when it competes.+ for (const row of protect.slice(MAX_PROTECT)) {+ if (row.overlaps > 0) {+ rows.push({+ ...row,+ action: 'optimize',+ why: { kind: 'overlap', pages: row.overlaps },+ source: 'overlap',+ score: OVERLAP_SCORE,+ });+ }+ }++ rows.sort((a, b) => b.score - a.score || a.title.localeCompare(b.title));+ return {+ rows,+ counts: {+ create: rows.filter((r) => r.action === 'create').length,+ optimize: rows.filter((r) => r.action === 'optimize').length,+ protect: rows.filter((r) => r.action === 'protect').length,+ overlaps: rows.filter((r) => r.overlaps > 0).length,+ },+ };+}++/** The rows a card shows, the first MAX_ROWS: its action's, or the pages competing; all without a card. */+export function rowsFor(rows: PlanRow[], card: PlanCard | null): PlanRow[] {+ const shown = !card+ ? rows+ : card === 'overlaps'+ ? rows.filter((r) => r.overlaps > 0)+ : rows.filter((r) => r.action === card);+ return shown.slice(0, MAX_ROWS);+}++/**+ * How much ground a page lost, per tracked answer: null when it isn't losing+ * any (or the brand had no answers in a period to compare). `lost` is the+ * citations it would have had at the earlier rate, less the ones it got.+ */+function dropOf(page: PlanPage, answers: PlanAnswers): { pct: number; lost: number } | null {+ const { cur, prev } = page.citations;+ if (prev < MIN_PREV_CITATIONS || answers.cur <= 0 || answers.prev <= 0) return null;+ const rateNow = cur / answers.cur;+ const rateBefore = prev / answers.prev;+ if (rateNow > rateBefore * (1 - DROP_SHARE)) return null;+ return {+ pct: Math.round(((rateBefore - rateNow) / rateBefore) * 100),+ lost: Math.max(0, Math.round(rateBefore * answers.cur - cur)),+ };+}++function dropWhy(page: PlanPage, drop: { pct: number }): PlanWhy {+ return { kind: 'citationsDown', pct: drop.pct, platforms: page.platformsDown };+}diff --git a/web/src/lib/dashboard-navigation.test.ts b/web/src/lib/dashboard-navigation.test.tsindex a840a5afc..c1bb49a5b 100644--- a/web/src/lib/dashboard-navigation.test.ts+++ b/web/src/lib/dashboard-navigation.test.ts@@ -40,13 +40,14 @@ describe('getDashboardNavLabel', () => {expect(items.some((item) => item.href === '/dashboard/topics')).toBe(false);});- // Content Editor (CE-001): Content is a group; Opportunities keeps today's- // route.- it('lists Opportunities and the Library under Content', () => {+ // Content Editor (CE-001): Content is a group, the Plan first and new+ // (CE-014); Opportunities keeps today's route.+ it('lists the Plan, Opportunities and the Library under Content', () => {const items = dashboardNav.flatMap((group) => group.items);const content = items.find((item) => item.title === 'Content')!;expect(content.href).toBe('/dashboard/content');expect(content.children).toEqual([+ { title: 'Plan', href: '/dashboard/content/plan', badge: 'New' },{ title: 'Opportunities', href: '/dashboard/content' },{title: 'Library',@@ -145,6 +146,7 @@ describe('activeChildHref', () => {'/dashboard/content/library',);expect(activeChildHref(children, '/dashboard/content/3f2a')).toBe('/dashboard/content');+ expect(activeChildHref(children, '/dashboard/content/plan')).toBe('/dashboard/content/plan');});it('keeps an opportunity’s own page under Opportunities', () => {diff --git a/web/src/lib/dashboard-navigation.ts b/web/src/lib/dashboard-navigation.tsindex 12339a26e..66325d373 100644--- a/web/src/lib/dashboard-navigation.ts+++ b/web/src/lib/dashboard-navigation.ts@@ -20,6 +20,7 @@ export const dashboardNavLabelKeys: Record<string, NavLabelKey> = {'Query Fan-outs': { namespace: 'nav', key: 'queryFanouts' },'Prompts Insights': { namespace: 'nav', key: 'promptsInsights' },Content: { namespace: 'nav', key: 'content' },+ Plan: { namespace: 'nav', key: 'contentPlan' },Opportunities: { namespace: 'nav', key: 'contentOpportunities' },Library: { namespace: 'nav', key: 'contentLibrary' },'Site Audit': { namespace: 'nav', key: 'audit' },diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 485585220..e14513d12 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3670,6 +3670,10 @@ export type Database = {Args: { p_brand_id: string; p_days: number; p_page: string }Returns: Json}+ content_plan_pages: {+ Args: { p_brand_id: string; p_days?: number }+ Returns: Json+ }content_page_overlap: {Args: { p_brand_id: string; p_prompt_ids: string[]; p_since?: string }Returns: {