Skip to content

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.

feat(action-center): raise an action's Priority Score with its prompts' measured demand (PROMPT-014, part 3) (#1652)

Cihan2a7be7e8d3ef
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdx
index 9ab31d8da..2f5487cb7 100644
--- a/docs/guides/action-center.mdx
+++ b/docs/guides/action-center.mdx
@@ -133,7 +133,7 @@ Every action has a **Priority Score** from 0 to 100: how soon to work on it besi
The score weighs seven things:
- **Impact** — the action's impact grade: high, medium or low.
-- **Demand** — how much the prompts, search queries or pages it is about are searched or visited. Only the most demanded few count, so a long list of low-demand prompts doesn't outrank a handful that people actually search for.
+- **Demand** — how much the prompts, search queries or pages it is about are searched or visited. Only the most demanded few count, so a long list of low-demand prompts doesn't outrank a handful that people actually search for. A prompt's measured [demand level](/guides/prompts#demand-level) raises it: High more, Medium a little, Low not at all.
- **Severity** — what kind of change it is. A loss ranks above a sharp drop, a drop above a slip, and a slip above a gap or a site issue. Room to grow and gains rank lowest.
- **Business value** — how commercial the searches are, or what a page is worth to the business (revenue, transactions or key events, from Google Analytics).
- **Confidence** — how many independent kinds of finding and data sources agree. Ten signals repeating one finding count as one.
@@ -154,7 +154,7 @@ An action is scored when it is created, and again every night from that night's
The action's **Overview** tab starts with **Why this priority?**: one sentence written from the facts the score rests on. It says what changed, on what, how recently, and what makes it matter, for example:
-> Lost ground on 7 high-demand prompts 2 days ago — commercial intent, previously visible, confirmed by 2 sources.
+> Lost ground on 7 high-demand prompts 2 days ago — measured demand High, commercial intent, previously visible, confirmed by 2 sources.
<Note>
The Content Plan has its own Priority Score, which ranks the Plan's pages. The two are worked out separately. See [Content Editor](/guides/content-editor).
diff --git a/docs/guides/prompts.mdx b/docs/guides/prompts.mdx
index 68fbb4e21..a02734978 100644
--- a/docs/guides/prompts.mdx
+++ b/docs/guides/prompts.mdx
@@ -127,7 +127,7 @@ Some estimates are built differently, and their note says so:
### Where you see estimates
- **Tracked Prompts** — the **Volume** column
-- **A prompt's page** — an **AI searches a month** card, when the prompt has a volume
+- **A prompt's page** — an **AI searches a month** card, when the prompt has a volume. The **Demand** card beside it is measured, not estimated (see [Real demand](#real-demand))
- **Insights** — **Total Est. AI Volume**, **Avg. AI Volume**, the **Prompt Volumes** table's **Est. AI Vol.** column, **High Opportunity Prompts**, and the Prompt Volumes chart's tooltip
- **Similar Topics** — the Insights card's **See all** page (`/dashboard/prompts/similar-topics`)
- **Prompt Suggestions** — each AI suggestion's `/mo` range
@@ -142,6 +142,44 @@ Exports mark estimated volumes, so a spreadsheet doesn't read them as counts:
- **A content opportunity's Copy All Data and exports** give **Est. AI volume** as a range, with **Volume type** and **Volume confidence**.
- The [MCP server](/guides/mcp-server)'s `get_prompt_volumes` returns `est_ai_volume_low`, `est_ai_volume_high`, `volume_confidence` and `volume_type` with each row.
+## Real demand
+
+The estimate says how many AI searches a prompt might get. A prompt's page also shows whether people really ask it, under **Demand · is this asked for real?**: four measured signals, each with its source and the day it was read.
+
+| Signal | What it shows | Read |
+|---|---|---|
+| **Search Console** | Impressions and clicks over the last 28 days for your Google queries that match the prompt, how many queries matched and the most seen one | Every night |
+| **Google Trends** | A 12-month line for the prompt's keyword: **Rising**, **Steady** or **Falling**, and the change on a year ago | About once a week |
+| **People Also Ask** | The related questions Google shows for the keyword | About once a week |
+| **YouTube** | The views across YouTube's top videos for the keyword, and the most viewed one | About once a week |
+
+Google Trends, People Also Ask and YouTube are read for the keyword with the most Google searches in the prompt's [volume analysis](#volume-analysis-insights-tab), with its location and language, so a prompt needs its volume analyzed first. A query matches a prompt when most of its words are in the prompt, the same rule the Action Center uses for Search Console signals.
+
+<Note>
+The weekly reads (Google Trends, People Also Ask and YouTube) are off by default: each one is a paid DataForSEO task. A self-hosted server turns them on with `DEMAND_SIGNALS` (see [Environment variables](/self-host/env-variables)). Until then their cards say **Weekly reads aren't turned on yet**. Search Console is read every night either way.
+</Note>
+
+When a signal isn't there, its card says why: **Connect Search Console to see real clicks** (with a **Connect** button for admins and managers), a Search Console property to pick for the brand, the first sync still running, **Analyze volume first**, a keyword Google has no searches for, being read, or not read yet.
+
+**Track a question.** Each People Also Ask question has a **+ Track** button: one click adds it as a tracked prompt in the prompt's topic, within your plan's prompt limit. A question your brand already tracks, however it's written (case, accents and punctuation aside), shows **Tracked** instead and isn't added twice.
+
+### Demand level
+
+The signals read come to a **demand level**, shown in the prompt's KPI row as **Demand · High** with how many of the four signals were read, for example **3 of 4 signals**. It carries a **Measured** badge, never **Estimate**.
+
+Each signal read gives 2 points when it's strong, 1 when there is some, 0 otherwise:
+
+- **Search Console**: 1,000 impressions or more is strong, 100 or more is some
+- **Google Trends**: rising is strong, steady is some; falling or too little data gives nothing
+- **People Also Ask**: 4 questions or more is strong, 1 or more is some
+- **YouTube**: 100,000 views or more is strong, 5,000 or more is some
+
+The level is the share of the points the signals read could give: **High** at 60% or more with at least two signals read, **Medium** at 30% or more, **Low** below. A signal that was read and found nothing counts; one never read doesn't.
+
+### Demand and the Priority Score
+
+The level feeds the [Priority Score](/guides/action-center#the-priority-score) of the Action Center's actions about the prompt. **High** raises its demand to at least what about 2,500 monthly AI searches would give, **Medium** to about 160; **Low** leaves it as it is, because signals that found little don't prove nobody asks. When a prompt's level changes, the brand's open actions are scored again that night, and **Why this priority?** names a High or Medium level, for example *measured demand High*. Low isn't named, since it doesn't change the score.
+
## Volume Analysis (Insights tab)
Volumes come from an analysis you run: **Analyze Volumes** the first time, **Analyze New Prompts** for prompts added since, **Refresh Volumes** for newer Google data, and **Re-analyze Keywords** to analyze every prompt again, keywords included. Each analysis counts against a monthly quota on cloud plans; the toolbar shows how many are left. Tracked Prompts also warns when some prompts haven't been analyzed yet.
diff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.js
index e7d0b9ecb..5a5c71110 100644
--- a/server/src/config/action-engine.js
+++ b/server/src/config/action-engine.js
@@ -344,6 +344,15 @@ export const ENGINE_THRESHOLDS = Object.freeze({
demandTopTargets: 5,
/** Demand and business value when nothing measures them: neither for nor against. */
demandUnknown: 0.4,
+ /**
+ * The demand a prompt's measured demand level (PROMPT-014: Search
+ * Console, Google Trends, People Also Ask, YouTube) brings an action
+ * about it up to, at least: High as much as about 2,500 monthly AI
+ * searches (0.85), Medium about 160 (0.55). Low adds nothing: signals
+ * that found little are not proof that nobody asks.
+ */
+ realDemandHigh: 0.85,
+ realDemandMedium: 0.55,
businessValueUnknown: 0.5,
/** Days for a finding's recency to halve. */
recencyHalfLifeDays: 10,
diff --git a/server/src/lib/action-center/priority-data.js b/server/src/lib/action-center/priority-data.js
index da9300719..4ba0f5d64 100644
--- a/server/src/lib/action-center/priority-data.js
+++ b/server/src/lib/action-center/priority-data.js
@@ -1,10 +1,12 @@
/**
* What the priority score reads from the database (AC-006): the demand and
- * intent of the prompts an action's evidence names, and how the brand's
- * earlier actions of each kind turned out (learning B4). Everything else it
- * needs — the action, its signals — the caller has in hand already.
+ * intent of the prompts an action's evidence names, their measured demand
+ * level (PROMPT-014), and how the brand's earlier actions of each kind turned
+ * out (learning B4). Everything else it needs — the action, its signals — the
+ * caller has in hand already.
*/
+import { isDeepStrictEqual } from 'node:util';
import supabaseAdmin from '../../config/supabase.js';
import { resolve } from '../../config/action-engine.js';
import { logger } from '../logger.js';
@@ -21,12 +23,39 @@ const CHUNK = 150;
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.
+ * Each prompt's measured demand level (PROMPT-014, prompt_demand), where one
+ * was read. Best effort: without it the score still has the volumes.
+ *
+ * @param {string[]} ids
+ * @returns {Promise<Map<string, 'high'|'medium'|'low'>>}
+ */
+async function loadDemandLevels(ids) {
+ const levels = new Map();
+ try {
+ for (let i = 0; i < ids.length; i += CHUNK) {
+ const { data, error } = await supabaseAdmin
+ .from('prompt_demand')
+ .select('prompt_id, level')
+ .in('prompt_id', ids.slice(i, i + CHUNK))
+ .not('level', 'is', null);
+ if (error) throw new Error(error.message);
+ for (const row of data ?? []) levels.set(row.prompt_id, row.level);
+ }
+ } catch (err) {
+ logger.warn({ err: err.message }, '[actions] demand levels unavailable');
+ return new Map();
+ }
+ return levels;
+}
+
+/**
+ * Per prompt, its estimated monthly AI searches, its intent and its measured
+ * demand level (null where none was read). A prompt can have a volume 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 }>>}
+ * @returns {Promise<Map<string, { volume: number|null, intent: string|null, level: 'high'|'medium'|'low'|null }>>}
*/
export async function loadPromptDemand(promptIds) {
const demand = new Map();
@@ -51,11 +80,17 @@ export async function loadPromptDemand(promptIds) {
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 });
+ demand.set(row.prompt_id, { volume, intent: row.intent ?? null, level: null });
} else if (volume !== null && (known.volume === null || volume > known.volume)) {
known.volume = volume;
}
}
+ if (ids.length === 0) return demand;
+ for (const [id, level] of await loadDemandLevels(ids)) {
+ const known = demand.get(id);
+ if (known) known.level = level;
+ else demand.set(id, { volume: null, intent: null, level });
+ }
return demand;
}
@@ -183,10 +218,14 @@ export async function rescoreAction(action, now = new Date(), track = null) {
* for no fresh results) and for the one-off backfill of actions opened
* before scores existed (scripts/rescore-actions.js).
*
+ * An action whose score, level and reason come out as they're stored is
+ * left as it is: a brand is often scored twice a night (the signal pass,
+ * then the demand sweep), and the second has nothing new to write.
+ *
* @param {string} brandId
* @param {{ now?: Date, statuses?: string[] | null, unscored?: boolean }} [options]
* statuses: the actions' statuses, null for all. unscored: only actions with no score yet.
- * @returns {Promise<number>} how many actions were scored
+ * @returns {Promise<number>} how many actions' scores changed and were saved
*/
export async function rescoreBrandActions(
brandId,
@@ -194,7 +233,9 @@ export async function rescoreBrandActions(
) {
let query = supabaseAdmin
.from('actions')
- .select('id, kind, category, impact, payload, created_at')
+ .select(
+ 'id, kind, category, impact, payload, created_at, priority_score, priority_level, priority_reason',
+ )
.eq('brand_id', brandId);
if (statuses) query = query.in('status', statuses);
if (unscored) query = query.is('priority_score', null);
@@ -236,6 +277,14 @@ export async function rescoreBrandActions(
{ action, signals: evidence.get(action.id) ?? [], prompts, track },
now,
);
+ // The reason as it would be stored (jsonb): no undefined keys, no -0.
+ if (
+ action.priority_score === priority.score &&
+ action.priority_level === priority.level &&
+ isDeepStrictEqual(action.priority_reason, JSON.parse(JSON.stringify(priority.reason)))
+ ) {
+ continue;
+ }
const { error: saveErr } = await supabaseAdmin
.from('actions')
.update(priorityColumns(priority, now))
diff --git a/server/src/lib/action-center/priority-data.test.js b/server/src/lib/action-center/priority-data.test.js
index f4af73a54..ebbfa6ca1 100644
--- a/server/src/lib/action-center/priority-data.test.js
+++ b/server/src/lib/action-center/priority-data.test.js
@@ -15,6 +15,9 @@ let signalRows = [];
let queries = [];
let saved = [];
let unsaved = new Set();
+let levelRows = [];
+let levelReads = [];
+let levelsFail = false;
let rpcCalls = [];
let rpcResult = { data: [], error: null };
@@ -40,6 +43,10 @@ vi.mock('../../config/supabase.js', () => ({
ids = values;
reads.push(values);
}
+ if (table === 'prompt_demand') {
+ ids = values;
+ levelReads.push(values);
+ }
return chain;
},
is: (column, value) => {
@@ -65,8 +72,15 @@ vi.mock('../../config/supabase.js', () => ({
op.update = row;
return chain;
},
- // An update, awaited after its .eq('id', …).
+ // An update, awaited after its .eq('id', …); or the demand levels' read.
then: (resolve) => {
+ if (table === 'prompt_demand') {
+ if (levelsFail) return resolve({ data: null, error: { message: 'no such table' } });
+ return resolve({
+ data: levelRows.filter((r) => ids.includes(r.prompt_id)),
+ error: null,
+ });
+ }
const id = op.filters.find(([, column]) => column === 'id')?.[2];
if (unsaved.has(id)) return resolve({ error: { message: 'write failed' } });
saved.push({ id, row: op.update });
@@ -91,6 +105,9 @@ beforeEach(() => {
queries = [];
saved = [];
unsaved = new Set();
+ levelRows = [];
+ levelReads = [];
+ levelsFail = false;
rpcCalls = [];
rpcResult = { data: [], error: null };
// Newest first, as the read orders them.
@@ -105,11 +122,31 @@ 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' },
+ p1: { volume: 900, intent: 'comparison', level: null },
+ p2: { volume: null, intent: 'how-to', level: null },
+ });
+ });
+
+ it("adds each prompt's measured demand level, also for a prompt with no volume", async () => {
+ levelRows = [
+ { prompt_id: 'p1', level: 'high' },
+ { prompt_id: 'p3', level: 'medium' },
+ ];
+ const demand = await loadPromptDemand(['p1', 'p2', 'p3']);
+ expect(levelReads).toEqual([['p1', 'p2', 'p3']]);
+ expect(Object.fromEntries(demand)).toEqual({
+ p1: { volume: 900, intent: 'comparison', level: 'high' },
+ p2: { volume: null, intent: 'how-to', level: null },
+ p3: { volume: null, intent: null, level: 'medium' },
});
});
+ it('keeps the volumes when the levels cannot be read', async () => {
+ levelsFail = true;
+ const demand = await loadPromptDemand(['p1']);
+ expect(demand.get('p1')).toEqual({ volume: 900, intent: 'comparison', level: null });
+ });
+
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]);
@@ -127,12 +164,13 @@ describe('loadPromptDemand', () => {
[0, 999],
[1000, 1999],
]);
- expect(demand.get('busy')).toEqual({ volume: 1199, intent: 'comparison' });
+ expect(demand.get('busy')).toEqual({ volume: 1199, intent: 'comparison', level: null });
});
it('reads nothing for no prompts', async () => {
expect((await loadPromptDemand([])).size).toBe(0);
expect(reads).toEqual([]);
+ expect(levelReads).toEqual([]);
});
});
@@ -269,6 +307,42 @@ describe('rescoreBrandActions', () => {
expect(queries.map((q) => q.table)).toEqual(['actions']);
});
+ it('leaves an action whose score, level and reason are what is stored', async () => {
+ const signal = {
+ id: 's1',
+ action_id: 'a1',
+ kind: 'citation_lost',
+ impact: 'high',
+ payload: {},
+ detected_at: '2026-10-16T02:00:00Z',
+ };
+ actionRows = [recover('a1', { promptIds: ['p1'] }), recover('a2')];
+ signalRows = [signal];
+ expect(await rescoreBrandActions('b1', { now: NOW })).toBe(2);
+
+ // Scored again the same night (the demand sweep after the signal pass):
+ // a1 is as stored (read back as jsonb), a2's stored score is older.
+ const stored = Object.fromEntries(saved.map(({ id, row }) => [id, row]));
+ actionRows = [
+ {
+ ...recover('a1', { promptIds: ['p1'] }),
+ priority_score: stored.a1.priority_score,
+ priority_level: stored.a1.priority_level,
+ priority_reason: JSON.parse(JSON.stringify(stored.a1.priority_reason)),
+ },
+ {
+ ...recover('a2'),
+ priority_score: stored.a2.priority_score - 5,
+ priority_level: stored.a2.priority_level,
+ priority_reason: stored.a2.priority_reason,
+ },
+ ];
+ saved = [];
+
+ expect(await rescoreBrandActions('b1', { now: NOW })).toBe(1);
+ expect(saved.map(({ id }) => id)).toEqual(['a2']);
+ });
+
it('carries on past a score it cannot save, and without demand', async () => {
actionRows = [recover('a1', { promptIds: ['p1'] }), recover('a2')];
unsaved.add('a1');
diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.js
index fc8d7d25c..700445afb 100644
--- a/server/src/lib/action-center/priority.js
+++ b/server/src/lib/action-center/priority.js
@@ -7,7 +7,9 @@
*
* 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;
+ * searched or visited — the most demanded few of them —
+ * at least what a prompt's measured demand level says
+ * (PROMPT-014: High, Medium);
* 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
@@ -183,6 +185,25 @@ const PAGE_VALUE = { revenue: 1, transactions: 0.95, key_events: 0.85, engagemen
/** Commercial enough to say so in "Why this priority?". */
const COMMERCIAL = 0.85;
+const LEVEL_RANK = { low: 1, medium: 2, high: 3 };
+
+/**
+ * The highest measured demand level (PROMPT-014) among the prompts the
+ * evidence names, and the demand it brings the action up to: High and
+ * Medium raise it (`realDemandHigh`, `realDemandMedium`), Low leaves it.
+ * Null without a level read.
+ */
+function realDemandOf(payloads, prompts) {
+ let level = null;
+ for (const id of promptIdsOf(payloads)) {
+ const known = prompts.get(id)?.level;
+ if (LEVEL_RANK[known] && (!level || LEVEL_RANK[known] > LEVEL_RANK[level])) level = known;
+ }
+ const floor =
+ level === 'high' ? P.realDemandHigh : level === 'medium' ? P.realDemandMedium : null;
+ return { level, floor };
+}
+
const clamp01 = (n) => Math.min(1, Math.max(0, n));
const round2 = (n) => Math.round(n * 100) / 100;
@@ -429,8 +450,8 @@ export function priorityLevel(score) {
* @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 {Map<string, { volume: number|null, intent: string|null, level?: string|null }>} [input.prompts]
+ * Demand, intent and measured demand level of the prompts the evidence names.
* @param {Map<string, { improved: number, results: number }>} [input.track]
* Per kind, the brand's results with a verdict and how many improved (loadKindTrack).
* @param {Date} now
@@ -456,7 +477,12 @@ export function scorePriority(
// 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 scaled = demandAndValue(payloads, signals, prompts);
+ const { promptDemand, businessValue } = scaled;
+ // A measured level is better evidence of demand than the estimate it
+ // stands beside: High or Medium raise the demand to at least theirs.
+ const real = realDemandOf(payloads, prompts);
+ const demand = real.floor === null ? scaled.demand : Math.max(scaled.demand ?? 0, real.floor);
const confidence = byHand
? { value: byHand.confidence, kinds: 0, sources: 0 }
@@ -516,6 +542,10 @@ export function scorePriority(
subject,
// Measured demand only: an unmeasured one is not called low.
demand: demand === null ? null : demand >= 0.67 ? 'high' : demand >= 0.4 ? 'medium' : 'low',
+ // The prompts' measured demand level (PROMPT-014), the highest, when it
+ // raised the demand (High, Medium); null otherwise. Low raises nothing,
+ // so it's no reason for the score.
+ realDemand: real.floor === null ? null : real.level,
searches: promptDemand,
commercial: businessValue !== null && businessValue >= COMMERCIAL,
heldBefore: recoverability >= 1,
diff --git a/server/src/lib/action-center/priority.test.js b/server/src/lib/action-center/priority.test.js
index 16b038d61..60cac3d57 100644
--- a/server/src/lib/action-center/priority.test.js
+++ b/server/src/lib/action-center/priority.test.js
@@ -399,6 +399,64 @@ describe('scorePriority', () => {
});
});
+describe('scorePriority with a measured demand level (PROMPT-014)', () => {
+ const gap = (prompts) =>
+ scorePriority(
+ {
+ action: action({
+ kind: 'close_visibility_gap',
+ category: 'growth',
+ impact: 'medium',
+ payload: { targetEntity: 'prompts', targetCount: 2 },
+ }),
+ signals: [signal({ kind: 'prompt_visibility_gap', payload: { promptIds: ['p1', 'p2'] } })],
+ prompts,
+ },
+ NOW,
+ );
+ const withLevels = (p1, p2) =>
+ new Map([
+ ['p1', { volume: 40, intent: 'informational', level: p1 }],
+ ['p2', { volume: 10, intent: 'informational', level: p2 }],
+ ]);
+
+ it('raises the score with High, a little with Medium, and leaves it with Low', () => {
+ const none = gap(withLevels(null, null));
+ const high = gap(withLevels('low', 'high'));
+ const medium = gap(withLevels('medium', null));
+ const low = gap(withLevels('low', 'low'));
+
+ expect(high.score).toBeGreaterThan(medium.score);
+ expect(medium.score).toBeGreaterThan(none.score);
+ expect(low.score).toBe(none.score);
+ // The demand factor is at least the level's.
+ expect(high.reason.factors.demand).toBe(0.85);
+ expect(medium.reason.factors.demand).toBe(0.55);
+ expect(low.reason.factors.demand).toBe(none.reason.factors.demand);
+ });
+
+ it('says the highest level in "Why this priority?", and calls the demand high', () => {
+ expect(gap(withLevels('low', 'high')).reason).toMatchObject({
+ realDemand: 'high',
+ demand: 'high',
+ });
+ // Low raises nothing, so it's no reason for the score.
+ expect(gap(withLevels('low', 'low')).reason.realDemand).toBeNull();
+ expect(gap(withLevels(null, null)).reason.realDemand).toBeNull();
+ });
+
+ it('never lowers a demand the volumes already put higher', () => {
+ const busy = new Map([['p1', { volume: 25_000, intent: 'comparison', level: 'medium' }]]);
+ const { reason } = gap(busy);
+ expect(reason.factors.demand).toBe(1);
+ });
+
+ it('counts a level for a prompt with no volume analysis', () => {
+ const { reason } = gap(new Map([['p2', { volume: null, intent: null, level: 'high' }]]));
+ expect(reason).toMatchObject({ realDemand: 'high', demand: 'high', searches: null });
+ });
+});
+
/**
* Past success (learning B4): a kind that has improved results at this
* brand before sits a little higher, one that rarely has a little lower;
@@ -458,6 +516,38 @@ describe('past success', () => {
expect(other.score).toBe(scorePriority({ action: action(), signals }, NOW).score);
expect(other.reason.pastSuccess).toBeNull();
});
+
+ it('adds to the measured demand level rather than replacing it', () => {
+ const gap = (prompts, track) =>
+ scorePriority(
+ {
+ action: action({
+ kind: 'close_visibility_gap',
+ category: 'growth',
+ impact: 'medium',
+ payload: { targetEntity: 'prompts', targetCount: 1 },
+ }),
+ signals: [signal({ kind: 'prompt_visibility_gap', payload: { promptIds: ['p1'] } })],
+ prompts,
+ track,
+ },
+ NOW,
+ );
+ const level = (l) => new Map([['p1', { volume: 40, intent: 'informational', level: l }]]);
+ const track = new Map([['close_visibility_gap', { improved: 3, results: 3 }]]);
+
+ const neither = gap(level(null), new Map());
+ const demand = gap(level('high'), new Map());
+ const both = gap(level('high'), track);
+
+ expect(demand.score).toBeGreaterThan(neither.score);
+ expect(both.score).toBeGreaterThan(demand.score);
+ expect(both.reason).toMatchObject({
+ realDemand: 'high',
+ pastSuccess: { improved: 3, results: 3, points: 3.75 },
+ });
+ expect(both.reason.factors.demand).toBe(0.85);
+ });
});
describe('promptIdsOf', () => {
diff --git a/server/src/lib/prompt-demand.js b/server/src/lib/prompt-demand.js
index 76fd8405f..338013ba4 100644
--- a/server/src/lib/prompt-demand.js
+++ b/server/src/lib/prompt-demand.js
@@ -25,7 +25,8 @@
*
* The level weighs the signals read (demandLevel). The Demand card on the
* prompt's page shows all of it (GET /api/prompts/:id/demand), and the
- * Action Center's priority reads the level.
+ * Action Center's priority reads the level: a brand whose levels changed
+ * has its open actions scored again (rescoreDemandBrands).
*
* A workspace whose plan has ended is skipped (2026-10-27, #1608): nothing
* is matched, set or read for it.
@@ -37,6 +38,7 @@ import { activeBrandFilter, activeOrgFilter } from './active-subscriptions.js';
import { getTask, isDataForSeoConfigured, postTasks, readyTasks } from './dataforseo.js';
import { matchPrompt, tokens } from './signals/library/classify.js';
import { logger } from './logger.js';
+import { rescoreBrandActions } from './action-center/priority-data.js';
const DAY_MS = 86_400_000;
@@ -567,7 +569,8 @@ export async function postDemandTasks(due, { now = Date.now() } = {}) {
return rows.size;
}
-const DEMAND_ROW_COLUMNS = 'prompt_id, brand_id, gsc, trends, paa, youtube, tasks, posted_at';
+const DEMAND_ROW_COLUMNS =
+ 'prompt_id, brand_id, gsc, trends, paa, youtube, tasks, posted_at, level';
/** The prompt_demand rows with tasks waiting, paged. */
async function waitingRows() {
@@ -636,13 +639,13 @@ async function orphanRows(ready, waiting) {
* each of ours on it, and the done ones no row knew (orphanRows). A task
* older than TASK_EXPIRE_DAYS is read whether listed or not, and given up
* if it still has nothing; the prompt is set again when it's next due. The
- * level is worked out again for each prompt read. Workspaces whose plan
- * has ended are left out.
+ * level is worked out again for each prompt read; `brands` are those where
+ * a level changed. Workspaces whose plan has ended are left out.
*
- * @returns {Promise<{ read: number, waiting: number, skipped?: 'off' }>}
+ * @returns {Promise<{ read: number, waiting: number, brands: string[], skipped?: 'off' }>}
*/
export async function collectDemandTasks({ now = Date.now() } = {}) {
- if (!paidSignalsEnabled()) return { read: 0, waiting: 0, skipped: 'off' };
+ if (!paidSignalsEnabled()) return { read: 0, waiting: 0, brands: [], skipped: 'off' };
const ready = {};
for (const name of PAID_SIGNALS) {
try {
@@ -657,13 +660,14 @@ export async function collectDemandTasks({ now = Date.now() } = {}) {
}
const waitingNow = await waitingRows();
const rows = [...waitingNow, ...(await orphanRows(ready, waitingNow))];
- if (rows.length === 0) return { read: 0, waiting: 0 };
+ if (rows.length === 0) return { read: 0, waiting: 0, brands: [] };
const isActive = await activeBrandFilter(rows.map((r) => r.brand_id));
const mine = rows.filter((r) => isActive(r.brand_id));
- if (mine.length === 0) return { read: 0, waiting: 0 };
+ if (mine.length === 0) return { read: 0, waiting: 0, brands: [] };
const at = new Date(now).toISOString();
const writes = [];
+ const brands = new Set();
let waiting = 0;
await eachLimited(mine, READ_CONCURRENCY, async (row) => {
const tasks = { ...row.tasks };
@@ -699,6 +703,7 @@ export async function collectDemandTasks({ now = Date.now() } = {}) {
if (left) waiting += 1;
if (!changed) return;
const { level, signals } = demandLevel(next);
+ if (level !== (row.level ?? null)) brands.add(row.brand_id);
writes.push({
...next,
tasks: left ? tasks : null,
@@ -708,7 +713,30 @@ export async function collectDemandTasks({ now = Date.now() } = {}) {
});
});
await upsertRows(writes);
- return { read: writes.length, waiting };
+ return { read: writes.length, waiting, brands: [...brands] };
+}
+
+/**
+ * The brands whose demand levels changed, their open actions scored again
+ * (AC-006): the priority reads the levels, and shows the change the same
+ * night. Best effort, one brand at a time. An action whose score comes out
+ * as stored isn't written again (rescoreBrandActions).
+ *
+ * @returns {Promise<number>} actions whose scores changed
+ */
+export async function rescoreDemandBrands(brandIds, { now = Date.now() } = {}) {
+ let scored = 0;
+ for (const brandId of new Set(brandIds)) {
+ try {
+ scored += await rescoreBrandActions(brandId, { now: new Date(now) });
+ } catch (err) {
+ logger.warn(
+ { err: { message: err?.message }, brandId },
+ '[prompt-demand] actions not scored again',
+ );
+ }
+ }
+ return scored;
}
// ─── The nightly sweep ──────────────────────────────────────────────────────
@@ -764,11 +792,12 @@ async function promptVolumes(promptIds) {
/**
* One brand's night: each active prompt's Search Console demand and level
* written where they changed, and the prompts whose paid signals are due.
- * Rows are only made for a prompt with something read.
+ * Rows are only made for a prompt with something read. `levelsChanged`:
+ * a prompt's level is not what it was.
*/
export async function refreshBrandDemand(brand, { now = Date.now(), paid = false } = {}) {
const prompts = await activePrompts(brand.id);
- if (prompts.length === 0) return { written: 0, due: [] };
+ if (prompts.length === 0) return { written: 0, due: [], levelsChanged: false };
const at = new Date(now).toISOString();
const [existing, gsc, volumes] = await Promise.all([
brandDemandRows(brand.id).then((rows) => new Map(rows.map((r) => [r.prompt_id, r]))),
@@ -780,6 +809,7 @@ export async function refreshBrandDemand(brand, { now = Date.now(), paid = false
const writes = [];
const due = [];
+ let levelsChanged = false;
for (const prompt of prompts) {
const row = existing.get(prompt.id);
const signals = {
@@ -789,6 +819,7 @@ export async function refreshBrandDemand(brand, { now = Date.now(), paid = false
youtube: row?.youtube ?? null,
};
const level = demandLevel(signals);
+ if (level.level !== (row?.level ?? null)) levelsChanged = true;
// Search Console is read again every night, and says so (its `at`).
const changed =
signals.gsc !== null ||
@@ -818,7 +849,7 @@ export async function refreshBrandDemand(brand, { now = Date.now(), paid = false
}
}
await upsertRows(writes);
- return { written: writes.length, due };
+ return { written: writes.length, due, levelsChanged };
}
/**
@@ -846,14 +877,15 @@ export function sweepOrder(brands, updates) {
* The night's demand (server.js daily run): last night's tasks read, every
* active brand's prompts matched to its Search Console queries and their
* levels kept, then the paid signals set for the prompts due, the
- * NIGHTLY_LIMIT waiting longest. Brands whose workspace's plan has ended
- * are skipped; one brand's failure is logged and the rest go on.
+ * NIGHTLY_LIMIT waiting longest. The brands whose levels changed have
+ * their actions scored again. Brands whose workspace's plan has ended are
+ * skipped; one brand's failure is logged and the rest go on.
*
* The brands go in sweepOrder, for SWEEP_DEADLINE_MS at most: the ones not
* reached are `unfinished`, logged, and go first the next night. `due`:
* the prompts whose paid signals were due, before the cap.
*
- * @returns {Promise<{ brands: number, written: number, skipped: number, failed: number, unfinished: number, due: number, posted: number, read: number, paid: boolean }>}
+ * @returns {Promise<{ brands: number, written: number, skipped: number, failed: number, unfinished: number, due: number, posted: number, read: number, rescored: number, paid: boolean }>}
*/
export async function sweepPromptDemand({
now = Date.now(),
@@ -870,12 +902,16 @@ export async function sweepPromptDemand({
due: 0,
posted: 0,
read: 0,
+ rescored: 0,
paid,
};
+ const changed = new Set();
if (paid) {
try {
- outcome.read = (await collectDemandTasks({ now })).read;
+ const collected = await collectDemandTasks({ now });
+ outcome.read = collected.read;
+ for (const id of collected.brands) changed.add(id);
} catch (err) {
logger.error({ err: { message: err?.message } }, '[prompt-demand] tasks not collected');
}
@@ -903,6 +939,7 @@ export async function sweepPromptDemand({
outcome.brands += 1;
outcome.written += result.written;
due.push(...result.due);
+ if (result.levelsChanged) changed.add(brand.id);
} catch (err) {
outcome.failed += 1;
logger.warn(
@@ -920,6 +957,7 @@ export async function sweepPromptDemand({
}
outcome.due = due.length;
if (paid && due.length) outcome.posted = await postDemandTasks(pickDue(due, limit), { now });
+ outcome.rescored = await rescoreDemandBrands([...changed], { now });
logger.info(outcome, '[prompt-demand] nightly sweep done');
return outcome;
}
@@ -932,9 +970,11 @@ export async function sweepPromptDemand({
export function scheduleDemandCollect(delayMs = COLLECT_DELAY_MS) {
if (!paidSignalsEnabled()) return null;
const timer = setTimeout(() => {
- collectDemandTasks().catch((err) =>
- logger.error({ err: { message: err?.message } }, '[prompt-demand] late collect failed'),
- );
+ collectDemandTasks()
+ .then(({ brands }) => rescoreDemandBrands(brands))
+ .catch((err) =>
+ logger.error({ err: { message: err?.message } }, '[prompt-demand] late collect failed'),
+ );
}, delayMs);
timer.unref?.();
return timer;
diff --git a/server/src/lib/prompt-demand.test.js b/server/src/lib/prompt-demand.test.js
index a20c24e03..a597b279c 100644
--- a/server/src/lib/prompt-demand.test.js
+++ b/server/src/lib/prompt-demand.test.js
@@ -148,6 +148,10 @@ vi.mock('./dataforseo.js', () => ({
getTask,
}));
+// The Action Center's priority reads the levels: a brand whose levels changed is scored again.
+const rescoreBrandActions = vi.fn();
+vi.mock('./action-center/priority-data.js', () => ({ rescoreBrandActions }));
+
/** postTasks setting every task, each id `${path}#${tag}`, in one request. */
async function setAll(path, tasks, { onChunk } = {}) {
const ids = new Map(tasks.map((t) => [t.tag, `${path}#${t.tag}`]));
@@ -411,6 +415,7 @@ beforeEach(() => {
postTasks.mockReset();
readyTasks.mockReset().mockResolvedValue(new Map());
getTask.mockReset();
+ rescoreBrandActions.mockReset().mockResolvedValue(3);
vi.stubEnv('DEMAND_SIGNALS', 'false');
});
@@ -1131,7 +1136,12 @@ describe('collectDemandTasks', () => {
it('does nothing with DEMAND_SIGNALS off', async () => {
tables.prompt_demand = [waiting({ posted_at: daysAgo(1), trends: 't1' })];
- expect(await collectDemandTasks({ now: NOW })).toEqual({ read: 0, waiting: 0, skipped: 'off' });
+ expect(await collectDemandTasks({ now: NOW })).toEqual({
+ read: 0,
+ waiting: 0,
+ brands: [],
+ skipped: 'off',
+ });
expect(readyTasks).not.toHaveBeenCalled();
});
@@ -1159,7 +1169,8 @@ describe('collectDemandTasks', () => {
throw new Error(`unexpected ${path}`);
});
- expect(await collectDemandTasks({ now: NOW })).toEqual({ read: 1, waiting: 1 });
+ // The level went from medium to high: the brand's actions are scored again.
+ expect(await collectDemandTasks({ now: NOW })).toEqual({ read: 1, waiting: 1, brands: ['b1'] });
const row = demandRow('p1');
expect(row.trends).toMatchObject({ trend: 'rising', change: 64, at: AT });
@@ -1206,6 +1217,29 @@ describe('collectDemandTasks', () => {
});
});
+describe("the Action Center's priority", () => {
+ it("scores a brand's actions again when a level changed, once a night", async () => {
+ const outcome = await sweepPromptDemand({ now: NOW });
+ expect(outcome.rescored).toBe(3);
+ expect(rescoreBrandActions).toHaveBeenCalledTimes(1);
+ expect(rescoreBrandActions).toHaveBeenCalledWith('b1', { now: new Date(NOW) });
+ });
+
+ it('leaves them when no level changed', async () => {
+ await sweepPromptDemand({ now: NOW });
+ rescoreBrandActions.mockClear();
+ // The same queries the next night: new numbers' dates, the same levels.
+ const outcome = await sweepPromptDemand({ now: NOW + DAY });
+ expect(outcome.written).toBe(2);
+ expect(rescoreBrandActions).not.toHaveBeenCalled();
+ });
+
+ it('carries on when the scores cannot be saved', async () => {
+ rescoreBrandActions.mockRejectedValue(new Error('timeout'));
+ await expect(sweepPromptDemand({ now: NOW })).resolves.toMatchObject({ rescored: 0 });
+ });
+});
+
describe('collecting the tasks whose ids were lost', () => {
// A prompt's id is the tag its tasks are set with.
const P1 = '6f1c2a3b-0d4e-4f5a-9b6c-7d8e9f0a1b2c';
@@ -1244,7 +1278,11 @@ describe('collecting the tasks whose ids were lost', () => {
);
getTask.mockResolvedValue({ status: 'done', result: SERP_RESULT });
- expect(await collectDemandTasks({ now: NOW })).toEqual({ read: 1, waiting: 0 });
+ expect(await collectDemandTasks({ now: NOW })).toEqual({
+ read: 1,
+ waiting: 0,
+ brands: ['b1'],
+ });
expect(getTask.mock.calls).toEqual([['/v3/serp/google/organic/task_get/advanced/lost-paa']]);
expect(demandRow(P1)).toMatchObject({ tasks: null, signals: 1 });
@@ -1271,7 +1309,11 @@ describe('collecting the tasks whose ids were lost', () => {
);
getTask.mockResolvedValue({ status: 'done', result: SERP_RESULT });
- expect(await collectDemandTasks({ now: NOW })).toEqual({ read: 1, waiting: 1 });
+ expect(await collectDemandTasks({ now: NOW })).toEqual({
+ read: 1,
+ waiting: 1,
+ brands: ['b1'],
+ });
expect(demandRow(P1).tasks).toEqual({
posted_at: daysAgo(1),
diff --git a/web/messages/en.json b/web/messages/en.json
index f85318263..69acad08a 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1043,6 +1043,10 @@
"days": "{days, plural, one {# day ago} other {# days ago}}"
},
"highDemand": "high search demand",
+ "realDemand": {
+ "high": "measured demand High",
+ "medium": "measured demand Medium"
+ },
"commercial": "commercial intent",
"heldBefore": "previously visible",
"pastSuccess": {
diff --git a/web/src/components/action-center/action-export-buttons.test.tsx b/web/src/components/action-center/action-export-buttons.test.tsx
index e4b109706..1ca87d492 100644
--- a/web/src/components/action-center/action-export-buttons.test.tsx
+++ b/web/src/components/action-center/action-export-buttons.test.tsx
@@ -91,6 +91,7 @@ const action = {
change: 'dropped',
subject: { entity: 'prompts', count: 3 },
demand: 'high',
+ realDemand: null,
commercial: true,
heldBefore: true,
days: 2,
diff --git a/web/src/lib/action-center/priority.test.ts b/web/src/lib/action-center/priority.test.ts
index 249736dc4..deadeaf78 100644
--- a/web/src/lib/action-center/priority.test.ts
+++ b/web/src/lib/action-center/priority.test.ts
@@ -40,6 +40,7 @@ const reason = (over: Partial<PriorityReason> = {}): PriorityReason => ({
heldBefore: true,
days: 2,
sources: 1,
+ realDemand: null,
pastSuccess: null,
...over,
});
@@ -202,6 +203,47 @@ describe('priorityReasonText', () => {
).toBe('Its findings have resolved.');
});
+ it("says the prompts' measured demand level, and reads it from what was stored", () => {
+ expect(priorityReasonText(reason({ realDemand: 'high' }), t)).toBe(
+ 'Lost ground on 7 high-demand prompts 2 days ago — measured demand High, commercial intent, previously visible.',
+ );
+ expect(
+ priorityReasonText(
+ reason({ demand: 'medium', realDemand: 'medium', commercial: false, heldBefore: false }),
+ t,
+ ),
+ ).toBe('Lost ground on 7 prompts 2 days ago — measured demand Medium.');
+ expect(parsePriorityReason({ change: 'gap', realDemand: 'medium' })?.realDemand).toBe('medium');
+ expect(parsePriorityReason({ change: 'gap', realDemand: 'huge' })?.realDemand).toBeNull();
+ });
+
+ it('says both the measured demand and the track, when a reason has both', () => {
+ const stored = parsePriorityReason({
+ change: 'lost',
+ subject: { entity: 'prompts', count: 7 },
+ demand: 'high',
+ heldBefore: true,
+ days: 2,
+ realDemand: 'high',
+ pastSuccess: { improved: 3, results: 4, points: 3.33 },
+ });
+ expect(priorityReasonText(stored!, t)).toBe(
+ 'Lost ground on 7 high-demand prompts 2 days ago — measured demand High, previously visible, 3 of 4 earlier actions of this kind improved results here.',
+ );
+ });
+
+ it('never gives Low as a reason: it raises nothing', () => {
+ const stored = parsePriorityReason({
+ change: 'dropped',
+ subject: { entity: 'prompts', count: 7 },
+ demand: 'medium',
+ realDemand: 'low',
+ days: 2,
+ });
+ expect(stored?.realDemand).toBeNull();
+ expect(priorityReasonText(stored!, t)).not.toContain('measured demand');
+ });
+
it('falls back to a plain subject when the count is unknown', () => {
expect(
priorityReasonText(
diff --git a/web/src/lib/action-center/priority.ts b/web/src/lib/action-center/priority.ts
index 08b322441..17e160144 100644
--- a/web/src/lib/action-center/priority.ts
+++ b/web/src/lib/action-center/priority.ts
@@ -21,6 +21,12 @@ export interface PriorityReason {
subject: { entity: string | null; count: number | null };
/** Measured demand; null when nothing measures it. */
demand: 'high' | 'medium' | 'low' | null;
+ /**
+ * The prompts' measured demand level (PROMPT-014: Search Console, Google
+ * Trends, People Also Ask, YouTube), the highest, when it raised the score:
+ * High or Medium. Null otherwise: Low raises nothing, so it's no reason.
+ */
+ realDemand: 'high' | 'medium' | null;
commercial: boolean;
/** Ground the brand held and lost. */
heldBefore: boolean;
@@ -89,6 +95,7 @@ export function parsePriorityReason(
count: num(subject.count),
},
demand: r.demand === 'high' || r.demand === 'medium' || r.demand === 'low' ? r.demand : null,
+ realDemand: r.realDemand === 'high' || r.realDemand === 'medium' ? r.realDemand : null,
commercial: r.commercial === true,
heldBefore: r.heldBefore === true,
days: daysSince(num(r.days), scoredAt, now),
@@ -171,7 +178,7 @@ const SUBJECTS = new Set([
* "Why this priority?": what changed, on what, how recently, and what makes
* it matter — from the action's own facts, in the reader's language
* (actionsPage.priority.reason). "Lost ground on 7 high-demand prompts
- * 2 days ago — commercial intent, previously visible."
+ * 2 days ago — measured demand High, commercial intent, previously visible."
*/
export function priorityReasonText(reason: PriorityReason, t: Translator): string {
const { entity, count } = reason.subject;
@@ -199,6 +206,7 @@ export function priorityReasonText(reason: PriorityReason, t: Translator): strin
const extras: string[] = [];
if (reason.demand === 'high' && !inSubject) extras.push(t('reason.highDemand'));
+ if (reason.realDemand) extras.push(t(`reason.realDemand.${reason.realDemand}`));
if (reason.commercial) extras.push(t('reason.commercial'));
if (
reason.heldBefore &&