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): rank the Content Plan by the Action Center's Priority Score model (#1356)
Cihan73dbf0db750b
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 591278780..94eb54262 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3176,11 +3176,24 @@"score": {"label": "Priority Score {score}: how it is worked out","title": "How this score is worked out",- "opportunity": "The content opportunity's own score: {score}",- "citationsDown": "{base} + {pctPoints} for {pct}% fewer citations + {lostPoints} for {lost, plural, one {# citation} other {# citations}} lost = {score}{capped, select, true { (at most {max})} other {}}",- "protect": "{base} + {citations, plural, one {# citation} other {# citations}} = {score}{capped, select, true { (at most {max})} other {}}",- "higher": "The higher of the two counts.",- "marked": "Marked as a priority, so it's listed first."+ "severity": {+ "drop": "Losing citations: {pct}% fewer, {lost, plural, one {# citation} other {# citations}} lost",+ "create": "A new page AI needs",+ "opportunity": "An existing page to improve",+ "protect": "A page to protect"+ },+ "opportunity": "Content opportunity scored {score}",+ "opportunityNone": "No content opportunity behind it (neutral)",+ "pageValue": {+ "visits": "{visits, plural, one {# AI visit} other {# AI visits}} this period",+ "newPage": "A new page, no visits yet (neutral)",+ "unknown": "No AI traffic data (neutral)"+ },+ "citations": "{citations, plural, =0 {Not cited} one {# citation} other {# citations}} this period",+ "points": "{text}: {points} of {max}",+ "total": "Together: {score} of 100",+ "marked": "Marked as a priority, so it's listed first.",+ "planOnly": "This score ranks the Plan. The Action Center scores its tasks on its own."},"rowMenu": {"label": "Actions for {title}",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.tsxindex 4f99fbadc..2cb170ed5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-table.tsx@@ -27,8 +27,14 @@ import { DRAFT_METHOD_BADGE, DRAFT_STATUS_BADGE } from '@/components/content/draimport { contentEditorPath, isPageType } from '@/lib/content/drafts';import { platformNames } from '@/lib/content/impact';import { pagePath } from '@/lib/content/overlap';-import type { PlanAction, PlanPeriod, PlanRow, PlanScorePart, PlanWhy } from '@/lib/content/plan';-import { priorityLevelOf } from '@/lib/action-center/priority';+import {+ planPriorityLevel,+ type PlanAction,+ type PlanPeriod,+ type PlanRow,+ type PlanScorePart,+ type PlanWhy,+} from '@/lib/content/plan';import { formatNumber } from '@/lib/format';import { cn } from '@/lib/utils';@@ -234,8 +240,9 @@ function RowMenu({}/**- * The row's Priority Score, coloured by its level as the Action Center's- * are, and on hover or focus what it is made of.+ * The row's Priority Score, coloured by its level in the Action Center's+ * colours but at the Plan's own cut-offs (planPriorityLevel), and on hover or+ * focus what it is made of.*/function ScoreBadge({ row }: { row: PlanRow }) {const t = useTranslations('contentEditor.plan.score');@@ -255,7 +262,7 @@ function ScoreBadge({ row }: { row: PlanRow }) {><PriorityBadgescore={score}- level={priorityLevelOf(score)}+ level={planPriorityLevel(score)}levelClassName="hidden xl:inline"/></TooltipTrigger>@@ -266,38 +273,34 @@ function ScoreBadge({ row }: { row: PlanRow }) {<ScorePartText part={part} /></p>))}- {row.scoreParts.length > 1 && <p className="opacity-80">{t('higher')}</p>}+ <p className="opacity-80">{t('total', { score })}</p>{row.priority && <p className="opacity-80">{t('marked')}</p>}+ <p className="opacity-80">{t('planOnly')}</p></TooltipContent></Tooltip>);}+/** One factor of the score, and the points it gives out of its weight. */function ScorePartText({ part }: { part: PlanScorePart }) {const t = useTranslations('contentEditor.plan.score');- switch (part.kind) {- case 'opportunity':- return t('opportunity', { score: part.score });- case 'citationsDown':- return t('citationsDown', {- base: part.base,- pct: part.pct,- pctPoints: part.pctPoints,- lost: part.lost,- lostPoints: part.lostPoints,- score: part.score,- capped: String(part.base + part.pctPoints + part.lostPoints > part.max),- max: part.max,- });- case 'protect':- return t('protect', {- base: part.base,- citations: part.citations,- score: part.score,- capped: String(part.base + part.citations > part.max),- max: part.max,- });- }+ const text = (() => {+ switch (part.kind) {+ case 'severity':+ return part.reason === 'drop'+ ? t('severity.drop', { pct: part.pct, lost: part.lost })+ : t(`severity.${part.reason}`);+ case 'opportunity':+ return part.score === null ? t('opportunityNone') : t('opportunity', { score: part.score });+ case 'pageValue':+ return part.reason === 'visits'+ ? t('pageValue.visits', { visits: part.visits })+ : t(`pageValue.${part.reason}`);+ case 'citations':+ return t('citations', { citations: part.citations });+ }+ })();+ return t('points', { text, points: formatNumber(part.points), max: part.max });}function WhyText({ why }: { why: PlanWhy }) {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.tsxindex 8da9d75c5..5d0cdedd3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx@@ -209,17 +209,24 @@ describe('the Content plan', () => {it("shows each row's Priority Score, and on focus how it is worked out", async () => {await renderPage();const scores = [...container.querySelectorAll('tbody tr')].map((tr) => tr.children[1]);- // The opportunity's 74; 40 + 14 for −70% + 7 citations lost; 20 + 12 citations.- expect(scores.map((td) => td.textContent)).toEqual(['74Medium', '61Medium', '32Low']);+ // 40 severity, 30 opportunity, 20 page value, 10 citations: the new page+ // (74) 52.2; the page losing ground, with no AI visits, 48.2; the top page 34.9.+ // The Plan's own levels: Medium from 40, High from 60.+ expect(scores.map((td) => td.textContent)).toEqual(['52Medium', '48Medium', '35Low']);expect(container.querySelector('thead')!.textContent).toContain('Priority Score');const trigger = scores[1].querySelector('button')!;- expect(trigger.getAttribute('aria-label')).toBe('Priority Score 61: how it is worked out');+ expect(trigger.getAttribute('aria-label')).toBe('Priority Score 48: how it is worked out');act(() => trigger.focus());await act(() => new Promise((resolve) => setTimeout(resolve, 400)));expect(document.querySelector('[data-slot="tooltip-content"]')?.textContent).toBe('How this score is worked out' +- '40 + 14 for 70% fewer citations + 7 for 7 citations lost = 61',+ 'Losing citations: 70% fewer, 7 citations lost: 35.2 of 40' ++ 'No content opportunity behind it (neutral): 12 of 30' ++ '0 AI visits this period: 0 of 20' ++ '3 citations this period: 1 of 10' ++ 'Together: 48 of 100' ++ 'This score ranks the Plan. The Action Center scores its tasks on its own.',);});diff --git a/web/src/lib/content/plan.test.ts b/web/src/lib/content/plan.test.tsindex 2fd724e27..1dac89b2a 100644--- a/web/src/lib/content/plan.test.ts+++ b/web/src/lib/content/plan.test.ts@@ -2,8 +2,8 @@ import { describe, expect, it } from 'vitest';import {MAX_ROWS,buildPlan,- citationsDownScore,- protectScore,+ dropSeverity,+ planPriorityLevel,rowsFor,type PlanAnswers,type PlanDraft,@@ -70,7 +70,8 @@ describe('buildPlan', () => {pageType: 'comparison',why: { kind: 'competitors', names: ['HubSpot'], visibility: 6 },source: 'opportunity',- score: 81,+ // 20 a new page + 24.3 the opportunity's 81 + 10 page value (neutral) + 0 citations.+ score: 54.3,opportunityId: 'o1',draft: null,}),@@ -132,7 +133,8 @@ describe('buildPlan', () => {page: 'https://acme.example/features/forecasting',why: { kind: 'citationsDown', pct: 40, platforms: ['chatgpt-web', 'perplexity-web'] },source: 'citations',- score: citationsDownScore(40, 4),+ // 30.4 the drop + 12 no opportunity + 10 page value (no traffic data) + 2 citations.+ score: 54.4,});expect(rows[1]).toMatchObject({ action: 'protect', title: 'features/email' });});@@ -146,12 +148,12 @@ describe('buildPlan', () => {// The same answers: down 50%, 5 citations lost.expect(plan(pages).rows[0]).toMatchObject({why: { kind: 'citationsDown', pct: 50 },- score: citationsDownScore(50, 5),+ score: 55.7,});// 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),+ score: 59.7,});// No answers before: nothing to compare with.expect(plan(pages, [], [], { cur: 100, prev: 0 }).rows[0]).toMatchObject({@@ -159,8 +161,12 @@ describe('buildPlan', () => {});});- it('ranks a drop by the citations lost more than by its share', () => {- expect(citationsDownScore(41, 82)).toBeGreaterThan(citationsDownScore(100, 3));+ it('reckons a drop as bad as its share or its citations lost say, whichever says more', () => {+ expect(dropSeverity(20, 2)).toBeCloseTo(0.68);+ expect(dropSeverity(20, 10)).toBeCloseTo(0.8);+ // 82 citations lost is as bad as losing them all.+ expect(dropSeverity(41, 82)).toBe(1);+ expect(dropSeverity(100, 3)).toBe(1);});it('keeps one row for a page an opportunity targets, with the period’s signal when it is losing', () => {@@ -183,7 +189,8 @@ describe('buildPlan', () => {opportunityId: 'o1',source: 'citations',why: { kind: 'citationsDown', pct: 75 },- score: citationsDownScore(75, 6),+ // 36 the drop + 15 the opportunity's 50 + 10 page value + 0.7 citations.+ score: 61.7,});});@@ -196,7 +203,8 @@ describe('buildPlan', () => {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),+ // 8 protect + 12 no opportunity + 6.9 for 10 AI visits + 10 for 30 citations.+ score: 36.9,});});@@ -277,9 +285,9 @@ describe('buildPlan', () => {[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']);- expect(rows[1].draft?.assignee).toEqual({ id: 'u2', name: 'Ada Lovelace' });+ // The page losing ground (1 of 9: 60.5) ranks over the new page (70: 51).+ expect(rows.map((r) => r.draft?.id)).toEqual(['d2', 'd1']);+ expect(rows[0].draft?.assignee).toEqual({ id: 'u2', name: 'Ada Lovelace' });});it('puts the rows marked as a priority first, and counts them', () => {@@ -313,38 +321,53 @@ describe('buildPlan', () => {marks,);expect(rows.map((r) => r.key)).toEqual(['opportunity:o2']);- expect(hidden.map((r) => r.key)).toEqual(['opportunity:o1', 'page:acme.example/losing']);+ expect(hidden.map((r) => r.key)).toEqual(['page:acme.example/losing', 'opportunity:o1']);expect(counts).toEqual({ create: 1, optimize: 0, protect: 0, priority: 0 });});});-// The Priority Score column shows each row's score and what it is made of.+// The Priority Score column shows each row's score and what it is made of:+// 40 severity, 30 opportunity, 20 page value, 10 citation strength.describe("a row's score breakdown", () => {- it("is the opportunity's own score, rounded as the row's", () => {+ it('gives a new page its opportunity, a neutral page value and no citations', () => {const { rows } = plan([], [opportunity('o1', { score: 81.4 })]);- expect(rows[0].score).toBe(81);- expect(rows[0].scoreParts).toEqual([{ kind: 'opportunity', score: 81 }]);+ expect(rows[0].scoreParts).toEqual([+ { kind: 'severity', reason: 'create', value: 0.5, points: 20, max: 40 },+ { kind: 'opportunity', score: 81, value: 0.81, points: 24.3, max: 30 },+ { kind: 'pageValue', reason: 'newPage', value: 0.5, points: 10, max: 20 },+ { kind: 'citations', citations: 0, value: 0, points: 0, max: 10 },+ ]);+ expect(rows[0].score).toBe(54.3);});- it("adds up a drop's points to the row's score", () => {+ it("reckons a drop's severity, and a page with no opportunity as neutral", () => {const { rows } = plan([page('/features/forecasting', { citations: { cur: 6, prev: 10 } })]);- // Down 40% (+8), 4 citations lost (+4), on a base of 40.expect(rows[0].scoreParts).toEqual([- {- kind: 'citationsDown',- base: 40,- pct: 40,- pctPoints: 8,- lost: 4,- lostPoints: 4,- max: 100,- score: 52,- },+ { kind: 'severity', reason: 'drop', pct: 40, lost: 4, value: 0.76, points: 30.4, max: 40 },+ { kind: 'opportunity', score: null, value: 0.4, points: 12, max: 30 },+ // No page with AI visits: the brand has no traffic data, so value is unknown.+ { kind: 'pageValue', reason: 'unknown', value: 0.5, points: 10, max: 20 },+ { kind: 'citations', citations: 6, value: 0.2, points: 2, max: 10 },]);- expect(rows[0].score).toBe(52);+ expect(rows[0].score).toBe(54.4);});- it('gives an opportunity on a page losing ground both parts, the higher counting', () => {+ it('values a page by its AI visits once the brand has traffic data, 1,000 counting in full', () => {+ const { rows } = plan([+ page('/a', { citations: { cur: 18, prev: 18 }, aiVisits: 1000 }),+ page('/b', { citations: { cur: 55, prev: 55 }, aiVisits: 0 }),+ ]);+ expect(rows.map((r) => [r.title, r.scoreParts[2], r.score])).toEqual([+ [+ 'a',+ { kind: 'pageValue', reason: 'visits', visits: 1000, value: 1, points: 20, max: 20 },+ 46,+ ],+ ['b', { kind: 'pageValue', reason: 'visits', visits: 0, value: 0, points: 0, max: 20 }, 30],+ ]);+ });++ it('gives an opportunity on a page losing ground the drop and the opportunity both', () => {const { rows } = plan([page('/guides/espresso', { citations: { cur: 2, prev: 8 } })],[@@ -355,28 +378,65 @@ describe("a row's score breakdown", () => {}),],);- expect(rows[0].scoreParts.map((p) => [p.kind, p.score])).toEqual([- ['opportunity', 50],- ['citationsDown', citationsDownScore(75, 6)],+ expect(rows[0].scoreParts.map((p) => [p.kind, p.points])).toEqual([+ ['severity', 36],+ ['opportunity', 15],+ ['pageValue', 10],+ ['citations', 0.7],]);- expect(rows[0].score).toBe(Math.max(...rows[0].scoreParts.map((p) => p.score)));+ expect(rows[0].score).toBe(61.7);});- it("counts a top page's citations on a base of 20, up to 60", () => {- const { rows } = plan([- page('/a', { citations: { cur: 18, prev: 18 } }),- page('/b', { citations: { cur: 55, prev: 55 } }),- ]);- expect(rows.map((r) => r.scoreParts)).toEqual([- [{ kind: 'protect', base: 20, citations: 55, max: 60, score: 60 }],- [{ kind: 'protect', base: 20, citations: 18, max: 60, score: 38 }],+ it('ranks a drop first, then new and existing pages, protecting last', () => {+ const { rows } = plan(+ [+ page('/losing', { citations: { cur: 2, prev: 8 } }),+ page('/top', { citations: { cur: 30, prev: 30 } }),+ page('/existing', { citations: { cur: 3, prev: 3 } }),+ ],+ [+ opportunity('new', { score: 80 }),+ opportunity('improve', {+ decision: 'optimize',+ targetPage: 'https://acme.example/existing',+ score: 70,+ }),+ ],+ );+ expect(rows.map((r) => [r.action, r.title])).toEqual([+ ['optimize', 'losing'],+ ['create', 'Opportunity new'],+ ['optimize', 'Opportunity improve'],+ ['protect', 'top'],]);});- it('caps a drop at 100 and its citations lost at 40 points', () => {+ it('caps a drop at full severity', () => {const { rows } = plan([page('/x', { citations: { cur: 0, prev: 90 } })]);- expect(rows[0].scoreParts).toEqual([- expect.objectContaining({ pctPoints: 20, lost: 90, lostPoints: 40, score: 100 }),- ]);+ expect(rows[0].scoreParts[0]).toEqual(+ expect.objectContaining({ pct: 100, lost: 90, value: 1, points: 40 }),+ );+ });+});++describe("the Plan badge's level", () => {+ it("uses the Plan's own cut-offs, so each kind of row can read above Low", () => {+ // An existing page with no drop tops out at 74, a top page with no opportunity at 50.+ expect(planPriorityLevel(74)).toBe('high');+ expect(planPriorityLevel(50)).toBe('medium');+ expect(planPriorityLevel(39.9)).toBe('low');+ // Only a page losing citations reaches Critical.+ expect(planPriorityLevel(75)).toBe('critical');+ });++ it('reads a strong new page High, a middling one Medium', () => {+ const levelOf = (score: number) => {+ const [row] = plan([], [opportunity('o1', { score })]).rows;+ return planPriorityLevel(Math.round(row.score));+ };+ // 20 a new page + 25.5 the opportunity's 85 + 10 page value (neutral): 55.5.+ expect(levelOf(85)).toBe('high');+ // The fixture's 70: 20 + 21 + 10 = 51.+ expect(levelOf(70)).toBe('medium');});});diff --git a/web/src/lib/content/plan.ts b/web/src/lib/content/plan.tsindex 600da3e1b..2cf700859 100644--- a/web/src/lib/content/plan.ts+++ b/web/src/lib/content/plan.ts@@ -15,6 +15,7 @@ import { opportunityPageType } from './asset-types';import { detectPageType, type SiteType } from './page-types';import type { DraftMethod, PageType } from './drafts';import { pageKey } from './sources';+import type { PriorityLevel } from '@/lib/action-center/priority';/** The Plan's periods: a week, a month, a quarter. */export const PLAN_PERIODS = [7, 30, 90] as const;@@ -125,72 +126,143 @@ export const MIN_TOP_CITATIONS = 5;export const MAX_PROTECT = 5;export const MAX_ROWS = 50;-const DROP_BASE = 40;-const PROTECT_BASE = 20;-const MAX_PROTECT_SCORE = 60;-/** A drop's points: a fifth of the drop in percent, and the citations lost (up to 40). */-function citationsDownPoints(pct: number, lost: number) {- return { pct: Math.round(pct / 5), lost: Math.min(40, lost) };-}+/**+ * The Priority Score (spec v2: the Action Center's model, AC-006 priority.js):+ * 0–100 from four factors, each 0–1 and weighted. An unknown value counts as+ * neutral, not as zero, so a brand without AI traffic data, or a page still+ * to write, isn't pushed down for what nobody can know yet.+ */+export const SCORE_WEIGHTS = { severity: 40, opportunity: 30, pageValue: 20, citations: 10 };/**- * 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 top page by how much it is cited (20 + citations, at most 60), so- * protecting comes after the work to do.+ * The Plan badge's level from its score: its own cut-offs, not the Action+ * Center's 90/75/50. Under SCORE_WEIGHTS a new page tops out at 60, an+ * existing page with no drop at 74 and a top page with no opportunity at 50,+ * so on those nearly every row read Low. Here a new page reads High from an+ * opportunity score of about 82, an existing page can too, a top page with+ * no opportunity tops out at Medium (a defend opportunity can reach High),+ * and only a page losing citations can be Critical.*/-export function citationsDownScore(pct: number, lost: number): number {- const points = citationsDownPoints(pct, lost);- return Math.min(100, DROP_BASE + points.pct + points.lost);+export const PLAN_LEVEL_CUTOFFS = { critical: 75, high: 55, medium: 40 } as const;++export function planPriorityLevel(score: number): PriorityLevel {+ if (score >= PLAN_LEVEL_CUTOFFS.critical) return 'critical';+ if (score >= PLAN_LEVEL_CUTOFFS.high) return 'high';+ if (score >= PLAN_LEVEL_CUTOFFS.medium) return 'medium';+ return 'low';+}++/** How bad the signal is, by what the row is (a drop is reckoned, 0.6–1). */+const SEVERITY = { create: 0.5, opportunity: 0.35, protect: 0.2 } as const;+/** A page row with no opportunity behind it: neither good nor bad. */+const NO_OPPORTUNITY = 0.4;+/** A page still to write, or a brand with no AI traffic data. */+const NEUTRAL_PAGE_VALUE = 0.5;+/** AI visits in the period that count in full (on a log scale), and citations. */+const FULL_VISITS = 1000;+const FULL_CITATIONS = 30;+/** Citations lost that make a drop as bad as losing them all. */+const FULL_LOST = 20;++/** A drop's severity: 0.6, and up to 0.4 more for its share or the citations lost, whichever says more. */+export function dropSeverity(pct: number, lost: number): number {+ return Math.min(1, 0.6 + 0.4 * Math.max(pct / 100, Math.min(1, lost / FULL_LOST)));}-export function protectScore(citations: number): number {- return Math.min(MAX_PROTECT_SCORE, PROTECT_BASE + citations);+/** A page's AI visits as value: log10(1 + visits) against FULL_VISITS'. */+export function visitsValue(visits: number): number {+ return Math.min(1, Math.log10(1 + Math.max(0, visits)) / Math.log10(1 + FULL_VISITS));}/**- * What a row's score is made of, for the Priority Score's breakdown: the- * opportunity's own score; for a page losing citations, the base and the- * points for the drop and the citations lost; for a top page, the base and- * its citations. An opportunity whose page is losing ground has both, and- * ranks by the higher. `max` is where a score stops.+ * What a row's score is made of, for the Priority Score's breakdown: each+ * factor's value (0–1) and the points it gives (value × weight, to one+ * decimal). The score is their sum.*/-export type PlanScorePart =- | { kind: 'opportunity'; score: number }- | {- kind: 'citationsDown';- base: number;- pct: number;- pctPoints: number;- lost: number;- lostPoints: number;- max: number;- score: number;- }- | { kind: 'protect'; base: number; citations: number; max: number; score: number };+export type PlanScorePart = { value: number; points: number; max: number } & (+ | { kind: 'severity'; reason: 'drop'; pct: number; lost: number }+ | { kind: 'severity'; reason: 'create' | 'opportunity' | 'protect' }+ | { kind: 'opportunity'; score: number | null }+ | { kind: 'pageValue'; reason: 'visits'; visits: number }+ | { kind: 'pageValue'; reason: 'newPage' | 'unknown' }+ | { kind: 'citations'; citations: number }+);-function citationsDownPart(drop: { pct: number; lost: number }): PlanScorePart {- const points = citationsDownPoints(drop.pct, drop.lost);- return {- kind: 'citationsDown',- base: DROP_BASE,- pct: drop.pct,- pctPoints: points.pct,- lost: drop.lost,- lostPoints: points.lost,- max: 100,- score: citationsDownScore(drop.pct, drop.lost),- };+/** A part's own fields: its points and weight follow from them. */+type PartFields = PlanScorePart extends infer P+ ? P extends PlanScorePart+ ? Omit<P, 'points' | 'max'>+ : never+ : never;+/** To one decimal: whole points would tie pages a citation apart. */+const round1 = (n: number) => Math.round(n * 10) / 10;+function part(fields: PartFields): PlanScorePart {+ const max = SCORE_WEIGHTS[fields.kind];+ return { ...fields, max, points: round1(fields.value * max) } as PlanScorePart;}-function protectPart(citations: number): PlanScorePart {- return {- kind: 'protect',- base: PROTECT_BASE,- citations,- max: MAX_PROTECT_SCORE,- score: protectScore(citations),- };++/** The score: the parts' points, at most 100, to one decimal (shown whole). */+export function scoreOf(parts: PlanScorePart[]): number {+ return round1(+ Math.min(+ 100,+ parts.reduce((sum, p) => sum + p.points, 0),+ ),+ );+}++/** The four parts of a row's score, from what the row is and the page it works on. */+function scoreParts({+ action,+ drop,+ opportunityScore,+ page,+ trafficKnown,+}: {+ action: PlanAction;+ drop: { pct: number; lost: number } | null;+ /** The opportunity's own score; null for a page row with none. */+ opportunityScore: number | null;+ /** The page as AI cites it; absent for a new page, or one not cited. */+ page: PlanPage | undefined;+ /** Whether the brand has AI traffic data at all. */+ trafficKnown: boolean;+}): PlanScorePart[] {+ const create = action === 'create';+ return [+ drop+ ? part({+ kind: 'severity',+ reason: 'drop',+ pct: drop.pct,+ lost: drop.lost,+ value: dropSeverity(drop.pct, drop.lost),+ })+ : part({+ kind: 'severity',+ reason: create ? 'create' : action === 'protect' ? 'protect' : 'opportunity',+ value: SEVERITY[create ? 'create' : action === 'protect' ? 'protect' : 'opportunity'],+ }),+ part({+ kind: 'opportunity',+ score: opportunityScore,+ value: opportunityScore === null ? NO_OPPORTUNITY : opportunityScore / 100,+ }),+ create+ ? part({ kind: 'pageValue', reason: 'newPage', value: NEUTRAL_PAGE_VALUE })+ : trafficKnown && page+ ? part({+ kind: 'pageValue',+ reason: 'visits',+ visits: page.aiVisits,+ value: visitsValue(page.aiVisits),+ })+ : part({ kind: 'pageValue', reason: 'unknown', value: NEUTRAL_PAGE_VALUE }),+ part({+ kind: 'citations',+ citations: create ? 0 : (page?.citations.cur ?? 0),+ value: create ? 0 : Math.min(1, (page?.citations.cur ?? 0) / FULL_CITATIONS),+ }),+ ];}const CREATE_DECISIONS = new Set(['create']);@@ -239,6 +311,10 @@ export function buildPlan({const rows: PlanRow[] = [];const pagesTaken = new Set<string>();+ // No page with an AI visit: the brand has no AI traffic data (no+ // Analytics, no snippet), so a page's value is unknown, not nothing.+ const trafficKnown = pages.some((p) => p.aiVisits > 0);+for (const o of opportunities) {const create = !o.decision || CREATE_DECISIONS.has(o.decision) || !o.targetPage;const key = o.targetPage ? pageKey(o.targetPage) : null;@@ -246,9 +322,21 @@ export function buildPlan({// 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;+ const action: PlanAction = create+ ? 'create'+ : PROTECT_DECISIONS.has(o.decision ?? '')+ ? 'protect'+ : 'optimize';+ const parts = scoreParts({+ action,+ drop,+ opportunityScore: Math.round(o.score),+ page,+ trafficKnown,+ });rows.push({key: `opportunity:${o.id}`,- action: create ? 'create' : PROTECT_DECISIONS.has(o.decision ?? '') ? 'protect' : 'optimize',+ action,title,page: create ? null : o.targetPage,// A new page is what the opportunity names; an existing one is what@@ -264,13 +352,8 @@ export function buildPlan({? { kind: 'competitors', names: o.competitorsCited, visibility: o.visibility }: { kind: 'opportunity', prompts: o.prompts },source: drop ? 'citations' : 'opportunity',- score: drop- ? Math.max(o.score, citationsDownScore(drop.pct, drop.lost))- : Math.round(o.score),- scoreParts: [- { kind: 'opportunity', score: Math.round(o.score) },- ...(drop ? [citationsDownPart(drop)] : []),- ],+ score: scoreOf(parts),+ scoreParts: parts,opportunityId: o.id,draft: draftFor(o.id, create ? null : o.targetPage),priority: false,@@ -292,24 +375,38 @@ export function buildPlan({};const drop = dropOf(page, answers);if (drop) {+ const parts = scoreParts({+ action: 'optimize',+ drop,+ opportunityScore: null,+ page,+ trafficKnown,+ });rows.push({...base,key: `page:${key}`,action: 'optimize',why: dropWhy(page, drop),source: 'citations',- score: citationsDownScore(drop.pct, drop.lost),- scoreParts: [citationsDownPart(drop)],+ score: scoreOf(parts),+ scoreParts: parts,});} else if (page.citations.cur >= MIN_TOP_CITATIONS) {+ const parts = scoreParts({+ action: 'protect',+ drop: null,+ opportunityScore: null,+ page,+ trafficKnown,+ });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),- scoreParts: [protectPart(page.citations.cur)],+ score: scoreOf(parts),+ scoreParts: parts,});}}