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): measure the position outcome of sent Improve actions (#1018)
Cihan3f56a6f0cb1f
diff --git a/server/src/lib/action-center/from-prompt-improve.js b/server/src/lib/action-center/from-prompt-improve.jsindex b736e9270..73593ff02 100644--- a/server/src/lib/action-center/from-prompt-improve.js+++ b/server/src/lib/action-center/from-prompt-improve.js@@ -7,11 +7,13 @@* Unlike it, the tasks are not library tasks: each is one suggestion exactly* as the user edited it, with the platform and the evidence behind it in* `details`. The action is measured on its own prompt (validate.js), and the- * positions at send time are kept as its baseline for PROMPT-008.+ * prompt's last 7 days at send time are kept as its baseline for the Outcome+ * card (improve-outcome.js, PROMPT-008).*/import supabaseAdmin from '../../config/supabase.js';import { IMPROVE_PLATFORM_LABELS } from '../prompt-improve.js';+import { compareOutcome, outcomeWindow, readPlatformStates } from './improve-outcome.js';export const IMPROVE_ACTION_KIND = 'prompt_improve';@@ -94,20 +96,12 @@ export function improveGoal(promptText, platforms) {)}.`;}-/** The positions at send time, per platform the action covers (PROMPT-008). */-export function improveBaseline(platforms, capturedAt) {- return {- capturedAt,- platforms: platforms.map((p) => ({- platform: p.id,- state: p.state,- runs: p.runs ?? null,- mentionedRuns: p.mentionedRuns ?? null,- citedRuns: p.citedRuns ?? null,- mentionPosition: p.mentionPosition ?? null,- citationRank: p.citationRank ?? null,- })),- };+/**+ * The prompt's last 7 days at send time, per platform the action covers+ * (PROMPT-008). Written once, at creation; nothing updates it.+ */+export function improveBaseline(snapshots, capturedAt, window) {+ return { capturedAt, window, platforms: snapshots };}/** One task row per selected suggestion, in the order they were shown. */@@ -172,8 +166,17 @@ export async function sendImproveToActionCenter({.limit(1).maybeSingle();- const now = new Date().toISOString();+ const sentAt = new Date();+ const now = sentAt.toISOString();const pages = improvePages(suggestions);+ const window = outcomeWindow(sentAt);+ const snapshots = await readPlatformStates({+ promptId: prompt.id,+ brandId,+ region: set.region || null,+ platforms: platforms.map((p) => p.id),+ window,+ });const payload = {source: IMPROVE_ACTION_KIND,title: `Improve position: "${prompt.text}"`,@@ -203,7 +206,14 @@ export async function sendImproveToActionCenter({impact: improveImpact(platforms, volumeRow?.est_ai_volume),payload,kpi_keys: improveKpiKeys(pages),- baseline: improveBaseline(platforms, now),+ baseline: improveBaseline(snapshots, now, window),+ // The first read is the baseline itself; the daily sweep moves it on.+ position_outcome: {+ measuredAt: now,+ window,+ final: false,+ ...compareOutcome(snapshots, snapshots),+ },dedup_key: dedupKey,}).select('id, action_no')diff --git a/server/src/lib/action-center/from-prompt-improve.test.js b/server/src/lib/action-center/from-prompt-improve.test.jsindex ee2613b7c..f172411d5 100644--- a/server/src/lib/action-center/from-prompt-improve.test.js+++ b/server/src/lib/action-center/from-prompt-improve.test.js@@ -75,25 +75,21 @@ describe('improveWhy / improveGoal', () => {});describe('improveBaseline', () => {- it('keeps the positions per platform at send time', () => {- expect(- improveBaseline(- [P('chatgpt-web', 'mentioned_late', { runs: 8, mentionedRuns: 8, mentionPosition: 3.4 })],- '2026-10-13T10:00:00.000Z',- ),- ).toEqual({+ it('keeps the 7-day read per platform at send time, with its window', () => {+ const window = { from: '2026-10-06T10:00:00.000Z', to: '2026-10-13T10:00:00.000Z' };+ const snapshot = {+ platform: 'chatgpt-web',+ state: 'mentioned_late',+ runs: 8,+ mentionedRuns: 8,+ citedRuns: 0,+ mentionPosition: 3.4,+ citationRank: null,+ };+ expect(improveBaseline([snapshot], '2026-10-13T10:00:00.000Z', window)).toEqual({capturedAt: '2026-10-13T10:00:00.000Z',- platforms: [- {- platform: 'chatgpt-web',- state: 'mentioned_late',- runs: 8,- mentionedRuns: 8,- citedRuns: null,- mentionPosition: 3.4,- citationRank: null,- },- ],+ window,+ platforms: [snapshot],});});});diff --git a/server/src/lib/action-center/improve-outcome.js b/server/src/lib/action-center/improve-outcome.jsnew file mode 100644index 000000000..4d379a894--- /dev/null+++ b/server/src/lib/action-center/improve-outcome.js@@ -0,0 +1,230 @@+/**+ * Did an Improve action move the prompt's positions? (PROMPT-008)+ *+ * The action's baseline is the prompt's last 7 days per platform when it was+ * sent, fixed at creation. Every day the same 7-day read is taken again and+ * stored next to it as `position_outcome`, which the action's Outcome card,+ * the Positions panel and History show. Both reads use classifyPlatform, the+ * rule the Positions panel and the Improve tab already share, so the numbers+ * agree with the panel for the same days.+ *+ * Tracking runs while the action is open and for 30 days after it is+ * completed; the read at day 30 is final and is recorded in History.+ *+ * Like validate.js, it reports movement, not causality, and a platform with+ * no runs on either side is "not enough data" rather than a delta.+ */++import supabaseAdmin from '../../config/supabase.js';+import { logger } from '../logger.js';+import { classifyPlatform } from '../prompt-improve.js';++const DAY_MS = 86_400_000;++/** Each read covers this many days, ending at the moment of the read. */+export const OUTCOME_WINDOW_DAYS = 7;++/** Days a completed action is still tracked; the read on the last one is final. */+export const OUTCOME_TRACKING_DAYS = 30;++/** A mention position must move at least this far to count as a change. */+export const POSITION_CHANGE = 0.5;++const OPEN = ['new', 'in_progress', 'on_hold'];++/** The 7 days ending at `end`. */+export function outcomeWindow(end) {+ const to = new Date(end);+ return {+ from: new Date(to.getTime() - OUTCOME_WINDOW_DAYS * DAY_MS).toISOString(),+ to: to.toISOString(),+ };+}++/** What one read keeps per platform. */+export function platformSnapshot(platform, state) {+ return {+ platform,+ state: state.state,+ runs: state.runs,+ mentionedRuns: state.mentionedRuns,+ citedRuns: state.citedRuns,+ mentionPosition: state.mentionPosition,+ citationRank: state.citationRank,+ };+}++/**+ * One prompt's state per platform over a window, from the same answers and+ * rule as the Positions panel.+ */+export async function readPlatformStates({ promptId, brandId, region, platforms, window }) {+ if (platforms.length === 0) return [];+ let q = supabaseAdmin+ .from('prompt_results')+ .select('platform, mention_count, mention_position, mentioned_entity_count, citations')+ .eq('prompt_id', promptId)+ .eq('brand_id', brandId)+ .in('platform', platforms)+ .gte('created_at', window.from)+ .lte('created_at', window.to);+ if (region) q = q.eq('region', region);+ const [{ data: rows, error }, { data: domainRows }] = await Promise.all([+ q.limit(2000),+ supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brandId),+ ]);+ if (error) throw new Error(error.message);+ const domains = (domainRows ?? []).map((r) => r.domain);+ return platforms.map((platform) =>+ platformSnapshot(+ platform,+ classifyPlatform(+ (rows ?? []).filter((r) => r.platform === platform),+ domains,+ ),+ ),+ );+}++/**+ * Mentioned or not, by the Improve tab's rule: classifyPlatform already set+ * `state`, and a brand in fewer than MIN_MENTION_RATE of the runs is+ * not_mentioned there, so 1 mention in 10 runs is still not mentioned.+ */+const mentioned = (p) => p.runs > 0 && p.state !== 'no_runs' && p.state !== 'not_mentioned';++/**+ * - not_enough_data no runs before or after+ * - improved now mentioned, or named at least POSITION_CHANGE earlier+ * - declined no longer mentioned, or named at least POSITION_CHANGE later+ * - unchanged anything smaller+ */+export function platformVerdict(before, after) {+ if (!before?.runs || !after?.runs) return 'not_enough_data';+ if (!mentioned(before) && mentioned(after)) return 'improved';+ if (mentioned(before) && !mentioned(after)) return 'declined';+ if (!mentioned(before)) return 'unchanged';+ const b = before.mentionPosition;+ const a = after.mentionPosition;+ if (b === null || a === null) return 'unchanged';+ if (b - a >= POSITION_CHANGE) return 'improved';+ if (a - b >= POSITION_CHANGE) return 'declined';+ return 'unchanged';+}++const round1 = (n) => Math.round(n * 10) / 10;++/** Baseline next to the latest read, per platform, with the counts History reports. */+export function compareOutcome(baselinePlatforms, currentPlatforms) {+ const platforms = baselinePlatforms.map((before) => {+ const after = currentPlatforms.find((p) => p.platform === before.platform) ?? null;+ return { platform: before.platform, before, after, verdict: platformVerdict(before, after) };+ });+ const count = (v) => platforms.filter((p) => p.verdict === v).length;+ // The panel's one-line delta: the mean position over the platforms mentioned+ // and ranked on both sides, so a not-mentioned side's stray position is left out.+ const ranked = platforms.filter(+ (p) =>+ p.verdict !== 'not_enough_data' &&+ mentioned(p.before) &&+ mentioned(p.after) &&+ p.before.mentionPosition !== null &&+ p.after.mentionPosition != null,+ );+ const mean = (xs) => (xs.length ? round1(xs.reduce((a, b) => a + b, 0) / xs.length) : null);+ return {+ platforms,+ summary: {+ total: platforms.length,+ measurable: platforms.length - count('not_enough_data'),+ improved: count('improved'),+ declined: count('declined'),+ avgBefore: mean(ranked.map((p) => p.before.mentionPosition)),+ avgAfter: mean(ranked.map((p) => p.after.mentionPosition)),+ },+ };+}++/** When a completed action's tracking ends; null while it is open. */+export function trackingEndsAt(action) {+ if (action.status !== 'completed' || !action.completed_at) return null;+ return new Date(Date.parse(action.completed_at) + OUTCOME_TRACKING_DAYS * DAY_MS);+}++/**+ * Take today's read for one action and store it. A completed action past its+ * 30 days gets its final read, over the 7 days ending on day 30, and a+ * History event.+ */+export async function refreshImproveOutcome(action, { now = new Date() } = {}) {+ const baseline = action.baseline?.platforms ?? [];+ if (baseline.length === 0 || !action.payload?.promptId) return null;+ if (action.position_outcome?.final) return action.position_outcome;++ const ends = trackingEndsAt(action);+ const final = !!ends && ends <= now;+ const window = outcomeWindow(final ? ends : now);+ const current = await readPlatformStates({+ promptId: action.payload.promptId,+ brandId: action.brand_id,+ region: action.payload.region ?? null,+ platforms: baseline.map((p) => p.platform),+ window,+ });+ const outcome = {+ measuredAt: now.toISOString(),+ window,+ final,+ ...compareOutcome(baseline, current),+ };++ const { error } = await supabaseAdmin+ .from('actions')+ .update({ position_outcome: outcome })+ .eq('id', action.id);+ if (error) throw new Error(error.message);++ if (final) {+ await supabaseAdmin.from('action_events').insert({+ action_id: action.id,+ event: 'position_outcome_recorded',+ actor_id: null,+ data: {+ improved: outcome.summary.improved,+ declined: outcome.summary.declined,+ measurable: outcome.summary.measurable,+ total: outcome.summary.total,+ },+ });+ }+ return outcome;+}++/**+ * The daily refresh: every Improve action still open, and every completed one+ * whose final read hasn't been recorded. Dismissed actions are not tracked.+ * Final reads are left out by the query itself: they pile up over time and+ * would otherwise fill the limit before the actions still being tracked.+ */+export async function sweepImproveOutcomes({ now = new Date() } = {}) {+ const { data: actions, error } = await supabaseAdmin+ .from('actions')+ .select('id, brand_id, status, payload, baseline, completed_at, position_outcome')+ .eq('kind', 'prompt_improve')+ .in('status', [...OPEN, 'completed'])+ .or('position_outcome.is.null,position_outcome->>final.neq.true')+ .limit(1000);+ if (error) throw new Error(error.message);++ let refreshed = 0;+ for (const action of actions ?? []) {+ try {+ await refreshImproveOutcome(action, { now });+ refreshed += 1;+ } catch (err) {+ logger.warn({ err, actionId: action.id }, 'improve outcome refresh failed');+ }+ }+ logger.info({ refreshed }, 'improve outcomes refreshed');+ return { refreshed };+}diff --git a/server/src/lib/action-center/improve-outcome.test.js b/server/src/lib/action-center/improve-outcome.test.jsnew file mode 100644index 000000000..dff867d5b--- /dev/null+++ b/server/src/lib/action-center/improve-outcome.test.js@@ -0,0 +1,278 @@+import { describe, expect, it, vi } from 'vitest';++const from = vi.fn();+vi.mock('../../config/supabase.js', () => ({ default: { from: (...a) => from(...a) } }));+vi.mock('../logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++const {+ POSITION_CHANGE,+ compareOutcome,+ outcomeWindow,+ platformVerdict,+ refreshImproveOutcome,+ sweepImproveOutcomes,+ trackingEndsAt,+} = await import('./improve-outcome.js');++const snap = (platform, over = {}) => ({+ platform,+ state: 'mentioned_late',+ runs: 7,+ mentionedRuns: 7,+ citedRuns: 0,+ mentionPosition: 2,+ citationRank: null,+ ...over,+});++describe('platformVerdict', () => {+ it('is not enough data when either side had no runs', () => {+ expect(platformVerdict(snap('a', { runs: 0 }), snap('a'))).toBe('not_enough_data');+ expect(platformVerdict(snap('a'), snap('a', { runs: 0 }))).toBe('not_enough_data');+ expect(platformVerdict(snap('a'), null)).toBe('not_enough_data');+ });++ it('counts starting to be mentioned as improved, and dropping out as declined', () => {+ const missing = snap('a', { mentionedRuns: 0, mentionPosition: null, state: 'not_mentioned' });+ expect(platformVerdict(missing, snap('a'))).toBe('improved');+ expect(platformVerdict(snap('a'), missing)).toBe('declined');+ expect(platformVerdict(missing, missing)).toBe('unchanged');+ });++ it('uses the Improve tab rule: fewer than half the runs is still not mentioned', () => {+ const none = snap('a', {+ runs: 10,+ mentionedRuns: 0,+ mentionPosition: null,+ state: 'not_mentioned',+ });+ const oneInTen = snap('a', {+ runs: 10,+ mentionedRuns: 1,+ mentionPosition: 1,+ state: 'not_mentioned',+ });+ const half = snap('a', { runs: 10, mentionedRuns: 5, mentionPosition: 3 });+ expect(platformVerdict(none, oneInTen)).toBe('unchanged');+ expect(platformVerdict(oneInTen, none)).toBe('unchanged');+ expect(platformVerdict(oneInTen, half)).toBe('improved');+ expect(platformVerdict(half, oneInTen)).toBe('declined');+ });++ it(`needs the position to move at least ${POSITION_CHANGE}`, () => {+ expect(+ platformVerdict(snap('a', { mentionPosition: 2 }), snap('a', { mentionPosition: 1.2 })),+ ).toBe('improved');+ expect(+ platformVerdict(snap('a', { mentionPosition: 2 }), snap('a', { mentionPosition: 1.6 })),+ ).toBe('unchanged');+ expect(+ platformVerdict(snap('a', { mentionPosition: 2 }), snap('a', { mentionPosition: 2.5 })),+ ).toBe('declined');+ });+});++describe('compareOutcome', () => {+ it('pairs each baseline platform with its read and counts the verdicts', () => {+ const result = compareOutcome(+ [+ snap('google-aimode'),+ snap('chatgpt-web', { mentionPosition: 3 }),+ snap('gemini-web', { runs: 0 }),+ ],+ [+ snap('google-aimode', { mentionPosition: 1.2 }),+ snap('chatgpt-web', { mentionPosition: 3.2 }),+ snap('gemini-web', { runs: 0 }),+ ],+ );+ expect(result.platforms.map((p) => [p.platform, p.verdict])).toEqual([+ ['google-aimode', 'improved'],+ ['chatgpt-web', 'unchanged'],+ ['gemini-web', 'not_enough_data'],+ ]);+ expect(result.summary).toEqual({+ total: 3,+ measurable: 2,+ improved: 1,+ declined: 0,+ avgBefore: 2.5,+ avgAfter: 2.2,+ });+ });++ it('leaves a not-mentioned side out of the position delta', () => {+ const result = compareOutcome(+ [+ snap('chatgpt-web', {+ runs: 10,+ mentionedRuns: 1,+ mentionPosition: 1,+ state: 'not_mentioned',+ }),+ ],+ [snap('chatgpt-web', { runs: 10, mentionedRuns: 8, mentionPosition: 3 })],+ );+ expect(result.platforms[0].verdict).toBe('improved');+ expect(result.summary).toMatchObject({ avgBefore: null, avgAfter: null });+ });+});++describe('windows', () => {+ it('reads the 7 days ending at the moment of the read', () => {+ expect(outcomeWindow(new Date('2026-10-13T10:00:00.000Z'))).toEqual({+ from: '2026-10-06T10:00:00.000Z',+ to: '2026-10-13T10:00:00.000Z',+ });+ });++ it('tracks a completed action for 30 days; an open one has no end', () => {+ expect(trackingEndsAt({ status: 'in_progress', completed_at: null })).toBeNull();+ expect(+ trackingEndsAt({+ status: 'completed',+ completed_at: '2026-10-01T00:00:00.000Z',+ }).toISOString(),+ ).toBe('2026-10-31T00:00:00.000Z');+ });+});++/** actions, prompt_results, brand_domains, and the writes a refresh makes. */+function mockDb(results, { actions = [] } = {}) {+ const writes = { updated: [], inserted: [], windows: [], filters: [] };+ from.mockImplementation((table) => {+ const b = {+ select: () => b,+ eq: () => b,+ in: (column, values) => {+ writes.filters.push({ table, in: [column, values] });+ return b;+ },+ or: (filter) => {+ writes.filters.push({ table, or: filter });+ return b;+ },+ gte: (_c, v) => {+ writes.windows.push(v);+ return b;+ },+ lte: () => b,+ limit: () => Promise.resolve({ data: table === 'actions' ? actions : results, error: null }),+ update: (patch) => {+ writes.updated.push(patch);+ return { eq: () => Promise.resolve({ error: null }) };+ },+ insert: (row) => {+ writes.inserted.push({ table, row });+ return Promise.resolve({ error: null });+ },+ then: (resolve) => resolve({ data: table === 'brand_domains' ? [] : results, error: null }),+ };+ return b;+ });+ return writes;+}++const action = (over = {}) => ({+ id: 'a1',+ brand_id: 'b1',+ status: 'in_progress',+ completed_at: null,+ payload: { promptId: 'p1', region: null },+ baseline: { platforms: [snap('chatgpt-web', { mentionPosition: 3 })] },+ position_outcome: null,+ ...over,+});++const row = (position) => ({+ platform: 'chatgpt-web',+ mention_count: 1,+ mention_position: position,+ mentioned_entity_count: 5,+ citations: [],+});++describe('refreshImproveOutcome', () => {+ it('stores today’s 7-day read next to the baseline while the action is open', async () => {+ const writes = mockDb([row(1), row(2)]);+ const now = new Date('2026-10-20T06:00:00.000Z');+ const outcome = await refreshImproveOutcome(action(), { now });+ expect(outcome.final).toBe(false);+ expect(outcome.window.to).toBe(now.toISOString());+ expect(outcome.platforms[0]).toMatchObject({ verdict: 'improved' });+ expect(outcome.platforms[0].after).toMatchObject({ runs: 2, mentionPosition: 1.5 });+ expect(writes.updated).toHaveLength(1);+ expect(writes.inserted).toHaveLength(0);+ });++ it('keeps 1 mention in 10 runs as not mentioned, like the Improve tab', async () => {+ mockDb([row(1), ...Array.from({ length: 9 }, () => ({ ...row(null), mention_count: 0 }))]);+ const outcome = await refreshImproveOutcome(+ action({+ baseline: {+ platforms: [+ snap('chatgpt-web', {+ runs: 10,+ mentionedRuns: 0,+ mentionPosition: null,+ state: 'not_mentioned',+ }),+ ],+ },+ }),+ { now: new Date('2026-10-20T06:00:00.000Z') },+ );+ expect(outcome.platforms[0].after).toMatchObject({+ runs: 10,+ mentionedRuns: 1,+ state: 'not_mentioned',+ });+ expect(outcome.platforms[0].verdict).toBe('unchanged');+ expect(outcome.summary.improved).toBe(0);+ });++ it('records the final read in History 30 days after completion, over the 7 days ending then', async () => {+ const writes = mockDb([row(1)]);+ const outcome = await refreshImproveOutcome(+ action({ status: 'completed', completed_at: '2026-09-01T00:00:00.000Z' }),+ { now: new Date('2026-10-13T06:00:00.000Z') },+ );+ expect(outcome.final).toBe(true);+ expect(outcome.window).toEqual({+ from: '2026-09-24T00:00:00.000Z',+ to: '2026-10-01T00:00:00.000Z',+ });+ expect(writes.inserted[0]).toMatchObject({+ table: 'action_events',+ row: {+ event: 'position_outcome_recorded',+ data: { improved: 1, declined: 0, measurable: 1, total: 1 },+ },+ });+ });++ it('leaves a final outcome alone', async () => {+ const writes = mockDb([]);+ const done = { final: true, summary: {} };+ expect(await refreshImproveOutcome(action({ position_outcome: done }))).toBe(done);+ expect(writes.updated).toHaveLength(0);+ });+});++describe('sweepImproveOutcomes', () => {+ it('leaves final reads out of the query, so they never fill the limit', async () => {+ const writes = mockDb([row(1)], { actions: [action({ id: 'a1' }), action({ id: 'a2' })] });+ const result = await sweepImproveOutcomes({ now: new Date('2026-10-20T06:00:00.000Z') });+ const query = writes.filters.filter((f) => f.table === 'actions');+ expect(query).toContainEqual({+ table: 'actions',+ in: ['status', ['new', 'in_progress', 'on_hold', 'completed']],+ });+ expect(query).toContainEqual({+ table: 'actions',+ or: 'position_outcome.is.null,position_outcome->>final.neq.true',+ });+ expect(result).toEqual({ refreshed: 2 });+ expect(writes.updated).toHaveLength(2);+ });+});diff --git a/server/src/server.js b/server/src/server.jsindex 001eee828..9c2205105 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -23,6 +23,7 @@ import { runTrackingJob, recoverWaitingJobs } from './lib/job-runner.js';import { sweepInsightsRollups } from './lib/insights-rollups.js';import { rebuildQueuedCitationRollups, REBUILD_QUEUE_SCHEDULE } from './lib/citations-rollups.js';import { sweepActionValidation } from './lib/action-center/validate.js';+import { sweepImproveOutcomes } from './lib/action-center/improve-outcome.js';import { parseScraperResponse } from './lib/cloro-scraper.js';import { handleScraperResult } from './lib/cloro-result-handler.js';import { verifyCloroWebhook } from './lib/cloro-webhook-verify.js';@@ -165,6 +166,12 @@ async function runDailyTracking() {logger.error({ err }, '[action-validation] daily sweep crashed');});+ // Today's 7-day positions for every Improve action still being tracked+ // (PROMPT-008): the Outcome card, the Positions panel and History read them.+ sweepImproveOutcomes().catch((err) => {+ logger.error({ err }, '[improve-outcome] daily sweep crashed');+ });+// Skip paused brands (is_active = false): the user has explicitly suspended// tracking for them, so they should not spend Cloro / LLM credits daily.const { data: brands, error } = await supabaseAdmindiff --git a/supabase/migrations/00124_prompt_improve_outcome.sql b/supabase/migrations/00124_prompt_improve_outcome.sqlnew file mode 100644index 000000000..cd4a18ef8--- /dev/null+++ b/supabase/migrations/00124_prompt_improve_outcome.sql@@ -0,0 +1,38 @@+-- Did an Improve action move the prompt's positions? (PROMPT-008)+--+-- actions.baseline already holds the prompt's last 7 days per platform at+-- send time (from-prompt-improve.js). position_outcome is the same 7-day read+-- taken again every day while the action is open and for 30 days after it is+-- completed (improve-outcome.js), shown by the action's Outcome card, the+-- Positions panel and History:+--+-- { measuredAt, window: { from, to }, final,+-- platforms: [{ platform, before, after, verdict }],+-- summary: { total, measurable, improved, declined, avgBefore, avgAfter } }+--+-- verdict is improved | declined | unchanged | not_enough_data. final is true+-- for the read at day 30 after completion, which is not refreshed again.+alter table public.actions add column if not exists position_outcome jsonb;++comment on column public.actions.position_outcome is+ 'Improve actions (PROMPT-008): the latest 7-day positions per platform next to the baseline, refreshed daily until 30 days after completion. Null for other kinds.';++-- The baseline is what the outcome is measured against, so it is fixed once+-- the action exists. Enforced here rather than trusted to every writer.+create or replace function public.actions_keep_improve_baseline()+returns trigger+language plpgsql+set search_path = public+as $$+begin+ if old.kind = 'prompt_improve' and new.baseline is distinct from old.baseline then+ raise exception 'The baseline of an Improve action cannot be changed';+ end if;+ return new;+end;+$$;++drop trigger if exists actions_keep_improve_baseline on public.actions;+create trigger actions_keep_improve_baseline+ before update of baseline on public.actions+ for each row execute function public.actions_keep_improve_baseline();diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 8b0f4d966..9474a6eef 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -14484,6 +14484,48 @@ comment on functionpublic.prompt_position_summaries(uuid, timestamptz, timestamptz, text) is'Per-prompt, per-platform mention position sums for the Tracked Prompts Positions column (PROMPT-007). Sums, not averages, so platforms combine exactly.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00124_prompt_improve_outcome.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Did an Improve action move the prompt's positions? (PROMPT-008)+--+-- actions.baseline already holds the prompt's last 7 days per platform at+-- send time (from-prompt-improve.js). position_outcome is the same 7-day read+-- taken again every day while the action is open and for 30 days after it is+-- completed (improve-outcome.js), shown by the action's Outcome card, the+-- Positions panel and History:+--+-- { measuredAt, window: { from, to }, final,+-- platforms: [{ platform, before, after, verdict }],+-- summary: { total, measurable, improved, declined, avgBefore, avgAfter } }+--+-- verdict is improved | declined | unchanged | not_enough_data. final is true+-- for the read at day 30 after completion, which is not refreshed again.+alter table public.actions add column if not exists position_outcome jsonb;++comment on column public.actions.position_outcome is+ 'Improve actions (PROMPT-008): the latest 7-day positions per platform next to the baseline, refreshed daily until 30 days after completion. Null for other kinds.';++-- The baseline is what the outcome is measured against, so it is fixed once+-- the action exists. Enforced here rather than trusted to every writer.+create or replace function public.actions_keep_improve_baseline()+returns trigger+language plpgsql+set search_path = public+as $$+begin+ if old.kind = 'prompt_improve' and new.baseline is distinct from old.baseline then+ raise exception 'The baseline of an Improve action cannot be changed';+ end if;+ return new;+end;+$$;++drop trigger if exists actions_keep_improve_baseline on public.actions;+create trigger actions_keep_improve_baseline+ before update of baseline on public.actions+ for each row execute function public.actions_keep_improve_baseline();+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00125_opportunity_usage.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 14a3ba23f..170b6058f 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -712,7 +712,8 @@"task_status": "Task updated","task_ran": "{task} — carried out automatically ({tool})","task_run_failed": "{task} — the automatic attempt failed; it needs doing by hand",- "task_awaiting_approval": "{task} — waiting for your approval before it reaches outside Ansvisor"+ "task_awaiting_approval": "{task} — waiting for your approval before it reaches outside Ansvisor",+ "position_outcome_recorded": "{measurable, plural, =0 {30-day result: not enough data to compare positions} other {30-day result: position improved on {improved} of # platforms}}"},"taskText": "Task text","renameTask": "Rename task",@@ -751,6 +752,29 @@"not_cited": "Mentioned early · not cited","doing_well": "Doing well","no_runs": "No runs"+ },+ "outcome": {+ "title": "Outcome",+ "summary": "{measurable, plural, =0 {Not enough data to compare yet} other {Position improved on {improved} of # platforms}}",+ "updated": "Updated {date}",+ "final": "Final result · {date}",+ "platform": "Platform",+ "before": "Before",+ "after": "Last 7 days",+ "afterFinal": "Day 30",+ "reads": {+ "not_mentioned": "Not mentioned",+ "mentioned": "Mentioned",+ "no_runs": "No runs"+ },+ "verdicts": {+ "improved": "Improved",+ "declined": "Declined",+ "unchanged": "No meaningful change",+ "not_enough_data": "Not enough data"+ },+ "note": "Before is the 7 days before this action was sent. The latest 7 days are re-read daily while the action is open and for 30 days after it's completed. A position counts as changed when it moves at least 0.5.",+ "noteFinal": "The 7 days before this action was sent, next to the 7 days ending 30 days after it was completed. A position counts as changed when it moves at least 0.5."}}}@@ -1429,6 +1453,7 @@"title": "No brand selected","description": "Select a brand to view its action history."},+ "positionResult": "{measurable, plural, =0 {Positions: not enough data} other {Position improved on {improved} of # platforms}}","outcomeHint": {"pending_measurement": "no result recorded","improved": "vs before",diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex 7b49c6da2..e9929e03c 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -60,6 +60,8 @@ import { ImpactDots, isSuperseded, SignalStatusBadge } from './signal-table';import { ActionIcon } from './action-table';import { OpportunityContext } from './opportunity-context';import { ImproveContext } from './improve-context';+import { ImproveOutcomeCard } from './improve-outcome-card';+import { improvePlatformLabels } from '@/lib/improve-outcome';import { cn } from '@/lib/utils';type DrawerTab = 'overview' | 'tasks' | 'signals' | 'history';@@ -249,7 +251,18 @@ export function ActionDrawer({</section><Separator />{action.kind === 'prompt_improve' ? (- <ImproveContext payload={action.payload ?? {}} />+ <>+ {detail.positionOutcome && (+ <>+ <ImproveOutcomeCard+ outcome={detail.positionOutcome}+ labels={improvePlatformLabels(action.payload)}+ />+ <Separator />+ </>+ )}+ <ImproveContext payload={action.payload ?? {}} />+ </>) : opportunityId ? (<OpportunityContextopportunityId={opportunityId}@@ -366,6 +379,8 @@ export function ActionDrawer({// translated.task: eventTaskText(event.data.task, tTasks),tool: String(event.data.tool ?? ''),+ improved: Number(event.data.improved ?? 0),+ measurable: Number(event.data.measurable ?? 0),})}</p><p className="text-xs text-muted-foreground">diff --git a/web/src/components/action-center/history-drawer.tsx b/web/src/components/action-center/history-drawer.tsxindex f094e629f..1af98e083 100644--- a/web/src/components/action-center/history-drawer.tsx+++ b/web/src/components/action-center/history-drawer.tsx@@ -18,6 +18,8 @@ import { UNCOUNTED_TASK_STATUSES } from '@/lib/action-center/registry';import { ImpactDots } from './signal-table';import { ActionIcon } from './action-table';import { HistoryStatusBadge } from './history-table';+import { ImproveOutcomeCard } from './improve-outcome-card';+import { improvePlatformLabels } from '@/lib/improve-outcome';import { cn } from '@/lib/utils';/**@@ -194,6 +196,16 @@ export function HistoryDrawer({<Separator />+ {item.positionOutcome && (+ <>+ <ImproveOutcomeCard+ outcome={item.positionOutcome}+ labels={improvePlatformLabels(item.payload)}+ />+ <Separator />+ </>+ )}+<section><p className="text-xs font-medium text-muted-foreground">{t('drawer.affected')}</p>{item.affected.length > 0 ? (diff --git a/web/src/components/action-center/history-table.tsx b/web/src/components/action-center/history-table.tsxindex f3e630d43..c64103cbe 100644--- a/web/src/components/action-center/history-table.tsx+++ b/web/src/components/action-center/history-table.tsx@@ -57,9 +57,28 @@ function ResultCell({ item }: { item: ActionHistoryItem }) {const tOutcome = useTranslations('actionCenter.actionOutcome');const tRegistry = useTranslations('actionCenter.registry');+ // An Improve action's 30-day position result (PROMPT-008) leads the cell.+ const outcome = item.positionOutcome?.final ? item.positionOutcome : null;+ const position = outcome && (+ <p+ className={cn(+ 'text-xs',+ outcome.summary.improved > 0+ ? 'text-emerald-600 dark:text-emerald-400'+ : 'text-muted-foreground',+ )}+ >+ {t('positionResult', {+ improved: outcome.summary.improved,+ measurable: outcome.summary.measurable,+ })}+ </p>+ );+if (item.results.length > 0) {return (<div className="space-y-0.5">+ {position}{item.results.slice(0, 2).map((metric) => (<pkey={metric.id}@@ -80,6 +99,8 @@ function ResultCell({ item }: { item: ActionHistoryItem }) {);}+ if (position) return <div className="space-y-0.5">{position}</div>;+return (<div className="space-y-0.5"><p className="text-xs text-muted-foreground">{tOutcome(item.outcome)}</p>diff --git a/web/src/components/action-center/improve-outcome-card.tsx b/web/src/components/action-center/improve-outcome-card.tsxnew file mode 100644index 000000000..23b1249d5--- /dev/null+++ b/web/src/components/action-center/improve-outcome-card.tsx@@ -0,0 +1,102 @@+'use client';++import { useTranslations } from 'next-intl';+import { ArrowRight, Check, Minus, X } from 'lucide-react';+import { cn } from '@/lib/utils';+import {+ readLabel,+ type ImproveOutcome,+ type OutcomeVerdict,+ type PlatformRead,+} from '@/lib/improve-outcome';++const VERDICT_CLASS: Record<OutcomeVerdict, string> = {+ improved: 'text-emerald-600 dark:text-emerald-400',+ declined: 'text-red-600 dark:text-red-400',+ unchanged: 'text-muted-foreground',+ not_enough_data: 'text-muted-foreground',+};++const DATE_FMT = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric' });++/**+ * Did the Improve action move the prompt's positions? (PROMPT-008) The+ * prompt's 7 days before it was sent next to its latest 7 days, per platform,+ * refreshed daily by the server and fixed 30 days after completion.+ */+export function ImproveOutcomeCard({+ outcome,+ labels,+}: {+ outcome: ImproveOutcome;+ /** Platform id → name, from the action's payload. */+ labels: Record<string, string>;+}) {+ const t = useTranslations('actionCenter.actionsPage.drawer.improve.outcome');++ const read = (r: PlatformRead | null) => {+ const label = readLabel(r);+ if (label.kind === 'position') return label.value;+ return t(`reads.${label.kind}`);+ };++ return (+ <section>+ <div className="flex items-baseline justify-between gap-2">+ <p className="text-xs font-medium text-muted-foreground">{t('title')}</p>+ <p className="text-xs text-muted-foreground">+ {t(outcome.final ? 'final' : 'updated', {+ date: DATE_FMT.format(new Date(outcome.measuredAt)),+ })}+ </p>+ </div>+ <p className="mt-1 text-sm font-medium">+ {t('summary', {+ improved: outcome.summary.improved,+ measurable: outcome.summary.measurable,+ })}+ </p>+ <div className="mt-2 divide-y rounded-md border">+ <div className="grid grid-cols-[1fr_auto] gap-2 px-3 py-1.5 text-[11px] text-muted-foreground">+ <span>{t('platform')}</span>+ <span>+ {t('before')} → {t(outcome.final ? 'afterFinal' : 'after')}+ </span>+ </div>+ {outcome.platforms.map((p) => (+ <div+ key={p.platform}+ className="grid grid-cols-[1fr_auto] items-center gap-2 px-3 py-2 text-xs"+ >+ <span className="truncate font-medium">{labels[p.platform] ?? p.platform}</span>+ {p.verdict === 'not_enough_data' ? (+ <span className="text-muted-foreground">{t('verdicts.not_enough_data')}</span>+ ) : (+ <span className="inline-flex items-center gap-1.5 tabular-nums">+ <span className="text-muted-foreground">{read(p.before)}</span>+ <ArrowRight className="h-3 w-3 text-muted-foreground" />+ <span className="font-medium">{read(p.after)}</span>+ <span+ className={cn('inline-flex items-center', VERDICT_CLASS[p.verdict])}+ title={t(`verdicts.${p.verdict}`)}+ aria-label={t(`verdicts.${p.verdict}`)}+ >+ {p.verdict === 'improved' ? (+ <Check className="h-3.5 w-3.5" />+ ) : p.verdict === 'declined' ? (+ <X className="h-3.5 w-3.5" />+ ) : (+ <Minus className="h-3.5 w-3.5" />+ )}+ </span>+ </span>+ )}+ </div>+ ))}+ </div>+ <p className="mt-2 text-[11px] text-muted-foreground">+ {t(outcome.final ? 'noteFinal' : 'note')}+ </p>+ </section>+ );+}diff --git a/web/src/components/prompts/prompt-positions-sheet.tsx b/web/src/components/prompts/prompt-positions-sheet.tsxindex 1d0a9f295..19070adba 100644--- a/web/src/components/prompts/prompt-positions-sheet.tsx+++ b/web/src/components/prompts/prompt-positions-sheet.tsx@@ -19,6 +19,7 @@ import {ExternalLink,MessageSquareText,RefreshCw,+ TrendingUp,} from 'lucide-react';import { Link } from '@/i18n/navigation';import {@@ -53,6 +54,7 @@ import type {PositionStats,} from '@/lib/prompt-positions';import type { Sentiment } from '@/types';+import { actionCenterLink } from '@/lib/prompt-improve';export type { PositionsRange } from '@/lib/positions-range';@@ -210,6 +212,26 @@ export function PromptPositionsSheet({{data.prompt.topicName}</Badge>)}+ {data.improving && (+ // An Improve action sent for this prompt is still being+ // tracked (PROMPT-008): the delta is the mean position over+ // its platforms, 7 days before it was sent → the last 7 days.+ <Link+ href={actionCenterLink(data.improving.actionId)}+ title="Open the action and its Outcome"+ className="inline-flex h-5 items-center gap-1 rounded-4xl border border-primary/30 bg-primary/5 px-2 text-[11px] font-medium text-primary transition-colors hover:bg-primary/10"+ >+ <TrendingUp className="h-3 w-3" />+ Improving · AC-{data.improving.actionNo}+ {data.improving.avgBefore !== null && data.improving.avgAfter !== null && (+ <span className="tabular-nums">+ {' '}+ · #{data.improving.avgBefore.toFixed(1)} → #+ {data.improving.avgAfter.toFixed(1)}+ </span>+ )}+ </Link>+ )}</div>)}<SheetDescription className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">diff --git a/web/src/lib/action-center/history.ts b/web/src/lib/action-center/history.tsindex 46d55f71d..2946f9407 100644--- a/web/src/lib/action-center/history.ts+++ b/web/src/lib/action-center/history.ts@@ -31,6 +31,7 @@ import type {TaskStatus,} from './registry';import type { SignalSource } from '@/lib/signals/registry';+import type { ImproveOutcome } from '@/lib/improve-outcome';/** A metric an action moved, read before and after it ran. */export interface ActionResultMetric {@@ -101,6 +102,8 @@ export interface ActionHistoryItem {affected: AffectedEntity[];/** Empty until something measures an action's effect. */results: ActionResultMetric[];+ /** Improve actions only: positions per platform against the baseline (PROMPT-008). */+ positionOutcome: ImproveOutcome | null;tasks: ActionHistoryTask[];assignee: { id: string; fullName: string | null; avatarUrl: string | null } | null;createdAt: string;diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex d5104633a..a3b06b4cb 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -20,6 +20,7 @@ import {} from '@/lib/action-center/registry';import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';import type { KpiTimeframe } from '@/lib/kpis/registry';+import { parseImproveOutcome, type ImproveOutcome } from '@/lib/improve-outcome';export interface ActionAssignee {id: string;@@ -193,6 +194,8 @@ export interface ActionDetail {signals: Signal[];events: ActionEvent[];kpis: ActionKpiRef[];+ /** Improve actions only: positions now next to the baseline (PROMPT-008). */+ positionOutcome: ImproveOutcome | null;}/** Everything the drawer's tabs need beyond the list row, in one round trip@@ -200,7 +203,7 @@ export interface ActionDetail {* action's kpi_keys — evidence of which goals this work serves. */export async function getActionDetail(brandId: string, actionId: string): Promise<ActionDetail> {const supabase = await createClient();- const [tasksRes, signalsRes, eventsRes, kpisRes] = await Promise.all([+ const [tasksRes, signalsRes, eventsRes, kpisRes, outcomeRes] = await Promise.all([supabase.from('action_tasks').select(@@ -224,6 +227,12 @@ export async function getActionDetail(brandId: string, actionId: string): Promis.select('kpi_key, target, timeframe').eq('brand_id', brandId).eq('is_active', true),+ supabase+ .from('actions')+ .select('position_outcome')+ .eq('brand_id', brandId)+ .eq('id', actionId)+ .maybeSingle(),]);if (tasksRes.error) throw new Error(tasksRes.error.message);if (signalsRes.error) throw new Error(signalsRes.error.message);@@ -255,6 +264,7 @@ export async function getActionDetail(brandId: string, actionId: string): Promistarget: Number(kpi.target),timeframe: kpi.timeframe as KpiTimeframe,})),+ positionOutcome: parseImproveOutcome(outcomeRes.data?.position_outcome ?? null),};}diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.tsindex 0d2fbd919..4fe0809c6 100644--- a/web/src/lib/actions/action-history.ts+++ b/web/src/lib/actions/action-history.ts@@ -18,6 +18,7 @@ import { createClient } from '@/lib/supabase/server';import type { ActionCategory, ActionImpact } from '@/lib/action-center/registry';import type { ActionOutcome, ActionStatus, TaskStatus } from '@/lib/action-center/registry';import { SIGNAL_SOURCES, type SignalSource } from '@/lib/signals/registry';+import { parseImproveOutcome } from '@/lib/improve-outcome';import {HISTORY_STATUSES,daysBetween,@@ -37,6 +38,7 @@ interface HistoryRow {status: string;outcome: string;validation: ValidationSnapshot | null;+ position_outcome: unknown;payload: Record<string, unknown>;kpi_keys: string[];assignee_id: string | null;@@ -46,7 +48,7 @@ interface HistoryRow {}const HISTORY_COLUMNS =- 'id, action_no, category, kind, impact, status, outcome, validation, payload, kpi_keys, assignee_id, created_at, completed_at, updated_at';+ 'id, action_no, category, kind, impact, status, outcome, validation, position_outcome, payload, kpi_keys, assignee_id, created_at, completed_at, updated_at';/** What the validation sweep stores on an action. */interface ValidationSnapshot {@@ -244,6 +246,7 @@ export async function getActionHistory(impact: row.impact as ActionImpact,status: row.status as ActionStatus,outcome: row.outcome as ActionOutcome,+ positionOutcome: parseImproveOutcome(row.position_outcome ?? null),payload: row.payload ?? {},kpiKeys: row.kpi_keys ?? [],sources: [...(sourcesByAction.get(row.id) ?? [])],diff --git a/web/src/lib/actions/prompt-positions.ts b/web/src/lib/actions/prompt-positions.tsindex 7399b9f22..1947fe9bf 100644--- a/web/src/lib/actions/prompt-positions.ts+++ b/web/src/lib/actions/prompt-positions.ts@@ -14,6 +14,7 @@ import {} from '@/lib/prompt-positions';import { isTimeZone } from '@/lib/time-zone';import type { Sentiment } from '@/types';+import { pickImprovingAction, type ImprovingAction } from '@/lib/improve-outcome';export interface PromptPositionsData {prompt: { id: string; text: string; topicName: string | null; isActive: boolean };@@ -21,6 +22,8 @@ export interface PromptPositionsData {window: { from: string; to: string };summary: PositionsSummary;platforms: PlatformPositions[];+ /** An Improve action sent for this prompt that is still tracked (PROMPT-008). */+ improving: ImprovingAction | null;}/** 90 days × 8 engines × a few locations, with room to spare. */@@ -67,13 +70,22 @@ export async function getPromptPositions(const brandId = promptSet?.brand_id as string | undefined;if (!brandId) return null;- const [{ data: brand }, { data: domainRows }, { data: topic }] = await Promise.all([- supabase.from('brands').select('organization_id').eq('id', brandId).maybeSingle(),- supabase.from('brand_domains').select('domain').eq('brand_id', brandId),- prompt.topic_id- ? supabase.from('topics').select('name').eq('id', prompt.topic_id).maybeSingle()- : Promise.resolve({ data: null }),- ]);+ const [{ data: brand }, { data: domainRows }, { data: topic }, { data: improveRows }] =+ await Promise.all([+ supabase.from('brands').select('organization_id').eq('id', brandId).maybeSingle(),+ supabase.from('brand_domains').select('domain').eq('brand_id', brandId),+ prompt.topic_id+ ? supabase.from('topics').select('name').eq('id', prompt.topic_id).maybeSingle()+ : Promise.resolve({ data: null }),+ supabase+ .from('actions')+ .select('id, action_no, status, position_outcome')+ .eq('brand_id', brandId)+ .eq('kind', 'prompt_improve')+ .eq('payload->>promptId', promptId)+ .order('created_at', { ascending: false })+ .limit(10),+ ]);if (!brand?.organization_id) return null;const plan = await getOrgPlan(brand.organization_id as string);@@ -158,5 +170,6 @@ export async function getPromptPositions(window,summary,platforms: rowsByPlatform,+ improving: pickImprovingAction(improveRows ?? []),};}diff --git a/web/src/lib/improve-outcome.test.ts b/web/src/lib/improve-outcome.test.tsnew file mode 100644index 000000000..02ea83224--- /dev/null+++ b/web/src/lib/improve-outcome.test.ts@@ -0,0 +1,119 @@+/**+ * improve-outcome.test.ts (PROMPT-008)+ *+ * Reading an Improve action's stored position outcome.+ */++import { describe, expect, test } from 'vitest';+import {+ improvePlatformLabels,+ parseImproveOutcome,+ pickImprovingAction,+ readLabel,+ type PlatformRead,+} from './improve-outcome';++const read = (over: Partial<PlatformRead> = {}): PlatformRead => ({+ platform: 'google-aimode',+ state: 'mentioned_late',+ runs: 7,+ mentionedRuns: 7,+ mentionPosition: 2,+ ...over,+});++const stored = {+ measuredAt: '2026-10-14T06:00:00.000Z',+ window: { from: '2026-10-07T06:00:00.000Z', to: '2026-10-14T06:00:00.000Z' },+ final: false,+ platforms: [+ {+ platform: 'google-aimode',+ before: read(),+ after: read({ mentionPosition: 1.2 }),+ verdict: 'improved',+ },+ { platform: 'gemini-web', before: read({ runs: 0 }), after: null, verdict: 'not_enough_data' },+ ],+ summary: { total: 2, measurable: 1, improved: 1, declined: 0, avgBefore: 2, avgAfter: 1.2 },+};++describe('parseImproveOutcome', () => {+ test('reads the stored outcome', () => {+ const outcome = parseImproveOutcome(stored);+ expect(outcome?.platforms.map((p) => p.verdict)).toEqual(['improved', 'not_enough_data']);+ expect(outcome?.summary.improved).toBe(1);+ });++ test('null when missing or not an outcome', () => {+ expect(parseImproveOutcome(null)).toBeNull();+ expect(parseImproveOutcome({})).toBeNull();+ });++ test('drops rows with an unknown verdict instead of guessing', () => {+ const outcome = parseImproveOutcome({+ ...stored,+ platforms: [...stored.platforms, { ...stored.platforms[0], verdict: 'great' }],+ });+ expect(outcome?.platforms).toHaveLength(2);+ });+});++describe('readLabel', () => {+ test('a position, not mentioned, mentioned without a position, or no runs', () => {+ expect(readLabel(read({ mentionPosition: 1.24 }))).toEqual({ kind: 'position', value: '#1.2' });+ expect(readLabel(read({ mentionedRuns: 0, mentionPosition: null }))).toEqual({+ kind: 'not_mentioned',+ });+ expect(+ readLabel(read({ runs: 10, mentionedRuns: 1, mentionPosition: 1, state: 'not_mentioned' })),+ ).toEqual({ kind: 'not_mentioned' });+ expect(readLabel(read({ mentionPosition: null }))).toEqual({ kind: 'mentioned' });+ expect(readLabel(read({ runs: 0 }))).toEqual({ kind: 'no_runs' });+ expect(readLabel(null)).toEqual({ kind: 'no_runs' });+ });+});++describe('improvePlatformLabels', () => {+ test('maps the payload platforms to their names', () => {+ expect(+ improvePlatformLabels({+ platforms: [+ { id: 'google-aimode', label: 'Google AI Mode', state: 'mentioned_late' },+ { id: 1 },+ ],+ }),+ ).toEqual({ 'google-aimode': 'Google AI Mode' });+ expect(improvePlatformLabels(null)).toEqual({});+ });+});++describe('pickImprovingAction', () => {+ const row = (over: Record<string, unknown> = {}) => ({+ id: 'a1',+ action_no: 61,+ status: 'in_progress',+ position_outcome: stored,+ ...over,+ });++ test('the newest tracked action, with the delta across platforms', () => {+ expect(pickImprovingAction([row()])).toEqual({+ actionId: 'a1',+ actionNo: 61,+ avgBefore: 2,+ avgAfter: 1.2,+ });+ });++ test('skips dismissed actions and ones whose 30 days are over', () => {+ expect(+ pickImprovingAction([+ row({ id: 'd', status: 'dismissed' }),+ row({ id: 'f', status: 'completed', position_outcome: { ...stored, final: true } }),+ row({ id: 'c', status: 'completed' }),+ ])?.actionId,+ ).toBe('c');+ expect(pickImprovingAction([row({ status: 'dismissed' })])).toBeNull();+ });+});diff --git a/web/src/lib/improve-outcome.ts b/web/src/lib/improve-outcome.tsnew file mode 100644index 000000000..6d5fa8971--- /dev/null+++ b/web/src/lib/improve-outcome.ts@@ -0,0 +1,126 @@+/**+ * An Improve action's position outcome (PROMPT-008), as the server's daily+ * sweep stores it on `actions.position_outcome` (improve-outcome.js): the+ * prompt's last 7 days per platform next to the baseline taken at send time.+ *+ * Pure on purpose: the Outcome card, the Positions panel and History all read+ * the same stored value through these helpers.+ */++export type OutcomeVerdict = 'improved' | 'declined' | 'unchanged' | 'not_enough_data';++/** One 7-day read of one platform. */+export interface PlatformRead {+ platform: string;+ state: string;+ runs: number;+ mentionedRuns: number;+ mentionPosition: number | null;+}++export interface OutcomePlatform {+ platform: string;+ before: PlatformRead;+ after: PlatformRead | null;+ verdict: OutcomeVerdict;+}++export interface ImproveOutcome {+ measuredAt: string;+ window: { from: string; to: string };+ /** The read 30 days after completion; it is not refreshed again. */+ final: boolean;+ platforms: OutcomePlatform[];+ summary: {+ total: number;+ measurable: number;+ improved: number;+ declined: number;+ /** Mean position over the platforms ranked on both sides. */+ avgBefore: number | null;+ avgAfter: number | null;+ };+}++const VERDICTS: OutcomeVerdict[] = ['improved', 'declined', 'unchanged', 'not_enough_data'];++const isRead = (v: unknown): v is PlatformRead =>+ !!v && typeof v === 'object' && typeof (v as PlatformRead).platform === 'string';++/** The stored JSON, or null when it is missing or not the shape this build reads. */+export function parseImproveOutcome(value: unknown): ImproveOutcome | null {+ if (!value || typeof value !== 'object') return null;+ const v = value as Partial<ImproveOutcome>;+ if (typeof v.measuredAt !== 'string' || !Array.isArray(v.platforms) || !v.summary) return null;+ const platforms = v.platforms.filter(+ (p): p is OutcomePlatform =>+ !!p &&+ typeof p.platform === 'string' &&+ isRead(p.before) &&+ (p.after === null || isRead(p.after)) &&+ VERDICTS.includes(p.verdict),+ );+ return { ...(v as ImproveOutcome), final: !!v.final, platforms };+}++/** How one side of a row reads: "#2.0", "Not mentioned", "Mentioned" or "No runs". */+export type ReadLabel =+ | { kind: 'position'; value: string }+ | { kind: 'not_mentioned' }+ | { kind: 'mentioned' }+ | { kind: 'no_runs' };++/**+ * "Not mentioned" follows the Improve tab's rule, as the verdict does: the+ * server's `state` is not_mentioned when the brand is in fewer than half the+ * runs, so 1 mention in 10 runs reads "Not mentioned", not its position.+ */+export function readLabel(read: PlatformRead | null): ReadLabel {+ if (!read || !read.runs) return { kind: 'no_runs' };+ if (read.state === 'not_mentioned' || !read.mentionedRuns) return { kind: 'not_mentioned' };+ if (read.mentionPosition === null) return { kind: 'mentioned' };+ return { kind: 'position', value: `#${read.mentionPosition.toFixed(1)}` };+}++/** Platform id → name, from the platforms an Improve action's payload lists. */+export function improvePlatformLabels(+ payload: Record<string, unknown> | null,+): Record<string, string> {+ const platforms = Array.isArray(payload?.platforms) ? payload.platforms : [];+ const labels: Record<string, string> = {};+ for (const p of platforms as { id?: unknown; label?: unknown }[]) {+ if (typeof p?.id === 'string' && typeof p.label === 'string') labels[p.id] = p.label;+ }+ return labels;+}++/** What the Positions panel says about an Improve action still being tracked. */+export interface ImprovingAction {+ actionId: string;+ actionNo: number;+ avgBefore: number | null;+ avgAfter: number | null;+}++const TRACKED = ['new', 'in_progress', 'on_hold', 'completed'];++/**+ * The newest of a prompt's Improve actions that is still tracked: open, or+ * completed with its final read not yet taken. Dismissed ones never count.+ */+export function pickImprovingAction(+ rows: { id: string; action_no: number; status: string; position_outcome: unknown }[],+): ImprovingAction | null {+ for (const row of rows) {+ if (!TRACKED.includes(row.status)) continue;+ const outcome = parseImproveOutcome(row.position_outcome);+ if (outcome?.final) continue;+ return {+ actionId: row.id,+ actionNo: Number(row.action_no),+ avgBefore: outcome?.summary.avgBefore ?? null,+ avgAfter: outcome?.summary.avgAfter ?? null,+ };+ }+ return null;+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 5dfef5d4a..ab8418c2e 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -138,6 +138,7 @@ export type Database = {kpi_keys: string[]outcome: stringpayload: Json+ position_outcome: Json | nullstatus: stringupdated_at: stringvalidated_at: string | null@@ -159,6 +160,7 @@ export type Database = {kpi_keys?: string[]outcome?: stringpayload?: Json+ position_outcome?: Json | nullstatus?: stringupdated_at?: stringvalidated_at?: string | null@@ -180,6 +182,7 @@ export type Database = {kpi_keys?: string[]outcome?: stringpayload?: Json+ position_outcome?: Json | nullstatus?: stringupdated_at?: stringvalidated_at?: string | null