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 each action's priority and work the list by it (#1072)
Cihan95be2f63d64c
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex 832b4587e..fef4c5b6f 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -283,8 +283,8 @@ intent, not during exploratory queries.| Tool | What it does | Writes || --- | --- | --- |-| `list_actions` | Recommended actions for a brand with status, impact, assignee, due date, and task progress. | |-| `get_action` | One action in full: payload, triggering signals, tasks (`mode`, `permission`), and event trail. | |+| `list_actions` | Recommended actions for a brand with priority (0–100 score, level and reasons), status, impact, assignee, due date, and task progress. Highest priority first; `sort: "updated"` lists the most recently updated first. | |+| `get_action` | One action in full: priority, payload, triggering signals, tasks (`mode`, `permission`), and event trail. | || `list_signals` | Detected changes (visibility, citations, traffic), each with `where` (prompt, topic, platforms, locations, domain, competitor), `change` (labelled figures with unit and period), `evidence` (detection dates, app links) and `used_by_actions`. | || `list_action_history` | Closed actions with measured outcomes and before/after validation results. | || `update_task_status` | Record progress on a task (`in_progress`, `completed`, `skipped`, `failed`); does not execute the task. | **yes** |diff --git a/web/messages/en.json b/web/messages/en.jsonindex 8f06dec1a..ff29cf380 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -786,19 +786,19 @@"subtitle": "Know what changed, what matters, and what to do next.","cards": {"top": "Top Actions",- "topSub": "Highest priority right now",+ "topSub": "Highest-priority actions to work on next","atRisk": "At Risk","atRiskSub": "Recover and Fix — visibility or traffic declining","opportunities": "Opportunities","opportunitiesSub": "High potential to grow","inProgress": "In Progress","inProgressSub": "Actions currently running",- "impact": "Potential Impact",- "impactSub": "Across open actions"+ "priority": "Highest Priority",+ "prioritySub": "Across open actions"},"allActions": "All","filters": {- "impact": "Impact",+ "priority": "Priority","status": "Status","assignee": "Assignee","all": "All",@@ -809,14 +809,13 @@"sort": {"label": "Sort","priority": "Priority",- "impact": "Impact","newest": "Newest","due_date": "Due date","updated": "Recently updated"},"table": {+ "priority": "Priority Score","action": "Action",- "impact": "Impact","status": "Status","assignee": "Assignee","dueDate": "Due date",@@ -830,11 +829,6 @@"completed": "Completed","dismissed": "Dismissed"},- "impact": {- "high": "High",- "medium": "Medium",- "low": "Low"- },"taskProgress": "{completed}/{total} tasks","tags": {"signals": "{count, plural, one {1 signal} other {# signals}}",@@ -864,6 +858,66 @@"description": "Select a brand to view its actions."},"updateFailed": "Couldn't update the action.",+ "priority": {+ "label": "Priority",+ "levels": {+ "critical": "Critical",+ "high": "High",+ "medium": "Medium",+ "low": "Low"+ },+ "notScored": "Not scored yet",+ "why": "Why this priority?",+ "reason": {+ "change": {+ "lost": "Lost ground on {subject}",+ "dropped": "A sharp drop on {subject}",+ "slipping": "Slipping on {subject}",+ "gap": "A gap to close on {subject}",+ "issue": "A site issue on {subject}",+ "opportunity": "Room to grow on {subject}",+ "gain": "A gain on {subject}",+ "none": "Its findings have resolved"+ },+ "subject": {+ "prompts": "{count, plural, one {# {demand}prompt} other {# {demand}prompts}}",+ "pages": "{count, plural, one {# {demand}page} other {# {demand}pages}}",+ "queries": "{count, plural, one {# {demand}query} other {# {demand}queries}}",+ "topics": "{count, plural, one {# {demand}topic} other {# {demand}topics}}",+ "platforms": "{count, plural, one {# platform} other {# platforms}}",+ "regions": "{count, plural, one {# region} other {# regions}}",+ "competitors": "{count, plural, one {# competitor} other {# competitors}}",+ "sources": "{count, plural, one {# source} other {# sources}}"+ },+ "alone": {+ "lost": "Lost ground",+ "dropped": "A sharp drop",+ "slipping": "Slipping",+ "gap": "A gap to close",+ "issue": "A site issue",+ "opportunity": "Room to grow",+ "gain": "A gain"+ },+ "demand": {+ "high": "high-demand",+ "low": "low-demand"+ },+ "when": {+ "today": "today",+ "days": "{days, plural, one {# day ago} other {# days ago}}"+ },+ "highDemand": "high search demand",+ "commercial": "commercial intent",+ "heldBefore": "previously visible",+ "sources": "confirmed by {count} sources",+ "sentence": {+ "withWhen": "{what} {when}",+ "withExtras": "{text} — {extras}",+ "separator": ", ",+ "end": "{text}."+ }+ }+ },"export": {"copyAll": "Copy Data","csv": "Export CSV",@@ -888,6 +942,9 @@},"action": "Action","title": "Title",+ "priority": "Priority",+ "priorityValue": "{score} ({level})",+ "priorityWhy": "Why this priority","category": "Category","impact": "Impact","status": "Status",@@ -1631,7 +1688,7 @@"table": {"action": "Action","type": "Type",- "impact": "Impact",+ "priority": "Priority Score","affected": "Affected","result": "Result","status": "Status",@@ -1662,12 +1719,12 @@"sort": {"newest": "Newest","oldest": "Oldest",- "impact": "Impact"+ "priority": "Priority"},"filters": {"status": "Status","type": "Type",- "impact": "Impact",+ "priority": "Priority","source": "Source","sort": "Sort","all": "All",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsxindex 0bdcdf13c..49b552e9b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx@@ -21,20 +21,21 @@ import { listMembers, type TeamMember } from '@/lib/actions/team';import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';import {ACTION_CATEGORIES,- ACTION_IMPACTS,ACTION_SORTS,ACTION_STATUSES,+ OPEN_ACTION_STATUSES,type ActionCategory,- type ActionImpact,type ActionSort,type ActionStatus,} from '@/lib/action-center/registry';+import { actionContextTags, actionTexts, memberLabel } from '@/lib/action-center/display';import {- actionContextTags,- actionTexts,+ PRIORITY_LEVELS,comparePriority,- memberLabel,-} from '@/lib/action-center/display';+ highestPriorityLevel,+ topActionIds,+ type PriorityLevel,+} from '@/lib/action-center/priority';import { ActionCenterTabs } from '@/components/action-center/action-center-tabs';import { ActionTable } from '@/components/action-center/action-table';import { ActionDrawer } from '@/components/action-center/action-drawer';@@ -54,9 +55,10 @@ import { toCsv } from '@/lib/csv';const ACTION_EXPORT_HEADERS = ['number',+ 'priority_score',+ 'priority_level','title','category',- 'impact','status','assignee','due_date',@@ -65,9 +67,7 @@ const ACTION_EXPORT_HEADERS = ['created',];-const OPEN_STATUSES: ActionStatus[] = ['new', 'in_progress', 'on_hold'];--const isOpen = (action: ActionItem) => OPEN_STATUSES.includes(action.status);+const isOpen = (action: ActionItem) => OPEN_ACTION_STATUSES.includes(action.status);/*** What each summary card counts, one predicate per card.@@ -79,14 +79,14 @@ const isOpen = (action: ActionItem) => OPEN_STATUSES.includes(action.status);* the count and the filter read the same predicate they cannot disagree.*/const CARD_FILTERS = {- top: (action: ActionItem) => isOpen(action) && action.impact === 'high',atRisk: (action: ActionItem) =>isOpen(action) && (action.category === 'recover' || action.category === 'fix'),opportunities: (action: ActionItem) => isOpen(action) && action.category === 'growth',inProgress: (action: ActionItem) => action.status === 'in_progress',} as const;-type CardFocus = keyof typeof CARD_FILTERS;+/** Top Actions is the five highest-priority open actions (AC-006), not a predicate. */+type CardFocus = keyof typeof CARD_FILTERS | 'top';export default function ActionCenterActionsPage() {const brand = useBrandStore((s) => s.getActiveBrand());@@ -123,7 +123,7 @@ function ActionsContent({ brand }: { brand: Brand }) {const [loadFailed, setLoadFailed] = useState(false);const [category, setCategory] = useState<ActionCategory | 'all'>('all');- const [impact, setImpact] = useState<ActionImpact | 'all'>('all');+ const [priority, setPriority] = useState<PriorityLevel | 'all'>('all');const [status, setStatus] = useState<ActionStatus | 'all'>('all');const [assignee, setAssignee] = useState<string>('all');const [sort, setSort] = useState<ActionSort>('priority');@@ -137,7 +137,9 @@ function ActionsContent({ brand }: { brand: Brand }) {setCategory(readUrlChoice<ActionCategory | 'all'>('category', ['all', ...ACTION_CATEGORIES], 'all'),);- setImpact(readUrlChoice<ActionImpact | 'all'>('impact', ['all', ...ACTION_IMPACTS], 'all'));+ setPriority(+ readUrlChoice<PriorityLevel | 'all'>('priority', ['all', ...PRIORITY_LEVELS], 'all'),+ );setStatus(readUrlChoice<ActionStatus | 'all'>('status', ['all', ...ACTION_STATUSES], 'all'));setAssignee(readUrlParam('assignee') || 'all');setSort(readUrlChoice<ActionSort>('sort', ACTION_SORTS, 'priority'));@@ -151,13 +153,13 @@ function ActionsContent({ brand }: { brand: Brand }) {const timer = setTimeout(() =>writeUrlParams(- { category, impact, status, assignee, sort, q: search.trim() },- { category: 'all', impact: 'all', status: 'all', assignee: 'all', sort: 'priority' },+ { category, priority, status, assignee, sort, q: search.trim() },+ { category: 'all', priority: 'all', status: 'all', assignee: 'all', sort: 'priority' },),300,);return () => clearTimeout(timer);- }, [urlRead, category, impact, status, assignee, sort, search]);+ }, [urlRead, category, priority, status, assignee, sort, search]);const [selectedId, setSelectedId] = useState<string | null>(null);@@ -209,12 +211,16 @@ function ActionsContent({ brand }: { brand: Brand }) {[actions, selectedId],);+ // The card and its filter read one set, so they cannot disagree.+ const topIds = useMemo(() => topActionIds(actions ?? []), [actions]);+const visible = useMemo(() => {const needle = search.trim().toLowerCase();const filtered = (actions ?? []).filter((action) => {- if (focus && !CARD_FILTERS[focus](action)) return false;+ if (focus === 'top' ? !topIds.has(action.id) : focus && !CARD_FILTERS[focus](action))+ return false;if (category !== 'all' && action.category !== category) return false;- if (impact !== 'all' && action.impact !== impact) return false;+ if (priority !== 'all' && action.priorityLevel !== priority) return false;if (status !== 'all' && action.status !== status) return false;if (assignee !== 'all') {if (assignee === 'unassigned' ? action.assignee !== null : action.assignee?.id !== assignee)@@ -230,8 +236,6 @@ function ActionsContent({ brand }: { brand: Brand }) {});return filtered.sort((a, b) => {switch (sort) {- case 'impact':- return comparePriority(a, b);case 'newest':return b.createdAt.localeCompare(a.createdAt);case 'due_date':@@ -242,16 +246,17 @@ function ActionsContent({ brand }: { brand: Brand }) {return comparePriority(a, b);}});- }, [actions, focus, category, impact, status, assignee, search, sort, tTexts, t]);+ }, [actions, topIds, focus, category, priority, status, assignee, search, sort, tTexts, t]);const handleExportCsv = useCallback(() => {if (visible.length === 0) return;const rows = visible.map((action) => ({number: action.actionNo,+ priority_score: action.priorityScore ?? '',+ priority_level: action.priorityLevel ? t(`priority.levels.${action.priorityLevel}`) : '',title: actionTexts(action, tTexts).title,category: tCategories(action.category),- impact: t(`impact.${action.impact}`),status: t(`status.${action.status}`),assignee: action.assignee?.fullName ?? '',due_date: action.dueDate ?? '',@@ -285,21 +290,19 @@ function ActionsContent({ brand }: { brand: Brand }) {const summary = useMemo(() => {const all = actions ?? [];const open = all.filter(isOpen);- const impacts = open.map((action) => action.impact);return {- top: all.filter(CARD_FILTERS.top).length,+ top: topIds.size,atRisk: all.filter(CARD_FILTERS.atRisk).length,opportunities: all.filter(CARD_FILTERS.opportunities).length,inProgress: all.filter(CARD_FILTERS.inProgress).length,- potential: impacts.includes('high') ? 'high' : impacts.includes('medium') ? 'medium' : 'low',- hasOpen: open.length > 0,+ highest: highestPriorityLevel(open.map((action) => action.priorityLevel)),};- }, [actions]);+ }, [actions, topIds]);const hasActiveFilters =focus !== null ||category !== 'all' ||- impact !== 'all' ||+ priority !== 'all' ||status !== 'all' ||assignee !== 'all' ||search !== '';@@ -307,7 +310,7 @@ function ActionsContent({ brand }: { brand: Brand }) {const clearFilters = () => {setFocus(null);setCategory('all');- setImpact('all');+ setPriority('all');setStatus('all');setAssignee('all');setSearch('');@@ -395,12 +398,12 @@ function ActionsContent({ brand }: { brand: Brand }) {<div className="flex h-7 w-7 items-center justify-center rounded-md border bg-muted/40"><TrendingUp className="h-3.5 w-3.5 text-muted-foreground" /></div>- <p className="text-xs font-medium text-muted-foreground">{t('cards.impact')}</p>+ <p className="text-xs font-medium text-muted-foreground">{t('cards.priority')}</p></div><p className="mt-2 text-2xl font-bold">- {summary.hasOpen ? t(`impact.${summary.potential}`) : '—'}+ {summary.highest ? t(`priority.levels.${summary.highest}`) : '—'}</p>- <p className="mt-0.5 text-xs text-muted-foreground">{t('cards.impactSub')}</p>+ <p className="mt-0.5 text-xs text-muted-foreground">{t('cards.prioritySub')}</p></CardContent></Card></div>@@ -444,10 +447,10 @@ function ActionsContent({ brand }: { brand: Brand }) {<div className="flex flex-wrap items-center gap-2"><FilterSelect- label={t('filters.impact')}- value={impact}- onChange={(v) => setImpact(v as ActionImpact | 'all')}- options={ACTION_IMPACTS.map((v) => ({ value: v, label: t(`impact.${v}`) }))}+ label={t('filters.priority')}+ value={priority}+ onChange={(v) => setPriority(v as PriorityLevel | 'all')}+ options={PRIORITY_LEVELS.map((v) => ({ value: v, label: t(`priority.levels.${v}`) }))}allLabel={t('filters.all')}/><FilterSelect@@ -534,7 +537,7 @@ function SummaryCard({label: string;value: number;sub: string;- /** Omit both to render a card that only reports, like Potential Impact. */+ /** Omit both to render a card that only reports, like Highest Priority. */isActive?: boolean;onClick?: () => void;}) {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 64cebdc99..4692768b0 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@@ -22,17 +22,17 @@ import {HISTORY_PAGE_SIZE,HISTORY_SORTS,HISTORY_STATUSES,+ compareHistory,summarize,type ActionHistoryItem,type HistorySort,} from '@/lib/action-center/history';import {ACTION_CATEGORIES,- ACTION_IMPACTS,type ActionCategory,- type ActionImpact,type ActionStatus,} from '@/lib/action-center/registry';+import { PRIORITY_LEVELS, type PriorityLevel } from '@/lib/action-center/priority';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';@@ -68,7 +68,7 @@ export default function ActionCenterHistoryPage() {const [range, setRange] = useState<RangePreset>('30d');const [status, setStatus] = useState<ActionStatus | 'all'>('all');const [type, setType] = useState<ActionCategory | 'all'>('all');- const [impact, setImpact] = useState<ActionImpact | 'all'>('all');+ const [priority, setPriority] = useState<PriorityLevel | 'all'>('all');const [source, setSource] = useState<SignalSource | 'all'>('all');const [search, setSearch] = useState('');const [sort, setSort] = useState<HistorySort>('newest');@@ -82,7 +82,9 @@ export default function ActionCenterHistoryPage() {setRange(readUrlChoice('range', RANGE_PRESETS, '30d'));setStatus(readUrlChoice<ActionStatus | 'all'>('status', ['all', ...HISTORY_STATUSES], 'all'));setType(readUrlChoice<ActionCategory | 'all'>('type', ['all', ...ACTION_CATEGORIES], 'all'));- setImpact(readUrlChoice<ActionImpact | 'all'>('impact', ['all', ...ACTION_IMPACTS], 'all'));+ setPriority(+ readUrlChoice<PriorityLevel | 'all'>('priority', ['all', ...PRIORITY_LEVELS], 'all'),+ );setSource(readUrlChoice<SignalSource | 'all'>('source', ['all', ...SIGNAL_SOURCES], 'all'));setSort(readUrlChoice('sort', HISTORY_SORTS, 'newest'));setSearch(readUrlParam('q'));@@ -95,12 +97,12 @@ export default function ActionCenterHistoryPage() {const timer = setTimeout(() =>writeUrlParams(- { range, status, type, impact, source, sort, q: search.trim() },+ { range, status, type, priority, source, sort, q: search.trim() },{range: '30d',status: 'all',type: 'all',- impact: 'all',+ priority: 'all',source: 'all',sort: 'newest',},@@ -108,7 +110,7 @@ export default function ActionCenterHistoryPage() {300,);return () => clearTimeout(timer);- }, [urlRead, range, status, type, impact, source, sort, search]);+ }, [urlRead, range, status, type, priority, source, sort, search]);const load = useCallback(async () => {if (!brandId) {@@ -137,14 +139,14 @@ export default function ActionCenterHistoryPage() {// that now has one page shows nothing and looks like a failure.useEffect(() => {setPage(1);- }, [status, type, impact, source, search, sort, range]);+ }, [status, type, priority, source, search, sort, range]);const filtered = useMemo(() => {const needle = search.trim().toLowerCase();const rows = (items ?? []).filter((item) => {if (status !== 'all' && item.status !== status) return false;if (type !== 'all' && item.type !== type) return false;- if (impact !== 'all' && item.impact !== impact) return false;+ if (priority !== 'all' && item.priorityLevel !== priority) return false;if (source !== 'all' && !item.sources.includes(source)) return false;if (needle) {// Titles are composed from i18n templates rather than stored, so the@@ -159,20 +161,8 @@ export default function ActionCenterHistoryPage() {return true;});- const impactRank = { high: 0, medium: 1, low: 2 };- return rows.sort((a, b) => {- const aDate = a.completedAt ?? a.createdAt;- const bDate = b.completedAt ?? b.createdAt;- switch (sort) {- case 'oldest':- return aDate.localeCompare(bDate);- case 'impact':- return impactRank[a.impact] - impactRank[b.impact] || bDate.localeCompare(aDate);- default:- return bDate.localeCompare(aDate);- }- });- }, [items, status, type, impact, source, search, sort, tTexts]);+ return rows.sort(compareHistory(sort));+ }, [items, status, type, priority, source, search, sort, tTexts]);const summary = useMemo(() => summarize(filtered), [filtered]);@@ -180,12 +170,12 @@ export default function ActionCenterHistoryPage() {const visible = filtered.slice((page - 1) * HISTORY_PAGE_SIZE, page * HISTORY_PAGE_SIZE);const hasActiveFilters =- status !== 'all' || type !== 'all' || impact !== 'all' || source !== 'all' || search !== '';+ status !== 'all' || type !== 'all' || priority !== 'all' || source !== 'all' || search !== '';const clearFilters = () => {setStatus('all');setType('all');- setImpact('all');+ setPriority('all');setSource('all');setSearch('');};@@ -305,10 +295,13 @@ export default function ActionCenterHistoryPage() {allLabel={t('filters.all')}/><FilterSelect- label={t('filters.impact')}- value={impact}- onChange={(v) => setImpact(v as ActionImpact | 'all')}- options={ACTION_IMPACTS.map((v) => ({ value: v, label: tActions(`impact.${v}`) }))}+ 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')}/><FilterSelectdiff --git a/web/src/app/api/mcp/actions/route.ts b/web/src/app/api/mcp/actions/route.tsindex 90a107bac..3f986122c 100644--- a/web/src/app/api/mcp/actions/route.ts+++ b/web/src/app/api/mcp/actions/route.ts@@ -19,6 +19,7 @@ export async function GET(req: Request) {const statusRaw = url.searchParams.get('status');const categoryRaw = url.searchParams.get('category');const limitRaw = url.searchParams.get('limit');+ const sortRaw = url.searchParams.get('sort');const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;try {@@ -27,6 +28,7 @@ export async function GET(req: Request) {status: statusRaw && STATUSES.includes(statusRaw) ? statusRaw : undefined,category: categoryRaw && CATEGORIES.includes(categoryRaw) ? categoryRaw : undefined,limit: Number.isFinite(limit) ? limit : undefined,+ sort: sortRaw === 'priority' || sortRaw === 'updated' ? sortRaw : undefined,});if (actions === null) {return NextResponse.json({ error: 'Brand not found' }, { status: 404 });diff --git a/web/src/components/action-center/action-drawer.test.tsx b/web/src/components/action-center/action-drawer.test.tsxindex cd5a2a400..0fce6c492 100644--- a/web/src/components/action-center/action-drawer.test.tsx+++ b/web/src/components/action-center/action-drawer.test.tsx@@ -40,6 +40,9 @@ const action: ActionItem = {category: 'recover',kind: 'recover_lost_citations',impact: 'high',+ priorityScore: 72,+ priorityLevel: 'high',+ priorityReason: null,status: 'in_progress',payload: {},kpiKeys: [],diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex dc72fc84b..2743214cf 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -57,7 +57,8 @@ import {import { signalTexts } from '@/lib/signals/display';import { isKpiKey } from '@/lib/kpis/registry';import { ImpactDots, isSuperseded, SignalStatusBadge } from './signal-table';-import { ActionIcon } from './action-table';+import { ActionIcon, PriorityBadge } from './action-table';+import { priorityReasonText } from '@/lib/action-center/priority';import { OpportunityContext } from './opportunity-context';import { ActionExportButtons } from './action-export-buttons';import { ImproveContext } from './improve-context';@@ -97,6 +98,7 @@ export function ActionDrawer({const tRegistry = useTranslations('actionCenter.registry');const tTasks = useTranslations('actionCenter.actionTasks');const tTaskStatus = useTranslations('actionCenter.taskStatus');+ const tPriority = useTranslations('actionCenter.actionsPage.priority');const router = useRouter();const [tab, setTab] = useState<DrawerTab>('overview');@@ -164,10 +166,9 @@ export function ActionDrawer({<Badge variant="outline" className="text-[10px]">{tCategories(action.category)}</Badge>- <span className="flex items-center gap-1.5 text-muted-foreground">- <ImpactDots impact={action.impact} />- {t(`impact.${action.impact}`)}- </span>+ {action.priorityScore !== null && (+ <PriorityBadge score={action.priorityScore} level={action.priorityLevel} />+ )}<span className="ml-auto text-muted-foreground">{t('drawer.actionId')}: AC-{action.actionNo}</span>@@ -304,6 +305,15 @@ export function ActionDrawer({</div>) : tab === 'overview' ? (<>+ {action.priorityReason && (+ <>+ <section>+ <p className="text-xs font-medium text-muted-foreground">{t('priority.why')}</p>+ <p className="mt-1">{priorityReasonText(action.priorityReason, tPriority)}</p>+ </section>+ <Separator />+ </>+ )}<section><p className="text-xs font-medium text-muted-foreground">{t('drawer.why')}</p><p className="mt-1">{texts.description}</p>diff --git a/web/src/components/action-center/action-export-buttons.test.tsx b/web/src/components/action-center/action-export-buttons.test.tsxindex 8a7dedd9f..bcb902b6a 100644--- a/web/src/components/action-center/action-export-buttons.test.tsx+++ b/web/src/components/action-center/action-export-buttons.test.tsx@@ -72,6 +72,17 @@ const action = {taskTotal: 1,taskCompleted: 0,signalCount: 1,+ priorityScore: 84,+ priorityLevel: 'high',+ priorityReason: {+ change: 'dropped',+ subject: { entity: 'prompts', count: 3 },+ demand: 'high',+ commercial: true,+ heldBefore: true,+ days: 2,+ sources: 1,+ },} as ActionItem;const detail = {@@ -149,6 +160,12 @@ describe('ActionExportButtons', () => {await act(async () => button('Copy Data').click());const shown = document.querySelector('textarea')?.value ?? '';expect(shown).toMatch(/^# Recover lost visibility \(AC-52\)\n/);+ // The priority stands where impact used to: impact is one of its factors.+ expect(shown).toContain('Priority: 84 (High) · Category: Recover · Status:');+ expect(shown).not.toContain('Impact:');+ expect(shown).toContain(+ 'Why this priority: A sharp drop on 3 high-demand prompts 2 days ago — commercial intent, previously visible.',+ );expect(shown).toContain('## Tasks (1)\n1. Refresh /pricing (To Do)');expect(shown).toContain('## Signals (1)\n- Visibility · ');expect(shown).toContain('## History (1)\n- 2026-10-08 · ');diff --git a/web/src/components/action-center/action-export-buttons.tsx b/web/src/components/action-center/action-export-buttons.tsxindex 6249aad88..a6a8cb275 100644--- a/web/src/components/action-center/action-export-buttons.tsx+++ b/web/src/components/action-center/action-export-buttons.tsx@@ -25,6 +25,7 @@ import {type ExportFact,} from '@/lib/action-center/export';import { opportunityLists } from '@/lib/content/opportunity-lists';+import { priorityReasonText } from '@/lib/action-center/priority';import { isKpiKey } from '@/lib/kpis/registry';import { signalAffected, signalTexts } from '@/lib/signals/display';import { SIGNAL_KINDS } from '@/lib/signals/registry';@@ -74,6 +75,7 @@ export function ActionExportButtons({const tSignals = useTranslations('actionCenter.signalsPage');const tSignalTexts = useTranslations('actionCenter.signalTexts');const tSignalCategories = useTranslations('actionCenter.signalCategories');+ const tPriority = useTranslations('actionCenter.actionsPage.priority');const [isBusy, setIsBusy] = useState(false);// The Markdown Copy Data shows, and what to say once it is copied.const [preview, setPreview] = useState<{ text: string; copied: string } | null>(null);@@ -176,10 +178,22 @@ export function ActionExportButtons({detail,{title: texts.title,+ // A scored action always has a level: one read from its score if need be.+ priority:+ action.priorityScore !== null && action.priorityLevel !== null+ ? {+ label: t('export.priorityValue', {+ score: action.priorityScore,+ level: tPriority(`levels.${action.priorityLevel}`),+ }),+ why: action.priorityReason+ ? priorityReasonText(action.priorityReason, tPriority)+ : '',+ }+ : null,why: texts.description,goal: actionGoal(action.kind, tTexts, action.payload),category: tCategories(action.category),- impact: t(`impact.${action.impact}`),status: t(`status.${action.status}`),tags: actionContextTags(action, t),kpis: detail.kpisdiff --git a/web/src/components/action-center/action-table.tsx b/web/src/components/action-center/action-table.tsxindex 2f69e82ea..2e6618be6 100644--- a/web/src/components/action-center/action-table.tsx+++ b/web/src/components/action-center/action-table.tsx@@ -26,7 +26,7 @@ import {import type { ActionItem } from '@/lib/actions/action-center';import type { ActionCategory, ActionKind, ActionStatus } from '@/lib/action-center/registry';import { actionContextTags, actionTexts } from '@/lib/action-center/display';-import { ImpactDots } from './signal-table';+import type { PriorityLevel } from '@/lib/action-center/priority';import { formatRelative } from '@/lib/format-relative';import { cn } from '@/lib/utils';@@ -92,6 +92,43 @@ export function ActionStatusBadge({ status }: { status: ActionStatus }) {);}+export const PRIORITY_BADGE: Record<PriorityLevel, string> = {+ critical: 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400',+ high: 'border-orange-500/30 bg-orange-500/10 text-orange-600 dark:text-orange-400',+ medium: 'border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-400',+ low: 'border-border bg-muted/50 text-muted-foreground',+};++/**+ * The priority score (AC-006), coloured by its level, and the level's name:+ * "84 High". It stands where Impact used to, since the score weighs impact+ * in. A dash until the server has scored the action.+ */+export function PriorityBadge({+ score,+ level,+}: {+ score: number | null;+ level: PriorityLevel | null;+}) {+ const t = useTranslations('actionCenter.actionsPage.priority');+ if (score === null || level === null) {+ return (+ <span className="text-xs text-muted-foreground" title={t('notScored')}>+ —+ </span>+ );+ }+ return (+ <span className="flex items-center gap-1.5">+ <Badge variant="outline" className={cn('font-semibold tabular-nums', PRIORITY_BADGE[level])}>+ {score}+ </Badge>+ <span className="text-xs">{t(`levels.${level}`)}</span>+ </span>+ );+}+export function AssigneeAvatar({ assignee }: { assignee: ActionItem['assignee'] }) {if (!assignee) return <span className="text-xs text-muted-foreground">—</span>;const initials = (assignee.fullName ?? '?')@@ -126,7 +163,7 @@ export function ActionTable({<TableHeader><TableRow><TableHead className="text-xs">{t('table.action')}</TableHead>- <TableHead className="text-xs">{t('table.impact')}</TableHead>+ <TableHead className="text-xs">{t('table.priority')}</TableHead><TableHead className="text-xs">{t('table.status')}</TableHead><TableHead className="text-xs">{t('table.assignee')}</TableHead><TableHead className="text-xs">{t('table.dueDate')}</TableHead>@@ -165,10 +202,7 @@ export function ActionTable({</div></TableCell><TableCell>- <div className="flex items-center gap-1.5">- <span className="text-xs">{t(`impact.${action.impact}`)}</span>- <ImpactDots impact={action.impact} />- </div>+ <PriorityBadge score={action.priorityScore} level={action.priorityLevel} /></TableCell><TableCell><ActionStatusBadge status={action.status} />diff --git a/web/src/components/action-center/history-drawer.test.tsx b/web/src/components/action-center/history-drawer.test.tsxindex 952012df4..9d219dd32 100644--- a/web/src/components/action-center/history-drawer.test.tsx+++ b/web/src/components/action-center/history-drawer.test.tsx@@ -22,7 +22,8 @@ const item = (signalCount: number): ActionHistoryItem => ({actionNo: 1,kind: 'recover_visibility',type: 'recover',- impact: 'high',+ priorityScore: 72,+ priorityLevel: 'high',status: 'completed',outcome: 'pending_measurement',payload: {},diff --git a/web/src/components/action-center/history-drawer.tsx b/web/src/components/action-center/history-drawer.tsxindex a46c2e16d..6dd426418 100644--- a/web/src/components/action-center/history-drawer.tsx+++ b/web/src/components/action-center/history-drawer.tsx@@ -15,8 +15,7 @@ import {import { actionGoal, actionTexts } from '@/lib/action-center/display';import type { ActionHistoryItem } from '@/lib/action-center/history';import { UNCOUNTED_TASK_STATUSES } from '@/lib/action-center/registry';-import { ImpactDots } from './signal-table';-import { ActionIcon } from './action-table';+import { ActionIcon, PriorityBadge } from './action-table';import { HistoryStatusBadge } from './history-table';import { ImproveOutcomeCard } from './improve-outcome-card';import { improvePlatformLabels } from '@/lib/improve-outcome';@@ -79,7 +78,6 @@ export function HistoryDrawer({onOpenChange: (open: boolean) => void;}) {const t = useTranslations('actionCenter.historyPage');- const tActions = useTranslations('actionCenter.actionsPage');const tTexts = useTranslations('actionCenter.actionTexts');const tTypes = useTranslations('actionCenter.actionCategories');const tTasks = useTranslations('actionCenter.actionTasks');@@ -110,10 +108,9 @@ export function HistoryDrawer({<Badge variant="outline" className="text-[10px]">{tTypes(item.type)}</Badge>- <span className="flex items-center gap-1.5 text-muted-foreground">- <ImpactDots impact={item.impact} />- {tActions(`impact.${item.impact}`)}- </span>+ {item.priorityScore !== null && (+ <PriorityBadge score={item.priorityScore} level={item.priorityLevel} />+ )}<HistoryStatusBadge status={item.status} /><span className="ml-auto text-muted-foreground">AC-{item.actionNo}</span></div>diff --git a/web/src/components/action-center/history-table.test.tsx b/web/src/components/action-center/history-table.test.tsxindex fde538b72..51dc212e1 100644--- a/web/src/components/action-center/history-table.test.tsx+++ b/web/src/components/action-center/history-table.test.tsx@@ -23,7 +23,8 @@ const item = (overrides: Partial<ActionHistoryItem> = {}): ActionHistoryItem =>actionNo: 1,kind: 'recover_visibility',type: 'recover',- impact: 'high',+ priorityScore: 72,+ priorityLevel: 'high',status: 'completed',outcome: 'pending_measurement',payload: {},diff --git a/web/src/components/action-center/history-table.tsx b/web/src/components/action-center/history-table.tsxindex c64103cbe..db646199c 100644--- a/web/src/components/action-center/history-table.tsx+++ b/web/src/components/action-center/history-table.tsx@@ -13,8 +13,7 @@ import {import { actionTexts } from '@/lib/action-center/display';import type { ActionHistoryItem } from '@/lib/action-center/history';import type { ActionStatus } from '@/lib/action-center/registry';-import { ImpactDots } from './signal-table';-import { ActionIcon } from './action-table';+import { ActionIcon, PriorityBadge } from './action-table';import { cn } from '@/lib/utils';/** Low-saturation per type, the way the Signals table tints its categories —@@ -119,7 +118,6 @@ export function HistoryTable({onSelect: (item: ActionHistoryItem) => void;}) {const t = useTranslations('actionCenter.historyPage');- const tActions = useTranslations('actionCenter.actionsPage');const tTexts = useTranslations('actionCenter.actionTexts');const tTypes = useTranslations('actionCenter.actionCategories');const tAffected = useTranslations('actionCenter.historyPage.affected');@@ -131,7 +129,7 @@ export function HistoryTable({<TableRow><TableHead className="text-xs">{t('table.action')}</TableHead><TableHead className="text-xs">{t('table.type')}</TableHead>- <TableHead className="text-xs">{t('table.impact')}</TableHead>+ <TableHead className="text-xs">{t('table.priority')}</TableHead><TableHead className="text-xs">{t('table.affected')}</TableHead><TableHead className="text-xs">{t('table.result')}</TableHead><TableHead className="text-xs">{t('table.status')}</TableHead>@@ -175,10 +173,7 @@ export function HistoryTable({</Badge></TableCell><TableCell>- <div className="flex items-center gap-1.5">- <span className="text-xs">{tActions(`impact.${item.impact}`)}</span>- <ImpactDots impact={item.impact} />- </div>+ <PriorityBadge score={item.priorityScore} level={item.priorityLevel} /></TableCell><TableCell><div className="space-y-0.5">diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex d1d908569..8f20da4f2 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -202,18 +202,6 @@ export function actionContextTags(action: ActionItem, t: Translator): string[] {return tags;}-const IMPACT_RANK: Record<ActionItem['impact'], number> = { high: 3, medium: 2, low: 1 };--/** Priority: impact first, then weight of evidence, then recency. The- * scoring formula stays out of the UI per the brief — this order IS it. */-export function comparePriority(a: ActionItem, b: ActionItem): number {- return (- IMPACT_RANK[b.impact] - IMPACT_RANK[a.impact] ||- b.signalCount - a.signalCount ||- b.updatedAt.localeCompare(a.updatedAt)- );-}-/*** How a team member is named in an assignee picker.*diff --git a/web/src/lib/action-center/export.test.ts b/web/src/lib/action-center/export.test.tsindex 16be7175f..68437a2a4 100644--- a/web/src/lib/action-center/export.test.ts+++ b/web/src/lib/action-center/export.test.ts@@ -28,6 +28,9 @@ const action = {taskTotal: 2,taskCompleted: 1,signalCount: 1,+ priorityScore: 94,+ priorityLevel: 'critical',+ priorityReason: null,} as ActionItem;const signal: Signal = {@@ -92,10 +95,10 @@ const detail = {const texts: ExportTexts = {title: 'Recover lost citations on 7 prompts',+ priority: { label: '94 (Critical)', why: 'Lost ground on 7 high-demand prompts 2 days ago.' },why: '7 prompts lost their citations.',goal: 'Citations back on 5 of 7 prompts',category: 'Recover',- impact: 'High',status: 'In progress',tags: ['Recover', '1 platform'],kpis: ['AI Visibility (target 40)'],@@ -165,9 +168,10 @@ describe('actionMarkdown', () => {expect(actionMarkdown(exported, label)).toBe(['# Recover lost citations on 7 prompts (AC-52)',- 'category: Recover · impact: High · status: In progress',+ 'priority: 94 (Critical) · category: Recover · status: In progress','assignee: Ada Lovelace · dueDate: 2026-11-09','tags: Recover, 1 platform',+ 'priorityWhy: Lost ground on 7 high-demand prompts 2 days ago.','why: 7 prompts lost their citations.','goal: Citations back on 5 of 7 prompts','kpis: AI Visibility (target 40)',@@ -195,6 +199,7 @@ describe('actionMarkdown', () => {it('leaves out what an action has none of', () => {const bare = {...exported,+ priority: null,assignee: '',dueDate: '',tags: [],@@ -205,7 +210,7 @@ describe('actionMarkdown', () => {events: [],};const md = actionMarkdown(bare, label);- expect(md).not.toMatch(/assignee|tags|kpis|historyHeading/);+ expect(md).not.toMatch(/priority|assignee|tags|kpis|historyHeading/);expect(md).toContain('## tasksHeading(0)');});});@@ -235,6 +240,13 @@ describe('actionWorkbook', () => {'sheets.signals','sheets.history',]);+ expect(sheets[0].data).toContainEqual([+ { value: 'priority', fontWeight: 'bold' },+ '94 (Critical)',+ ]);+ expect(sheets[0].data.map((row) => (row[0] as { value: string }).value)).not.toContain(+ 'impact',+ );expect(sheets[0].data).toContainEqual([{ value: 'Platforms at send time', fontWeight: 'bold' },'Gemini · No runs; ChatGPT · Not cited',diff --git a/web/src/lib/action-center/export.ts b/web/src/lib/action-center/export.tsindex 218a40d69..4b1b1d18c 100644--- a/web/src/lib/action-center/export.ts+++ b/web/src/lib/action-center/export.ts@@ -24,8 +24,9 @@ export interface ActionExport {/** "AC-52". */ref: string;title: string;+ /** "94 (Critical)" and "Why this priority?"; null before the action is scored. */+ priority: { label: string; why: string } | null;category: string;- impact: string;status: string;/** Empty when no one is assigned. */assignee: string;@@ -83,10 +84,10 @@ export interface ExportSignal {/** The labels an `ActionExport` is built from, each already in the reader's language. */export interface ExportTexts {title: string;+ priority: { label: string; why: string } | null;why: string;goal: string;category: string;- impact: string;status: string;tags: string[];kpis: string[];@@ -129,8 +130,8 @@ export function buildActionExport(return {ref: `AC-${action.actionNo}`,title: texts.title,+ priority: texts.priority,category: texts.category,- impact: texts.impact,status: texts.status,assignee: action.assignee?.fullName?.trim() ?? '',dueDate: day(action.dueDate),@@ -210,8 +211,8 @@ export function actionMarkdown(a: ActionExport, label: Labels): string {const lines = [`# ${a.title} (${a.ref})`,facts([+ ['priority', a.priority?.label ?? ''],['category', a.category],- ['impact', a.impact],['status', a.status],]),facts([@@ -219,6 +220,7 @@ export function actionMarkdown(a: ActionExport, label: Labels): string {['dueDate', a.dueDate],]),a.tags.length ? `${label('tags')}: ${a.tags.join(', ')}` : '',+ a.priority?.why ? `${label('priorityWhy')}: ${a.priority.why}` : '',`${label('why')}: ${a.why}`,`${label('goal')}: ${a.goal}`,a.kpis.length ? `${label('kpis')}: ${a.kpis.join(', ')}` : '',@@ -309,8 +311,9 @@ export function actionWorkbook(a: ActionExport, label: Labels): Sheet<Blob>[] {const summary: [string, string][] = [[label('action'), a.ref],[label('title'), a.title],+ [label('priority'), a.priority?.label ?? ''],+ [label('priorityWhy'), a.priority?.why ?? ''],[label('category'), a.category],- [label('impact'), a.impact],[label('status'), a.status],[label('assignee'), a.assignee],[label('dueDate'), a.dueDate],diff --git a/web/src/lib/action-center/history.test.ts b/web/src/lib/action-center/history.test.tsnew file mode 100644index 000000000..388504710--- /dev/null+++ b/web/src/lib/action-center/history.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';+import { compareHistory, summarize, type ActionHistoryItem } from './history';++const item = (over: Partial<ActionHistoryItem> = {}): ActionHistoryItem =>+ ({+ id: 'a',+ status: 'completed',+ outcome: 'pending_measurement',+ priorityScore: null,+ priorityLevel: null,+ createdAt: '2026-10-01T00:00:00Z',+ completedAt: '2026-10-05T00:00:00Z',+ ...over,+ }) as ActionHistoryItem;++describe('compareHistory', () => {+ it('lists the highest priority first, the never-scored last, then the newest', () => {+ const items = [+ item({ id: 'unscored' }),+ item({ id: 'p60-old', priorityScore: 60, completedAt: '2026-10-02T00:00:00Z' }),+ item({ id: 'p92', priorityScore: 92 }),+ item({ id: 'p60-new', priorityScore: 60, completedAt: '2026-10-09T00:00:00Z' }),+ ];+ expect(items.sort(compareHistory('priority')).map((i) => i.id)).toEqual([+ 'p92',+ 'p60-new',+ 'p60-old',+ 'unscored',+ ]);+ });+});++describe('summarize', () => {+ it('reads the highest priority among the actions in range', () => {+ expect(+ summarize([item({ priorityLevel: 'medium' }), item({ priorityLevel: 'critical' })])+ .topPriority,+ ).toBe('critical');+ expect(summarize([item()]).topPriority).toBeNull();+ });+});diff --git a/web/src/lib/action-center/history.ts b/web/src/lib/action-center/history.tsindex 2946f9407..892e7981b 100644--- a/web/src/lib/action-center/history.ts+++ b/web/src/lib/action-center/history.ts@@ -23,13 +23,8 @@* populating these, not reshaping them.*/-import type {- ActionCategory,- ActionImpact,- ActionOutcome,- ActionStatus,- TaskStatus,-} from './registry';+import type { ActionCategory, ActionOutcome, ActionStatus, TaskStatus } from './registry';+import { highestPriorityLevel, type PriorityLevel } from './priority';import type { SignalSource } from '@/lib/signals/registry';import type { ImproveOutcome } from '@/lib/improve-outcome';@@ -91,7 +86,12 @@ export interface ActionHistoryItem {kind: string;/** Grow / Recover / Protect / Fix / Compete — the module's one classification. */type: ActionCategory;- impact: ActionImpact;+ /**+ * The priority score and level (AC-006). An open action's are from last+ * night's scoring; a closed one keeps the last it had. Null if never scored.+ */+ priorityScore: number | null;+ priorityLevel: PriorityLevel | null;status: ActionStatus;/** Did it help? Read from the action's own column, not inferred here. */outcome: ActionOutcome;@@ -122,9 +122,9 @@ export interface HistorySummary {noImprovementPercent: number;dismissed: number;dismissedPercent: number;- /** Highest impact among the actions in range — a readout of what was worked- * on, not a claim about what it achieved. That claim needs validation. */- topImpact: ActionImpact | null;+ /** Highest priority among the actions in range — a readout of what was+ * worked on, not a claim about what it achieved. That claim needs validation. */+ topPriority: PriorityLevel | null;}/** Statuses History covers: an action that has run its course, plus the ones@@ -136,11 +136,28 @@ export const HISTORY_STATUSES: readonly ActionStatus[] = ['dismissed',];-export const HISTORY_SORTS = ['newest', 'oldest', 'impact'] as const;+export const HISTORY_SORTS = ['newest', 'oldest', 'priority'] as const;export type HistorySort = (typeof HISTORY_SORTS)[number];export const HISTORY_PAGE_SIZE = 10;+/** The order the History list shows for a sort, by the date each row shows. */+export function compareHistory(sort: HistorySort) {+ return (a: ActionHistoryItem, b: ActionHistoryItem): number => {+ const aDate = a.completedAt ?? a.createdAt;+ const bDate = b.completedAt ?? b.createdAt;+ switch (sort) {+ case 'oldest':+ return aDate.localeCompare(bDate);+ case 'priority':+ // Highest score first; never-scored actions last.+ return (b.priorityScore ?? -1) - (a.priorityScore ?? -1) || bDate.localeCompare(aDate);+ default:+ return bDate.localeCompare(aDate);+ }+ };+}+const pct = (part: number, total: number) => (total === 0 ? 0 : Math.round((part / total) * 100));export function summarize(items: ActionHistoryItem[]): HistorySummary {@@ -153,15 +170,6 @@ export function summarize(items: ActionHistoryItem[]): HistorySummary {const noImprovement = items.filter((i) => i.outcome === 'no_meaningful_change').length;const dismissed = count('dismissed');- const impacts = items.map((i) => i.impact);- const topImpact: ActionImpact | null = impacts.includes('high')- ? 'high'- : impacts.includes('medium')- ? 'medium'- : impacts.includes('low')- ? 'low'- : null;-return {totalActions: total,completed,@@ -172,7 +180,7 @@ export function summarize(items: ActionHistoryItem[]): HistorySummary {noImprovementPercent: pct(noImprovement, total),dismissed,dismissedPercent: pct(dismissed, total),- topImpact,+ topPriority: highestPriorityLevel(items.map((i) => i.priorityLevel)),};}diff --git a/web/src/lib/action-center/priority.test.ts b/web/src/lib/action-center/priority.test.tsnew file mode 100644index 000000000..2626c6bcf--- /dev/null+++ b/web/src/lib/action-center/priority.test.ts@@ -0,0 +1,184 @@+import { describe, expect, it } from 'vitest';+import { createTranslator } from 'next-intl';+import messages from '../../../messages/en.json';+import type { ActionItem } from '@/lib/actions/action-center';+import {+ comparePriority,+ highestPriorityLevel,+ parsePriorityReason,+ priorityLevelOf,+ priorityReasonText,+ storedPriorityLevel,+ topActionIds,+ type PriorityReason,+} from './priority';++const t = createTranslator({+ locale: 'en',+ messages,+ namespace: 'actionCenter.actionsPage.priority',+}) as unknown as (key: string, values?: Record<string, string | number>) => string;++const action = (over: Partial<ActionItem> = {}): ActionItem =>+ ({+ id: 'a',+ impact: 'medium',+ status: 'new',+ signalCount: 1,+ updatedAt: '2026-10-10T00:00:00Z',+ priorityScore: null,+ priorityLevel: null,+ priorityReason: null,+ ...over,+ }) as ActionItem;++const reason = (over: Partial<PriorityReason> = {}): PriorityReason => ({+ change: 'lost',+ subject: { entity: 'prompts', count: 7 },+ demand: 'high',+ commercial: true,+ heldBefore: true,+ days: 2,+ sources: 1,+ ...over,+});++describe('comparePriority', () => {+ it('puts the highest score first, and unscored actions after scored ones', () => {+ const list = [+ action({ id: 'unscored-high', impact: 'high' }),+ action({ id: 'p60', priorityScore: 60 }),+ action({ id: 'p94', priorityScore: 94 }),+ ];+ expect(list.sort(comparePriority).map((a) => a.id)).toEqual(['p94', 'p60', 'unscored-high']);+ });++ it('breaks a tie by impact, as the list did before scores', () => {+ const list = [+ action({ id: 'medium', priorityScore: 80 }),+ action({ id: 'high', priorityScore: 80, impact: 'high' }),+ ];+ expect(list.sort(comparePriority).map((a) => a.id)).toEqual(['high', 'medium']);+ });+});++describe('topActionIds', () => {+ it('names the five highest-priority open actions', () => {+ const list = [+ ...Array.from({ length: 7 }, (_, i) => action({ id: `open-${i}`, priorityScore: 50 + i })),+ action({ id: 'done', status: 'completed', priorityScore: 99 }),+ ];+ expect([...topActionIds(list)]).toEqual(['open-6', 'open-5', 'open-4', 'open-3', 'open-2']);+ });+});++describe('parsePriorityReason', () => {+ it('reads what the server stored, and drops what it does not know', () => {+ expect(+ parsePriorityReason({+ version: 1,+ change: 'lost',+ subject: { entity: 'prompts', count: 7 },+ demand: 'high',+ commercial: true,+ heldBefore: true,+ days: 2,+ sources: 2,+ factors: { impact: 1 },+ }),+ ).toEqual(reason({ sources: 2 }));+ expect(parsePriorityReason({ change: 'exploded', subject: null })).toMatchObject({+ change: null,+ subject: { entity: null, count: null },+ demand: null,+ });+ expect(parsePriorityReason(null)).toBeNull();+ });+});++describe('the age of the evidence', () => {+ it('counts the days since it was scored, so "2 days ago" stays true', () => {+ const parsed = parsePriorityReason(+ { change: 'lost', days: 2 },+ { scoredAt: '2026-10-12T06:00:00Z', now: new Date('2026-10-15T07:00:00Z') },+ );+ expect(parsed?.days).toBe(5);+ });+});++describe('priorityLevelOf', () => {+ it('reads a level from a score, as the server does', () => {+ expect([95, 80, 60, 10].map(priorityLevelOf)).toEqual(['critical', 'high', 'medium', 'low']);+ });++ it("keeps the stored level, and reads the score's when that is unknown", () => {+ expect(storedPriorityLevel('critical', 80)).toBe('critical');+ expect(storedPriorityLevel('urgent', 80)).toBe('high');+ expect(storedPriorityLevel(null, null)).toBeNull();+ });+});++describe('highestPriorityLevel', () => {+ it('names the highest level, for the summary cards', () => {+ expect(highestPriorityLevel(['medium', null, 'high', 'low'])).toBe('high');+ expect(highestPriorityLevel([null])).toBeNull();+ expect(highestPriorityLevel([])).toBeNull();+ });+});++describe('priorityReasonText', () => {+ it('says what changed, on what, when, and why it matters', () => {+ expect(priorityReasonText(reason(), t)).toBe(+ 'Lost ground on 7 high-demand prompts 2 days ago — commercial intent, previously visible.',+ );+ });++ it('names high demand apart when the subject is not what is searched', () => {+ expect(+ priorityReasonText(+ reason({+ change: 'gap',+ subject: { entity: 'platforms', count: 2 },+ heldBefore: false,+ days: null,+ sources: 0,+ }),+ t,+ ),+ ).toBe('A gap to close on 2 platforms — high search demand, commercial intent.');+ });++ it('counts independent sources, and says today for a fresh finding', () => {+ expect(+ priorityReasonText(+ reason({ change: 'slipping', days: 0, demand: null, commercial: false, sources: 3 }),+ t,+ ),+ ).toBe('Slipping on 7 prompts today — previously visible, confirmed by 3 sources.');+ });++ it('says so when nothing open supports the action any more', () => {+ expect(+ priorityReasonText(+ reason({ change: null, demand: null, commercial: false, heldBefore: false }),+ t,+ ),+ ).toBe('Its findings have resolved.');+ });++ it('falls back to a plain subject when the count is unknown', () => {+ expect(+ priorityReasonText(+ reason({+ change: 'issue',+ subject: { entity: null, count: null },+ demand: 'low',+ commercial: false,+ heldBefore: false,+ days: 5,+ }),+ t,+ ),+ ).toBe('A site issue 5 days ago.');+ });+});diff --git a/web/src/lib/action-center/priority.ts b/web/src/lib/action-center/priority.tsnew file mode 100644index 000000000..89d9e8693--- /dev/null+++ b/web/src/lib/action-center/priority.ts@@ -0,0 +1,202 @@+import type { ActionItem } from '@/lib/actions/action-center';+import { OPEN_ACTION_STATUSES } from '@/lib/action-center/registry';++/**+ * An action's priority as the app shows it (AC-006): the 0–100 score and its+ * level, worked out on the server (server/src/lib/action-center/priority.js),+ * the order the Actions list and the Top Actions card follow, and the+ * "Why this priority?" sentence written from the facts the score rests on.+ */++export const PRIORITY_LEVELS = ['critical', 'high', 'medium', 'low'] as const;+export type PriorityLevel = (typeof PRIORITY_LEVELS)[number];++const CHANGES = ['lost', 'dropped', 'slipping', 'gap', 'issue', 'opportunity', 'gain'] as const;+type PriorityChange = (typeof CHANGES)[number];++/** The facts the server stored with the score (`actions.priority_reason`). */+export interface PriorityReason {+ /** The worst finding's change; null when nothing open supports the action. */+ change: PriorityChange | null;+ subject: { entity: string | null; count: number | null };+ /** Measured demand; null when nothing measures it. */+ demand: 'high' | 'medium' | 'low' | null;+ commercial: boolean;+ /** Ground the brand held and lost. */+ heldBefore: boolean;+ /** Days since the newest evidence; null for an action a person sent. */+ days: number | null;+ /** Independent data sources behind it. */+ sources: number;+}++/** How many actions the Top Actions card names (spec: at most five). */+export const TOP_ACTIONS = 5;++export function isPriorityLevel(value: unknown): value is PriorityLevel {+ return (PRIORITY_LEVELS as readonly unknown[]).includes(value);+}++/** A score's level, as the server assigns it: critical 90+, high 75+, medium 50+. */+export function priorityLevelOf(score: number): PriorityLevel {+ if (score >= 90) return 'critical';+ if (score >= 75) return 'high';+ if (score >= 50) return 'medium';+ return 'low';+}++/** The stored level, or the score's when the stored one is missing or unknown. */+export function storedPriorityLevel(level: unknown, score: number | null): PriorityLevel | null {+ if (isPriorityLevel(level)) return level;+ return score === null ? null : priorityLevelOf(score);+}++/** The highest of these levels — what a summary card shows; null when none is scored. */+export function highestPriorityLevel(levels: (PriorityLevel | null)[]): PriorityLevel | null {+ return PRIORITY_LEVELS.find((level) => levels.includes(level)) ?? null;+}++const DAY_MS = 86_400_000;++/**+ * The stored reason, read defensively: a row from an older scorer may lack+ * parts. Its `days` were counted when it was scored; with `scoredAt` they are+ * brought up to `now`.+ */+export function parsePriorityReason(+ value: unknown,+ { scoredAt, now = new Date() }: { scoredAt?: string | null; now?: Date } = {},+): PriorityReason | null {+ if (!value || typeof value !== 'object') return null;+ const r = value as Record<string, unknown>;+ const subject = (r.subject && typeof r.subject === 'object' ? r.subject : {}) as Record<+ string,+ unknown+ >;+ const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : null);+ return {+ change: (CHANGES as readonly unknown[]).includes(r.change)+ ? (r.change as PriorityChange)+ : null,+ subject: {+ entity: typeof subject.entity === 'string' ? subject.entity : null,+ count: num(subject.count),+ },+ demand: r.demand === 'high' || r.demand === 'medium' || r.demand === 'low' ? r.demand : null,+ commercial: r.commercial === true,+ heldBefore: r.heldBefore === true,+ days: daysSince(num(r.days), scoredAt, now),+ sources: num(r.sources) ?? 0,+ };+}++function daysSince(days: number | null, scoredAt: string | null | undefined, now: Date) {+ if (days === null) return null;+ const at = Date.parse(scoredAt ?? '');+ if (!Number.isFinite(at)) return days;+ return days + Math.max(0, Math.floor((now.getTime() - at) / DAY_MS));+}++const IMPACT_RANK: Record<ActionItem['impact'], number> = { high: 3, medium: 2, low: 1 };++/**+ * Impact first, then weight of evidence, then recency: the order before+ * scores, kept to break ties and to order actions not scored yet.+ */+function compareImpact(a: ActionItem, b: ActionItem): number {+ return (+ IMPACT_RANK[b.impact] - IMPACT_RANK[a.impact] ||+ b.signalCount - a.signalCount ||+ b.updatedAt.localeCompare(a.updatedAt)+ );+}++/**+ * Highest priority first. An action not scored yet (before its first nightly+ * pass) comes after the scored ones, in impact order.+ */+export function comparePriority(a: ActionItem, b: ActionItem): number {+ if (a.priorityScore !== null && b.priorityScore !== null) {+ return b.priorityScore - a.priorityScore || compareImpact(a, b);+ }+ if (a.priorityScore !== null) return -1;+ if (b.priorityScore !== null) return 1;+ return compareImpact(a, b);+}++/** The Top Actions card: the open actions to work on next, at most five. */+export function topActionIds(actions: ActionItem[]): Set<string> {+ return new Set(+ actions+ .filter((action) => OPEN_ACTION_STATUSES.includes(action.status))+ .sort(comparePriority)+ .slice(0, TOP_ACTIONS)+ .map((action) => action.id),+ );+}++type Translator = (key: string, values?: Record<string, string | number>) => string;++/** Entities a count reads naturally with "high-demand" in front. */+const DEMANDED = new Set(['prompts', 'queries', 'pages', 'topics']);+const SUBJECTS = new Set([+ 'prompts',+ 'pages',+ 'queries',+ 'topics',+ 'platforms',+ 'regions',+ 'competitors',+ 'sources',+]);++/**+ * "Why this priority?": what changed, on what, how recently, and what makes+ * it matter — from the action's own facts, in the reader's language+ * (actionsPage.priority.reason). "Lost ground on 7 high-demand prompts+ * 2 days ago — commercial intent, previously visible."+ */+export function priorityReasonText(reason: PriorityReason, t: Translator): string {+ const { entity, count } = reason.subject;+ const adjective =+ reason.demand === 'high' || reason.demand === 'low' ? t(`reason.demand.${reason.demand}`) : '';+ const inSubject =+ Boolean(adjective) && entity !== null && DEMANDED.has(entity) && count !== null && count > 0;+ const known = entity !== null && SUBJECTS.has(entity) && count !== null && count > 0;+ const what = !reason.change+ ? t('reason.change.none')+ : known+ ? t(`reason.change.${reason.change}`, {+ subject: t(`reason.subject.${entity}`, {+ count,+ demand: inSubject ? `${adjective} ` : '',+ }),+ })+ : t(`reason.alone.${reason.change}`);+ const when =+ reason.change && reason.days !== null+ ? reason.days === 0+ ? t('reason.when.today')+ : t('reason.when.days', { days: reason.days })+ : '';++ const extras: string[] = [];+ if (reason.demand === 'high' && !inSubject) extras.push(t('reason.highDemand'));+ if (reason.commercial) extras.push(t('reason.commercial'));+ if (+ reason.heldBefore &&+ (reason.change === 'lost' || reason.change === 'dropped' || reason.change === 'slipping')+ ) {+ extras.push(t('reason.heldBefore'));+ }+ if (reason.sources >= 2) extras.push(t('reason.sources', { count: reason.sources }));++ let text = when ? t('reason.sentence.withWhen', { what, when }) : what;+ if (extras.length) {+ text = t('reason.sentence.withExtras', {+ text,+ extras: extras.join(t('reason.sentence.separator')),+ });+ }+ return t('reason.sentence.end', { text });+}diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex b71a8a98e..e16ff5b26 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -134,6 +134,9 @@ export const ACTION_STATUSES: readonly ActionStatus[] = ['dismissed',];+/** Statuses of an action still to be worked on. */+export const OPEN_ACTION_STATUSES: readonly ActionStatus[] = ['new', 'in_progress', 'on_hold'];+export const ACTION_OUTCOMES: readonly ActionOutcome[] = ['pending_measurement','improved',@@ -145,8 +148,6 @@ export const ACTION_OUTCOMES: readonly ActionOutcome[] = [/** An action whose cycle is over: it is history, and its kind's slot is free. */export const CLOSED_ACTION_STATUSES: readonly ActionStatus[] = ['completed', 'dismissed'];-export const ACTION_IMPACTS: readonly ActionImpact[] = ['high', 'medium', 'low'];-export const TASK_STATUSES: readonly TaskStatus[] = ['todo','in_progress',@@ -238,12 +239,9 @@ export function isActionKind(value: string): value is ActionKind {return (ACTION_KINDS as readonly string[]).includes(value);}-/** Sort orders the toolbar offers. Priority is impact-weighted evidence. */-export type ActionSort = 'priority' | 'impact' | 'newest' | 'due_date' | 'updated';-export const ACTION_SORTS: readonly ActionSort[] = [- 'priority',- 'impact',- 'newest',- 'due_date',- 'updated',-];+/**+ * Sort orders the toolbar offers. Priority is the server's score (AC-006),+ * which already weighs impact in, so impact is not an order of its own.+ */+export type ActionSort = 'priority' | 'newest' | 'due_date' | 'updated';+export const ACTION_SORTS: readonly ActionSort[] = ['priority', 'newest', 'due_date', 'updated'];diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex a3b06b4cb..e5ec3b1c2 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -21,6 +21,12 @@ import {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';+import {+ parsePriorityReason,+ storedPriorityLevel,+ type PriorityLevel,+ type PriorityReason,+} from '@/lib/action-center/priority';export interface ActionAssignee {id: string;@@ -49,6 +55,10 @@ export interface ActionItem {taskTotal: number;taskCompleted: number;signalCount: number;+ /** 0–100 (AC-006); null until the server has scored the action. */+ priorityScore: number | null;+ priorityLevel: PriorityLevel | null;+ priorityReason: PriorityReason | null;}interface ActionRow {@@ -64,10 +74,14 @@ interface ActionRow {due_date: string | null;created_at: string;updated_at: string;+ priority_score: number | null;+ priority_level: string | null;+ priority_reason: unknown;+ priority_updated_at: string | null;}const ACTION_COLUMNS =- 'id, action_no, category, kind, impact, status, payload, kpi_keys, assignee_id, due_date, created_at, updated_at';+ 'id, action_no, category, kind, impact, status, payload, kpi_keys, assignee_id, due_date, created_at, updated_at, priority_score, priority_level, priority_reason, priority_updated_at';export async function getActions(brandId: string): Promise<ActionItem[]> {const supabase = await createClient();@@ -140,6 +154,14 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {taskTotal: taskTotals.get(row.id)?.total ?? 0,taskCompleted: taskTotals.get(row.id)?.completed ?? 0,signalCount: signalCounts.get(row.id) ?? 0,+ priorityScore: row.priority_score === null ? null : Number(row.priority_score),+ priorityLevel: storedPriorityLevel(+ row.priority_level,+ row.priority_score === null ? null : Number(row.priority_score),+ ),+ priorityReason: parsePriorityReason(row.priority_reason, {+ scoredAt: row.priority_updated_at,+ }),}));}diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.tsindex 4fe0809c6..8c1d1d10d 100644--- a/web/src/lib/actions/action-history.ts+++ b/web/src/lib/actions/action-history.ts@@ -15,10 +15,11 @@*/import { createClient } from '@/lib/supabase/server';-import type { ActionCategory, ActionImpact } from '@/lib/action-center/registry';+import type { ActionCategory } 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 { storedPriorityLevel } from '@/lib/action-center/priority';import {HISTORY_STATUSES,daysBetween,@@ -34,7 +35,6 @@ interface HistoryRow {action_no: number;category: string;kind: string;- impact: string;status: string;outcome: string;validation: ValidationSnapshot | null;@@ -45,10 +45,12 @@ interface HistoryRow {created_at: string;completed_at: string | null;updated_at: string;+ priority_score: number | null;+ priority_level: string | null;}const HISTORY_COLUMNS =- 'id, action_no, category, kind, impact, status, outcome, validation, position_outcome, payload, kpi_keys, assignee_id, created_at, completed_at, updated_at';+ 'id, action_no, category, kind, status, outcome, validation, position_outcome, payload, kpi_keys, assignee_id, created_at, completed_at, updated_at, priority_score, priority_level';/** What the validation sweep stores on an action. */interface ValidationSnapshot {@@ -238,12 +240,14 @@ export async function getActionHistory(return rows.map((row) => {const triggerSignals = signalsByAction.get(row.id) ?? [];const results = resultsFrom(row.validation);+ const score = row.priority_score === null ? null : Number(row.priority_score);return {id: row.id,actionNo: Number(row.action_no),kind: row.kind,type: row.category as ActionCategory,- impact: row.impact as ActionImpact,+ priorityScore: score,+ priorityLevel: storedPriorityLevel(row.priority_level, score),status: row.status as ActionStatus,outcome: row.outcome as ActionOutcome,positionOutcome: parseImproveOutcome(row.position_outcome ?? null),diff --git a/web/src/lib/mcp/action-priority.test.ts b/web/src/lib/mcp/action-priority.test.tsnew file mode 100644index 000000000..8163f46c1--- /dev/null+++ b/web/src/lib/mcp/action-priority.test.ts@@ -0,0 +1,115 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { McpAuthContext } from '@/lib/mcp-auth';++/**+ * list_actions carries each action's priority (AC-006) and can list them in+ * the order to work on them.+ */++let orders: [string, Record<string, unknown> | undefined][] = [];++const ACTIONS = [+ {+ id: 'a1',+ action_no: 52,+ category: 'recover',+ kind: 'recover_lost_citations',+ impact: 'high',+ status: 'new',+ outcome: null,+ assignee_id: null,+ due_date: null,+ created_at: '2026-10-01T00:00:00Z',+ updated_at: '2026-10-14T00:00:00Z',+ priority_score: 94,+ priority_level: 'critical',+ priority_reason: { change: 'lost', demand: 'high' },+ },+ {+ id: 'a2',+ action_no: 53,+ category: 'growth',+ kind: 'create_content_for_demand',+ impact: 'medium',+ status: 'new',+ outcome: null,+ assignee_id: null,+ due_date: null,+ created_at: '2026-10-01T00:00:00Z',+ updated_at: '2026-10-15T00:00:00Z',+ priority_score: null,+ priority_level: null,+ priority_reason: null,+ },+];++function builder(table: string) {+ const chain = {+ select: () => chain,+ eq: () => chain,+ in: () => chain,+ order: (column: string, options?: Record<string, unknown>) => {+ if (table === 'actions') orders.push([column, options]);+ return chain;+ },+ limit: () => chain,+ maybeSingle: async () => ({+ data:+ table === 'actions'+ ? { ...ACTIONS[0], brand_id: 'brand-1', payload: {} }+ : { id: 'brand-1' },+ error: null,+ }),+ then: (resolve: (v: { data: unknown; error: null }) => void) =>+ resolve({ data: table === 'actions' ? ACTIONS : [], error: null }),+ };+ return chain;+}++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: { from: (table: string) => builder(table) },+}));++const { getActionFor, listActionsFor } = await import('./data');++const auth: McpAuthContext = {+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+};++describe('listActionsFor', () => {+ beforeEach(() => {+ orders = [];+ });++ it('gives each action its priority, or null before it is scored', async () => {+ const rows = await listActionsFor(auth, { brandId: 'brand-1' });+ expect(rows?.map((r) => r.priority)).toEqual([+ { score: 94, level: 'critical', reason: { change: 'lost', demand: 'high' } },+ null,+ ]);+ // Highest priority first, unscored ones last, as the app lists them.+ expect(orders).toEqual([+ ['priority_score', { ascending: false, nullsFirst: false }],+ ['updated_at', { ascending: false }],+ ]);+ });++ it('lists the most recently updated first when asked', async () => {+ await listActionsFor(auth, { brandId: 'brand-1', sort: 'updated' });+ expect(orders).toEqual([['updated_at', { ascending: false }]]);+ });+});++describe('getActionFor', () => {+ it('gives the action its priority', async () => {+ const action = await getActionFor(auth, 'a1');+ expect(action?.priority).toEqual({+ score: 94,+ level: 'critical',+ reason: { change: 'lost', demand: 'high' },+ });+ });+});diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex 5d6362b68..fe89811fd 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -2522,15 +2522,49 @@ export interface ActionListRow {assignee: { id: string; full_name: string | null } | null;due_date: string | null;task_progress: { completed: number; total: number };+ priority: ActionPriorityForMcp | null;created_at: string;updated_at: string;}+/**+ * An action's priority (AC-006): its 0–100 score, its level, and the facts+ * the score rests on (change, subject, demand, commercial intent, whether the+ * ground was held before, days since the evidence, and each factor 0–1).+ * Null until the server has scored the action.+ */+export interface ActionPriorityForMcp {+ score: number;+ level: string | null;+ reason: Record<string, unknown> | null;+}++function priorityFor(row: {+ priority_score?: number | null;+ priority_level?: string | null;+ priority_reason?: unknown;+}): ActionPriorityForMcp | null {+ if (row.priority_score === null || row.priority_score === undefined) return null;+ return {+ score: Number(row.priority_score),+ level: row.priority_level ?? null,+ reason:+ row.priority_reason && typeof row.priority_reason === 'object'+ ? (row.priority_reason as Record<string, unknown>)+ : null,+ };+}+export interface ListActionsParams {brandId: string;status?: string;category?: string;limit?: number;+ /**+ * `priority` (default): highest priority score first, unscored last — the+ * order the app lists them in; `updated`: most recently updated first.+ */+ sort?: 'updated' | 'priority';}export async function listActionsFor(@@ -2543,11 +2577,16 @@ export async function listActionsFor(let query = supabaseAdmin.from('actions').select(- 'id, action_no, category, kind, impact, status, outcome, assignee_id, due_date, created_at, updated_at',+ 'id, action_no, category, kind, impact, status, outcome, assignee_id, due_date, created_at, updated_at, priority_score, priority_level, priority_reason',)- .eq('brand_id', params.brandId)- .order('updated_at', { ascending: false })- .limit(limit);+ .eq('brand_id', params.brandId);+ query =+ params.sort === 'updated'+ ? query.order('updated_at', { ascending: false })+ : query+ .order('priority_score', { ascending: false, nullsFirst: false })+ .order('updated_at', { ascending: false });+ query = query.limit(limit);if (params.status) query = query.eq('status', params.status);if (params.category) query = query.eq('category', params.category);@@ -2588,6 +2627,7 @@ export async function listActionsFor(: null,due_date: r.due_date ?? null,task_progress: progress.get(r.id) ?? { completed: 0, total: 0 },+ priority: priorityFor(r),created_at: r.created_at,updated_at: r.updated_at,}));@@ -2606,6 +2646,7 @@ export interface ActionDetailForMcp {kpi_keys: string[];assignee: { id: string; full_name: string | null } | null;due_date: string | null;+ priority: ActionPriorityForMcp | null;created_at: string;updated_at: string;completed_at: string | null;@@ -2634,7 +2675,7 @@ export async function getActionFor(const { data: action, error } = await supabaseAdmin.from('actions').select(- 'id, action_no, brand_id, category, kind, impact, status, outcome, payload, kpi_keys, assignee_id, due_date, created_at, updated_at, completed_at, brands!inner(organization_id)',+ 'id, action_no, brand_id, category, kind, impact, status, outcome, payload, kpi_keys, assignee_id, due_date, created_at, updated_at, completed_at, priority_score, priority_level, priority_reason, brands!inner(organization_id)',).eq('id', actionId).eq('brands.organization_id', auth.organizationId)@@ -2682,6 +2723,7 @@ export async function getActionFor(? { id: action.assignee_id, full_name: names.get(action.assignee_id) ?? null }: null,due_date: action.due_date ?? null,+ priority: priorityFor(action),created_at: action.created_at,updated_at: action.updated_at,completed_at: action.completed_at ?? null,diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex eb09fd173..eebdfc427 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -888,7 +888,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'list_actions',{description:- 'List the Action Center actions for a brand: what the product thinks should be done about its AI visibility. Each action was consolidated from one or more detected signals and carries a task plan. Returns category, kind, impact, status, outcome, assignee, due date and task progress, most recently updated first. `kind` is an opaque definition id (e.g. "close_competitor_gap"); the action payload with the specifics is on get_action. Use this to see open work ("what should we do next?") or to check what is in progress.',+ 'List the Action Center actions for a brand: what the product thinks should be done about its AI visibility. Each action was consolidated from one or more detected signals and carries a task plan. Returns category, kind, impact, priority (a 0–100 score, its level — critical, high, medium or low — and the facts it rests on; null until scored), status, outcome, assignee, due date and task progress, highest priority first (unscored last), or most recently updated first with sort "updated". `kind` is an opaque definition id (e.g. "close_competitor_gap"); the action payload with the specifics is on get_action. Use this to see open work ("what should we do next?") or to check what is in progress.',inputSchema: {brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),status: z@@ -906,6 +906,12 @@ export function createMcpServer(auth: McpAuthContext): McpServer {.max(200).optional().describe('Row cap limit (default 50, max 200).'),+ sort: z+ .enum(['updated', 'priority'])+ .optional()+ .describe(+ 'Order: "priority" (default) highest priority score first — the order to work on them; "updated" most recently updated first.',+ ),},},async (args) => {@@ -914,6 +920,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {status: args.status,category: args.category,limit: args.limit,+ sort: args.sort,});if (actions === null) {return {@@ -931,7 +938,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'get_action',{description:- 'Get one Action Center action in full: its payload (the prompts, pages, competitors or numbers it is about), the signals that triggered it, its task list and its event trail. Each task carries `mode` (who carries it out: system, agent, human or human_or_agent) and `permission` (read, write or execute). Read both before proposing to act on a task — anything beyond read needs a human to approve it in the dashboard. A task is described by `title` when someone wrote one, otherwise by `task_key` with `title_params`.',+ 'Get one Action Center action in full: its priority (score, level and the facts it rests on), its payload (the prompts, pages, competitors or numbers it is about), the signals that triggered it, its task list and its event trail. Each task carries `mode` (who carries it out: system, agent, human or human_or_agent) and `permission` (read, write or execute). Read both before proposing to act on a task — anything beyond read needs a human to approve it in the dashboard. A task is described by `title` when someone wrote one, otherwise by `task_key` with `title_params`.',inputSchema: {action_id: relaxedUuid.describe('Action UUID, from list_actions or list_action_history.'),},