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): weigh how a kind of action did at the brand before into its priority (learning B4) (#1696)
Cihanee44f2c6257c
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdxindex 49c9e375b..fe6f8bd65 100644--- a/docs/guides/action-center.mdx+++ b/docs/guides/action-center.mdx@@ -142,6 +142,8 @@ The score weighs seven things:Demand or business value that nothing measures counts as neutral: it neither raises nor lowers the score.+On top of these, **past success** nudges the score: how this brand's own earlier actions of the same kind turned out over the last six months, as the History scorecard counts them. A kind that improved results here sits up to 10 points higher, one that rarely did up to 10 lower. A few results barely move it, and a kind with no results yet doesn't move at all. Other brands' results are never used. When it moves the score by a point or more, **Why this priority?** says so, for example *3 of 4 earlier actions of this kind improved results here*.+An action sent from another page has no detection signals, so it is scored from what it carries: the prompt's platforms for an Improve action, the prompts of a content opportunity or draft, the pages sent from AI Traffic.### When it changesdiff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.jsindex 9069c1554..e7d0b9ecb 100644--- a/server/src/config/action-engine.js+++ b/server/src/config/action-engine.js@@ -354,6 +354,21 @@ export const ENGINE_THRESHOLDS = Object.freeze({/** In the queue of waiting findings, per day waited, up to `waitCapDays`. */waitPerDay: 1,waitCapDays: 14,+ /**+ * Past success (learning B4): how this brand's own earlier actions of+ * the same kind turned out, from its History scorecard over the last+ * `pastSuccessDays`. The share that improved, pulled toward+ * `pastSuccessPrior` by `pastSuccessPseudoCount` imagined results, so a+ * couple of results barely move it: a kind with none sits at the prior+ * and its score doesn't move. Never another brand's history. The score+ * moves by the rate's distance from the prior times `pastSuccessSwing`:+ * up to 10 points either way, about 6.7 for a kind that improved 10+ * times out of 10.+ */+ pastSuccessSwing: 20,+ pastSuccessPrior: 0.5,+ pastSuccessPseudoCount: 5,+ pastSuccessDays: 180,}),/** How an action's effect is measured once it closes. */diff --git a/server/src/lib/action-center/from-content-draft.js b/server/src/lib/action-center/from-content-draft.jsindex fdc7ba79c..b4001d158 100644--- a/server/src/lib/action-center/from-content-draft.js+++ b/server/src/lib/action-center/from-content-draft.js@@ -110,7 +110,13 @@ export async function sendContentDraftToActionCenter(brandId, { draftId, userIdkpi_keys: KPI_KEYS,baseline: {},dedup_key: dedupKey,- ...(await priorityOnCreate({ kind: CONTENT_DRAFT_ACTION_KIND, category, impact, payload })),+ ...(await priorityOnCreate({+ brand_id: brandId,+ kind: CONTENT_DRAFT_ACTION_KIND,+ category,+ impact,+ payload,+ })),}).select('id, action_no').single();diff --git a/server/src/lib/action-center/from-opportunity.js b/server/src/lib/action-center/from-opportunity.jsindex d7e67b47e..7db491d3c 100644--- a/server/src/lib/action-center/from-opportunity.js+++ b/server/src/lib/action-center/from-opportunity.js@@ -214,6 +214,7 @@ export async function sendToActionCenter(baseline: {},dedup_key: dedupKey,...(await priorityOnCreate({+ brand_id: opportunity.brand_id,kind: OPPORTUNITY_ACTION_KIND,category: 'growth',impact: opportunity.impact,diff --git a/server/src/lib/action-center/from-prompt-improve.js b/server/src/lib/action-center/from-prompt-improve.jsindex e97c3799d..459847631 100644--- a/server/src/lib/action-center/from-prompt-improve.js+++ b/server/src/lib/action-center/from-prompt-improve.js@@ -331,6 +331,7 @@ export async function sendImproveToActionCenter({},dedup_key: dedupKey,...(await priorityOnCreate({+ brand_id: brandId,kind: IMPROVE_ACTION_KIND,category: 'compete',impact,diff --git a/server/src/lib/action-center/from-traffic-pages.js b/server/src/lib/action-center/from-traffic-pages.jsindex 980795c00..efc1f9367 100644--- a/server/src/lib/action-center/from-traffic-pages.js+++ b/server/src/lib/action-center/from-traffic-pages.js@@ -235,7 +235,13 @@ export async function sendTrafficPagesToActionCenter(brandId, { pages, reason, fsessions: payload.sessions,},dedup_key: dedupKey,- ...(await priorityOnCreate({ kind: TRAFFIC_PAGES_ACTION_KIND, category, impact, payload })),+ ...(await priorityOnCreate({+ brand_id: brandId,+ kind: TRAFFIC_PAGES_ACTION_KIND,+ category,+ 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 de919fe46..eea16946a 100644--- a/server/src/lib/action-center/generate.js+++ b/server/src/lib/action-center/generate.js@@ -53,7 +53,7 @@ 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';+import { kindTrackOrNone, loadPromptDemand } from './priority-data.js';const DAY_MS = 86_400_000;@@ -272,6 +272,8 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc} catch (err) {logger.warn({ brandId, err: err.message }, '[actions] prompt demand unavailable');}+ // How each kind did here before (learning B4), read once for the night.+ const track = await kindTrackOrNone(brandId, now);const ready = [];const seen = new Set();let refreshed = 0;@@ -336,6 +338,7 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourcaction: { kind: definition.id, category: definition.category, impact, payload },signals: unclaimed,prompts: demand,+ track,},now,);@@ -444,7 +447,7 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourcfor (const row of activeRows ?? []) {// Including the signals linked to it tonight: the rows in hand say so.const evidence = (openSignals ?? []).filter((signal) => signal.action_id === row.id);- const priority = scorePriority({ action: row, signals: evidence, prompts: demand }, now);+ const priority = scorePriority({ action: row, signals: evidence, prompts: demand, track }, now);const { error } = await supabaseAdmin.from('actions').update(priorityColumns(priority, now))diff --git a/server/src/lib/action-center/priority-data.js b/server/src/lib/action-center/priority-data.jsindex 588ccf561..da9300719 100644--- a/server/src/lib/action-center/priority-data.js+++ b/server/src/lib/action-center/priority-data.js@@ -1,13 +1,19 @@/*** 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.+ * 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.*/import supabaseAdmin from '../../config/supabase.js';+import { resolve } from '../../config/action-engine.js';import { logger } from '../logger.js';import { priorityColumns, promptIdsOf, scorePriority } from './priority.js';+const DAY_MS = 86_400_000;++const { priority: P } = resolve();+/** Prompt ids per request, so the filter stays well inside a URL's length. */const CHUNK = 150;@@ -53,13 +59,54 @@ export async function loadPromptDemand(promptIds) {return demand;}+/**+ * Per kind, how the brand's own actions of it turned out over the last+ * `pastSuccessDays` (learning B4): its results with a verdict and how many+ * improved, from the History scorecard (action_scorecard, 00368). Never+ * another brand's.+ *+ * @param {string} brandId+ * @returns {Promise<Map<string, { improved: number, results: number }>>}+ */+export async function loadKindTrack(brandId, now = new Date()) {+ const { data, error } = await supabaseAdmin.rpc('action_scorecard', {+ p_brand_id: brandId,+ p_since: new Date(now.getTime() - P.pastSuccessDays * DAY_MS).toISOString(),+ });+ if (error) throw new Error(`action scorecard read failed: ${error.message}`);+ const n = (v) => Number(v) || 0;+ return new Map(+ (data ?? []).map((row) => [+ row.kind,+ {+ improved: n(row.improved),+ results: n(row.improved) + n(row.mixed) + n(row.no_change) + n(row.declined),+ },+ ]),+ );+}++/**+ * The brand's track by kind, or none when it can't be read: the score is+ * still worked out, its kinds read as having no history.+ */+export async function kindTrackOrNone(brandId, now = new Date()) {+ if (!brandId) return new Map();+ try {+ return await loadKindTrack(brandId, now);+ } catch (err) {+ logger.warn({ brandId, err: err.message }, '[actions] past success unavailable');+ return new Map();+ }+}+/*** 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+ * @param {{ brand_id: string, kind: string, category: string, impact: string, payload: object }} action*/export async function priorityOnCreate(action, now = new Date()) {let prompts = new Map();@@ -68,8 +115,9 @@ export async function priorityOnCreate(action, now = new Date()) {} catch (err) {logger.warn({ err: err.message, kind: action.kind }, '[actions] prompt demand unavailable');}+ const track = await kindTrackOrNone(action.brand_id, now);const priority = scorePriority(- { action: { ...action, created_at: now.toISOString() }, signals: [], prompts },+ { action: { ...action, created_at: now.toISOString() }, signals: [], prompts, track },now,);return priorityColumns(priority, now);@@ -85,10 +133,11 @@ const OPEN_SIGNAL_STATUSES = ['new', 'acknowledged'];* they stand now, as the nightly pass would. Best effort: a score that can't* be read or saved is logged and left for the night.*- * @param {{ id: string, kind: string, category: string, impact: string, payload?: object, created_at?: string }} action+ * @param {{ id: string, brand_id?: string, kind: string, category: string, impact: string, payload?: object, created_at?: string }} action+ * @param {Map<string, { improved: number, results: number }>} [track] the brand's, when read already* @returns {Promise<boolean>} whether the score was saved*/-export async function rescoreAction(action, now = new Date()) {+export async function rescoreAction(action, now = new Date(), track = null) {const { data: signals, error } = await supabaseAdmin.from('signals').select('id, kind, impact, payload, current_value, source, detected_at')@@ -107,7 +156,15 @@ export async function rescoreAction(action, now = new Date()) {} catch (err) {logger.warn({ actionId: action.id, err: err.message }, '[actions] prompt demand unavailable');}- const priority = scorePriority({ action, signals: signals ?? [], prompts }, now);+ const priority = scorePriority(+ {+ action,+ signals: signals ?? [],+ prompts,+ track: track ?? (await kindTrackOrNone(action.brand_id, now)),+ },+ now,+ );const { error: saveErr } = await supabaseAdmin.from('actions').update(priorityColumns(priority, now))@@ -165,6 +222,7 @@ export async function rescoreBrandActions(} catch (err) {logger.warn({ brandId, err: err.message }, '[actions] prompt demand unavailable');}+ const track = await kindTrackOrNone(brandId, now);const evidence = new Map();for (const signal of signals ?? []) {@@ -175,7 +233,7 @@ export async function rescoreBrandActions(let scored = 0;for (const action of actions) {const priority = scorePriority(- { action, signals: evidence.get(action.id) ?? [], prompts },+ { action, signals: evidence.get(action.id) ?? [], prompts, track },now,);const { error: saveErr } = await supabaseAdmin@@ -209,14 +267,19 @@ export async function rescoreActionsForSignal(signalId, now = new Date()) {const { data: actions, error: actionsErr } = await supabaseAdmin.from('actions')- .select('id, kind, category, impact, payload, created_at')+ .select('id, brand_id, kind, category, impact, payload, created_at').in('id', ids).in('status', ACTIVE_STATUSES);if (actionsErr) throw new Error(actionsErr.message);+ // A signal's actions are its brand's: their track is read once.+ const brandId = actions?.[0]?.brand_id ?? null;+ const track = await kindTrackOrNone(brandId, now);let rescored = 0;for (const action of actions ?? []) {- if (await rescoreAction(action, now)) rescored += 1;+ if (await rescoreAction(action, now, action.brand_id === brandId ? track : null)) {+ rescored += 1;+ }}return rescored;}diff --git a/server/src/lib/action-center/priority-data.test.js b/server/src/lib/action-center/priority-data.test.jsindex 96d53aa91..f4af73a54 100644--- a/server/src/lib/action-center/priority-data.test.js+++ b/server/src/lib/action-center/priority-data.test.js@@ -15,9 +15,15 @@ let signalRows = [];let queries = [];let saved = [];let unsaved = new Set();+let rpcCalls = [];+let rpcResult = { data: [], error: null };vi.mock('../../config/supabase.js', () => ({default: {+ rpc: async (fn, args) => {+ rpcCalls.push([fn, args]);+ return rpcResult;+ },from: (table) => {let ids = [];const op = { table, filters: [] };@@ -73,7 +79,7 @@ vi.mock('../../config/supabase.js', () => ({}));vi.mock('../logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));-const { loadPromptDemand, priorityOnCreate, rescoreBrandActions } =+const { loadKindTrack, loadPromptDemand, priorityOnCreate, rescoreBrandActions } =await import('./priority-data.js');beforeEach(() => {@@ -85,6 +91,8 @@ beforeEach(() => {queries = [];saved = [];unsaved = new Set();+ rpcCalls = [];+ rpcResult = { data: [], error: null };// Newest first, as the read orders them.rows = [{ prompt_id: 'p1', est_ai_volume: 300, intent: 'comparison', fetched_at: '2026-10-10' },@@ -128,6 +136,26 @@ describe('loadPromptDemand', () => {});});+describe('loadKindTrack', () => {+ it("reads the brand's own results by kind over the last half year (learning B4)", async () => {+ rpcResult = {+ data: [+ { kind: 'recover_lost_citations', improved: 2, mixed: 1, no_change: 1, declined: 1 },+ { kind: 'fix_low_scores', improved: 0, mixed: 0, no_change: 0, declined: 0 },+ ],+ error: null,+ };++ const track = await loadKindTrack('b1', new Date('2026-10-15T00:00:00Z'));++ expect(rpcCalls).toEqual([+ ['action_scorecard', { p_brand_id: 'b1', p_since: '2026-04-18T00:00:00.000Z' }],+ ]);+ expect(track.get('recover_lost_citations')).toEqual({ improved: 2, results: 5 });+ expect(track.get('fix_low_scores')).toEqual({ improved: 0, results: 0 });+ });+});+describe('priorityOnCreate', () => {const NOW = new Date('2026-10-15T00:00:00Z');const improve = {@@ -151,6 +179,26 @@ describe('priorityOnCreate', () => {expect(columns.priority_reason.demand).toBeNull();expect(columns.priority_score).toEqual(expect.any(Number));});++ it("weighs how its kind did at the brand, and scores it without when that can't be read", async () => {+ rpcResult = {+ data: [{ kind: 'prompt_improve', improved: 3, mixed: 0, no_change: 0, declined: 0 }],+ error: null,+ };+ const withTrack = await priorityOnCreate({ ...improve, brand_id: 'b1' }, NOW);+ expect(rpcCalls).toHaveLength(1);+ expect(withTrack.priority_reason.pastSuccess).toEqual({+ improved: 3,+ results: 3,+ points: 3.75,+ });++ rpcResult = { data: null, error: { message: 'timeout' } };+ const without = await priorityOnCreate({ ...improve, brand_id: 'b1' }, NOW);+ expect(without.priority_reason.pastSuccess).toBeNull();+ expect(without.priority_reason.factors).not.toHaveProperty('pastSuccess');+ expect(without.priority_score).toBeLessThan(withTrack.priority_score);+ });});describe('rescoreBrandActions', () => {@@ -189,9 +237,12 @@ describe('rescoreBrandActions', () => {['in', 'status', ['new', 'acknowledged']],['not', 'action_id', null],]);- // The signals and the demand are read once for the brand, not per action.+ // The signals, the demand and the track are read once for the brand, not per action.expect(queries.filter((q) => q.table === 'signals')).toHaveLength(1);expect(reads).toEqual([['p1']]);+ expect(rpcCalls.map(([fn, args]) => [fn, args.p_brand_id])).toEqual([+ ['action_scorecard', 'b1'],+ ]);const byId = Object.fromEntries(saved.map(({ id, row }) => [id, row]));expect(byId.a1).toMatchObject({diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.jsindex 8ad5724f5..fc8d7d25c 100644--- a/server/src/lib/action-center/priority.js+++ b/server/src/lib/action-center/priority.js@@ -18,6 +18,10 @@* nearer to hand than winning it from nothing;* recency how new the latest evidence is, halving every few days.*+ * And, on top, past success: a kind of action that has improved results at+ * this brand before sits a little higher, one that rarely has a little+ * lower (learning B4).+ ** 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.@@ -392,6 +396,22 @@ function sentByHand(action) {return null;}+/**+ * Past success (learning B4): from a kind's results at this brand, the+ * share that improved, shrunk toward the prior by a few imagined results,+ * and the points that moves the score. None read: the prior, no points.+ *+ * @param {{ improved?: number, results?: number } | undefined} track+ */+export function pastSuccessOf(track) {+ const improved = Math.max(0, Math.floor(Number(track?.improved) || 0));+ const results = Math.max(improved, Math.floor(Number(track?.results) || 0));+ const rate =+ (improved + P.pastSuccessPseudoCount * P.pastSuccessPrior) /+ (results + P.pastSuccessPseudoCount);+ return { rate, points: (rate - P.pastSuccessPrior) * P.pastSuccessSwing, improved, results };+}+/** The level a score falls in. */export function priorityLevel(score) {if (score >= P.levelCritical) return 'critical';@@ -411,10 +431,15 @@ export function priorityLevel(score) {* 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, { improved: number, results: number }>} [input.track]+ * Per kind, the brand's results with a verdict and how many improved (loadKindTrack).* @param {Date} now* @returns {{ score: number, level: string, reason: object }}*/-export function scorePriority({ action, signals = [], prompts = new Map() }, now = new Date()) {+export function scorePriority(+ { action, signals = [], prompts = new Map(), track = new Map() },+ now = new Date(),+) {const payloads = [action.payload, ...signals.map((s) => s.payload)].filter(Boolean);const byHand = signals.length === 0 ? sentByHand(action) : null;@@ -463,6 +488,7 @@ export function scorePriority({ action, signals = [], prompts = new Map() }, nowrecoverability,recency,};+ const past = pastSuccessOf(track.get(action.kind));const score = Math.round(factors.impact * P.weightImpact +factors.demand * P.weightDemand +@@ -470,7 +496,8 @@ export function scorePriority({ action, signals = [], prompts = new Map() }, nowfactors.businessValue * P.weightBusinessValue +factors.confidence * P.weightConfidence +factors.recoverability * P.weightRecoverability +- factors.recency * P.weightRecency,+ factors.recency * P.weightRecency ++ past.points,);const bounded = Math.min(100, Math.max(0, score));@@ -495,7 +522,17 @@ export function scorePriority({ action, signals = [], prompts = new Map() }, nowdays: signals.length ? Math.floor(days) : null,kinds: confidence.kinds,sources: confidence.sources,- factors: Object.fromEntries(Object.entries(factors).map(([k, v]) => [k, round2(v)])),+ // How its kind did here before (learning B4); null with nothing to go on.+ pastSuccess: past.results+ ? { improved: past.improved, results: past.results, points: round2(past.points) }+ : null,+ // Its rate only with a result behind it: with none, the prior would+ // read as a measured 0.5.+ factors: Object.fromEntries(+ Object.entries({ ...factors, ...(past.results ? { pastSuccess: past.rate } : {}) }).map(+ ([k, v]) => [k, round2(v)],+ ),+ ),},};}diff --git a/server/src/lib/action-center/priority.test.js b/server/src/lib/action-center/priority.test.jsindex b4a790fad..16b038d61 100644--- a/server/src/lib/action-center/priority.test.js+++ b/server/src/lib/action-center/priority.test.js@@ -1,5 +1,11 @@import { describe, expect, it } from 'vitest';-import { priorityColumns, priorityLevel, promptIdsOf, scorePriority } from './priority.js';+import {+ pastSuccessOf,+ priorityColumns,+ priorityLevel,+ promptIdsOf,+ scorePriority,+} from './priority.js';/*** The priority score (AC-006): how soon to work on an action, 0–100, from@@ -393,6 +399,67 @@ describe('scorePriority', () => {});});+/**+ * 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;+ * a couple of results barely move it, and none move nothing.+ */+describe('past success', () => {+ it('reads no history as the prior, moving nothing', () => {+ expect(pastSuccessOf(undefined)).toEqual({ rate: 0.5, points: 0, improved: 0, results: 0 });+ });++ it('pulls a few results toward the prior, and many less so', () => {+ expect(pastSuccessOf({ improved: 3, results: 3 }).points).toBeCloseTo(3.75);+ expect(pastSuccessOf({ improved: 0, results: 3 }).points).toBeCloseTo(-3.75);+ expect(pastSuccessOf({ improved: 10, results: 10 }).points).toBeCloseTo(6.67, 1);+ expect(pastSuccessOf({ improved: 1, results: 1 }).points).toBeLessThan(2);+ });++ it("moves the score by its kind's track here, and says so", () => {+ const signals = [signal()];+ const none = scorePriority({ action: action(), signals }, NOW);+ const worked = scorePriority(+ {+ action: action(),+ signals,+ track: new Map([['recover_lost_citations', { improved: 3, results: 3 }]]),+ },+ NOW,+ );+ const rarely = scorePriority(+ {+ action: action(),+ signals,+ track: new Map([['recover_lost_citations', { improved: 0, results: 3 }]]),+ },+ NOW,+ );++ expect(none.reason.pastSuccess).toBeNull();+ // No result behind it: no rate, rather than the prior read as one.+ expect(none.reason.factors).not.toHaveProperty('pastSuccess');+ expect(worked.reason.factors.pastSuccess).toBe(0.69);+ expect(worked.score).toBeGreaterThan(none.score);+ expect(rarely.score).toBeLessThan(none.score);+ expect(worked.reason.pastSuccess).toEqual({ improved: 3, results: 3, points: 3.75 });+ });++ it("reads only its own kind's track", () => {+ const signals = [signal()];+ const other = scorePriority(+ {+ action: action(),+ signals,+ track: new Map([['fix_low_scores', { improved: 0, results: 9 }]]),+ },+ NOW,+ );+ expect(other.score).toBe(scorePriority({ action: action(), signals }, NOW).score);+ expect(other.reason.pastSuccess).toBeNull();+ });+});+describe('promptIdsOf', () => {it('finds the prompts payloads name, once each', () => {expect(diff --git a/web/messages/en.json b/web/messages/en.jsonindex f5de37488..1d7f3260d 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1045,6 +1045,10 @@"highDemand": "high search demand","commercial": "commercial intent","heldBefore": "previously visible",+ "pastSuccess": {+ "worked": "{improved} of {results} earlier {results, plural, one {action} other {actions}} of this kind improved results here",+ "rarely": "only {improved} of {results} earlier {results, plural, one {action} other {actions}} of this kind improved results here"+ },"sources": "confirmed by {count} sources","sentence": {"withWhen": "{what} {when}",diff --git a/web/src/lib/action-center/priority.test.ts b/web/src/lib/action-center/priority.test.tsindex 2626c6bcf..249736dc4 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,+ pastSuccess: null,...over,});@@ -148,6 +149,41 @@ describe('priorityReasonText', () => {).toBe('A gap to close on 2 platforms — high search demand, commercial intent.');});+ /** Its kind's track at the brand (learning B4), once it moved the score a point. */+ it('says how earlier actions of its kind did here', () => {+ expect(+ priorityReasonText(+ reason({ commercial: false, pastSuccess: { improved: 3, results: 4, points: 3.33 } }),+ t,+ ),+ ).toBe(+ 'Lost ground on 7 high-demand prompts 2 days ago — previously visible, 3 of 4 earlier actions of this kind improved results here.',+ );+ expect(+ priorityReasonText(+ reason({ commercial: false, pastSuccess: { improved: 0, results: 1, points: -1.67 } }),+ t,+ ),+ ).toBe(+ 'Lost ground on 7 high-demand prompts 2 days ago — previously visible, only 0 of 1 earlier action of this kind improved results here.',+ );+ // A point's nudge or less isn't worth a word.+ expect(+ priorityReasonText(+ reason({ commercial: false, pastSuccess: { improved: 1, results: 2, points: 0 } }),+ t,+ ),+ ).toBe('Lost ground on 7 high-demand prompts 2 days ago — previously visible.');+ });++ it('reads a stored track defensively', () => {+ expect(+ parsePriorityReason({ pastSuccess: { improved: 2, results: 3, points: 1.4 } })?.pastSuccess,+ ).toEqual({ improved: 2, results: 3, points: 1.4 });+ expect(parsePriorityReason({ pastSuccess: { improved: 2 } })?.pastSuccess).toBeNull();+ expect(parsePriorityReason({})?.pastSuccess).toBeNull();+ });+it('counts independent sources, and says today for a fresh finding', () => {expect(priorityReasonText(diff --git a/web/src/lib/action-center/priority.ts b/web/src/lib/action-center/priority.tsindex 89d9e8693..08b322441 100644--- a/web/src/lib/action-center/priority.ts+++ b/web/src/lib/action-center/priority.ts@@ -28,6 +28,12 @@ export interface PriorityReason {days: number | null;/** Independent data sources behind it. */sources: number;+ /**+ * How the brand's earlier actions of its kind turned out (learning B4):+ * results with a verdict, how many improved, and the points that moved+ * its score. Null with no history, or from a scorer before it.+ */+ pastSuccess?: { improved: number; results: number; points: number } | null;}/** How many actions the Top Actions card names (spec: at most five). */@@ -87,9 +93,20 @@ export function parsePriorityReason(heldBefore: r.heldBefore === true,days: daysSince(num(r.days), scoredAt, now),sources: num(r.sources) ?? 0,+ pastSuccess: pastSuccessOf(r.pastSuccess),};}+function pastSuccessOf(value: unknown): PriorityReason['pastSuccess'] {+ if (!value || typeof value !== 'object') return null;+ const p = value as Record<string, unknown>;+ const [improved, results, points] = [p.improved, p.results, p.points].map((v) =>+ typeof v === 'number' && Number.isFinite(v) ? v : null,+ );+ if (improved === null || results === null || points === null || results < 1) return null;+ return { improved, results, points };+}+function daysSince(days: number | null, scoredAt: string | null | undefined, now: Date) {if (days === null) return null;const at = Date.parse(scoredAt ?? '');@@ -190,6 +207,16 @@ export function priorityReasonText(reason: PriorityReason, t: Translator): strinextras.push(t('reason.heldBefore'));}if (reason.sources >= 2) extras.push(t('reason.sources', { count: reason.sources }));+ // Its kind's track here (learning B4), once it moved the score a point or more.+ const past = reason.pastSuccess;+ if (past && Math.abs(past.points) >= 1) {+ extras.push(+ t(past.points > 0 ? 'reason.pastSuccess.worked' : 'reason.pastSuccess.rarely', {+ improved: past.improved,+ results: past.results,+ }),+ );+ }let text = when ? t('reason.sentence.withWhen', { what, when }) : what;if (extras.length) {