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): show what each kind of action did at the brand on a History scorecard (learning B3) (#1695)
Cihan938c07f19115
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdxindex abf7fc7ef..49c9e375b 100644--- a/docs/guides/action-center.mdx+++ b/docs/guides/action-center.mdx@@ -195,6 +195,10 @@ Click an action to see **What was the goal?**, **What happened?** (the signals i- Only a completed action is measured: a dismissed one reads **Not measured**, dismissed. One with no metric to read is **Not measurable**.- An action sent from a prompt's Improve tab reports on how many platforms its position improved. It is read again daily while the action is open and for 30 days after it is completed.+### Scorecard++Switch History from **Actions** to **Scorecard** to see what each kind of action did at this brand over the range (90 days unless you pick another, since an action's final reading comes 30 days after it closes): how many were completed, their results so far, the **Success rate** (the share of results that improved, shown once a kind has three), the median change in each action's main metric, and how many were dismissed, with the reason given most often. It counts this brand's own actions only, never another brand's.+When an action is closed, its condition can open a new action after a two-week rest if it is still firing. The old one stays in History as the record of that round of work.## Where actions come fromdiff --git a/supabase/migrations/00368_action_scorecard.sql b/supabase/migrations/00368_action_scorecard.sqlnew file mode 100644index 000000000..b786a59a8--- /dev/null+++ b/supabase/migrations/00368_action_scorecard.sql@@ -0,0 +1,101 @@+-- ============================================================================+-- 00368: what worked at a brand, by kind of action (learning B3)+-- ============================================================================+-- Each completed action keeps its result (server action-center/validate.js,+-- read a week, two weeks and a month after it closed) and a dismissed one+-- why it was turned down (00366). Read one at a time, a brand can't see+-- which kinds of work pay off for it. This sums the brand's actions raised+-- since a day by kind: how many were completed, what their results read,+-- the median change in each one's main metric, and how many were dismissed+-- and why. One brand's own actions only, never another's: the History tab+-- reads it with the member's session (RLS keeps it to their organization),+-- the API with the service role.++create or replace function public.action_scorecard(+ p_brand_id uuid,+ p_since timestamptz default null+)+returns table (+ kind text,+ completed integer,+ improved integer,+ mixed integer,+ no_change integer,+ declined integer,+ not_measurable integer,+ pending integer,+ final integer,+ median_change numeric,+ dismissed integer,+ dismiss_reasons jsonb+)+language sql+stable+security invoker+set search_path to 'public'+as $$+ with closed as (+ select a.kind,+ a.status,+ a.outcome,+ a.dismiss_reason,+ a.validation->>'final' = 'true' as is_final,+ -- The relative change in its main metric (learning A4), when the+ -- metric was read before and after and had a before to scale by.+ (select (m->>'after')::numeric / nullif((m->>'before')::numeric, 0) - 1+ from jsonb_array_elements(+ case when jsonb_typeof(a.validation->'metrics') = 'array'+ then a.validation->'metrics' else '[]'::jsonb end+ ) as m+ where m->>'metric' = a.validation->>'primary'+ and jsonb_typeof(m->'before') = 'number'+ and jsonb_typeof(m->'after') = 'number'+ limit 1) as change+ from public.actions a+ where a.brand_id = p_brand_id+ and a.deleted_at is null+ and a.status in ('completed', 'dismissed')+ and (p_since is null or a.created_at >= p_since)+ )+ select c.kind,+ count(*) filter (where c.status = 'completed')::integer,+ count(*) filter (where c.status = 'completed' and c.outcome = 'improved')::integer,+ count(*) filter (where c.status = 'completed' and c.outcome = 'mixed')::integer,+ count(*) filter (where c.status = 'completed' and c.outcome = 'no_meaningful_change')::integer,+ count(*) filter (where c.status = 'completed' and c.outcome = 'declined')::integer,+ count(*) filter (where c.status = 'completed' and c.outcome = 'not_measurable')::integer,+ count(*) filter (+ where c.status = 'completed'+ and (c.outcome is null or c.outcome = 'pending_measurement')+ )::integer,+ count(*) filter (where c.status = 'completed' and c.is_final)::integer,+ -- The median, so one small page that went from 1 to 20 doesn't+ -- read as the kind's typical result. Over the results with a+ -- verdict only.+ round(+ (percentile_cont(0.5) within group (order by c.change) filter (+ where c.status = 'completed'+ and c.outcome in ('improved', 'mixed', 'no_meaningful_change', 'declined')+ ))::numeric,+ 4+ ),+ count(*) filter (where c.status = 'dismissed')::integer,+ coalesce(+ (select jsonb_object_agg(r.reason, r.n)+ from (select coalesce(d.dismiss_reason, 'none') as reason, count(*) as n+ from closed d+ where d.kind = c.kind and d.status = 'dismissed'+ group by 1) as r),+ '{}'::jsonb+ )+ from closed c+ group by c.kind;+$$;++revoke all on function public.action_scorecard(uuid, timestamptz) from public, anon;+grant execute on function public.action_scorecard(uuid, timestamptz) to authenticated, service_role;++comment on function public.action_scorecard(uuid, timestamptz) is+ 'A brand''s actions raised since a day, by kind: completed, results, median change in the main metric, dismissed and why (00368, learning B3). RLS applies to the caller.';++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 06a937358..cd7d9efc4 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -41977,3 +41977,108 @@ comment on function public.content_suggestion_decisions(uuid, timestamptz) isnotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00368_action_scorecard.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00368: what worked at a brand, by kind of action (learning B3)+-- ============================================================================+-- Each completed action keeps its result (server action-center/validate.js,+-- read a week, two weeks and a month after it closed) and a dismissed one+-- why it was turned down (00366). Read one at a time, a brand can't see+-- which kinds of work pay off for it. This sums the brand's actions raised+-- since a day by kind: how many were completed, what their results read,+-- the median change in each one's main metric, and how many were dismissed+-- and why. One brand's own actions only, never another's: the History tab+-- reads it with the member's session (RLS keeps it to their organization),+-- the API with the service role.++create or replace function public.action_scorecard(+ p_brand_id uuid,+ p_since timestamptz default null+)+returns table (+ kind text,+ completed integer,+ improved integer,+ mixed integer,+ no_change integer,+ declined integer,+ not_measurable integer,+ pending integer,+ final integer,+ median_change numeric,+ dismissed integer,+ dismiss_reasons jsonb+)+language sql+stable+security invoker+set search_path to 'public'+as $$+ with closed as (+ select a.kind,+ a.status,+ a.outcome,+ a.dismiss_reason,+ a.validation->>'final' = 'true' as is_final,+ -- The relative change in its main metric (learning A4), when the+ -- metric was read before and after and had a before to scale by.+ (select (m->>'after')::numeric / nullif((m->>'before')::numeric, 0) - 1+ from jsonb_array_elements(+ case when jsonb_typeof(a.validation->'metrics') = 'array'+ then a.validation->'metrics' else '[]'::jsonb end+ ) as m+ where m->>'metric' = a.validation->>'primary'+ and jsonb_typeof(m->'before') = 'number'+ and jsonb_typeof(m->'after') = 'number'+ limit 1) as change+ from public.actions a+ where a.brand_id = p_brand_id+ and a.deleted_at is null+ and a.status in ('completed', 'dismissed')+ and (p_since is null or a.created_at >= p_since)+ )+ select c.kind,+ count(*) filter (where c.status = 'completed')::integer,+ count(*) filter (where c.status = 'completed' and c.outcome = 'improved')::integer,+ count(*) filter (where c.status = 'completed' and c.outcome = 'mixed')::integer,+ count(*) filter (where c.status = 'completed' and c.outcome = 'no_meaningful_change')::integer,+ count(*) filter (where c.status = 'completed' and c.outcome = 'declined')::integer,+ count(*) filter (where c.status = 'completed' and c.outcome = 'not_measurable')::integer,+ count(*) filter (+ where c.status = 'completed'+ and (c.outcome is null or c.outcome = 'pending_measurement')+ )::integer,+ count(*) filter (where c.status = 'completed' and c.is_final)::integer,+ -- The median, so one small page that went from 1 to 20 doesn't+ -- read as the kind's typical result. Over the results with a+ -- verdict only.+ round(+ (percentile_cont(0.5) within group (order by c.change) filter (+ where c.status = 'completed'+ and c.outcome in ('improved', 'mixed', 'no_meaningful_change', 'declined')+ ))::numeric,+ 4+ ),+ count(*) filter (where c.status = 'dismissed')::integer,+ coalesce(+ (select jsonb_object_agg(r.reason, r.n)+ from (select coalesce(d.dismiss_reason, 'none') as reason, count(*) as n+ from closed d+ where d.kind = c.kind and d.status = 'dismissed'+ group by 1) as r),+ '{}'::jsonb+ )+ from closed c+ group by c.kind;+$$;++revoke all on function public.action_scorecard(uuid, timestamptz) from public, anon;+grant execute on function public.action_scorecard(uuid, timestamptz) to authenticated, service_role;++comment on function public.action_scorecard(uuid, timestamptz) is+ 'A brand''s actions raised since a day, by kind: completed, results, median change in the main metric, dismissed and why (00368, learning B3). RLS applies to the caller.';++notify pgrst, 'reload schema';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex f8a13863a..f5de37488 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2660,6 +2660,29 @@"description": "Select a brand to view its action history."},"positionResult": "{measurable, plural, =0 {Positions: not enough data} other {Position improved on {improved} of # platforms}}",+ "view": {+ "actions": "Actions",+ "scorecard": "Scorecard"+ },+ "scorecard": {+ "note": "What each kind of action did at this brand, from its own actions only. Results are the readings so far; each is final a month after its action closed. Median change is in each action's main metric.",+ "columns": {+ "kind": "Kind of action",+ "completed": "Completed",+ "results": "Results",+ "successRate": "Success rate",+ "medianChange": "Median change",+ "dismissed": "Dismissed"+ },+ "tooFew": "Too few results",+ "mostly": "Mostly: {reason}",+ "empty": {+ "title": "Nothing to score in this range",+ "description": "A kind of action shows here once one of its actions is completed or dismissed."+ },+ "error": "The scorecard couldn't be loaded.",+ "retry": "Try again"+ },"outcomeSoFar": "so far: day {day} of {final}","outcomeHint": {"pending_measurement": "no result recorded",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.test.tsxnew file mode 100644index 000000000..594d365ad--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.test.tsx@@ -0,0 +1,111 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * History's range: the Actions list starts on 30 days, the scorecard on 90,+ * since an action's final reading comes 30 days after it closed (learning+ * B1). A range in the URL, or one picked, holds in either view.+ */++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++vi.mock('next-intl', () => ({+ useTranslations: () => (key: string) => key,+}));+vi.mock('@/stores/use-brand-store', () => ({+ useBrandStore: (selector: (state: { getActiveBrand: () => { id: string } }) => unknown) =>+ selector({ getActiveBrand: () => ({ id: 'b1' }) }),+}));+vi.mock('@/components/ai-usage/ai-usage-meter', () => ({+ HeaderWithAiUsage: ({ children }: { children: React.ReactNode }) => children,+}));+vi.mock('@/components/action-center/action-center-tabs', () => ({+ ActionCenterTabs: () => null,+}));+vi.mock('@/components/action-center/history-table', () => ({ HistoryTable: () => null }));+vi.mock('@/components/action-center/history-drawer', () => ({ HistoryDrawer: () => null }));+vi.mock('@/components/action-center/scorecard-table', () => ({ ScorecardTable: () => null }));++const { getActionHistory, getActionScorecard } = vi.hoisted(() => ({+ getActionHistory: vi.fn(),+ getActionScorecard: vi.fn(),+}));+vi.mock('@/lib/actions/action-history', () => ({ getActionHistory }));+vi.mock('@/lib/actions/action-scorecard', () => ({ getActionScorecard }));++import ActionCenterHistoryPage from './page';++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ getActionHistory.mockResolvedValue([{ id: 'a1', status: 'completed', outcome: 'improved' }]);+ getActionScorecard.mockResolvedValue([]);+ container = document.createElement('div');+ document.body.append(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ document.body.replaceChildren();+ getActionHistory.mockReset();+ getActionScorecard.mockReset();+ window.history.replaceState(null, '', '/');+});++async function renderAt(url: string) {+ window.history.replaceState(null, '', url);+ await act(async () => {+ root.render(<ActionCenterHistoryPage />);+ });+}++/** The days back the latest call to `read` asked from. */+function daysAsked(read: typeof getActionHistory): number {+ const { from } = read.mock.calls.at(-1)?.[1] as { from: string };+ return Math.round((Date.now() - Date.parse(from)) / 86_400_000);+}++function button(text: string): HTMLButtonElement {+ const found = [...container.querySelectorAll('button')].find((b) => b.textContent === text);+ if (!found) throw new Error(`no ${text} button`);+ return found;+}++describe('History range', () => {+ it('starts the Actions list on 30 days', async () => {+ await renderAt('/');+ expect(daysAsked(getActionHistory)).toBe(30);+ expect(getActionScorecard).not.toHaveBeenCalled();+ });++ it('starts the scorecard on 90 days when the URL names no range', async () => {+ await renderAt('/?view=scorecard');+ expect(daysAsked(getActionScorecard)).toBe(90);+ expect(button('range.90d').className).toContain('bg-primary');+ });++ it('keeps a range the URL names', async () => {+ await renderAt('/?view=scorecard&range=30d');+ expect(daysAsked(getActionScorecard)).toBe(30);+ });++ it('moves to 90 days on switching to the scorecard, unless a range was picked', async () => {+ await renderAt('/');+ await act(async () => button('view.scorecard').click());+ expect(daysAsked(getActionScorecard)).toBe(90);+ // The URL is written after a pause; the view's own default stays out of it.+ await act(() => new Promise((resolve) => setTimeout(resolve, 350)));+ expect(window.location.search).toBe('?view=scorecard');++ await act(async () => button('range.7d').click());+ await act(async () => button('view.actions').click());+ expect(daysAsked(getActionHistory)).toBe(7);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsxindex 0334f4e0f..1b60585c0 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx@@ -16,6 +16,8 @@ import {import { Skeleton } from '@/components/ui/skeleton';import { useBrandStore } from '@/stores/use-brand-store';import { getActionHistory } from '@/lib/actions/action-history';+import { getActionScorecard } from '@/lib/actions/action-scorecard';+import type { ScorecardRow } from '@/lib/action-center/scorecard';import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';import { actionTexts } from '@/lib/action-center/display';import {@@ -37,6 +39,7 @@ import { SIGNAL_SOURCES, type SignalSource } from '@/lib/signals/registry';import { ActionCenterTabs } from '@/components/action-center/action-center-tabs';import { HistoryTable } from '@/components/action-center/history-table';import { HistoryDrawer } from '@/components/action-center/history-drawer';+import { ScorecardTable } from '@/components/action-center/scorecard-table';import { cn } from '@/lib/utils';import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';@@ -44,6 +47,17 @@ const RANGE_DAYS = { '7d': 7, '30d': 30, '90d': 90, all: null } as const;type RangePreset = keyof typeof RANGE_DAYS;const RANGE_PRESETS = Object.keys(RANGE_DAYS) as RangePreset[];+/** The list of actions, or the scorecard of what each kind did (learning B3). */+const VIEWS = ['actions', 'scorecard'] as const;+type HistoryView = (typeof VIEWS)[number];++/**+ * The range each view starts on until one is picked. An action's final+ * reading comes 30 days after it closed (learning B1), so the scorecard+ * over 30 days would hold mostly readings so far.+ */+const DEFAULT_RANGE: Record<HistoryView, RangePreset> = { actions: '30d', scorecard: '90d' };+/*** History: what was done, and what it moved.*@@ -66,7 +80,10 @@ export default function ActionCenterHistoryPage() {const [isLoading, setIsLoading] = useState(true);const [loadFailed, setLoadFailed] = useState(false);- const [range, setRange] = useState<RangePreset>('30d');+ const [view, setView] = useState<HistoryView>('actions');+ // Null until one is picked: the view's own default.+ const [pickedRange, setRange] = useState<RangePreset | null>(null);+ const range = pickedRange ?? DEFAULT_RANGE[view];const [status, setStatus] = useState<ActionStatus | 'all'>('all');const [type, setType] = useState<ActionCategory | 'all'>('all');const [priority, setPriority] = useState<PriorityLevel | 'all'>('all');@@ -75,12 +92,16 @@ export default function ActionCenterHistoryPage() {const [sort, setSort] = useState<HistorySort>('newest');const [page, setPage] = useState(1);const [selected, setSelected] = useState<ActionHistoryItem | null>(null);+ const [scorecard, setScorecard] = useState<ScorecardRow[] | null>(null);+ const [scorecardFailed, setScorecardFailed] = useState(false);// Filters, sort and search live in the URL (#896) so a refresh keeps them// and a filtered view can be shared. Read after mount, before the first load.const [urlRead, setUrlRead] = useState(false);useEffect(() => {- setRange(readUrlChoice('range', RANGE_PRESETS, '30d'));+ setView(readUrlChoice('view', VIEWS, 'actions'));+ const urlRange = readUrlParam('range');+ setRange(RANGE_PRESETS.find((preset) => preset === urlRange) ?? null);setStatus(readUrlChoice<ActionStatus | 'all'>('status', ['all', ...HISTORY_STATUSES], 'all'));setType(readUrlChoice<ActionCategory | 'all'>('type', ['all', ...ACTION_CATEGORIES], 'all'));setPriority(@@ -98,9 +119,10 @@ export default function ActionCenterHistoryPage() {const timer = setTimeout(() =>writeUrlParams(- { range, status, type, priority, source, sort, q: search.trim() },+ { view, range, status, type, priority, source, sort, q: search.trim() },{- range: '30d',+ view: 'actions',+ range: DEFAULT_RANGE[view],status: 'all',type: 'all',priority: 'all',@@ -111,7 +133,7 @@ export default function ActionCenterHistoryPage() {300,);return () => clearTimeout(timer);- }, [urlRead, range, status, type, priority, source, sort, search]);+ }, [urlRead, view, range, status, type, priority, source, sort, search]);const load = useCallback(async () => {if (!brandId) {@@ -136,6 +158,24 @@ export default function ActionCenterHistoryPage() {if (urlRead) void load();}, [load, urlRead]);+ // The scorecard is read only when it's shown, over the same range.+ const loadScorecard = useCallback(async () => {+ if (!brandId) return;+ setScorecard(null);+ setScorecardFailed(false);+ try {+ const days = RANGE_DAYS[range];+ const from = days ? new Date(Date.now() - days * 86_400_000).toISOString() : undefined;+ setScorecard(await getActionScorecard(brandId, { from }));+ } catch {+ setScorecardFailed(true);+ }+ }, [brandId, range]);++ useEffect(() => {+ if (urlRead && view === 'scorecard') void loadScorecard();+ }, [loadScorecard, urlRead, view]);+// Any narrowing puts the reader back on page 1; staying on page 4 of a list// that now has one page shows nothing and looks like a failure.useEffect(() => {@@ -165,7 +205,11 @@ export default function ActionCenterHistoryPage() {return rows.sort(compareHistory(sort));}, [items, status, type, priority, source, search, sort, tTexts]);- const summary = useMemo(() => summarize(filtered), [filtered]);+ // The scorecard hides the filters, so its cards count the whole range.+ const summary = useMemo(+ () => summarize(view === 'scorecard' ? (items ?? []) : filtered),+ [view, items, filtered],+ );const pageCount = Math.max(1, Math.ceil(filtered.length / HISTORY_PAGE_SIZE));const visible = filtered.slice((page - 1) * HISTORY_PAGE_SIZE, page * HISTORY_PAGE_SIZE);@@ -266,6 +310,24 @@ export default function ActionCenterHistoryPage() {</div><div className="flex flex-wrap items-center gap-2">+ <div className="inline-flex overflow-hidden rounded-md border">+ {VIEWS.map((option) => (+ <button+ key={option}+ type="button"+ aria-pressed={view === option}+ onClick={() => setView(option)}+ className={cn(+ 'px-3 py-1.5 text-xs font-medium transition-colors',+ view === option+ ? 'bg-primary text-primary-foreground'+ : 'bg-card text-foreground hover:bg-muted',+ )}+ >+ {t(`view.${option}`)}+ </button>+ ))}+ </div><div className="inline-flex overflow-hidden rounded-md border">{RANGE_PRESETS.map((preset) => (<button@@ -283,62 +345,88 @@ export default function ActionCenterHistoryPage() {</button>))}</div>- <FilterSelect- label={t('filters.status')}- value={status}- onChange={(v) => setStatus(v as ActionStatus | 'all')}- options={HISTORY_STATUSES.map((v) => ({ value: v, label: t(`status.${v}`) }))}- allLabel={t('filters.all')}- />- <FilterSelect- label={t('filters.type')}- value={type}- onChange={(v) => setType(v as ActionCategory | 'all')}- options={ACTION_CATEGORIES.map((v) => ({ value: v, label: tTypes(v) }))}- allLabel={t('filters.all')}- />- <FilterSelect- label={t('filters.priority')}- value={priority}- onChange={(v) => setPriority(v as PriorityLevel | 'all')}- options={PRIORITY_LEVELS.map((v) => ({- value: v,- label: tActions(`priority.levels.${v}`),- }))}- allLabel={t('filters.all')}- />- <FilterSelect- label={t('filters.source')}- value={source}- onChange={(v) => setSource(v as SignalSource | 'all')}- options={SIGNAL_SOURCES.map((v) => ({ value: v, label: tSources(v) }))}- allLabel={t('filters.all')}- />- <FilterSelect- label={t('filters.sort')}- value={sort}- onChange={(v) => setSort((v === 'all' ? 'newest' : v) as HistorySort)}- options={HISTORY_SORTS.map((v) => ({ value: v, label: t(`sort.${v}`) }))}- allLabel={t('sort.newest')}- />- <div className="relative">- <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />- <Input- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder={t('filters.search')}- className="h-8 w-56 pl-8 text-xs"- />- </div>- {hasActiveFilters && (- <Button variant="ghost" size="sm" className="text-xs" onClick={clearFilters}>- <X className="h-3.5 w-3.5" />- {t('filters.clear')}- </Button>+ {view === 'actions' && (+ <>+ <FilterSelect+ label={t('filters.status')}+ value={status}+ onChange={(v) => setStatus(v as ActionStatus | 'all')}+ options={HISTORY_STATUSES.map((v) => ({ value: v, label: t(`status.${v}`) }))}+ allLabel={t('filters.all')}+ />+ <FilterSelect+ label={t('filters.type')}+ value={type}+ onChange={(v) => setType(v as ActionCategory | 'all')}+ options={ACTION_CATEGORIES.map((v) => ({ value: v, label: tTypes(v) }))}+ allLabel={t('filters.all')}+ />+ <FilterSelect+ label={t('filters.priority')}+ value={priority}+ onChange={(v) => setPriority(v as PriorityLevel | 'all')}+ options={PRIORITY_LEVELS.map((v) => ({+ value: v,+ label: tActions(`priority.levels.${v}`),+ }))}+ allLabel={t('filters.all')}+ />+ <FilterSelect+ label={t('filters.source')}+ value={source}+ onChange={(v) => setSource(v as SignalSource | 'all')}+ options={SIGNAL_SOURCES.map((v) => ({ value: v, label: tSources(v) }))}+ allLabel={t('filters.all')}+ />+ <FilterSelect+ label={t('filters.sort')}+ value={sort}+ onChange={(v) => setSort((v === 'all' ? 'newest' : v) as HistorySort)}+ options={HISTORY_SORTS.map((v) => ({ value: v, label: t(`sort.${v}`) }))}+ allLabel={t('sort.newest')}+ />+ <div className="relative">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder={t('filters.search')}+ className="h-8 w-56 pl-8 text-xs"+ />+ </div>+ {hasActiveFilters && (+ <Button variant="ghost" size="sm" className="text-xs" onClick={clearFilters}>+ <X className="h-3.5 w-3.5" />+ {t('filters.clear')}+ </Button>+ )}+ </>)}</div>- {visible.length > 0 ? (+ {view === 'scorecard' ? (+ scorecardFailed ? (+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16 text-center">+ <h2 className="font-semibold">{t('scorecard.error')}</h2>+ <Button+ variant="outline"+ size="sm"+ className="mt-4 text-xs"+ onClick={() => void loadScorecard()}+ >+ {t('scorecard.retry')}+ </Button>+ </div>+ ) : scorecard ? (+ <ScorecardTable rows={scorecard} />+ ) : (+ <div className="space-y-2">+ {[0, 1, 2, 3].map((i) => (+ <Skeleton key={i} className="h-12 w-full" />+ ))}+ </div>+ )+ ) : visible.length > 0 ? (<><HistoryTableitems={visible}diff --git a/web/src/components/action-center/scorecard-table.test.tsx b/web/src/components/action-center/scorecard-table.test.tsxnew file mode 100644index 000000000..640dc022d--- /dev/null+++ b/web/src/components/action-center/scorecard-table.test.tsx@@ -0,0 +1,123 @@+import { act, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, describe, expect, it } from 'vitest';+import type { ScorecardRow } from '@/lib/action-center/scorecard';+import messages from '../../../messages/en.json';+import { ScorecardTable } from './scorecard-table';++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | null = null;++async function render(node: ReactNode) {+ const container = document.createElement('div');+ document.body.append(container);+ root = createRoot(container);+ await act(async () => {+ root!.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ {node}+ </NextIntlClientProvider>,+ );+ });+}++afterEach(() => {+ act(() => root?.unmount());+ root = null;+ document.body.innerHTML = '';+});++const row = (overrides: Partial<ScorecardRow> = {}): ScorecardRow => ({+ kind: 'recover_lost_citations',+ completed: 0,+ improved: 0,+ mixed: 0,+ noChange: 0,+ declined: 0,+ notMeasurable: 0,+ pending: 0,+ final: 0,+ medianChange: null,+ dismissed: 0,+ dismissReasons: {},+ ...overrides,+});++const cells = (index: number) =>+ Array.from(document.body.querySelectorAll('tbody tr')[index].querySelectorAll('td')).map(+ (td) => td.textContent,+ );++describe('ScorecardTable', () => {+ it('shows what each kind did: results, rate, median change and why it was dismissed', async () => {+ await render(+ <ScorecardTable+ rows={[+ row({+ completed: 4,+ improved: 2,+ mixed: 1,+ declined: 1,+ medianChange: 0.15,+ dismissed: 2,+ dismissReasons: { not_now: 1, none: 1 },+ }),+ ]}+ />,+ );++ expect(cells(0)).toEqual([+ 'Recover lost citations',+ '4',+ '2Improved1Mixed1Declined',+ '50%',+ '+15%',+ '2Mostly: Not now',+ ]);+ });++ /** A kind with a couple of results says so, rather than a rate of 0 or 100%. */+ it('says a kind has too few results for a rate', async () => {+ await render(+ <ScorecardTable+ rows={[+ row({+ kind: 'fix_low_scores',+ completed: 2,+ declined: 1,+ pending: 1,+ medianChange: -0.2,+ }),+ ]}+ />,+ );++ expect(cells(0)).toEqual([+ 'Fix low-scoring pages',+ '2',+ '1Declined1Not measured',+ 'Too few results',+ '−20%',+ '0',+ ]);+ });++ it('names a kind this build has no copy for from its id', async () => {+ await render(<ScorecardTable rows={[row({ kind: 'brand_new_kind', dismissed: 1 })]} />);++ expect(cells(0)[0]).toBe('Brand new kind');+ expect(cells(0)[2]).toBe('—');+ });++ it('says when there is nothing to score', async () => {+ await render(<ScorecardTable rows={[]} />);++ expect(document.body.textContent).toContain('Nothing to score in this range');+ });+});diff --git a/web/src/components/action-center/scorecard-table.tsx b/web/src/components/action-center/scorecard-table.tsxnew file mode 100644index 000000000..415193159--- /dev/null+++ b/web/src/components/action-center/scorecard-table.tsx@@ -0,0 +1,125 @@+'use client';++import { useTranslations } from 'next-intl';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import { actionKindName } from '@/lib/action-center/display';+import { successRate, topDismissReason, type ScorecardRow } from '@/lib/action-center/scorecard';+import type { ActionOutcome } from '@/lib/action-center/registry';+import { signedPercent } from '@/lib/signals/metrics';+import { cn } from '@/lib/utils';++/** The results a row lists, in the order they read, and each one's tone. */+const RESULTS: { key: keyof ScorecardRow; outcome: ActionOutcome; tone: string }[] = [+ { key: 'improved', outcome: 'improved', tone: 'text-emerald-600 dark:text-emerald-400' },+ { key: 'mixed', outcome: 'mixed', tone: 'text-amber-600 dark:text-amber-400' },+ { key: 'noChange', outcome: 'no_meaningful_change', tone: 'text-muted-foreground' },+ { key: 'declined', outcome: 'declined', tone: 'text-red-600 dark:text-red-400' },+ { key: 'notMeasurable', outcome: 'not_measurable', tone: 'text-muted-foreground' },+ { key: 'pending', outcome: 'pending_measurement', tone: 'text-muted-foreground' },+];++/**+ * The scorecard (learning B3): what each kind of action did at this brand,+ * from its own actions only. A kind with too few results says so instead of+ * a rate.+ */+export function ScorecardTable({ rows }: { rows: ScorecardRow[] }) {+ const t = useTranslations('actionCenter.historyPage.scorecard');+ const tTexts = useTranslations('actionCenter.actionTexts');+ const tOutcome = useTranslations('actionCenter.actionOutcome');+ const tReason = useTranslations('actionCenter.dismissReason');++ if (rows.length === 0) {+ return (+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16 text-center">+ <h2 className="font-semibold">{t('empty.title')}</h2>+ <p className="mt-1 max-w-md text-sm text-muted-foreground">{t('empty.description')}</p>+ </div>+ );+ }++ return (+ <div className="space-y-2">+ <p className="text-xs text-muted-foreground">{t('note')}</p>+ <div className="overflow-x-auto rounded-lg border bg-card">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="text-xs">{t('columns.kind')}</TableHead>+ <TableHead className="text-right text-xs">{t('columns.completed')}</TableHead>+ <TableHead className="text-xs">{t('columns.results')}</TableHead>+ <TableHead className="text-right text-xs">{t('columns.successRate')}</TableHead>+ <TableHead className="text-right text-xs">{t('columns.medianChange')}</TableHead>+ <TableHead className="text-right text-xs">{t('columns.dismissed')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.map((row) => {+ const rate = successRate(row);+ const reason = topDismissReason(row);+ const change = row.medianChange == null ? null : Math.round(row.medianChange * 100);+ const results = RESULTS.filter(({ key }) => (row[key] as number) > 0);+ return (+ <TableRow key={row.kind}>+ <TableCell className="text-sm font-medium">+ {actionKindName(row.kind, tTexts)}+ </TableCell>+ <TableCell className="text-right text-sm tabular-nums">{row.completed}</TableCell>+ <TableCell>+ {results.length > 0 ? (+ <div className="flex flex-wrap gap-x-3 gap-y-0.5">+ {results.map(({ key, outcome, tone }) => (+ <span key={key} className={cn('flex items-center gap-1.5 text-xs', tone)}>+ <span className="h-1.5 w-1.5 rounded-full bg-current" />+ <span className="tabular-nums">{row[key] as number}</span>+ {tOutcome(outcome)}+ </span>+ ))}+ </div>+ ) : (+ <span className="text-xs text-muted-foreground">—</span>+ )}+ </TableCell>+ <TableCell className="text-right">+ {rate == null ? (+ <span className="text-xs text-muted-foreground">{t('tooFew')}</span>+ ) : (+ <span className="text-sm font-medium tabular-nums">{rate}%</span>+ )}+ </TableCell>+ <TableCell+ className={cn(+ 'text-right text-sm tabular-nums',+ change == null || change === 0+ ? 'text-muted-foreground'+ : change > 0+ ? 'text-emerald-600 dark:text-emerald-400'+ : 'text-red-600 dark:text-red-400',+ )}+ >+ {change == null ? '—' : signedPercent(change)}+ </TableCell>+ <TableCell className="text-right">+ <p className="text-sm tabular-nums">{row.dismissed}</p>+ {reason && (+ <p className="text-[11px] text-muted-foreground">+ {t('mostly', { reason: tReason(`${reason}.label`) })}+ </p>+ )}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ </div>+ );+}diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 6ff10175c..840c01423 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -37,6 +37,14 @@ export function humanizeKind(kind: string): string {return words.charAt(0).toUpperCase() + words.slice(1);}+/**+ * A kind's name, as a group of actions (the History scorecard, learning+ * B3): its title without targets, else its id read as words.+ */+export function actionKindName(kind: string, t: Translator): string {+ return isActionKind(kind) ? t(`${kind}.titleGeneric`) : humanizeKind(kind);+}+/*** "11 prompts", "6 sources" — how many of what an action is about.*diff --git a/web/src/lib/action-center/scorecard.test.ts b/web/src/lib/action-center/scorecard.test.tsnew file mode 100644index 000000000..e4477b742--- /dev/null+++ b/web/src/lib/action-center/scorecard.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from 'vitest';+import {+ MIN_SCORECARD_VERDICTS,+ parseScorecardRow,+ sortScorecard,+ successRate,+ topDismissReason,+ type ScorecardRow,+} from './scorecard';++const row = (overrides: Partial<ScorecardRow> = {}): ScorecardRow => ({+ kind: 'recover_lost_citations',+ completed: 0,+ improved: 0,+ mixed: 0,+ noChange: 0,+ declined: 0,+ notMeasurable: 0,+ pending: 0,+ final: 0,+ medianChange: null,+ dismissed: 0,+ dismissReasons: {},+ ...overrides,+});++describe('parseScorecardRow', () => {+ it('reads an RPC row into the table shape', () => {+ expect(+ parseScorecardRow({+ kind: 'recover_lost_citations',+ completed: 4,+ improved: 1,+ mixed: 1,+ no_change: 0,+ declined: 1,+ not_measurable: 0,+ pending: 1,+ final: 1,+ median_change: '0.1500',+ dismissed: 2,+ dismiss_reasons: { not_now: 1, none: 1, made_up: 3 },+ }),+ ).toEqual(+ row({+ completed: 4,+ improved: 1,+ mixed: 1,+ declined: 1,+ pending: 1,+ final: 1,+ medianChange: 0.15,+ dismissed: 2,+ dismissReasons: { not_now: 1, none: 1 },+ }),+ );+ });++ it('drops a row with no kind, and keeps an unread median empty', () => {+ expect(parseScorecardRow({ completed: 2 })).toBeNull();+ expect(parseScorecardRow(null)).toBeNull();+ expect(parseScorecardRow({ kind: 'fix_low_scores', median_change: null })?.medianChange).toBe(+ null,+ );+ });+});++describe('successRate', () => {+ /** Two results can't tell whether a kind of work pays off here. */+ it('gives no rate below the minimum results with a verdict', () => {+ expect(successRate(row({ improved: MIN_SCORECARD_VERDICTS - 1 }))).toBeNull();+ // Results with no verdict don't count towards it.+ expect(successRate(row({ improved: 1, notMeasurable: 5, pending: 5 }))).toBeNull();+ });++ it('is the share of verdicts that improved', () => {+ expect(successRate(row({ improved: 2, mixed: 1, declined: 1 }))).toBe(50);+ expect(successRate(row({ improved: 1, noChange: 2 }))).toBe(33);+ });+});++describe('topDismissReason', () => {+ it('names the reason given most often, never the dismissals without one', () => {+ expect(topDismissReason(row({ dismissReasons: { not_now: 1, wrong_data: 2, none: 5 } }))).toBe(+ 'wrong_data',+ );+ expect(topDismissReason(row({ dismissReasons: { none: 3 } }))).toBeNull();+ });++ it('breaks a tie by the order the dialog lists them', () => {+ expect(topDismissReason(row({ dismissReasons: { not_now: 2, not_relevant: 2 } }))).toBe(+ 'not_relevant',+ );+ });+});++describe('sortScorecard', () => {+ it('puts the busiest kinds first, then the better rate', () => {+ const quiet = row({ kind: 'fix_low_scores', dismissed: 1 });+ const busy = row({ kind: 'recover_visibility', completed: 3, declined: 3 });+ const better = row({ kind: 'recover_lost_citations', completed: 3, improved: 3 });+ expect(sortScorecard([quiet, busy, better]).map((r) => r.kind)).toEqual([+ 'recover_lost_citations',+ 'recover_visibility',+ 'fix_low_scores',+ ]);+ });+});diff --git a/web/src/lib/action-center/scorecard.ts b/web/src/lib/action-center/scorecard.tsnew file mode 100644index 000000000..159d459d2--- /dev/null+++ b/web/src/lib/action-center/scorecard.ts@@ -0,0 +1,99 @@+/**+ * The History tab's scorecard (learning B3): what each kind of action did at+ * this brand.+ *+ * One row per kind, summed by the action_scorecard RPC (00368) from the+ * brand's own actions only — never another brand's. A kind with only a+ * couple of results says so rather than a rate: two actions can't tell+ * whether a kind of work pays off here.+ */++import { ACTION_DISMISS_REASONS, type ActionDismissReason } from './registry';++/** Results with a verdict a kind needs before its success rate is shown. */+export const MIN_SCORECARD_VERDICTS = 3;++export interface ScorecardRow {+ kind: string;+ completed: number;+ improved: number;+ mixed: number;+ noChange: number;+ declined: number;+ notMeasurable: number;+ /** Completed, not read yet. */+ pending: number;+ /** Completed and read for the last time, a month on (learning B1). */+ final: number;+ /** The median relative change in each one's main metric: 0.15 is +15%. */+ medianChange: number | null;+ dismissed: number;+ /** Dismissals by the reason given (learning A5); `none` when none was. */+ dismissReasons: Partial<Record<ActionDismissReason | 'none', number>>;+}++/** Its results with a verdict: improved, mixed, no change or declined. */+export function verdicts(row: ScorecardRow): number {+ return row.improved + row.mixed + row.noChange + row.declined;+}++/** The share of its verdicts that improved, 0–100; null below the minimum. */+export function successRate(row: ScorecardRow): number | null {+ const total = verdicts(row);+ if (total < MIN_SCORECARD_VERDICTS) return null;+ return Math.round((row.improved / total) * 100);+}++/** The reason given most often for dismissing it; ties go to the list's order. */+export function topDismissReason(row: ScorecardRow): ActionDismissReason | null {+ let top: ActionDismissReason | null = null;+ for (const reason of ACTION_DISMISS_REASONS) {+ const count = row.dismissReasons[reason] ?? 0;+ if (count > 0 && (top === null || count > (row.dismissReasons[top] ?? 0))) top = reason;+ }+ return top;+}++/** Busiest kinds first, then the better rate; the kind's id keeps it stable. */+export function sortScorecard(rows: ScorecardRow[]): ScorecardRow[] {+ return [...rows].sort(+ (a, b) =>+ b.completed + b.dismissed - (a.completed + a.dismissed) ||+ (successRate(b) ?? -1) - (successRate(a) ?? -1) ||+ a.kind.localeCompare(b.kind),+ );+}++const count = (value: unknown) => {+ const n = Number(value);+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;+};++/** One RPC row in the shape the table reads; null when it names no kind. */+export function parseScorecardRow(raw: unknown): ScorecardRow | null {+ if (!raw || typeof raw !== 'object') return null;+ const row = raw as Record<string, unknown>;+ if (typeof row.kind !== 'string' || !row.kind) return null;+ const change = row.median_change == null ? null : Number(row.median_change);+ const reasons: ScorecardRow['dismissReasons'] = {};+ if (row.dismiss_reasons && typeof row.dismiss_reasons === 'object') {+ const given = row.dismiss_reasons as Record<string, unknown>;+ for (const reason of [...ACTION_DISMISS_REASONS, 'none'] as const) {+ if (count(given[reason])) reasons[reason] = count(given[reason]);+ }+ }+ return {+ kind: row.kind,+ completed: count(row.completed),+ improved: count(row.improved),+ mixed: count(row.mixed),+ noChange: count(row.no_change),+ declined: count(row.declined),+ notMeasurable: count(row.not_measurable),+ pending: count(row.pending),+ final: count(row.final),+ medianChange: change != null && Number.isFinite(change) ? change : null,+ dismissed: count(row.dismissed),+ dismissReasons: reasons,+ };+}diff --git a/web/src/lib/actions/action-scorecard.test.ts b/web/src/lib/actions/action-scorecard.test.tsnew file mode 100644index 000000000..b1b878bd5--- /dev/null+++ b/web/src/lib/actions/action-scorecard.test.ts@@ -0,0 +1,41 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const rpc = vi.fn();++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({ rpc })),+}));++import { getActionScorecard } from './action-scorecard';++beforeEach(() => {+ rpc.mockReset();+});++describe('getActionScorecard', () => {+ it("reads the brand's scorecard since a day, busiest kinds first", async () => {+ rpc.mockResolvedValue({+ data: [+ { kind: 'fix_low_scores', completed: 1, dismissed: 0 },+ { kind: 'recover_lost_citations', completed: 3, improved: 3, dismissed: 1 },+ { completed: 9 },+ ],+ error: null,+ });++ const rows = await getActionScorecard('brand-1', { from: '2026-10-01T00:00:00.000Z' });++ expect(rpc).toHaveBeenCalledWith('action_scorecard', {+ p_brand_id: 'brand-1',+ p_since: '2026-10-01T00:00:00.000Z',+ });+ expect(rows.map((row) => row.kind)).toEqual(['recover_lost_citations', 'fix_low_scores']);+ });++ it('reads every action when no range is set, and fails loudly', async () => {+ rpc.mockResolvedValue({ data: null, error: { message: 'boom' } });++ await expect(getActionScorecard('brand-1')).rejects.toThrow('boom');+ expect(rpc).toHaveBeenCalledWith('action_scorecard', { p_brand_id: 'brand-1', p_since: null });+ });+});diff --git a/web/src/lib/actions/action-scorecard.ts b/web/src/lib/actions/action-scorecard.tsnew file mode 100644index 000000000..975ad859d--- /dev/null+++ b/web/src/lib/actions/action-scorecard.ts@@ -0,0 +1,26 @@+'use server';++/**+ * The History tab's scorecard read (learning B3): the brand's actions summed+ * by kind in the database (action_scorecard, 00368). Read with the member's+ * session, so RLS keeps it to their organization's brands.+ */++import { createClient } from '@/lib/supabase/server';+import { parseScorecardRow, sortScorecard, type ScorecardRow } from '@/lib/action-center/scorecard';++/** One row per kind of the brand's actions raised since `from`; every one when absent. */+export async function getActionScorecard(+ brandId: string,+ opts?: { from?: string },+): Promise<ScorecardRow[]> {+ const supabase = await createClient();+ const { data, error } = await supabase.rpc('action_scorecard', {+ p_brand_id: brandId,+ p_since: opts?.from ?? null,+ });+ if (error) throw new Error(error.message);+ return sortScorecard(+ (data ?? []).map(parseScorecardRow).filter((row): row is ScorecardRow => row !== null),+ );+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 9f1cfb69f..b9589ae2c 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -4530,6 +4530,23 @@ export type Database = {total: number}[]}+ action_scorecard: {+ Args: { p_brand_id: string; p_since?: string | null }+ Returns: {+ completed: number+ declined: number+ dismiss_reasons: Json+ dismissed: number+ final: number+ improved: number+ kind: string+ median_change: number | null+ mixed: number+ no_change: number+ not_measurable: number+ pending: number+ }[]+ }ai_traffic_merged: {Args: {p_analytics?: boolean