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(action-center): score every action's priority on the server (#1071)
Cihan048b6f1b478d
diff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.jsindex ffa5aab52..fad98cf7d 100644--- a/server/src/config/action-engine.js+++ b/server/src/config/action-engine.js@@ -297,50 +297,54 @@ export const ENGINE_THRESHOLDS = Object.freeze({}),/**- * How the queue of waiting findings is ordered (#818 phase 6).+ * An action's priority score (AC-006): how soon to work on it beside the+ * others, 0–100 (lib/action-center/priority.js). Impact says how much an+ * action could matter; priority weighs it with the evidence behind it.*- * Everything the engine finds becomes a candidate; only some become actions- * tonight, because a definition's slot may be busy, resting, or the brand- * may already have had its day's worth. These weights decide which of the- * ones that can be promoted goes first.+ * Seven factors, each read as 0–1 and weighted to sum to 100. Two rules the+ * numbers keep:*- * They reproduce the ordering the Action Center has always sorted by —- * impact, then weight of evidence — and add the one thing a queue needs- * that a sort does not: age. Without it a low-impact finding sitting behind- * a brand with a steady stream of urgent ones would never be worked on at- * all.+ * * **Quantity is not priority.** Demand counts the most demanded few+ * targets (`demandTopTargets`), on a logarithmic scale, and confidence+ * counts independent kinds and sources of evidence — never how many+ * signals repeat the same finding. Fifty low-demand prompts do not+ * outrank five high-demand commercial ones.+ * * **Impact is not the whole answer.** It is one factor of seven, so a+ * medium-impact loss on high-demand prompts can come before a+ * high-impact gap nobody searches for.*- * The numbers are chosen so two rules hold, and the arithmetic is the only- * thing enforcing them:- *- * * **Nothing starves.** A full two-week wait is worth 42, and the gap- * between low and medium is 35 — so a low-impact finding that has- * waited out the cap outranks a medium one detected tonight with- * comparable evidence. Patience is worth one grade.- * * **A high-impact finding is never outranked.** It sits at 200, out of- * reach of any wait and any amount of evidence (65 + 15 + 42 = 122 at- * most). A brand losing ground right now is worked on before a queue of- * older, milder findings, however patient — a queue that lets forty- * pages of low-impact opportunity outrank a visibility collapse is not- * a priority order, it is a vote.+ * The same score orders the queue of waiting findings, plus a little for+ * each day waited (`waitPerDay`, up to `waitCapDays`) so nothing starves:+ * two weeks of patience is worth about one level.*/priority: Object.freeze({- impactHigh: 200,- impactMedium: 65,- impactLow: 30,+ weightImpact: 20,+ weightDemand: 20,+ weightSeverity: 20,+ weightBusinessValue: 15,+ weightConfidence: 10,+ weightRecoverability: 10,+ weightRecency: 5,/**- * Per doubling of the targets the action covers, up to `evidenceMax`.- * Targets rather than signals: the library folds a group of prompts into- * one signal and keeps at most five signals a kind, so counting signals- * scored nearly every candidate the same. Logarithmic, so fifty prompts- * outrank five and five outrank one, but breadth never buys a grade.- * 1 target → 2.5, 5 → 6.5, 11 → 9, 50 → 14.2.+ * Monthly AI searches (or search impressions, or sessions) at which+ * demand counts in full; logarithmic below — 10 → 0.26, 100 → 0.5,+ * 1,000 → 0.75.*/- evidencePerDoubling: 2.5,- evidenceMax: 15,- /** Per day waited, up to `ageCapDays` days: at most 42. */- agePerDay: 3,- ageCapDays: 14,+ demandFullAt: 10000,+ /** The most demanded targets that count toward demand. */+ demandTopTargets: 5,+ /** Demand and business value when nothing measures them: neither for nor against. */+ demandUnknown: 0.4,+ businessValueUnknown: 0.5,+ /** Days for a finding's recency to halve. */+ recencyHalfLifeDays: 10,+ /** Levels: critical at 90 and above, high at 75, medium at 50, low below. */+ levelCritical: 90,+ levelHigh: 75,+ levelMedium: 50,+ /** In the queue of waiting findings, per day waited, up to `waitCapDays`. */+ waitPerDay: 1,+ waitCapDays: 14,}),/** How an action's effect is measured once it closes. */diff --git a/server/src/lib/action-center/candidates.js b/server/src/lib/action-center/candidates.jsindex 303248290..879c23e5a 100644--- a/server/src/lib/action-center/candidates.js+++ b/server/src/lib/action-center/candidates.js@@ -26,53 +26,31 @@ const DAY_MS = 86_400_000;const { priority } = resolve();-const IMPACT_SCORE = {- high: priority.impactHigh,- medium: priority.impactMedium,- low: priority.impactLow,-};-/*** What a candidate is worth acting on, tonight.*- * Three terms, in the order they matter: how bad it is, how much evidence- * stands behind it, and how long it has been waiting. The first two reproduce- * the ordering the Action Center has always used; the third is what a queue- * needs and a sort does not — without it, a low-impact finding behind a brand- * with a steady stream of high-impact ones would never come up at all.- *- * Both of the lower terms are capped, so evidence and patience can move a- * candidate up the queue but cannot make it outrank a whole grade of impact- * on their own. Deliberate: a queue that lets forty pages of low-impact- * opportunity outrank a visibility collapse is not a priority order, it is a- * vote.- *- * Evidence is the action's reach — how many prompts, pages, sources or- * topics it covers (`payload.targetCount`) — and falls back to the signal- * count for a definition whose payload does not name its targets.+ * Its priority score (AC-006, priority.js) — the same number its action will+ * carry once promoted, so the queue and the Actions list agree on what comes+ * first — plus a little for each day it has waited. The wait is what a queue+ * needs and a sort does not: without it a low-priority finding behind a+ * brand with a steady stream of urgent ones would never come up at all. It+ * is capped, so two weeks of patience is worth about one level and no more.*- * @param {{ impact: string, signalCount: number, reach?: number, firstSeenAt?: string|Date }} candidate+ * @param {{ priorityScore: number, firstSeenAt?: string|Date }} candidate* @param {Date} now*/-export function scoreCandidate({ impact, signalCount, reach, firstSeenAt }, now = new Date()) {- const base = IMPACT_SCORE[impact] ?? IMPACT_SCORE.low;-- // Defensive rather than trusting: a caller that forgets to pass the count- // used to produce NaN, which sorts as "no opinion" and silently degraded- // the whole queue to alphabetical order. A scoring bug that still promotes- // something every night, just the wrong thing, is not one anybody notices.- const count = Number.isFinite(signalCount) ? Math.max(signalCount, 0) : 0;- const breadth = Number.isFinite(reach) && reach > 0 ? reach : count;- const evidence = Math.min(- Math.log2(1 + breadth) * priority.evidencePerDoubling,- priority.evidenceMax,- );+export function scoreCandidate({ priorityScore, firstSeenAt }, now = new Date()) {+ // Defensive rather than trusting: a missing score used to produce NaN,+ // which sorts as "no opinion" and silently degraded the whole queue to+ // alphabetical order. A scoring bug that still promotes something every+ // night, just the wrong thing, is not one anybody notices.+ const base = Number.isFinite(priorityScore) ? priorityScore : 0;const seen = firstSeenAt ? new Date(firstSeenAt).getTime() : now.getTime();const waitedDays = Math.max(0, Math.floor((now.getTime() - seen) / DAY_MS));- const age = Math.min(waitedDays, priority.ageCapDays) * priority.agePerDay;+ const wait = Math.min(waitedDays, priority.waitCapDays) * priority.waitPerDay;- return base + evidence + age;+ return base + wait;}/**diff --git a/server/src/lib/action-center/candidates.test.js b/server/src/lib/action-center/candidates.test.jsindex db76921cb..f75e0b0c9 100644--- a/server/src/lib/action-center/candidates.test.js+++ b/server/src/lib/action-center/candidates.test.js@@ -8,30 +8,25 @@ const daysAgo = (n) => new Date(NOW.getTime() - n * 86_400_000).toISOString();const candidate = (over = {}) => ({definitionId: 'recover_visibility',- impact: 'medium',- signalCount: 1,+ priorityScore: 60,firstSeenAt: NOW.toISOString(),...over,});describe('scoreCandidate', () => {- it('ranks by impact before anything else', () => {- const high = scoreCandidate(candidate({ impact: 'high' }), NOW);- const medium = scoreCandidate(candidate({ impact: 'medium' }), NOW);- const low = scoreCandidate(candidate({ impact: 'low' }), NOW);-- expect(high).toBeGreaterThan(medium);- expect(medium).toBeGreaterThan(low);- });-- it('counts evidence, so two findings outrank one of the same grade', () => {- expect(scoreCandidate(candidate({ signalCount: 4 }), NOW)).toBeGreaterThan(- scoreCandidate(candidate({ signalCount: 1 }), NOW),+ /**+ * The queue and the Actions list read one number (AC-006): what comes+ * first among actions is what comes first among the findings waiting to+ * become one.+ */+ it('orders by the priority score its action would carry', () => {+ expect(scoreCandidate(candidate({ priorityScore: 80 }), NOW)).toBeGreaterThan(+ scoreCandidate(candidate({ priorityScore: 60 }), NOW),);});/**- * The term a queue needs and a sort does not. Without it a low-impact+ * The term a queue needs and a sort does not. Without it a low-priority* finding behind a brand with a steady stream of urgent ones is never* worked on at all.*/@@ -42,86 +37,15 @@ describe('scoreCandidate', () => {});it('stops paying for patience past the cap', () => {- const capped = scoreCandidate(candidate({ firstSeenAt: daysAgo(priority.ageCapDays) }), NOW);+ const capped = scoreCandidate(candidate({ firstSeenAt: daysAgo(priority.waitCapDays) }), NOW);expect(scoreCandidate(candidate({ firstSeenAt: daysAgo(400) }), NOW)).toBe(capped);});- it('stops paying for evidence past the cap', () => {- const base = scoreCandidate(candidate({ signalCount: 0 }), NOW);- expect(scoreCandidate(candidate({ reach: 100_000 }), NOW)).toBe(base + priority.evidenceMax);- });-- /**- * What the queue sorted on before: signals. The library folds fifty prompts- * into one signal and keeps five signals a kind, so nearly every candidate- * scored the same and the queue promoted in id order. Reach is what tells- * fifty prompts from two topics.- */- it('ranks by how much the action covers, not how many signals carry it', () => {- const wide = scoreCandidate(candidate({ signalCount: 1, reach: 50 }), NOW);- const narrow = scoreCandidate(candidate({ signalCount: 5, reach: 2 }), NOW);- expect(wide).toBeGreaterThan(narrow);- });-- it('separates five targets from one, and fifty from five', () => {- const score = (reach) => scoreCandidate(candidate({ reach }), NOW);- expect(score(5)).toBeGreaterThan(score(1));- expect(score(50)).toBeGreaterThan(score(5));- });-- it('falls back to the signal count when the payload names no targets', () => {- expect(scoreCandidate(candidate({ signalCount: 4, reach: undefined }), NOW)).toBe(- scoreCandidate(candidate({ signalCount: 1, reach: 4 }), NOW),- );- });-- /** Breadth moves a candidate within its grade, never across one. */- it('never lets breadth alone cross a grade', () => {- const widest = scoreCandidate(candidate({ impact: 'medium', reach: 100_000 }), NOW);- expect(widest).toBeLessThan(scoreCandidate(candidate({ impact: 'high', reach: 1 }), NOW));- });-- /**- * The caps exist for this: a queue where forty low-impact pages outrank a- * visibility collapse is not a priority order, it is a vote. A brand losing- * ground right now is worked on first, however patient the rest of the- * queue is.- */- it('never lets evidence and patience outrank a high-impact finding', () => {- const loudest = scoreCandidate(- candidate({ impact: 'medium', signalCount: 1000, firstSeenAt: daysAgo(400) }),- NOW,- );- expect(scoreCandidate(candidate({ impact: 'high' }), NOW)).toBeGreaterThan(loudest);- });-- /**- * The other half of the same rule: patience must be worth *something*, or- * the low-impact end of the queue is never reached at all. Compared at- * equal evidence, so it is the wait doing the work and not the count.- */- it('lets a candidate that waited out the cap cross the grade above it', () => {- const patient = scoreCandidate(- candidate({ impact: 'low', signalCount: 2, firstSeenAt: daysAgo(30) }),- NOW,- );- const fresh = scoreCandidate(candidate({ impact: 'medium', signalCount: 2 }), NOW);-- expect(patient).toBeGreaterThan(fresh);- });-- it('does not let it cross two grades, however long it waits', () => {- const patient = scoreCandidate(- candidate({ impact: 'low', signalCount: 1000, firstSeenAt: daysAgo(400) }),- NOW,- );- expect(patient).toBeLessThan(scoreCandidate(candidate({ impact: 'high' }), NOW));- });-- it('treats an unknown impact as the lowest grade rather than as nothing', () => {- expect(scoreCandidate(candidate({ impact: 'catastrophic' }), NOW)).toBe(- scoreCandidate(candidate({ impact: 'low' }), NOW),- );+ /** Patience is worth about one level, so the queue reaches everything. */+ it('lets two weeks of waiting cross about one level, and no more', () => {+ const patient = scoreCandidate(candidate({ priorityScore: 62, firstSeenAt: daysAgo(30) }), NOW);+ expect(patient).toBeGreaterThan(scoreCandidate(candidate({ priorityScore: 75 }), NOW));+ expect(patient).toBeLessThan(scoreCandidate(candidate({ priorityScore: 90 }), NOW));});it('scores a candidate first seen tonight without reading the clock wrong', () => {@@ -132,12 +56,12 @@ describe('scoreCandidate', () => {});describe('orderByPriority', () => {- it('puts the worst problem first', () => {+ it('puts the highest priority first', () => {const ordered = orderByPriority([- candidate({ definitionId: 'a', impact: 'low' }),- candidate({ definitionId: 'b', impact: 'high' }),- candidate({ definitionId: 'c', impact: 'medium' }),+ candidate({ definitionId: 'a', priorityScore: 40 }),+ candidate({ definitionId: 'b', priorityScore: 92 }),+ candidate({ definitionId: 'c', priorityScore: 70 }),],NOW,);@@ -148,14 +72,14 @@ describe('orderByPriority', () => {it('breaks a tie on how long it has waited, oldest first', () => {const ordered = orderByPriority([- candidate({ definitionId: 'new', firstSeenAt: daysAgo(priority.ageCapDays + 1) }),- candidate({ definitionId: 'older', firstSeenAt: daysAgo(priority.ageCapDays + 9) }),+ candidate({ definitionId: 'new', firstSeenAt: daysAgo(priority.waitCapDays + 1) }),+ candidate({ definitionId: 'older', firstSeenAt: daysAgo(priority.waitCapDays + 9) }),],NOW,);- // Both are past the age cap, so they score the same — the tie-break is- // what decides, and it has to be the one that has waited longer.+ // Both are past the cap, so they score the same — the tie-break is what+ // decides, and it has to be the one that has waited longer.expect(ordered.map((c) => c.definitionId)).toEqual(['older', 'new']);});@@ -165,15 +89,15 @@ describe('orderByPriority', () => {* is the shape that bug took once already.*/it('produces a real number for every candidate, never NaN', () => {- for (const c of [candidate(), candidate({ signalCount: undefined })]) {+ for (const c of [candidate(), candidate({ priorityScore: undefined })]) {expect(Number.isFinite(scoreCandidate(c, NOW))).toBe(true);}});it('does not modify the list it was given', () => {const list = [- candidate({ definitionId: 'a', impact: 'low' }),- candidate({ definitionId: 'b', impact: 'high' }),+ candidate({ definitionId: 'a', priorityScore: 30 }),+ candidate({ definitionId: 'b', priorityScore: 90 }),];orderByPriority(list, NOW);expect(list.map((c) => c.definitionId)).toEqual(['a', 'b']);diff --git a/server/src/lib/action-center/from-opportunity.js b/server/src/lib/action-center/from-opportunity.jsindex e41dfa3a7..815f42fb7 100644--- a/server/src/lib/action-center/from-opportunity.js+++ b/server/src/lib/action-center/from-opportunity.js@@ -13,6 +13,7 @@import supabaseAdmin from '../../config/supabase.js';import { resolveBrandSources } from './sources.js';import { planTasks } from './tasks/plan.js';+import { priorityOnCreate } from './priority-data.js';export const OPPORTUNITY_ACTION_KIND = 'content_opportunity';@@ -189,6 +190,12 @@ export async function sendToActionCenter(kpi_keys: KPI_KEYS,baseline: {},dedup_key: dedupKey,+ ...(await priorityOnCreate({+ kind: OPPORTUNITY_ACTION_KIND,+ category: 'growth',+ impact: opportunity.impact,+ payload,+ })),}).select('id').single();diff --git a/server/src/lib/action-center/from-prompt-improve.js b/server/src/lib/action-center/from-prompt-improve.jsindex 73593ff02..a44fa6c12 100644--- a/server/src/lib/action-center/from-prompt-improve.js+++ b/server/src/lib/action-center/from-prompt-improve.js@@ -14,6 +14,7 @@import supabaseAdmin from '../../config/supabase.js';import { IMPROVE_PLATFORM_LABELS } from '../prompt-improve.js';import { compareOutcome, outcomeWindow, readPlatformStates } from './improve-outcome.js';+import { priorityOnCreate } from './priority-data.js';export const IMPROVE_ACTION_KIND = 'prompt_improve';@@ -196,6 +197,7 @@ export async function sendImproveToActionCenter({targetCount: platforms.length,};+ const impact = improveImpact(platforms, volumeRow?.est_ai_volume);const { data: action, error } = await supabaseAdmin.from('actions').insert({@@ -203,7 +205,7 @@ export async function sendImproveToActionCenter({category: 'compete',kind: IMPROVE_ACTION_KIND,definition_version: 1,- impact: improveImpact(platforms, volumeRow?.est_ai_volume),+ impact,payload,kpi_keys: improveKpiKeys(pages),baseline: improveBaseline(snapshots, now, window),@@ -215,6 +217,12 @@ export async function sendImproveToActionCenter({...compareOutcome(snapshots, snapshots),},dedup_key: dedupKey,+ ...(await priorityOnCreate({+ kind: IMPROVE_ACTION_KIND,+ category: 'compete',+ impact,+ payload,+ })),}).select('id, action_no').single();diff --git a/server/src/lib/action-center/generate.js b/server/src/lib/action-center/generate.jsindex a9e45537f..6a6cee9c8 100644--- a/server/src/lib/action-center/generate.js+++ b/server/src/lib/action-center/generate.js@@ -52,6 +52,8 @@ import { isEligible, loadDefinitions } from './definitions/index.js';import { resolveBrandSources } from './sources.js';import { planTasks } from './tasks/plan.js';import { orderByPriority, scoreCandidate } from './candidates.js';+import { priorityColumns, promptIdsOf, scorePriority } from './priority.js';+import { loadPromptDemand } from './priority-data.js';const DAY_MS = 86_400_000;@@ -106,7 +108,16 @@ function startOfUtcDay(now) {return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());}-async function openCycle({ brandId, definition, signals, impact, available, payload }) {+async function openCycle({+ brandId,+ definition,+ signals,+ impact,+ available,+ payload,+ priority,+ now,+}) {const { data: inserted, error } = await supabaseAdmin.from('actions').insert({@@ -119,6 +130,7 @@ async function openCycle({ brandId, definition, signals, impact, available, paylkpi_keys: [...new Set(signals.flatMap((signal) => signal.kpi_keys ?? []))],baseline: buildBaseline(signals),dedup_key: definition.id,+ ...priorityColumns(priority, now),}).select('id').single();@@ -159,7 +171,7 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourcconst { data: openSignals, error: signalsErr } = await supabaseAdmin.from('signals').select(- 'id, kind, impact, kpi_keys, payload, previous_value, current_value, change_value, action_id',+ 'id, kind, impact, kpi_keys, payload, previous_value, current_value, change_value, action_id, source, detected_at',).eq('brand_id', brandId).in('status', ['new', 'acknowledged'])@@ -171,7 +183,7 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc// has no bearing on what happens tonight beyond the rest window below.const { data: activeRows, error: actionsErr } = await supabaseAdmin.from('actions')- .select('id, dedup_key, status, created_at')+ .select('id, dedup_key, status, created_at, kind, category, impact, payload').eq('brand_id', brandId).not('status', 'in', '("completed","dismissed")').limit(1000);@@ -219,6 +231,24 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourcif (waitingErr) throw new Error(waitingErr.message);const waiting = new Map((waitingRows ?? []).map((row) => [row.definition_id, row]));+ // The demand and intent of every prompt the evidence names, read once for+ // the night's priority scores. Without it the scores are still worked out,+ // with demand and intent unknown: a slower read is no reason to skip them.+ let demand = new Map();+ try {+ demand = await loadPromptDemand(+ promptIdsOf([+ ...(openSignals ?? []).map((signal) => signal.payload),+ ...(activeRows ?? []).map((row) => row.payload),+ ]),+ );+ } catch (err) {+ logger.warn({ brandId, err: err.message }, '[actions] prompt demand unavailable');+ }+ // Signals linked to an active action tonight, which the rows in hand do+ // not show yet: they are its evidence when its priority is refreshed.+ const linkedTonight = new Map();+const ready = [];const seen = new Set();let refreshed = 0;@@ -246,6 +276,9 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc// Those newcomers are not dropped any more, which is this phase: they// stay in the queue below and are what the next cycle covers.const linked = await linkSignals(current.id, matched);+ for (const signal of matched) {+ if (!signal.action_id) linkedTonight.set(signal.id, current.id);+ }if (linked > 0) {await supabaseAdmin.from('actions').update({ updated_at: nowIso }).eq('id', current.id);await logEvent(current.id, 'signals_linked', { count: linked });@@ -271,11 +304,17 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourcconst existing = waiting.get(definition.id);const firstSeenAt = existing?.first_seen_at ?? nowIso;- const reach = payload.targetCount;- const score = scoreCandidate(- { impact, signalCount: unclaimed.length, reach, firstSeenAt },+ // The priority its action would carry (AC-006): the queue is ordered by+ // the same number the Actions list is.+ const priority = scorePriority(+ {+ action: { kind: definition.id, category: definition.category, impact, payload },+ signals: unclaimed,+ prompts: demand,+ },now,);+ const score = scoreCandidate({ priorityScore: priority.score, firstSeenAt }, now);const row = {brand_id: brandId,definition_id: definition.id,@@ -330,12 +369,10 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourcdefinition,signals: unclaimed,impact,- // What the score reads. Named rather than derived from `signals` inside- // the scorer so the same shape can be scored straight out of the- // database, where the signals themselves are just ids.- signalCount: unclaimed.length,- reach,payload,+ priority,+ // What the queue's order reads, beside the time waited.+ priorityScore: priority.score,firstSeenAt,});}@@ -361,7 +398,7 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourcconst opening = ordered.slice(0, room);for (const candidate of opening) {- const actionId = await openCycle({ brandId, available, ...candidate });+ const actionId = await openCycle({ brandId, available, now, ...candidate });const { error } = await supabaseAdmin.from('action_candidates').update({@@ -374,8 +411,33 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourcif (error) throw new Error(error.message);}+ // Every active action's priority, worked out again from tonight's evidence:+ // its open signals, how recent they are, the demand behind them. Actions+ // opened tonight were scored as they were written. Best effort: a score+ // that cannot be written is logged, never a reason to fail the night.+ let rescored = 0;+ for (const row of activeRows ?? []) {+ const evidence = (openSignals ?? []).filter(+ (signal) => signal.action_id === row.id || linkedTonight.get(signal.id) === row.id,+ );+ const priority = scorePriority({ action: row, signals: evidence, prompts: demand }, now);+ const { error } = await supabaseAdmin+ .from('actions')+ .update(priorityColumns(priority, now))+ .eq('id', row.id);+ if (error) {+ logger.warn(+ { brandId, actionId: row.id, err: error.message },+ '[actions] priority not saved',+ );+ continue;+ }+ rescored += 1;+ }+const summary = {created: opening.length,+ rescored,refreshed,resting,ineligible,diff --git a/server/src/lib/action-center/generate.test.js b/server/src/lib/action-center/generate.test.jsindex 5d92968ac..08219bdcd 100644--- a/server/src/lib/action-center/generate.test.js+++ b/server/src/lib/action-center/generate.test.js@@ -27,7 +27,14 @@ const NOW = new Date('2026-09-16T04:00:00Z');* lets `await supabase.from(x).select(y).eq(...)` resolve without a terminal* call.*/-function mockDb({ signals = [], activeActions = [], closedActions = [], candidates = [] } = {}) {+function mockDb({+ signals = [],+ activeActions = [],+ closedActions = [],+ candidates = [],+ promptVolumes = [],+ failActionUpdates = false,+} = {}) {const writes = { inserted: [], updated: [] };from.mockImplementation((table) => {@@ -66,12 +73,17 @@ function mockDb({ signals = [], activeActions = [], closedActions = [], candidatfunction result() {if (state.op === 'insert') return { data: { id: `new-${table}` }, error: null };- if (state.op === 'update') return { data: null, error: null };+ if (state.op === 'update') {+ const failed =+ failActionUpdates && table === 'actions' && 'priority_score' in state.payload;+ return { data: null, error: failed ? { message: 'column does not exist' } : null };+ }if (table === 'signals') return { data: signals, error: null };if (table === 'actions') {return { data: state.negated ? activeActions : closedActions, error: null };}if (table === 'action_candidates') return { data: candidates, error: null };+ if (table === 'prompt_volumes') return { data: promptVolumes, error: null };return { data: [], error: null };}@@ -121,6 +133,13 @@ describe('generateActionsForBrand', () => {});// Its own baseline — the "before" half of a future measurement.expect(action.rows[0].baseline.signals).toHaveLength(1);+ // Written with its priority (AC-006), from the drop it rests on.+ expect(action.rows[0]).toMatchObject({+ priority_score: expect.any(Number),+ priority_level: expect.stringMatching(/^(critical|high|medium|low)$/),+ priority_reason: expect.objectContaining({ change: 'dropped' }),+ priority_updated_at: NOW.toISOString(),+ });// The plan comes from the specification's library, and ends in validation.const keys = writes.inserted.find((w) => w.table === 'action_tasks')@@ -235,6 +254,7 @@ describe('generateActionsForBrand', () => {expect(summary).toEqual({created: 0,+ rescored: 0,refreshed: 0,resting: 0,ineligible: 0,@@ -671,3 +691,134 @@ describe('the candidate queue', () => {expect(row.priority).toBeGreaterThan(0);});});++/**+ * AC-006: every action carries a priority score, and the queue is ordered by+ * it. Quantity is not priority — the spec's own example is forty-seven+ * repetitive low-demand signals against one high-demand commercial loss.+ */+describe('the priority score', () => {+ const VOLUMES = [+ ...Array.from({ length: 47 }, (_, i) => ({+ prompt_id: `tail-${i}`,+ est_ai_volume: 5,+ intent: 'what-is',+ fetched_at: NOW.toISOString(),+ })),+ { prompt_id: 'hot', est_ai_volume: 2000, intent: 'comparison', fetched_at: NOW.toISOString() },+ ];++ it('promotes one high-demand commercial loss before forty-seven low-demand gaps', async () => {+ const spent = Array.from({ length: maxNewActionsPerDay - 1 }, (_, i) => ({+ id: `spent-${i}`,+ dedup_key: `unrelated-${i}`,+ status: 'new',+ created_at: NOW.toISOString(),+ }));+ const writes = mockDb({+ signals: [+ // Same impact as the loss, and far more of them.+ ...Array.from({ length: 47 }, (_, i) =>+ signal({+ id: `gap-${i}`,+ kind: 'uncovered_demand',+ impact: 'high',+ payload: { entity: 'prompts', targets: [{ id: `tail-${i}`, volume: 5 }] },+ }),+ ),+ signal({+ id: 'loss',+ kind: 'lost_citations',+ impact: 'high',+ payload: { promptId: 'hot', promptText: 'Best AI rank tracker?' },+ }),+ ],+ activeActions: spent,+ promptVolumes: VOLUMES,+ });++ const summary = await generateActionsForBrand(BRAND, {+ now: NOW,+ sources: new Set([...ALL_SOURCES, 'volumes']),+ });++ expect(summary.created).toBe(1);+ const opened = writes.inserted.find((w) => w.table === 'actions').rows[0];+ expect(opened.kind).toBe('recover_lost_citations');+ expect(opened.priority_reason).toMatchObject({+ change: 'lost',+ demand: 'high',+ commercial: true,+ heldBefore: true,+ });+ // The queue holds the gaps, scored below it.+ const queued = writes.inserted+ .filter((w) => w.table === 'action_candidates')+ .flatMap((w) => w.rows);+ const byDefinition = Object.fromEntries(queued.map((r) => [r.definition_id, r.priority]));+ expect(byDefinition.recover_lost_citations).toBeGreaterThan(+ byDefinition.create_content_for_demand,+ );+ });++ it('works out every active action again from its evidence', async () => {+ const writes = mockDb({+ signals: [+ signal({+ id: 's9',+ action_id: 'a1',+ kind: 'lost_citations',+ source: ['ai_results'],+ detected_at: daysAgo(2),+ payload: { promptId: 'hot' },+ }),+ ],+ activeActions: [+ {+ id: 'a1',+ dedup_key: 'recover_lost_citations',+ status: 'in_progress',+ created_at: daysAgo(5),+ kind: 'recover_lost_citations',+ category: 'recover',+ impact: 'high',+ payload: {},+ },+ ],+ promptVolumes: VOLUMES,+ });++ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });++ expect(summary.rescored).toBe(1);+ const patch = writes.updated.find((w) => w.table === 'actions' && 'priority_score' in w.patch);+ expect(patch.patch).toMatchObject({+ priority_level: expect.any(String),+ priority_reason: expect.objectContaining({ change: 'lost', days: 2 }),+ });+ // A priority refresh is not an edit: the action's updated_at stays put.+ expect(patch.patch).not.toHaveProperty('updated_at');+ });++ it('keeps the night going when a priority cannot be saved', async () => {+ mockDb({+ signals: [],+ activeActions: [+ {+ id: 'a1',+ dedup_key: 'recover_lost_citations',+ status: 'new',+ created_at: daysAgo(1),+ kind: 'recover_lost_citations',+ category: 'recover',+ impact: 'high',+ payload: {},+ },+ ],+ failActionUpdates: true,+ });++ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });+ expect(summary.rescored).toBe(0);+ });+});diff --git a/server/src/lib/action-center/priority-data.js b/server/src/lib/action-center/priority-data.jsnew file mode 100644index 000000000..bfc761fca--- /dev/null+++ b/server/src/lib/action-center/priority-data.js@@ -0,0 +1,76 @@+/**+ * What the priority score reads from the database (AC-006): the demand and+ * intent of the prompts an action's evidence names. Everything else it needs+ * — the action, its signals — the caller has in hand already.+ */++import supabaseAdmin from '../../config/supabase.js';+import { logger } from '../logger.js';+import { priorityColumns, promptIdsOf, scorePriority } from './priority.js';++/** Prompt ids per request, so the filter stays well inside a URL's length. */+const CHUNK = 150;++/** Rows per page: a prompt has a row per location and fetch, past the 1,000 a response holds. */+const PAGE = 1000;++/**+ * Per prompt, its estimated monthly AI searches and its intent. A prompt can+ * have a row per location and per fetch: the largest volume counts, as in+ * the detectors' reads (`ae_prompt_stats`), and the newest intent.+ *+ * @param {string[]} promptIds+ * @returns {Promise<Map<string, { volume: number|null, intent: string|null }>>}+ */+export async function loadPromptDemand(promptIds) {+ const demand = new Map();+ const ids = [...new Set(promptIds)];+ const rows = [];+ for (let i = 0; i < ids.length; i += CHUNK) {+ for (let from = 0; ; from += PAGE) {+ const { data, error } = await supabaseAdmin+ .from('prompt_volumes')+ .select('prompt_id, est_ai_volume, intent, fetched_at')+ .in('prompt_id', ids.slice(i, i + CHUNK))+ .order('fetched_at', { ascending: false })+ .order('id', { ascending: true })+ .range(from, from + PAGE - 1);+ if (error) throw new Error(`prompt demand read failed: ${error.message}`);+ rows.push(...(data ?? []));+ if ((data ?? []).length < PAGE) break;+ }+ }+ // Each prompt's rows sit in one chunk, newest first: its first row has its newest intent.+ for (const row of rows) {+ const volume = row.est_ai_volume === null ? null : Number(row.est_ai_volume);+ const known = demand.get(row.prompt_id);+ if (!known) {+ demand.set(row.prompt_id, { volume, intent: row.intent ?? null });+ } else if (volume !== null && (known.volume === null || volume > known.volume)) {+ known.volume = volume;+ }+ }+ return demand;+}++/**+ * The priority columns for an action a person sends (from Content or the+ * Improve tab), worked out as it is written; the nightly pass refreshes them+ * after. Without the prompts' demand it is still scored, with demand unknown:+ * the action is not held back for it.+ *+ * @param {{ kind: string, category: string, impact: string, payload: object }} action+ */+export async function priorityOnCreate(action, now = new Date()) {+ let prompts = new Map();+ try {+ prompts = await loadPromptDemand(promptIdsOf([action.payload]));+ } catch (err) {+ logger.warn({ err: err.message, kind: action.kind }, '[actions] prompt demand unavailable');+ }+ const priority = scorePriority(+ { action: { ...action, created_at: now.toISOString() }, signals: [], prompts },+ now,+ );+ return priorityColumns(priority, now);+}diff --git a/server/src/lib/action-center/priority-data.test.js b/server/src/lib/action-center/priority-data.test.jsnew file mode 100644index 000000000..dba357337--- /dev/null+++ b/server/src/lib/action-center/priority-data.test.js@@ -0,0 +1,110 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * What the priority score reads (AC-006): each prompt's demand and intent,+ * the largest volume across its rows and the newest intent.+ */++let rows = [];+let reads = [];+let pages = [];+let fail = false;++vi.mock('../../config/supabase.js', () => ({+ default: {+ from: () => {+ let ids = [];+ const chain = {+ select: () => chain,+ in: (column, values) => {+ ids = values;+ reads.push(values);+ return chain;+ },+ order: () => chain,+ range: async (from, to) => {+ pages.push([from, to]);+ if (fail) return { data: null, error: { message: 'timeout' } };+ const matching = rows.filter((r) => ids.includes(r.prompt_id));+ return { data: matching.slice(from, to + 1), error: null };+ },+ };+ return chain;+ },+ },+}));+vi.mock('../logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++const { loadPromptDemand, priorityOnCreate } = await import('./priority-data.js');++beforeEach(() => {+ reads = [];+ pages = [];+ fail = false;+ // Newest first, as the read orders them.+ rows = [+ { prompt_id: 'p1', est_ai_volume: 300, intent: 'comparison', fetched_at: '2026-10-10' },+ { prompt_id: 'p1', est_ai_volume: 900, intent: 'other', fetched_at: '2026-09-01' },+ { prompt_id: 'p2', est_ai_volume: null, intent: 'how-to', fetched_at: '2026-10-10' },+ ];+});++describe('loadPromptDemand', () => {+ it("takes each prompt's largest volume and newest intent", async () => {+ const demand = await loadPromptDemand(['p1', 'p2', 'p1']);+ expect(Object.fromEntries(demand)).toEqual({+ p1: { volume: 900, intent: 'comparison' },+ p2: { volume: null, intent: 'how-to' },+ });+ });++ it('reads long lists in pieces', async () => {+ await loadPromptDemand(Array.from({ length: 320 }, (_, i) => `p${i}`));+ expect(reads.map((ids) => ids.length)).toEqual([150, 150, 20]);+ });++ it('pages through a prompt with more rows than a response holds', async () => {+ rows = Array.from({ length: 1200 }, (_, i) => ({+ prompt_id: 'busy',+ est_ai_volume: i,+ intent: i === 0 ? 'comparison' : 'other',+ fetched_at: '2026-10-10',+ }));+ const demand = await loadPromptDemand(['busy']);+ expect(pages).toEqual([+ [0, 999],+ [1000, 1999],+ ]);+ expect(demand.get('busy')).toEqual({ volume: 1199, intent: 'comparison' });+ });++ it('reads nothing for no prompts', async () => {+ expect((await loadPromptDemand([])).size).toBe(0);+ expect(reads).toEqual([]);+ });+});++describe('priorityOnCreate', () => {+ const NOW = new Date('2026-10-15T00:00:00Z');+ const improve = {+ kind: 'prompt_improve',+ category: 'compete',+ impact: 'medium',+ payload: { promptIds: ['p1'], platforms: [{ id: 'gemini-web', state: 'not_mentioned' }] },+ };++ it('scores an action as it is written', async () => {+ expect(await priorityOnCreate(improve, NOW)).toMatchObject({+ priority_score: expect.any(Number),+ priority_reason: expect.objectContaining({ demand: 'high', commercial: true }),+ priority_updated_at: NOW.toISOString(),+ });+ });++ it('still scores it when the demand cannot be read', async () => {+ fail = true;+ const columns = await priorityOnCreate(improve, NOW);+ expect(columns.priority_reason.demand).toBeNull();+ expect(columns.priority_score).toEqual(expect.any(Number));+ });+});diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.jsnew file mode 100644index 000000000..e107c93f6--- /dev/null+++ b/server/src/lib/action-center/priority.js@@ -0,0 +1,467 @@+/**+ * An action's priority score (AC-006): how soon to work on it, 0–100.+ *+ * Impact says how much an action could matter. Priority says what to do+ * first, and weighs seven things the evidence shows (config/action-engine.js+ * `priority`):+ *+ * impact the action's impact grade;+ * demand how much the affected prompts, queries or pages are+ * searched or visited — the most demanded few of them;+ * severity how bad the change is: lost before dropping, dropping+ * before slipping, slipping before a gap;+ * business value how commercial the searches are (intent), or what the+ * page is worth to the business;+ * confidence how many independent kinds and sources of evidence agree+ * — not how many signals repeat one finding;+ * recoverability whether the brand held this before and lost it, which is+ * nearer to hand than winning it from nothing;+ * recency how new the latest evidence is, halving every few days.+ *+ * Pure: the caller reads the signals and the prompts' demand and passes them+ * in. Alongside the score it returns the facts it rests on, from which the+ * app writes "Why this priority?" in the reader's language.+ */++import { resolve } from '../../config/action-engine.js';+import { INTENT_WEIGHTS } from '../opportunity-limits.js';++const DAY_MS = 86_400_000;++const { priority: P } = resolve();++const IMPACT = { high: 1, medium: 0.6, low: 0.3 };++/**+ * How bad a finding is, by its kind, and what kind of change it is. A loss+ * outranks a drop, a drop a slip, a slip a gap; a gain is barely urgent.+ */+const SEVERITY = {+ lost: 1,+ dropped: 0.85,+ slipping: 0.6,+ gap: 0.5,+ issue: 0.5,+ opportunity: 0.35,+ gain: 0.2,+};++const KIND_CHANGE = {+ // Something held is gone.+ lost_citations: 'lost',+ owned_page_citation_lost: 'lost',+ high_value_prompt_lost: 'lost',+ lost_mentions: 'lost',+ // A clear fall.+ sharp_drop: 'dropped',+ platform_drop: 'dropped',+ topic_drop: 'dropped',+ ai_traffic_drop: 'dropped',+ gsc_decline: 'dropped',+ visibility_traffic_loss: 'dropped',+ cross_channel_risk: 'dropped',+ converting_page_slipping: 'dropped',+ competitor_crossed: 'dropped',+ competitor_overtaken: 'dropped',+ competitor_surge: 'dropped',+ crawler_blocked: 'dropped',+ // Starting to fall.+ visibility_slipping: 'slipping',+ platform_slipping: 'slipping',+ topic_slipping: 'slipping',+ ai_traffic_slipping: 'slipping',+ page_citation_slipping: 'slipping',+ citation_at_risk: 'slipping',+ gsc_risk: 'slipping',+ competitor_momentum: 'slipping',+ // Something to fix on the site.+ structured_data_issue: 'issue',+ outdated_content: 'issue',+ weak_entity: 'issue',+ weak_internal_links: 'issue',+ content_gap: 'issue',+ audit_low_score: 'issue',+ // Ground to win.+ page_opportunity: 'opportunity',+ ai_landing_page_winner: 'opportunity',+ new_engine: 'opportunity',+ gsc_low_ctr: 'opportunity',+ // Ground never held: a gap to close or a lead to answer.+ prompt_visibility_gap: 'gap',+ high_demand_gap: 'gap',+ uncovered_demand: 'gap',+ prompt_unmapped: 'gap',+ content_underperforming: 'gap',+ topic_gap: 'gap',+ topic_uncovered: 'gap',+ country_gap: 'gap',+ platform_gap: 'gap',+ competitor_leads: 'gap',+ competitor_topic_lead: 'gap',+ competitor_high_value_lead: 'gap',+ competitor_uncovered_topic: 'gap',+ competitor_citation_gap: 'gap',+ authority_citation_gap: 'gap',+ third_party_citation_gap: 'gap',+ third_party_presence_gap: 'gap',+ competitor_cited_source: 'gap',+ competitor_winning_source: 'gap',+ fanout_gap: 'gap',+ competitor_fanout_gap: 'gap',+ gsc_demand_gap: 'gap',+ search_ai_misalignment: 'gap',+ ai_landing_underperforming: 'gap',+ uncited_mentions: 'gap',+ // Good news.+ prompt_gain: 'gain',+ first_citation: 'gain',+};++/** AI-traffic kinds whose page targets carry sessions (`before`/`now`). */+const SESSION_KINDS = new Set([+ 'ai_traffic_slipping',+ 'ai_traffic_drop',+ 'ai_landing_page_winner',+ 'ai_landing_underperforming',+ 'converting_page_slipping',+]);++/** Severity when an action has no open evidence left: its findings resolved. */+const NO_EVIDENCE_SEVERITY = 0.3;++/** Kinds that report losing ground the brand held: nearer to hand than new ground. */+const HELD_BEFORE = new Set([+ 'lost_citations',+ 'owned_page_citation_lost',+ 'high_value_prompt_lost',+ 'lost_mentions',+ 'sharp_drop',+ 'visibility_slipping',+ 'platform_drop',+ 'platform_slipping',+ 'topic_drop',+ 'topic_slipping',+ 'page_citation_slipping',+ 'citation_at_risk',+ 'ai_traffic_drop',+ 'ai_traffic_slipping',+ 'converting_page_slipping',+ 'gsc_decline',+ 'gsc_risk',+ 'visibility_traffic_loss',+ 'cross_channel_risk',+]);++/** Kinds whose cure is a fix on the brand's own site. */+const SITE_FIX = new Set([+ 'crawler_blocked',+ 'structured_data_issue',+ 'outdated_content',+ 'weak_internal_links',+ 'audit_low_score',+]);++/** Without a kind to go by, how recoverable an action's category usually is. */+const CATEGORY_RECOVERABILITY = { recover: 1, protect: 0.9, fix: 0.9, compete: 0.6, growth: 0.5 };++/** What a page is worth to the business, by the signal that ranked it. */+const PAGE_VALUE = { revenue: 1, transactions: 0.95, key_events: 0.85, engagement: 0.65 };++/** Commercial enough to say so in "Why this priority?". */+const COMMERCIAL = 0.85;++const clamp01 = (n) => Math.min(1, Math.max(0, n));+const round2 = (n) => Math.round(n * 100) / 100;++/** What kind of change a finding is; a kind this table has not met counts as a gap. */+function changeOf(kind) {+ return KIND_CHANGE[kind] ?? 'gap';+}++/** Demand on the shared log scale: 0 → 0, `demandFullAt` and above → 1. */+function demandScale(value) {+ return clamp01(Math.log10(1 + value) / Math.log10(1 + P.demandFullAt));+}++/** The sum of the `demandTopTargets` largest values. */+function topSum(values) {+ return [...values]+ .sort((a, b) => b - a)+ .slice(0, P.demandTopTargets)+ .reduce((sum, v) => sum + v, 0);+}++function targetsOf(payload) {+ return Array.isArray(payload?.targets) ? payload.targets.filter(Boolean) : [];+}++/**+ * The prompts an action is about, from its signals' payloads and its own:+ * a prompt id, a list of them, or targets naming prompts.+ */+export function promptIdsOf(payloads) {+ const ids = new Set();+ for (const p of payloads) {+ if (!p) continue;+ if (typeof p.promptId === 'string') ids.add(p.promptId);+ for (const id of Array.isArray(p.promptIds) ? p.promptIds : []) {+ if (typeof id === 'string') ids.add(id);+ }+ const entity = p.entity ?? p.targetEntity;+ if (entity === 'prompts') {+ for (const t of targetsOf(p)) if (typeof t.id === 'string') ids.add(t.id);+ }+ }+ return [...ids];+}++/**+ * Demand and business value from what the evidence names: prompts (their+ * monthly AI searches and intent), search queries (impressions) and pages+ * (sessions, and what the page is worth). Null where nothing is measured.+ */+function demandAndValue(payloads, signals, prompts) {+ // Prompts: the stored demand, else the volume the detector put on a target.+ const promptVolume = new Map();+ for (const id of promptIdsOf(payloads)) {+ const known = prompts.get(id);+ if (known && Number.isFinite(known.volume)) promptVolume.set(id, known.volume);+ }+ for (const p of payloads) {+ if ((p?.entity ?? p?.targetEntity) !== 'prompts') continue;+ for (const t of targetsOf(p)) {+ if (typeof t.id === 'string' && !promptVolume.has(t.id) && Number.isFinite(t.volume)) {+ promptVolume.set(t.id, t.volume);+ }+ }+ }++ const queryImpressions = [];+ const pageSessions = [];+ let pageValue = null;+ for (const p of payloads) {+ const entity = p?.entity ?? p?.targetEntity;+ for (const t of targetsOf(p)) {+ if (entity === 'queries' && Number.isFinite(t.impressions)) {+ queryImpressions.push(t.impressions);+ }+ }+ if (typeof p?.valueSignal === 'string' && PAGE_VALUE[p.valueSignal]) {+ pageValue = Math.max(pageValue ?? 0, PAGE_VALUE[p.valueSignal]);+ }+ }+ for (const s of signals) {+ // Sessions only from the AI-traffic kinds: other page targets carry+ // other counts in the same fields (an owned page's citations).+ if (SESSION_KINDS.has(s.kind)) {+ for (const t of targetsOf(s.payload)) {+ if (Number.isFinite(t.now) || Number.isFinite(t.before)) {+ pageSessions.push(Math.max(t.now ?? 0, t.before ?? 0));+ }+ }+ }+ // A page opportunity's value is the page's sessions over its window.+ if (s.kind === 'page_opportunity' && Number.isFinite(Number(s.current_value))) {+ pageSessions.push(Number(s.current_value));+ }+ // Pages that convert are worth more than pages that are read.+ if (s.kind === 'converting_page_slipping' || s.kind === 'ai_landing_page_winner') {+ pageValue = Math.max(pageValue ?? 0, PAGE_VALUE.key_events);+ }+ }++ const promptDemand = promptVolume.size ? topSum(promptVolume.values()) : null;+ const measured = [+ promptDemand,+ queryImpressions.length ? topSum(queryImpressions) : null,+ pageSessions.length ? topSum(pageSessions) : null,+ ].filter((v) => v !== null);+ const demand = measured.length ? Math.max(...measured.map(demandScale)) : null;++ // Intent, weighted by each prompt's demand so a long tail does not outvote+ // the prompts people search for.+ let weighted = 0;+ let weight = 0;+ for (const [id, volume] of promptVolume) {+ const intent = prompts.get(id)?.intent;+ if (!intent || INTENT_WEIGHTS[intent] === undefined) continue;+ const w = Math.max(volume, 1);+ weighted += INTENT_WEIGHTS[intent] * w;+ weight += w;+ }+ const intentValue = weight ? weighted / weight : null;+ const values = [intentValue, pageValue].filter((v) => v !== null);+ const businessValue = values.length ? Math.max(...values) : null;++ return { demand, promptDemand, businessValue };+}++/**+ * Independent confirmation: distinct kinds of finding and distinct data+ * sources, never the number of signals. One kind from one source is 0.3.+ */+function confidenceOf(signals) {+ const kinds = new Set(signals.map((s) => s.kind));+ const sources = new Set(signals.flatMap((s) => (Array.isArray(s.source) ? s.source : [])));+ const value = clamp01(+ 0.3 + 0.2 * Math.max(kinds.size - 1, 0) + 0.2 * Math.max(sources.size - 1, 0),+ );+ return { value, kinds: kinds.size, sources: sources.size };+}++/**+ * What an action sent by a person rests on, without detection signals: an+ * Improve action names its platforms and their state, a content opportunity+ * its prompts. Read from the action's own payload.+ */+function sentByHand(action) {+ const p = action.payload ?? {};+ if (action.kind === 'prompt_improve') {+ const states = Array.isArray(p.platforms) ? p.platforms.map((x) => x?.state) : [];+ const gaps = states.filter(+ (s) => s === 'not_mentioned' || s === 'mentioned_late' || s === 'not_cited',+ );+ const severity = states.includes('not_mentioned')+ ? 0.7+ : states.includes('mentioned_late')+ ? 0.55+ : gaps.length+ ? 0.45+ : 0.3;+ return {+ change: 'gap',+ severity,+ confidence: clamp01(0.3 + 0.15 * gaps.length),+ recoverability: 0.7,+ subject: { entity: 'platforms', count: gaps.length },+ };+ }+ if (action.kind === 'content_opportunity') {+ return {+ change: 'gap',+ severity: 0.45,+ confidence: 0.6,+ recoverability: 0.5,+ subject: { entity: p.targetEntity ?? 'prompts', count: p.targetCount ?? null },+ };+ }+ return null;+}++/** The level a score falls in. */+export function priorityLevel(score) {+ if (score >= P.levelCritical) return 'critical';+ if (score >= P.levelHigh) return 'high';+ if (score >= P.levelMedium) return 'medium';+ return 'low';+}++/**+ * An action's priority.+ *+ * @param {object} input+ * @param {{ kind: string, category: string, impact: string, payload?: object, created_at?: string }} input.action+ * An action, or a candidate shaped like one.+ * @param {Array<{ kind: string, impact?: string, source?: string[], payload?: object,+ * detected_at?: string, current_value?: number|null }>} input.signals+ * Its open signals: the evidence it rests on now.+ * @param {Map<string, { volume: number|null, intent: string|null }>} [input.prompts]+ * Demand and intent of the prompts the evidence names.+ * @param {Date} now+ * @returns {{ score: number, level: string, reason: object }}+ */+export function scorePriority({ action, signals = [], prompts = new Map() }, now = new Date()) {+ const payloads = [action.payload, ...signals.map((s) => s.payload)].filter(Boolean);+ const byHand = signals.length === 0 ? sentByHand(action) : null;++ // Severity and what kind of change: the worst finding speaks for the action.+ let change = byHand?.change ?? null;+ let severity = byHand?.severity ?? -1;+ for (const s of signals) {+ const c = changeOf(s.kind);+ if (SEVERITY[c] > severity) {+ severity = SEVERITY[c];+ change = c;+ }+ }+ // Every finding behind it resolved: nothing open says what changed.+ if (change === null) severity = NO_EVIDENCE_SEVERITY;++ const { demand, promptDemand, businessValue } = demandAndValue(payloads, signals, prompts);++ const confidence = byHand+ ? { value: byHand.confidence, kinds: 0, sources: 0 }+ : confidenceOf(signals);++ let recoverability = CATEGORY_RECOVERABILITY[action.category] ?? 0.6;+ if (byHand) recoverability = byHand.recoverability;+ if (signals.some((s) => HELD_BEFORE.has(s.kind))) recoverability = 1;+ else if (signals.some((s) => SITE_FIX.has(s.kind)))+ recoverability = Math.max(recoverability, 0.9);+ // Cited once, not mentioned now: the ground was held, if not lately.+ else if (signals.some((s) => s.kind === 'prompt_visibility_gap')) {+ recoverability = Math.max(recoverability, 0.8);+ }++ const newest = Math.max(+ ...signals.map((s) => Date.parse(s.detected_at ?? '') || 0),+ signals.length ? 0 : Date.parse(action.created_at ?? '') || now.getTime(),+ );+ const days = Math.max(0, (now.getTime() - (newest || now.getTime())) / DAY_MS);+ const recency = Math.max(0.1, 0.5 ** (days / P.recencyHalfLifeDays));++ const factors = {+ impact: IMPACT[action.impact] ?? IMPACT.low,+ demand: demand ?? P.demandUnknown,+ severity,+ businessValue: businessValue ?? P.businessValueUnknown,+ confidence: confidence.value,+ recoverability,+ recency,+ };+ const score = Math.round(+ factors.impact * P.weightImpact ++ factors.demand * P.weightDemand ++ factors.severity * P.weightSeverity ++ factors.businessValue * P.weightBusinessValue ++ factors.confidence * P.weightConfidence ++ factors.recoverability * P.weightRecoverability ++ factors.recency * P.weightRecency,+ );+ const bounded = Math.min(100, Math.max(0, score));++ const p = action.payload ?? {};+ const subject = byHand?.subject ?? {+ entity: p.targetEntity ?? null,+ count: Number.isFinite(p.targetCount) ? p.targetCount : null,+ };++ return {+ score: bounded,+ level: priorityLevel(bounded),+ reason: {+ version: 1,+ change,+ subject,+ // Measured demand only: an unmeasured one is not called low.+ demand: demand === null ? null : demand >= 0.67 ? 'high' : demand >= 0.4 ? 'medium' : 'low',+ searches: promptDemand,+ commercial: businessValue !== null && businessValue >= COMMERCIAL,+ heldBefore: recoverability >= 1,+ days: signals.length ? Math.floor(days) : null,+ kinds: confidence.kinds,+ sources: confidence.sources,+ factors: Object.fromEntries(Object.entries(factors).map(([k, v]) => [k, round2(v)])),+ },+ };+}++/** The columns an action's priority is stored in. */+export function priorityColumns({ score, level, reason }, now) {+ return {+ priority_score: score,+ priority_level: level,+ priority_reason: reason,+ priority_updated_at: now.toISOString(),+ };+}diff --git a/server/src/lib/action-center/priority.test.js b/server/src/lib/action-center/priority.test.jsnew file mode 100644index 000000000..fd4e06442--- /dev/null+++ b/server/src/lib/action-center/priority.test.js@@ -0,0 +1,345 @@+import { describe, expect, it } from 'vitest';+import { priorityColumns, priorityLevel, promptIdsOf, scorePriority } from './priority.js';++/**+ * The priority score (AC-006): how soon to work on an action, 0–100, from+ * impact, demand, severity, business value, independent confirmation,+ * recoverability and recency — and never from how many signals repeat.+ */++const NOW = new Date('2026-10-15T00:00:00Z');+const daysAgo = (n) => new Date(NOW.getTime() - n * 86_400_000).toISOString();++const action = (over = {}) => ({+ kind: 'recover_lost_citations',+ category: 'recover',+ impact: 'high',+ payload: {},+ ...over,+});+const signal = (over = {}) => ({+ kind: 'lost_citations',+ impact: 'high',+ source: ['ai_results'],+ detected_at: daysAgo(1),+ payload: {},+ ...over,+});+const demand = (entries) =>+ new Map(entries.map(([id, volume, intent]) => [id, { volume, intent }]));++describe('priorityLevel', () => {+ it('maps a score to the spec’s levels', () => {+ expect([100, 90, 89, 75, 74, 50, 49, 0].map(priorityLevel)).toEqual([+ 'critical',+ 'critical',+ 'high',+ 'high',+ 'medium',+ 'medium',+ 'low',+ 'low',+ ]);+ });+});++describe('scorePriority', () => {+ it('scores a recent loss on high-demand commercial prompts as critical', () => {+ const { score, level, reason } = scorePriority(+ {+ action: action({ payload: { targetEntity: 'prompts', targetCount: 7 } }),+ signals: [signal({ payload: { promptId: 'p1' } })],+ prompts: demand([['p1', 25_000, 'comparison']]),+ },+ NOW,+ );+ expect(score).toBeGreaterThanOrEqual(90);+ expect(level).toBe('critical');+ expect(reason).toMatchObject({+ change: 'lost',+ subject: { entity: 'prompts', count: 7 },+ demand: 'high',+ searches: 25_000,+ commercial: true,+ heldBefore: true,+ days: 1,+ });+ });++ /** The spec's fixture: quantity is not priority. */+ it('puts one high-demand commercial loss before forty-seven low-demand findings', () => {+ const tail = Array.from({ length: 47 }, (_, i) => [`t${i}`, 5, 'what-is']);+ const many = scorePriority(+ {+ action: action({ kind: 'create_content_for_demand', category: 'growth' }),+ signals: tail.map(([id]) =>+ signal({+ kind: 'uncovered_demand',+ payload: { entity: 'prompts', targets: [{ id, volume: 5 }] },+ }),+ ),+ prompts: demand(tail),+ },+ NOW,+ );+ const one = scorePriority(+ {+ action: action(),+ signals: [signal({ payload: { promptId: 'hot' } })],+ prompts: demand([['hot', 2000, 'comparison']]),+ },+ NOW,+ );+ expect(one.score).toBeGreaterThan(many.score);+ });++ it('counts the most demanded few targets, not all of them', () => {+ const fifty = Array.from({ length: 50 }, (_, i) => [`p${i}`, 100, 'other']);+ const five = Array.from({ length: 5 }, (_, i) => [`q${i}`, 1000, 'other']);+ const score = (list) =>+ scorePriority(+ {+ action: action({+ kind: 'expand_prompt_visibility',+ category: 'growth',+ impact: 'medium',+ }),+ signals: [+ signal({+ kind: 'prompt_visibility_gap',+ payload: { entity: 'prompts', targets: list.map(([id]) => ({ id })) },+ }),+ ],+ prompts: demand(list),+ },+ NOW,+ ).reason.factors.demand;+ expect(score(five)).toBeGreaterThan(score(fifty));+ });++ /** Impact is one factor of seven, not the whole answer. */+ it('can put a medium-impact loss on high demand before a high-impact gap nobody searches', () => {+ const loss = scorePriority(+ {+ action: action({ impact: 'medium' }),+ signals: [signal({ impact: 'medium', payload: { promptId: 'hot' } })],+ prompts: demand([['hot', 5000, 'best-top']]),+ },+ NOW,+ );+ const gap = scorePriority(+ {+ action: action({ kind: 'close_competitor_gap', category: 'compete' }),+ signals: [+ signal({+ kind: 'competitor_leads',+ payload: { promptId: 'cold' },+ detected_at: daysAgo(20),+ }),+ ],+ prompts: demand([['cold', 0, 'other']]),+ },+ NOW,+ );+ expect(loss.score).toBeGreaterThan(gap.score);+ });++ it('weighs independent kinds and sources, not repeats of one signal', () => {+ const once = scorePriority({ action: action(), signals: [signal()] }, NOW);+ const repeated = scorePriority(+ { action: action(), signals: Array.from({ length: 30 }, () => signal()) },+ NOW,+ );+ const confirmed = scorePriority(+ {+ action: action(),+ signals: [signal(), signal({ kind: 'lost_mentions', source: ['gsc'] })],+ },+ NOW,+ );+ expect(repeated.score).toBe(once.score);+ expect(confirmed.reason).toMatchObject({ kinds: 2, sources: 2 });+ expect(confirmed.score).toBeGreaterThan(once.score);+ });++ it('lets old evidence fade', () => {+ const fresh = scorePriority({ action: action(), signals: [signal()] }, NOW);+ const old = scorePriority(+ { action: action(), signals: [signal({ detected_at: daysAgo(30) })] },+ NOW,+ );+ expect(old.score).toBeLessThan(fresh.score);+ expect(old.reason.days).toBe(30);+ });++ it('ranks ground the brand held and lost above ground it never had', () => {+ const lost = scorePriority(+ {+ action: action({ impact: 'medium' }),+ signals: [signal({ kind: 'topic_drop', impact: 'medium' })],+ },+ NOW,+ ).reason;+ const never = scorePriority(+ {+ action: action({ category: 'growth', impact: 'medium' }),+ signals: [signal({ kind: 'topic_uncovered', impact: 'medium' })],+ },+ NOW,+ ).reason;+ expect(lost.heldBefore).toBe(true);+ expect(lost.factors.recoverability).toBeGreaterThan(never.factors.recoverability);+ expect(lost.factors.severity).toBeGreaterThan(never.factors.severity);+ });++ it('calls ground never held a gap, whatever its impact', () => {+ const { reason } = scorePriority(+ {+ action: action({ kind: 'create_content_for_demand', category: 'growth' }),+ signals: [signal({ kind: 'uncovered_demand' }), signal({ kind: 'competitor_leads' })],+ },+ NOW,+ );+ expect(reason).toMatchObject({ change: 'gap', heldBefore: false });+ expect(reason.factors.severity).toBe(0.5);+ });++ it("does not read an owned page's citations as its visits", () => {+ const { reason } = scorePriority(+ {+ action: action({ kind: 'recover_page_citations' }),+ signals: [+ signal({+ kind: 'owned_page_citation_lost',+ payload: { entity: 'pages', targets: [{ id: '/pricing', before: 6, now: 0 }] },+ }),+ ],+ },+ NOW,+ );+ expect(reason.demand).toBeNull();+ });++ it('weighs an action whose findings all resolved as having nothing open', () => {+ const { reason } = scorePriority({ action: action(), signals: [] }, NOW);+ expect(reason.change).toBeNull();+ expect(reason.factors.severity).toBe(0.3);+ });++ it('does not call unmeasured demand low', () => {+ const { reason } = scorePriority({ action: action(), signals: [signal()] }, NOW);+ expect(reason.demand).toBeNull();+ expect(reason.searches).toBeNull();+ });++ it('reads demand from search impressions and page sessions too', () => {+ const queries = scorePriority(+ {+ action: action({ kind: 'recover_search_demand', category: 'protect' }),+ signals: [+ signal({+ kind: 'gsc_decline',+ payload: { entity: 'queries', targets: [{ id: 'coffee', impressions: 4000 }] },+ }),+ ],+ },+ NOW,+ );+ const pages = scorePriority(+ {+ action: action({ kind: 'capture_ai_traffic', category: 'growth', impact: 'medium' }),+ signals: [+ signal({+ kind: 'page_opportunity',+ current_value: 900,+ payload: { landingPage: '/pricing', valueSignal: 'revenue' },+ }),+ ],+ },+ NOW,+ );+ expect(queries.reason.demand).toBe('high');+ expect(pages.reason).toMatchObject({ demand: 'high', commercial: true, change: 'opportunity' });+ });++ it('scores an action a person sent, from its own payload', () => {+ const improve = scorePriority(+ {+ action: action({+ kind: 'prompt_improve',+ category: 'compete',+ impact: 'medium',+ created_at: daysAgo(0),+ payload: {+ promptIds: ['p1'],+ platforms: [+ { id: 'gemini-web', state: 'not_mentioned' },+ { id: 'chatgpt-web', state: 'not_cited' },+ ],+ },+ }),+ prompts: demand([['p1', 300, 'recommendation']]),+ },+ NOW,+ );+ expect(improve.reason).toMatchObject({+ change: 'gap',+ subject: { entity: 'platforms', count: 2 },+ demand: 'medium',+ commercial: true,+ days: null,+ });+ const content = scorePriority(+ {+ action: action({+ kind: 'content_opportunity',+ category: 'growth',+ impact: 'high',+ created_at: daysAgo(0),+ payload: { promptIds: ['p1'], targetEntity: 'prompts', targetCount: 4 },+ }),+ prompts: demand([['p1', 300, 'how-to']]),+ },+ NOW,+ );+ expect(content.reason.subject).toEqual({ entity: 'prompts', count: 4 });+ expect(content.score).toBeGreaterThan(0);+ });++ it('stays within 0–100 and returns whole numbers', () => {+ for (const impact of ['high', 'medium', 'low', 'unknown']) {+ const { score } = scorePriority({ action: action({ impact }), signals: [] }, NOW);+ expect(Number.isInteger(score)).toBe(true);+ expect(score).toBeGreaterThanOrEqual(0);+ expect(score).toBeLessThanOrEqual(100);+ }+ });+});++describe('promptIdsOf', () => {+ it('finds the prompts payloads name, once each', () => {+ expect(+ promptIdsOf([+ { promptId: 'a' },+ { promptIds: ['a', 'b'] },+ { entity: 'prompts', targets: [{ id: 'c' }] },+ { targetEntity: 'prompts', targets: [{ id: 'd' }] },+ { entity: 'pages', targets: [{ id: '/pricing' }] },+ null,+ ]),+ ).toEqual(['a', 'b', 'c', 'd']);+ });+});++describe('priorityColumns', () => {+ it('names the columns the score is stored in', () => {+ expect(+ priorityColumns({ score: 94, level: 'critical', reason: { change: 'lost' } }, NOW),+ ).toEqual({+ priority_score: 94,+ priority_level: 'critical',+ priority_reason: { change: 'lost' },+ priority_updated_at: NOW.toISOString(),+ });+ });+});diff --git a/server/src/lib/opportunity-limits.js b/server/src/lib/opportunity-limits.jsindex 2ffcc8f02..c69c8fff6 100644--- a/server/src/lib/opportunity-limits.js+++ b/server/src/lib/opportunity-limits.js@@ -26,7 +26,7 @@ export const OPPORTUNITY_WINDOW_DAYS = 30;*/const DEMAND_CEILING = 1_000_000;-const INTENT_WEIGHTS = {+export const INTENT_WEIGHTS = {comparison: 1.0,'best-top': 0.95,'vs-review': 0.9,diff --git a/server/src/lib/signals/nightly-reads.test.js b/server/src/lib/signals/nightly-reads.test.jsindex 9a5ffe9e2..a087718a4 100644--- a/server/src/lib/signals/nightly-reads.test.js+++ b/server/src/lib/signals/nightly-reads.test.js@@ -25,6 +25,7 @@ const NIGHTLY_MODULES = ['src/lib/signals/traffic-evidence.js','src/lib/pulse/metrics.js','src/lib/action-center/generate.js',+ 'src/lib/action-center/priority-data.js','src/lib/action-center/validate.js','src/lib/action-center/execution/tools.js',];diff --git a/supabase/migrations/00144_action_priority_score.sql b/supabase/migrations/00144_action_priority_score.sqlnew file mode 100644index 000000000..b3c41b983--- /dev/null+++ b/supabase/migrations/00144_action_priority_score.sql@@ -0,0 +1,41 @@+-- An action's priority: how soon to work on it, beside the others (AC-006).+--+-- Impact (high / medium / low) says how much an action could matter; it was+-- also the only thing the Action Center sorted by, so a brand with eleven+-- high-impact actions had eleven "top" ones and no order among them. The+-- priority score answers the other question: what to do first. It is worked+-- out on the server from the action's evidence — impact, demand, severity,+-- business value, independent confirmation, recoverability and recency+-- (server/src/lib/action-center/priority.js) — every night and when an action+-- is created, and stored here so the list, its sort, the Top Actions card,+-- the exports and the API all read one number.+--+-- priority_score 0–100.+-- priority_level critical (90+), high (75–89), medium (50–74), low.+-- priority_reason what the score rests on, as facts (severity, the+-- subject and its count, demand, commercial intent,+-- recency…) from which the app writes "Why this+-- priority?" in the reader's language.+-- priority_updated_at when it was last worked out.+--+-- Null until the first scoring: the app falls back to ordering by impact.++alter table public.actions+ add column if not exists priority_score smallint+ check (priority_score between 0 and 100),+ add column if not exists priority_level text+ check (priority_level in ('critical', 'high', 'medium', 'low')),+ add column if not exists priority_reason jsonb,+ add column if not exists priority_updated_at timestamptz;++-- The list and the Top Actions card read a brand's open actions by score.+create index if not exists actions_brand_priority_idx+ on public.actions (brand_id, priority_score desc nulls last)+ where status not in ('completed', 'dismissed');++comment on column public.actions.priority_score is+ 'How soon to work on the action beside the others, 0–100 (AC-006). Worked out on the server; null until first scored.';+comment on column public.actions.priority_level is+ 'priority_score as a level: critical (90+), high (75–89), medium (50–74), low.';+comment on column public.actions.priority_reason is+ 'The facts the score rests on, for "Why this priority?" (server/src/lib/action-center/priority.js).';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex fed05e39a..c992d3e40 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -17882,6 +17882,51 @@ revoke all on function public.ae_page_traffic_evidence(uuid, text[], date, date,grant execute on function public.ae_page_traffic_evidence(uuid, text[], date, date, date, date, boolean)to service_role;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00144_action_priority_score.sql+-- ─────────────────────────────────────────────────────────────────────────+-- An action's priority: how soon to work on it, beside the others (AC-006).+--+-- Impact (high / medium / low) says how much an action could matter; it was+-- also the only thing the Action Center sorted by, so a brand with eleven+-- high-impact actions had eleven "top" ones and no order among them. The+-- priority score answers the other question: what to do first. It is worked+-- out on the server from the action's evidence — impact, demand, severity,+-- business value, independent confirmation, recoverability and recency+-- (server/src/lib/action-center/priority.js) — every night and when an action+-- is created, and stored here so the list, its sort, the Top Actions card,+-- the exports and the API all read one number.+--+-- priority_score 0–100.+-- priority_level critical (90+), high (75–89), medium (50–74), low.+-- priority_reason what the score rests on, as facts (severity, the+-- subject and its count, demand, commercial intent,+-- recency…) from which the app writes "Why this+-- priority?" in the reader's language.+-- priority_updated_at when it was last worked out.+--+-- Null until the first scoring: the app falls back to ordering by impact.++alter table public.actions+ add column if not exists priority_score smallint+ check (priority_score between 0 and 100),+ add column if not exists priority_level text+ check (priority_level in ('critical', 'high', 'medium', 'low')),+ add column if not exists priority_reason jsonb,+ add column if not exists priority_updated_at timestamptz;++-- The list and the Top Actions card read a brand's open actions by score.+create index if not exists actions_brand_priority_idx+ on public.actions (brand_id, priority_score desc nulls last)+ where status not in ('completed', 'dismissed');++comment on column public.actions.priority_score is+ 'How soon to work on the action beside the others, 0–100 (AC-006). Worked out on the server; null until first scored.';+comment on column public.actions.priority_level is+ 'priority_score as a level: critical (90+), high (75–89), medium (50–74), low.';+comment on column public.actions.priority_reason is+ 'The facts the score rests on, for "Why this priority?" (server/src/lib/action-center/priority.js).';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00147_insights_same_prompts_definer.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 83e075525..aea4ac64f 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -139,6 +139,10 @@ export type Database = {outcome: stringpayload: Jsonposition_outcome: Json | null+ priority_level: string | null+ priority_reason: Json | null+ priority_score: number | null+ priority_updated_at: string | nullstatus: stringupdated_at: stringvalidated_at: string | null@@ -161,6 +165,10 @@ export type Database = {outcome?: stringpayload?: Jsonposition_outcome?: Json | null+ priority_level?: string | null+ priority_reason?: Json | null+ priority_score?: number | null+ priority_updated_at?: string | nullstatus?: stringupdated_at?: stringvalidated_at?: string | null@@ -183,6 +191,10 @@ export type Database = {outcome?: stringpayload?: Jsonposition_outcome?: Json | null+ priority_level?: string | null+ priority_reason?: Json | null+ priority_score?: number | null+ priority_updated_at?: string | nullstatus?: stringupdated_at?: stringvalidated_at?: string | null