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): return an action as Markdown or CSV from the API and MCP (#1084)
Cihanda168bc325c7
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex fef4c5b6f..5702ccf53 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -284,12 +284,27 @@ intent, not during exploratory queries.| Tool | What it does | Writes || --- | --- | --- || `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. | |+| `get_action` | One action in full: priority, payload, triggering signals, tasks (`mode`, `permission`), and event trail. `format: "markdown"` or `"csv"` returns it as the dashboard's **Copy Data** and **Export CSV** write it instead. | || `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** || `create_improve_action` | Send a prompt's Improve suggestions to Action Center as a `prompt_improve` action (needs a generated suggestion set for the range and a plan with Improve; idempotent on `idempotency_key`). | **yes** |+#### Export an action++`get_action` takes an optional `format`:++- `json` (default): the fields above.+- `markdown`: everything the action's tabs show, ready to paste into a doc, a ticket or another agent. This is the same text as **Copy Data** in the dashboard.+- `csv`: a row per affected item, task and signal, with a `section` column. This is the same file as **Export CSV**.++Labels are in English and dates in UTC. The same export is available over REST with the same `ans_` key. The CSV comes as a download (`action-AC-52.csv`) that Excel opens as UTF-8.++```bash+curl "https://app.ansvisor.com/api/mcp/actions/<action_id>?format=markdown" \+ -H "Authorization: Bearer ans_..."+```+New tools may ship between releases — see `server.ts` and the [project roadmap](https://github.com/ansvisor/ansvisor#whats-next).## Try itdiff --git a/web/src/app/api/mcp/actions/[id]/route.test.ts b/web/src/app/api/mcp/actions/[id]/route.test.tsnew file mode 100644index 000000000..0e3b2e131--- /dev/null+++ b/web/src/app/api/mcp/actions/[id]/route.test.ts@@ -0,0 +1,74 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * GET /api/mcp/actions/{id}?format= (AC-005): the fields by default, the+ * Copy Data Markdown, or the Export CSV as a file Excel reads as UTF-8.+ */++const { exportActionFor, getActionFor } = vi.hoisted(() => ({+ exportActionFor: vi.fn(),+ getActionFor: vi.fn(),+}));+vi.mock('@/lib/mcp-auth', () => ({+ authenticateMcpRequest: vi.fn(async () => ({+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ })),+}));+vi.mock('@/lib/mcp/data', () => ({ getActionFor }));+vi.mock('@/lib/mcp/action-export', () => ({ exportActionFor }));++const { GET } = await import('./route');++const get = (query = '') =>+ GET(new Request(`http://localhost/api/mcp/actions/a1${query}`), {+ params: Promise.resolve({ id: 'a1' }),+ });++beforeEach(() => {+ exportActionFor.mockReset();+ getActionFor.mockReset();+});++describe('GET /api/mcp/actions/{id}', () => {+ it('returns the fields as JSON by default, as before', async () => {+ getActionFor.mockResolvedValue({ id: 'a1', action_no: 52 });+ const res = await get();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ id: 'a1', action_no: 52 });+ expect(exportActionFor).not.toHaveBeenCalled();+ });++ it('returns the Markdown Copy Data writes', async () => {+ exportActionFor.mockResolvedValue({ body: '# Title (AC-52)\n', fileName: 'action-AC-52.md' });+ const res = await get('?format=markdown');+ expect(exportActionFor).toHaveBeenCalledWith(expect.anything(), 'a1', 'markdown');+ expect(res.headers.get('content-type')).toBe('text/markdown; charset=utf-8');+ expect(await res.text()).toBe('# Title (AC-52)\n');+ });++ it('returns the CSV as a download, with the byte order mark Excel needs', async () => {+ exportActionFor.mockResolvedValue({ body: 'section,action\n', fileName: 'action-AC-52.csv' });+ const res = await get('?format=csv');+ expect(res.headers.get('content-type')).toBe('text/csv; charset=utf-8');+ expect(res.headers.get('content-disposition')).toBe('attachment; filename="action-AC-52.csv"');+ const bytes = new Uint8Array(await res.arrayBuffer());+ expect([...bytes.slice(0, 3)]).toEqual([0xef, 0xbb, 0xbf]);+ });++ it('refuses a format it does not know, and says which it does', async () => {+ const res = await get('?format=xml');+ expect(res.status).toBe(400);+ expect((await res.json()).error).toBe('format must be one of json, markdown, csv');+ });++ it("says so when the action isn't the key's", async () => {+ exportActionFor.mockResolvedValue(null);+ expect((await get('?format=csv')).status).toBe(404);+ getActionFor.mockResolvedValue(null);+ expect((await get()).status).toBe(404);+ });+});diff --git a/web/src/app/api/mcp/actions/[id]/route.ts b/web/src/app/api/mcp/actions/[id]/route.tsindex ae2d4fc72..b2d3d3313 100644--- a/web/src/app/api/mcp/actions/[id]/route.ts+++ b/web/src/app/api/mcp/actions/[id]/route.ts@@ -1,8 +1,16 @@import { NextResponse } from 'next/server';import { authenticateMcpRequest } from '@/lib/mcp-auth';import { getActionFor } from '@/lib/mcp/data';+import { exportActionFor } from '@/lib/mcp/action-export';+import { BYTE_ORDER_MARK } from '@/lib/action-center/export';-/** GET /api/mcp/actions/[id] — REST mirror of the `get_action` MCP tool. */+const FORMATS = ['json', 'markdown', 'csv'] as const;++/**+ * GET /api/mcp/actions/[id] — REST mirror of the `get_action` MCP tool.+ * `?format=markdown` or `?format=csv` returns the action as the dashboard's+ * Copy Data and Export CSV write it (AC-005); `json`, the default, the fields.+ */export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {const auth = await authenticateMcpRequest(req);if (auth instanceof NextResponse) return auth;@@ -11,8 +19,29 @@ export async function GET(req: Request, { params }: { params: Promise<{ id: striif (!id) {return NextResponse.json({ error: 'id is required' }, { status: 400 });}+ const format = new URL(req.url).searchParams.get('format') ?? 'json';+ if (!(FORMATS as readonly string[]).includes(format)) {+ return NextResponse.json(+ { error: `format must be one of ${FORMATS.join(', ')}` },+ { status: 400 },+ );+ }try {+ if (format === 'markdown' || format === 'csv') {+ const exported = await exportActionFor(auth, id, format);+ if (!exported) {+ return NextResponse.json({ error: 'Action not found' }, { status: 404 });+ }+ // The CSV starts with a byte order mark, so Excel reads it as UTF-8.+ return new Response(format === 'csv' ? BYTE_ORDER_MARK + exported.body : exported.body, {+ headers: {+ 'Content-Type':+ format === 'csv' ? 'text/csv; charset=utf-8' : 'text/markdown; charset=utf-8',+ 'Content-Disposition': `${format === 'csv' ? 'attachment' : 'inline'}; filename="${exported.fileName}"`,+ },+ });+ }const action = await getActionFor(auth, id);if (!action) {return NextResponse.json({ error: 'Action not found' }, { status: 404 });diff --git a/web/src/components/action-center/action-export-buttons.tsx b/web/src/components/action-center/action-export-buttons.tsxindex 306cb4408..8e323c05b 100644--- a/web/src/components/action-center/action-export-buttons.tsx+++ b/web/src/components/action-center/action-export-buttons.tsx@@ -8,39 +8,26 @@ import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';import type { ActionDetail, ActionItem } from '@/lib/actions/action-center';import { getOpportunity, getOpportunityBasket } from '@/lib/actions/content';-import {- actionContextTags,- actionEventText,- actionGoal,- actionTexts,- taskText,-} from '@/lib/action-center/display';import {BYTE_ORDER_MARK,actionCsv,actionExportFileName,actionMarkdown,actionWorkbook,- buildActionExport,type ActionExport,- type ExportFact,- type ExportAffected,} 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, signalTypeLabel } from '@/lib/signals/display';+import {+ EXPORT_NAMESPACES,+ labelActionExport,+ sentFromOpportunityId,+ type ExportTranslators,+ type SentFromOpportunity,+} from '@/lib/action-center/export-labels';import { viewerTimeZone } from '@/lib/time-zone';-import { isSuperseded } from './signal-table';-import { affectedCounts, leaderText, type Affected } from '@/lib/action-center/affected';+import { affectedCounts, type Affected } from '@/lib/action-center/affected';import type { ActionStory } from '@/lib/action-center/story';-import { platformName } from '@/lib/signals/names';-import { getPlatformName } from '@/lib/traffic-platforms';-import { formatCompactNumber } from '@/lib/format';import { saveBlob } from '@/lib/download';-const IMPROVE_STATES = ['not_mentioned', 'mentioned_late', 'not_cited', 'doing_well', 'no_runs'];-/*** Copy all, Export CSV and Export Excel for one action (AC-005): what every* tab of the drawer shows, to take into a doc, a ticket or a spreadsheet.@@ -63,229 +50,64 @@ export function ActionExportButtons({/** Why and Goal as the drawer words them, from the action's data (AC-003). */story?: ActionStory | null;}) {- const t = useTranslations('actionCenter.actionsPage');const tExport = useTranslations('actionCenter.actionsPage.export');- const tImprove = useTranslations('actionCenter.actionsPage.drawer.improve');- const tOpportunity = useTranslations('actionCenter.actionsPage.drawer.opportunity');- const tContent = useTranslations('content');- const tTexts = useTranslations('actionCenter.actionTexts');- const tCategories = useTranslations('actionCenter.actionCategories');- const tRegistry = useTranslations('actionCenter.registry');- const tTasks = useTranslations('actionCenter.actionTasks');- const tTaskStatus = useTranslations('actionCenter.taskStatus');- const tTaskTypes = useTranslations('actionCenter.taskTypes');- const tSignals = useTranslations('actionCenter.signalsPage');- const tSignalTexts = useTranslations('actionCenter.signalTexts');- const tSignalCategories = useTranslations('actionCenter.signalCategories');- const tPriority = useTranslations('actionCenter.actionsPage.priority');- const tAffected = useTranslations('actionCenter.actionsPage.drawer.affected');+ // Every label the export reads, from the same namespaces the API uses.+ const t: ExportTranslators = {+ page: useTranslations(EXPORT_NAMESPACES.page),+ export: tExport,+ improve: useTranslations(EXPORT_NAMESPACES.improve),+ opportunity: useTranslations(EXPORT_NAMESPACES.opportunity),+ content: useTranslations(EXPORT_NAMESPACES.content),+ texts: useTranslations(EXPORT_NAMESPACES.texts),+ categories: useTranslations(EXPORT_NAMESPACES.categories),+ registry: useTranslations(EXPORT_NAMESPACES.registry),+ tasks: useTranslations(EXPORT_NAMESPACES.tasks),+ taskStatus: useTranslations(EXPORT_NAMESPACES.taskStatus),+ taskTypes: useTranslations(EXPORT_NAMESPACES.taskTypes),+ signals: useTranslations(EXPORT_NAMESPACES.signals),+ signalTexts: useTranslations(EXPORT_NAMESPACES.signalTexts),+ signalCategories: useTranslations(EXPORT_NAMESPACES.signalCategories),+ priority: useTranslations(EXPORT_NAMESPACES.priority),+ affected: useTranslations(EXPORT_NAMESPACES.affected),+ };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);const [justCopied, setJustCopied] = useState(false);const previewRef = useRef<HTMLTextAreaElement>(null);- /** What the Overview tab shows of where a person sent the action from. */- const sentFrom = async (origin: string): Promise<ExportFact[]> => {- const p = action.payload ?? {};- if (action.kind === 'prompt_improve') {- const platforms = Array.isArray(p.platforms)- ? (p.platforms as { label?: unknown; state?: unknown }[]).filter(- (x): x is { label: string; state: string } =>- typeof x.label === 'string' &&- typeof x.state === 'string' &&- IMPROVE_STATES.includes(x.state),- )- : [];- const facts: ExportFact[] = [{ label: tImprove('source'), value: tImprove('sourceValue') }];- if (typeof p.promptText === 'string') {- facts.push({ label: tImprove('prompt'), value: p.promptText });- }- if (platforms.length) {- facts.push({- label: tImprove('platforms'),- value: platforms.map((x) => `${x.label} · ${tImprove(`states.${x.state}`)}`),- });- }- if (typeof p.panelLink === 'string') {- facts.push({ label: tImprove('openPanel'), value: `${origin}${p.panelLink}` });- }- return facts;- }- if (action.kind !== 'content_opportunity' || typeof p.opportunityId !== 'string') return [];-- const pageUrls = Array.isArray(p.pages)- ? (p.pages as unknown[]).filter((u): u is string => typeof u === 'string')- : [];+ /** A Content action's opportunity and basket, as the Overview tab reads them. */+ const readSentFrom = async (): Promise<SentFromOpportunity | null> => {+ const id = sentFromOpportunityId(action);+ if (!id) return null;try {const [opportunity, basket] = await Promise.all([- getOpportunity(p.opportunityId),- getOpportunityBasket(p.opportunityId),+ getOpportunity(id),+ getOpportunityBasket(id),]);- const { pages, prompts, queries } = opportunityLists(- opportunity,- basket,- p.assetKey ? pageUrls : undefined,- );- const brief = opportunity.brief;- const facts: ExportFact[] = [- { label: tOpportunity('title'), value: opportunity.title },- { label: tOpportunity('open'), value: `${origin}/dashboard/content/${opportunity.id}` },- ];- if (opportunity.decision) {- facts.push({- label: tExport('decision'),- value: tContent(`decision.${opportunity.decision}`),- });- }- if (pages.length) {- facts.push({ label: tExport('pages'), value: pages.map((page) => page.url) });- }- if (brief) {- facts.push({- label: tOpportunity('brief'),- value: [- `${brief.suggestedTitle} · ${brief.contentType.replace(/-/g, ' ')} · ${tOpportunity('words', { count: brief.targetWordCount })}`,- ...brief.outline.map(- (section, i) =>- `${i + 1}. ${section.heading}${section.keyPoints.length ? `: ${section.keyPoints.join('; ')}` : ''}`,- ),- ],- });- }- if (prompts.length) {- facts.push({- label: tOpportunity('prompts', { count: prompts.length }),- value: prompts.map((prompt) => prompt.text),- });- }- if (queries.length) {- facts.push({- label: tOpportunity('queries', { count: queries.length }),- value: queries.map((query) => query.query),- });- }- return facts;+ return { opportunity, basket };} catch {- return [{ label: tOpportunity('title'), value: tOpportunity('unavailable') }];+ return 'unavailable';}};const build = async (): Promise<ActionExport | null> => {if (!detail) return null;- const origin = window.location.origin;- const texts = actionTexts(action, tTexts);- const related: string[] = action.kpiKeys.filter(isKpiKey);- return buildActionExport(- action,- detail,+ return labelActionExport({- 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: story?.why ?? texts.description,- goal: story?.goal ?? actionGoal(action.kind, tTexts, action.payload),- category: tCategories(action.category),- status: t(`status.${action.status}`),- tags: actionContextTags(action, t),- kpis: detail.kpis- .filter((kpi) => related.includes(kpi.kpiKey) && isKpiKey(kpi.kpiKey))- .map(- (kpi) =>- `${tRegistry(`${kpi.kpiKey}.name`)} (${t('drawer.kpiTarget', { target: kpi.target })})`,- ),- context: await sentFrom(origin),- affected: exportAffected(origin),- taskTitle: (task) => taskText(task, tTasks),- taskStatus: (status) => tTaskStatus(status),- signal: (signal) => {- const affected = signalAffected(signal, tSignals);- return {- ...signalTexts(signal, tSignalTexts),- type: signalTypeLabel(signal, tSignalCategories, tSignals),- entity: affected.detail ?? affected.label,- category: tSignalCategories(signal.category),- status: isSuperseded(signal)- ? tSignals('superseded')- : tSignals(`status.${signal.status}`),- impact: tSignals(`impact.${signal.impact}`),- };- },- event: (event) => actionEventText(event, t, tTasks),- skipped: (reason) => tExport('skipped', { reason }),- taskType: (type) => tTaskTypes(type),- taskSent: (to) => tExport(to === 'content' ? 'sentToContent' : 'sentToWebhook'),- answerSource: tExport('answerSource'),+ action,+ detail,+ affected,+ volumes,+ story,+ sentFrom: await readSentFrom(),+ origin: window.location.origin,+ timeZone: viewerTimeZone(),},- { origin, timeZone: viewerTimeZone() },+ t,);};- /** The Affected tab's rows, labelled for the exports (AC-003). */- const exportAffected = (origin: string): ExportAffected[] => {- if (!affected) return [];- const row = (over: Partial<ExportAffected>): ExportAffected => ({- entity: '',- label: '',- volume: '',- platforms: [],- lostPages: [],- citedInstead: [],- details: '',- link: '',- ...over,- });- const leadersShown = affected.prompts.some((p) => p.leaders.length > 0);- return [- ...affected.prompts.map((prompt) => {- const volume = prompt.id ? volumes?.get(prompt.id) : undefined;- return row({- entity: tExport('affectedPrompt'),- label: prompt.text,- volume: volume ? `~${formatCompactNumber(volume)}` : '',- platforms: prompt.platforms.map(platformName),- lostPages: prompt.lostPages,- citedInstead: prompt.citedInstead,- details: prompt.leaders.map((leader) => leaderText(leader, tAffected)).join('; '),- link: prompt.id ? `${origin}/dashboard/prompts/${prompt.id}` : '',- });- }),- ...affected.pages.map((page) =>- row({- entity: tExport('affectedPage'),- label: page.url,- platforms: page.platforms.map(getPlatformName),- details: [- page.sessions !== null && page.before !== null- ? `${tAffected('visits')}: ${tAffected('visitsValue', { before: page.before, now: page.sessions })}`- : '',- page.issues.join(', '),- ]- .filter(Boolean)- .join('; '),- link: /^https?:\/\//.test(page.url) ? page.url : '',- }),- ),- ...(leadersShown- ? []- : affected.competitors.map((name) =>- row({ entity: tExport('affectedCompetitor'), label: name }),- )),- ...affected.topics.map((name) => row({ entity: tExport('affectedTopic'), label: name })),- ];- };-/** Builds the export once, holding the buttons while it runs. */const run = async (fn: (data: ActionExport) => Promise<void> | void) => {setIsBusy(true);diff --git a/web/src/components/action-center/signal-table.tsx b/web/src/components/action-center/signal-table.tsxindex 0054c04f1..af42d2702 100644--- a/web/src/components/action-center/signal-table.tsx+++ b/web/src/components/action-center/signal-table.tsx@@ -50,13 +50,16 @@ import {type SignalSource,type SignalStatus,} from '@/lib/signals/registry';-import { signalAffected, signalTexts } from '@/lib/signals/display';+import { isSuperseded, signalAffected, signalTexts } from '@/lib/signals/display';import { locationName, platformFamily, platformName } from '@/lib/signals/names';import type { SignalWhere } from '@/lib/signals/where';import { groupLead, groupStatus, groupWhere, type SignalGroup } from '@/lib/signals/group';import { formatRelative } from '@/lib/format-relative';import { cn } from '@/lib/utils';+// Kept here for the pages that import it with the table.+export { isSuperseded };+/** Icons for the original kinds. The library's forty-seven take their* category's — a traffic finding reads as traffic whichever detector wrote it. */export const SIGNAL_ICONS: Partial<@@ -138,15 +141,6 @@ const STATE_TEXT: Record<string, string> = {opportunity: 'text-emerald-600 dark:text-emerald-400',};-/**- * A signal the engine closed because its subject moved to another kind — a- * topic that went from slipping to dropped — reads "Changed", not "Resolved":- * nothing was fixed, the finding became a different one.- */-export function isSuperseded(signal: Pick<Signal, 'status' | 'payload'>): boolean {- return signal.status === 'resolved' && typeof signal.payload?.supersededBy === 'string';-}-export function SignalStatusBadge({status,superseded = false,diff --git a/web/src/lib/action-center/export-labels.ts b/web/src/lib/action-center/export-labels.tsnew file mode 100644index 000000000..3775fda7b--- /dev/null+++ b/web/src/lib/action-center/export-labels.ts@@ -0,0 +1,300 @@+import type { ActionDetail, ActionItem } from '@/lib/actions/action-center';+import type { ContentOpportunity, OpportunityBasket } from '@/types';+import {+ actionContextTags,+ actionEventText,+ actionGoal,+ actionTexts,+ taskText,+} from '@/lib/action-center/display';+import {+ buildActionExport,+ type ActionExport,+ type ExportAffected,+ type ExportFact,+} from '@/lib/action-center/export';+import { leaderText, type Affected } from '@/lib/action-center/affected';+import type { ActionStory } from '@/lib/action-center/story';+import { priorityReasonText } from '@/lib/action-center/priority';+import { opportunityLists } from '@/lib/content/opportunity-lists';+import { isKpiKey } from '@/lib/kpis/registry';+import { isSuperseded, signalAffected, signalTexts, signalTypeLabel } from '@/lib/signals/display';+import { platformName } from '@/lib/signals/names';+import { getPlatformName } from '@/lib/traffic-platforms';+import { formatCompactNumber } from '@/lib/format';++/**+ * An action's export, labelled (AC-005): what the drawer's Copy Data, Export+ * CSV and Export Excel show, and what the API and MCP return as Markdown or+ * CSV. Both read the same labels from en.json, so the two always say the same+ * thing; only where the data comes from differs.+ */++type Translator = ((key: string, values?: Record<string, string | number>) => string) & {+ has?: (key: string) => boolean;+};++/** The en.json namespaces the export's labels come from. */+export const EXPORT_NAMESPACES = {+ page: 'actionCenter.actionsPage',+ export: 'actionCenter.actionsPage.export',+ improve: 'actionCenter.actionsPage.drawer.improve',+ opportunity: 'actionCenter.actionsPage.drawer.opportunity',+ content: 'content',+ texts: 'actionCenter.actionTexts',+ categories: 'actionCenter.actionCategories',+ registry: 'actionCenter.registry',+ tasks: 'actionCenter.actionTasks',+ taskStatus: 'actionCenter.taskStatus',+ taskTypes: 'actionCenter.taskTypes',+ signals: 'actionCenter.signalsPage',+ signalTexts: 'actionCenter.signalTexts',+ signalCategories: 'actionCenter.signalCategories',+ priority: 'actionCenter.actionsPage.priority',+ affected: 'actionCenter.actionsPage.drawer.affected',+} as const;++export type ExportTranslators = Record<keyof typeof EXPORT_NAMESPACES, Translator>;++/** A Content action's opportunity and its basket, or that they couldn't be read. */+export type SentFromOpportunity =+ | {+ opportunity: Pick<ContentOpportunity, 'id' | 'title' | 'decision' | 'brief' | 'sourceData'>;+ basket: OpportunityBasket;+ }+ | 'unavailable';++const IMPROVE_STATES = ['not_mentioned', 'mentioned_late', 'not_cited', 'doing_well', 'no_runs'];++/** The opportunity a Content action was sent from, when it carries one. */+export function sentFromOpportunityId(action: Pick<ActionItem, 'kind' | 'payload'>): string | null {+ const id = action.payload?.opportunityId;+ return action.kind === 'content_opportunity' && typeof id === 'string' ? id : null;+}++/**+ * What the Overview tab shows of where a person sent the action from: the+ * Improve tab's prompt and platforms, or a content opportunity's pages, brief+ * and prompts.+ */+export function sentFromFacts(+ action: ActionItem,+ sent: SentFromOpportunity | null,+ origin: string,+ t: ExportTranslators,+): ExportFact[] {+ const p = action.payload ?? {};+ if (action.kind === 'prompt_improve') {+ const platforms = Array.isArray(p.platforms)+ ? (p.platforms as { label?: unknown; state?: unknown }[]).filter(+ (x): x is { label: string; state: string } =>+ typeof x.label === 'string' &&+ typeof x.state === 'string' &&+ IMPROVE_STATES.includes(x.state),+ )+ : [];+ const facts: ExportFact[] = [{ label: t.improve('source'), value: t.improve('sourceValue') }];+ if (typeof p.promptText === 'string') {+ facts.push({ label: t.improve('prompt'), value: p.promptText });+ }+ if (platforms.length) {+ facts.push({+ label: t.improve('platforms'),+ value: platforms.map((x) => `${x.label} · ${t.improve(`states.${x.state}`)}`),+ });+ }+ if (typeof p.panelLink === 'string') {+ facts.push({ label: t.improve('openPanel'), value: `${origin}${p.panelLink}` });+ }+ return facts;+ }+ if (!sentFromOpportunityId(action) || !sent) return [];+ if (sent === 'unavailable') {+ return [{ label: t.opportunity('title'), value: t.opportunity('unavailable') }];+ }++ const { opportunity, basket } = sent;+ const pageUrls = Array.isArray(p.pages)+ ? (p.pages as unknown[]).filter((u): u is string => typeof u === 'string')+ : [];+ const { pages, prompts, queries } = opportunityLists(+ opportunity,+ basket,+ p.assetKey ? pageUrls : undefined,+ );+ const brief = opportunity.brief;+ const facts: ExportFact[] = [+ { label: t.opportunity('title'), value: opportunity.title },+ { label: t.opportunity('open'), value: `${origin}/dashboard/content/${opportunity.id}` },+ ];+ if (opportunity.decision) {+ facts.push({+ label: t.export('decision'),+ value: t.content(`decision.${opportunity.decision}`),+ });+ }+ if (pages.length) {+ facts.push({ label: t.export('pages'), value: pages.map((page) => page.url) });+ }+ if (brief) {+ facts.push({+ label: t.opportunity('brief'),+ value: [+ `${brief.suggestedTitle} · ${brief.contentType.replace(/-/g, ' ')} · ${t.opportunity('words', { count: brief.targetWordCount })}`,+ ...brief.outline.map(+ (section, i) =>+ `${i + 1}. ${section.heading}${section.keyPoints.length ? `: ${section.keyPoints.join('; ')}` : ''}`,+ ),+ ],+ });+ }+ if (prompts.length) {+ facts.push({+ label: t.opportunity('prompts', { count: prompts.length }),+ value: prompts.map((prompt) => prompt.text),+ });+ }+ if (queries.length) {+ facts.push({+ label: t.opportunity('queries', { count: queries.length }),+ value: queries.map((query) => query.query),+ });+ }+ return facts;+}++/** The Affected tab's rows, labelled for the exports (AC-003). */+export function exportAffectedRows(+ affected: Affected | null,+ volumes: Map<string, number> | null,+ origin: string,+ t: ExportTranslators,+): ExportAffected[] {+ if (!affected) return [];+ const row = (over: Partial<ExportAffected>): ExportAffected => ({+ entity: '',+ label: '',+ volume: '',+ platforms: [],+ lostPages: [],+ citedInstead: [],+ details: '',+ link: '',+ ...over,+ });+ const leadersShown = affected.prompts.some((p) => p.leaders.length > 0);+ return [+ ...affected.prompts.map((prompt) => {+ const volume = prompt.id ? volumes?.get(prompt.id) : undefined;+ return row({+ entity: t.export('affectedPrompt'),+ label: prompt.text,+ volume: volume ? `~${formatCompactNumber(volume)}` : '',+ platforms: prompt.platforms.map(platformName),+ lostPages: prompt.lostPages,+ citedInstead: prompt.citedInstead,+ details: prompt.leaders.map((leader) => leaderText(leader, t.affected)).join('; '),+ link: prompt.id ? `${origin}/dashboard/prompts/${prompt.id}` : '',+ });+ }),+ ...affected.pages.map((page) =>+ row({+ entity: t.export('affectedPage'),+ label: page.url,+ platforms: page.platforms.map(getPlatformName),+ details: [+ page.sessions !== null && page.before !== null+ ? `${t.affected('visits')}: ${t.affected('visitsValue', { before: page.before, now: page.sessions })}`+ : '',+ page.issues.join(', '),+ ]+ .filter(Boolean)+ .join('; '),+ link: /^https?:\/\//.test(page.url) ? page.url : '',+ }),+ ),+ ...(leadersShown+ ? []+ : affected.competitors.map((name) =>+ row({ entity: t.export('affectedCompetitor'), label: name }),+ )),+ ...affected.topics.map((name) => row({ entity: t.export('affectedTopic'), label: name })),+ ];+}++export interface ActionExportInput {+ action: ActionItem;+ detail: ActionDetail;+ /** The Affected tab's list and its prompts' demand (AC-003). */+ affected: Affected | null;+ volumes: Map<string, number> | null;+ /** Why and Goal in the action's own terms (AC-003); null for an action a person sent. */+ story: ActionStory | null;+ /** A Content action's opportunity, read by the caller. */+ sentFrom: SentFromOpportunity | null;+ /** Where links point: the app's origin. */+ origin: string;+ /** The reader's time zone, for the dates. */+ timeZone: string;+}++/** The whole action, every tab, labelled as the drawer shows it. */+export function labelActionExport(input: ActionExportInput, t: ExportTranslators): ActionExport {+ const { action, detail, origin } = input;+ const texts = actionTexts(action, t.texts);+ const related: string[] = action.kpiKeys.filter(isKpiKey);+ return buildActionExport(+ action,+ 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.page('export.priorityValue', {+ score: action.priorityScore,+ level: t.priority(`levels.${action.priorityLevel}`),+ }),+ why: action.priorityReason+ ? priorityReasonText(action.priorityReason, t.priority)+ : '',+ }+ : null,+ why: input.story?.why ?? texts.description,+ goal: input.story?.goal ?? actionGoal(action.kind, t.texts, action.payload),+ category: t.categories(action.category),+ status: t.page(`status.${action.status}`),+ tags: actionContextTags(action, t.page),+ kpis: detail.kpis+ .filter((kpi) => related.includes(kpi.kpiKey) && isKpiKey(kpi.kpiKey))+ .map(+ (kpi) =>+ `${t.registry(`${kpi.kpiKey}.name`)} (${t.page('drawer.kpiTarget', { target: kpi.target })})`,+ ),+ context: sentFromFacts(action, input.sentFrom, origin, t),+ affected: exportAffectedRows(input.affected, input.volumes, origin, t),+ taskTitle: (task) => taskText(task, t.tasks),+ taskStatus: (status) => t.taskStatus(status),+ signal: (signal) => {+ const affected = signalAffected(signal, t.signals);+ return {+ ...signalTexts(signal, t.signalTexts),+ type: signalTypeLabel(signal, t.signalCategories, t.signals),+ entity: affected.detail ?? affected.label,+ category: t.signalCategories(signal.category),+ status: isSuperseded(signal)+ ? t.signals('superseded')+ : t.signals(`status.${signal.status}`),+ impact: t.signals(`impact.${signal.impact}`),+ };+ },+ event: (event) => actionEventText(event, t.page, t.tasks),+ skipped: (reason) => t.export('skipped', { reason }),+ taskType: (type) => t.taskTypes(type),+ taskSent: (to) => t.export(to === 'content' ? 'sentToContent' : 'sentToWebhook'),+ answerSource: t.export('answerSource'),+ },+ { origin, timeZone: input.timeZone },+ );+}diff --git a/web/src/lib/action-center/export.ts b/web/src/lib/action-center/export.tsindex 741d4b2ff..5109fc6f0 100644--- a/web/src/lib/action-center/export.ts+++ b/web/src/lib/action-center/export.ts@@ -640,6 +640,6 @@ export function actionWorkbook(a: ActionExport, label: Labels): Sheet<Blob>[] {}/** `action-AC-52.csv`, as the spec names it. */-export function actionExportFileName(a: ActionExport, extension: 'csv' | 'xlsx') {+export function actionExportFileName(a: ActionExport, extension: 'csv' | 'xlsx' | 'md') {return `action-${a.ref}.${extension}`;}diff --git a/web/src/lib/action-center/prompt-demand.ts b/web/src/lib/action-center/prompt-demand.tsnew file mode 100644index 000000000..64225b781--- /dev/null+++ b/web/src/lib/action-center/prompt-demand.ts@@ -0,0 +1,42 @@+import type { SupabaseClient } from '@supabase/supabase-js';+import { supabaseAdmin } from '@/lib/supabase/admin';++/** Prompt ids per request, so the filter stays well inside a URL's length. */+const DEMAND_CHUNK = 150;++/**+ * The estimated monthly AI searches of these prompts, for the Affected tab's+ * Volume column and the Why (AC-003). prompt_volumes is a server-only table,+ * so the prompts are first checked to be the brand's with `client` — the+ * signed-in user's (RLS), or the admin client once the API has checked the+ * key's organization — and only theirs are read with the admin client.+ */+export async function readPromptDemand(+ client: SupabaseClient,+ brandId: string,+ promptIds: string[],+): Promise<Map<string, number>> {+ const demand = new Map<string, number>();+ const ids = [...new Set(promptIds)];+ for (let i = 0; i < ids.length; i += DEMAND_CHUNK) {+ const chunk = ids.slice(i, i + DEMAND_CHUNK);+ const { data: visible, error } = await client+ .from('prompts')+ .select('id, prompt_sets!inner(brand_id)')+ .eq('prompt_sets.brand_id', brandId)+ .in('id', chunk);+ if (error) throw new Error(error.message);+ const allowed = (visible ?? []).map((row) => row.id as string);+ if (allowed.length === 0) continue;+ const { data: rows, error: volumeError } = await supabaseAdmin+ .from('prompt_volumes')+ .select('prompt_id, est_ai_volume')+ .in('prompt_id', allowed);+ if (volumeError) throw new Error(volumeError.message);+ for (const row of rows ?? []) {+ const volume = Number(row.est_ai_volume ?? 0);+ if (volume > 0) demand.set(row.prompt_id as string, volume);+ }+ }+ return demand;+}diff --git a/web/src/lib/action-center/rows.ts b/web/src/lib/action-center/rows.tsnew file mode 100644index 000000000..54f8a4e1a--- /dev/null+++ b/web/src/lib/action-center/rows.ts@@ -0,0 +1,116 @@+import type {+ ActionAssignee,+ ActionEvent,+ ActionItem,+ ActionKpiRef,+ ActionTask,+} from '@/lib/actions/action-center';+import type {+ ActionCategory,+ ActionImpact,+ ActionStatus,+ TaskStatus,+} from '@/lib/action-center/registry';+import type { KpiTimeframe } from '@/lib/kpis/registry';+import { parsePriorityReason, storedPriorityLevel } from '@/lib/action-center/priority';+import { parseTaskDetails } from '@/lib/action-center/task-details';++/**+ * Action Center rows → the shapes the dashboard reads, shared by its server+ * actions (as the signed-in user) and the API's export (through an API key).+ * Kept out of the 'use server' module, which may only export async functions.+ */++export interface ActionRow {+ id: string;+ action_no: number;+ category: string;+ kind: string;+ impact: string;+ status: string;+ payload: Record<string, unknown>;+ kpi_keys: string[];+ assignee_id: string | null;+ 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;+}++export const ACTION_COLUMNS =+ '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 const TASK_COLUMNS =+ 'id, position, task_key, title, status, skip_reason, title_params, depends_on, details';++export const EVENT_COLUMNS = 'id, event, data, actor_id, created_at';++/** An action row, with what the list counts beside it. */+export function actionItemFromRow(+ row: ActionRow,+ extra: {+ assignee: ActionAssignee | null;+ taskTotal: number;+ taskCompleted: number;+ signalCount: number;+ },+): ActionItem {+ const score = row.priority_score === null ? null : Number(row.priority_score);+ return {+ id: row.id,+ actionNo: Number(row.action_no),+ category: row.category as ActionCategory,+ kind: row.kind,+ impact: row.impact as ActionImpact,+ status: row.status as ActionStatus,+ payload: row.payload ?? {},+ kpiKeys: row.kpi_keys ?? [],+ assignee: extra.assignee,+ dueDate: row.due_date,+ createdAt: row.created_at,+ updatedAt: row.updated_at,+ taskTotal: extra.taskTotal,+ taskCompleted: extra.taskCompleted,+ signalCount: extra.signalCount,+ priorityScore: score,+ priorityLevel: storedPriorityLevel(row.priority_level, score),+ priorityReason: parsePriorityReason(row.priority_reason, {+ scoredAt: row.priority_updated_at,+ }),+ };+}++export function taskFromRow(task: Record<string, unknown>): ActionTask {+ return {+ id: task.id as string,+ position: task.position as number,+ taskKey: (task.task_key as string | null) ?? null,+ title: (task.title as string | null) ?? null,+ status: task.status as TaskStatus,+ titleParams: (task.title_params ?? {}) as Record<string, string | number>,+ dependsOn: (task.depends_on ?? []) as string[],+ skipReason: (task.skip_reason as string | null) ?? null,+ details: parseTaskDetails(task.details),+ };+}++export function eventFromRow(event: Record<string, unknown>): ActionEvent {+ return {+ id: event.id as string,+ event: event.event as string,+ data: (event.data ?? {}) as Record<string, unknown>,+ actorId: (event.actor_id as string | null) ?? null,+ createdAt: event.created_at as string,+ };+}++export function kpiFromRow(kpi: Record<string, unknown>): ActionKpiRef {+ return {+ kpiKey: kpi.kpi_key as string,+ target: Number(kpi.target),+ timeframe: kpi.timeframe as KpiTimeframe,+ };+}diff --git a/web/src/lib/action-center/story.ts b/web/src/lib/action-center/story.tsindex 6356873c0..96134937b 100644--- a/web/src/lib/action-center/story.ts+++ b/web/src/lib/action-center/story.ts@@ -180,7 +180,9 @@ function listOf(items: string[], t: Translator, format: StoryFormat): string {/** A calendar date ("2026-11-09") as that day where the reader is. */function calendarDay(value: string): Date {const [year, month, day] = value.slice(0, 10).split('-').map(Number);- return new Date(year, month - 1, day);+ // Noon, not midnight: the same day wherever it is written out — the+ // reader's zone in the drawer, UTC in the API's export (AC-005).+ return new Date(year, month - 1, day, 12);}export interface ActionStory {diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex a05b0e5ee..253bc834f 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -22,22 +22,26 @@ import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from 'import { OPEN_SIGNAL_STATUSES, type SignalStatus } from '@/lib/signals/registry';import { readPromptPlaces } from '@/lib/signals/prompt-places';import { affectedOf, affectedSignals, affectedSummary } from '@/lib/action-center/affected';-import { supabaseAdmin } from '@/lib/supabase/admin';+import { readPromptDemand } from '@/lib/action-center/prompt-demand';+import {+ ACTION_COLUMNS,+ EVENT_COLUMNS,+ TASK_COLUMNS,+ actionItemFromRow,+ eventFromRow,+ kpiFromRow,+ taskFromRow,+ type ActionRow,+} from '@/lib/action-center/rows';import type { KpiTimeframe } from '@/lib/kpis/registry';import { parseImproveOutcome, type ImproveOutcome } from '@/lib/improve-outcome';import {cleanTaskDetailsEdit,isTaskDetailsEdit,- parseTaskDetails,type ActionTaskDetails,type TaskDetailsEdit,} from '@/lib/action-center/task-details';-import {- parsePriorityReason,- storedPriorityLevel,- type PriorityLevel,- type PriorityReason,-} from '@/lib/action-center/priority';+import type { PriorityLevel, PriorityReason } from '@/lib/action-center/priority';export interface ActionAssignee {id: string;@@ -72,28 +76,6 @@ export interface ActionItem {priorityReason: PriorityReason | null;}-interface ActionRow {- id: string;- action_no: number;- category: string;- kind: string;- impact: string;- status: string;- payload: Record<string, unknown>;- kpi_keys: string[];- assignee_id: string | null;- 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, priority_score, priority_level, priority_reason, priority_updated_at';-export async function getActions(brandId: string): Promise<ActionItem[]> {const supabase = await createClient();const { data, error } = await supabase@@ -151,31 +133,14 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {]),);- return rows.map((row) => ({- id: row.id,- actionNo: Number(row.action_no),- category: row.category as ActionCategory,- kind: row.kind,- impact: row.impact as ActionImpact,- status: row.status as ActionStatus,- payload: row.payload ?? {},- kpiKeys: row.kpi_keys ?? [],- assignee: row.assignee_id ? (profiles.get(row.assignee_id) ?? null) : null,- dueDate: row.due_date,- createdAt: row.created_at,- updatedAt: row.updated_at,- 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,+ return rows.map((row) =>+ actionItemFromRow(row, {+ assignee: row.assignee_id ? (profiles.get(row.assignee_id) ?? null) : null,+ taskTotal: taskTotals.get(row.id)?.total ?? 0,+ taskCompleted: taskTotals.get(row.id)?.completed ?? 0,+ signalCount: signalCounts.get(row.id) ?? 0,}),- }));+ );}export interface ActionTask {@@ -233,13 +198,7 @@ export interface ActionDetail {export async function getActionDetail(brandId: string, actionId: string): Promise<ActionDetail> {const supabase = await createClient();const [tasksRes, signalsRes, eventsRes, kpisRes, outcomeRes, places] = await Promise.all([- supabase- .from('action_tasks')- .select(- 'id, position, task_key, title, status, skip_reason, title_params, depends_on, details',- )- .eq('action_id', actionId)- .order('position'),+ supabase.from('action_tasks').select(TASK_COLUMNS).eq('action_id', actionId).order('position'),// Every signal the action has taken as evidence (AC-007), kept after a// signal moves on to a later cycle: a closed action still shows its own.supabase@@ -250,7 +209,7 @@ export async function getActionDetail(brandId: string, actionId: string): Promis.order('detected_at', { ascending: false }),supabase.from('action_events')- .select('id, event, data, actor_id, created_at')+ .select(EVENT_COLUMNS).eq('action_id', actionId).order('created_at'),supabase@@ -274,30 +233,10 @@ export async function getActionDetail(brandId: string, actionId: string): Promisif (kpisRes.error) throw new Error(kpisRes.error.message);return {- tasks: (tasksRes.data ?? []).map((task) => ({- id: task.id,- position: task.position,- taskKey: task.task_key,- title: task.title,- status: task.status as TaskStatus,- titleParams: (task.title_params ?? {}) as Record<string, string | number>,- dependsOn: (task.depends_on ?? []) as string[],- skipReason: task.skip_reason,- details: parseTaskDetails(task.details),- })),+ tasks: (tasksRes.data ?? []).map(taskFromRow),signals: mapSignalRows((signalsRes.data ?? []) as SignalRow[], places),- events: (eventsRes.data ?? []).map((event) => ({- id: event.id,- event: event.event,- data: (event.data ?? {}) as Record<string, unknown>,- actorId: event.actor_id,- createdAt: event.created_at,- })),- kpis: (kpisRes.data ?? []).map((kpi) => ({- kpiKey: kpi.kpi_key,- target: Number(kpi.target),- timeframe: kpi.timeframe as KpiTimeframe,- })),+ events: (eventsRes.data ?? []).map(eventFromRow),+ kpis: (kpisRes.data ?? []).map(kpiFromRow),positionOutcome: parseImproveOutcome(outcomeRes.data?.position_outcome ?? null),};}@@ -539,44 +478,17 @@ export async function deleteTask(brandId: string, actionId: string, taskId: striawait touchAction(supabase, brandId, actionId);}-/** Prompt ids per request, so the filter stays well inside a URL's length. */-const DEMAND_CHUNK = 150;-/*** The estimated monthly AI searches of these prompts, for the Affected tab's- * Volume column (AC-003). prompt_volumes is a server-only table, so the- * prompts are first checked to be the brand's and visible to the caller- * (RLS), and only theirs are read with the admin client.+ * Volume column (AC-003); see readPromptDemand.*/export async function getPromptDemand(brandId: string,promptIds: string[],): Promise<Record<string, number>> {- const ids = [...new Set(promptIds)];- if (ids.length === 0) return {};+ if (promptIds.length === 0) return {};const supabase = await createClient();- const demand: Record<string, number> = {};- for (let i = 0; i < ids.length; i += DEMAND_CHUNK) {- const chunk = ids.slice(i, i + DEMAND_CHUNK);- const { data: visible, error } = await supabase- .from('prompts')- .select('id, prompt_sets!inner(brand_id)')- .eq('prompt_sets.brand_id', brandId)- .in('id', chunk);- if (error) throw new Error(error.message);- const allowed = (visible ?? []).map((row) => row.id as string);- if (allowed.length === 0) continue;- const { data: rows, error: volumeError } = await supabaseAdmin- .from('prompt_volumes')- .select('prompt_id, est_ai_volume')- .in('prompt_id', allowed);- if (volumeError) throw new Error(volumeError.message);- for (const row of rows ?? []) {- const volume = Number(row.est_ai_volume ?? 0);- if (volume > 0) demand[row.prompt_id as string] = volume;- }- }- return demand;+ return Object.fromEntries(await readPromptDemand(supabase, brandId, promptIds));}/** Action ids per request, and signal rows per page, for the list's export. */diff --git a/web/src/lib/content/opportunity-lists.ts b/web/src/lib/content/opportunity-lists.tsindex 451ff27ee..86dd6fc3f 100644--- a/web/src/lib/content/opportunity-lists.ts+++ b/web/src/lib/content/opportunity-lists.ts@@ -6,7 +6,7 @@ import type { ContentOpportunity, OpportunityBasket } from '@/types';* The action's export lists the same.*/export function opportunityLists(- opportunity: ContentOpportunity,+ opportunity: Pick<ContentOpportunity, 'sourceData'>,basket: OpportunityBasket,pageUrls?: string[],) {diff --git a/web/src/lib/mcp/action-export.test.ts b/web/src/lib/mcp/action-export.test.tsnew file mode 100644index 000000000..4aa930dad--- /dev/null+++ b/web/src/lib/mcp/action-export.test.ts@@ -0,0 +1,293 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { McpAuthContext } from '@/lib/mcp-auth';++/**+ * get_action's Markdown and CSV (AC-005): the drawer's Copy Data and Export+ * CSV, read through an API key — nothing for another organization's action,+ * and the Affected list, its demand, the Why and a Content action's+ * opportunity worked out here as the drawer works them out.+ */++type Row = Record<string, unknown>;+let rows: Record<string, Row[]>;+let reads: string[];+/** Tables whose reads fail. */+let failing: Set<string>;++/** A column, or a joined one ("brands.organization_id"), as PostgREST filters it. */+function valueOf(row: Row, column: string): unknown[] {+ const [head, tail] = column.split('.');+ if (!tail) return [row[head]];+ const joined = row[head];+ return (Array.isArray(joined) ? joined : [joined]).map((j) => (j as Row | null)?.[tail]);+}++function table(name: string) {+ reads.push(name);+ const tests: ((row: Row) => boolean)[] = [];+ let range: [number, number] | null = null;+ const result = () => {+ const found = (rows[name] ?? []).filter((row) => tests.every((test) => test(row)));+ return range ? found.slice(range[0], range[1] + 1) : found;+ };+ let head = false;+ const chain = {+ select: (_columns?: string, options?: { head?: boolean }) => {+ head = Boolean(options?.head);+ return chain;+ },+ eq: (column: string, value: unknown) => {+ tests.push((row) => valueOf(row, column).includes(value));+ return chain;+ },+ in: (column: string, values: unknown[]) => {+ tests.push((row) => valueOf(row, column).some((v) => values.includes(v)));+ return chain;+ },+ order: () => chain,+ range: (from: number, to: number) => {+ range = [from, to];+ return chain;+ },+ maybeSingle: async () => ({ data: result()[0] ?? null, error: null }),+ then: (resolve: (value: unknown) => unknown) =>+ resolve(+ failing.has(name)+ ? { data: null, error: { message: `${name} unavailable` } }+ : head+ ? { data: null, count: result().length, error: null }+ : { data: result(), error: null },+ ),+ };+ return chain;+}++vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: { from: table } }));++const { exportActionFor } = await import('./action-export');++const auth: McpAuthContext = {+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+};++const actionRow = (over: Row = {}): Row => ({+ id: 'a1',+ action_no: 52,+ brand_id: 'b1',+ brands: { organization_id: 'org-1' },+ category: 'recover',+ kind: 'recover_lost_citations',+ impact: 'high',+ status: 'new',+ payload: {},+ kpi_keys: [],+ assignee_id: null,+ due_date: null,+ created_at: '2026-10-10T00:00:00Z',+ updated_at: '2026-10-10T00:00:00Z',+ priority_score: 84,+ priority_level: 'high',+ priority_reason: null,+ priority_updated_at: null,+ ...over,+});++beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://app.example.com/');+ reads = [];+ failing = new Set();+ rows = {+ actions: [actionRow()],+ action_tasks: [+ {+ id: 't1',+ action_id: 'a1',+ position: 1,+ task_key: null,+ title: 'Add a 2026 table to /pricing',+ status: 'todo',+ skip_reason: null,+ title_params: {},+ depends_on: [],+ details: { where: 'acme.example/pricing', how: ['Add a table.'], type: 'content' },+ },+ ],+ signals: [+ {+ id: 's1',+ brand_id: 'b1',+ category: 'citation',+ kind: 'lost_citations',+ impact: 'high',+ status: 'new',+ source: ['ai_results'],+ detected_at: '2026-10-09T00:00:00Z',+ last_detected_at: '2026-10-09T00:00:00Z',+ resolved_at: null,+ previous_value: null,+ current_value: null,+ change_value: null,+ payload: {+ promptId: 'p1',+ promptText: 'Best coffee subscription?',+ lostUrls: [{ url: 'https://acme.example/pricing', position: 2 }],+ citedNow: [{ url: 'https://beanbox.example/guide', position: 1 }],+ },+ kpi_keys: [],+ action_id: 'a1',+ action_signals: [{ action_id: 'a1' }],+ },+ ],+ action_events: [+ {+ id: 'e1',+ action_id: 'a1',+ event: 'created',+ data: {},+ actor_id: null,+ created_at: '2026-10-10T00:00:00Z',+ },+ ],+ kpi_definitions: [],+ prompts: [+ {+ id: 'p1',+ text: 'Best coffee subscription?',+ prompt_sets: { brand_id: 'b1' },+ platforms: ['chatgpt-web'],+ regions: ['US'],+ topic_id: null,+ is_active: true,+ topics: null,+ },+ ],+ prompt_volumes: [{ prompt_id: 'p1', est_ai_volume: 5500 }],+ };+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('exportActionFor', () => {+ it('writes the action as Copy Data does: every tab, the Affected list with its demand', async () => {+ const exported = await exportActionFor(auth, 'a1', 'markdown');+ expect(exported?.fileName).toBe('action-AC-52.md');+ const md = exported!.body;++ expect(md).toMatch(/^# .+ \(AC-52\)\n/);+ expect(md).toContain('Priority: 84 (High) · Category: Recover · Status: New');+ // The list's tags: the signals that support it now.+ expect(md).toMatch(/^Tags: 1 signal$/m);+ expect(md).toContain('Link: https://app.example.com/dashboard/action-center/actions?action=a1');+ expect(md).toContain('## Affected (1)');+ expect(md).toContain('Best coffee subscription?');+ expect(md).toContain('~5.5k');+ expect(md).toContain('## Tasks (1)\n1. Add a 2026 table to /pricing (To Do)');+ expect(md).toContain('## Signals (1)');+ // The Why in the action's own terms, from its signal, with the day in UTC.+ expect(md).toMatch(/Why: .*Oct 9/);+ });++ it("still writes the action when its prompts' demand can't be read, without it", async () => {+ failing.add('prompt_volumes');+ const md = (await exportActionFor(auth, 'a1', 'markdown'))!.body;+ expect(md).toContain('Best coffee subscription?');+ expect(md).not.toContain('~5.5k');+ });++ it('dates the goal by its due date on a server east of UTC', async () => {+ const zone = process.env.TZ;+ process.env.TZ = 'Europe/Istanbul';+ try {+ rows.actions = [actionRow({ due_date: '2026-11-09' })];+ const md = (await exportActionFor(auth, 'a1', 'markdown'))!.body;+ expect(md).toMatch(/^Goal: .* by Nov 9\.$/m);+ } finally {+ process.env.TZ = zone;+ }+ });++ it('writes the CSV with a row per affected item, task and signal', async () => {+ const exported = await exportActionFor(auth, 'a1', 'csv');+ expect(exported?.fileName).toBe('action-AC-52.csv');+ const lines = exported!.body.split('\n');+ expect(lines[0]).toMatch(/^section,action,ref,title,/);+ expect(lines.slice(1).map((line) => line.split(',')[0])).toEqual([+ 'affected',+ 'task',+ 'signal',+ ]);+ });++ it("says nothing of another organization's action, and reads nothing more", async () => {+ expect(+ await exportActionFor({ ...auth, organizationId: 'org-2' }, 'a1', 'markdown'),+ ).toBeNull();+ expect(reads).toEqual(['actions']);+ expect(await exportActionFor({ ...auth, organizationId: null }, 'a1', 'csv')).toBeNull();+ });++ it('lists what a Content action was sent from: its opportunity, prompts and kept queries', async () => {+ rows.actions = [+ actionRow({+ kind: 'content_opportunity',+ category: 'growth',+ payload: { opportunityId: 'o1' },+ }),+ ];+ rows.signals = [];+ rows.content_opportunities = [+ {+ id: 'o1',+ brand_id: 'b1',+ title: 'Coffee subscription guide',+ decision: 'create',+ brief: null,+ source_data: { targetPages: [{ url: 'https://acme.example/subscriptions', title: '' }] },+ cluster_id: 'c1',+ related_cluster_ids: [],+ prompt_id: null,+ },+ ];+ rows.prompt_cluster_members = [+ { cluster_id: 'c1', prompts: { id: 'p1', text: 'Best coffee subscription?' } },+ ];+ rows.prompt_cluster_queries = [+ {+ cluster_id: 'c1',+ query: 'coffee subscription',+ times_searched: 3,+ included: true,+ reason: '',+ },+ {+ cluster_id: 'c1',+ query: 'free coffee',+ times_searched: 1,+ included: false,+ reason: 'off-topic',+ },+ ];++ const md = (await exportActionFor(auth, 'a1', 'markdown'))!.body;+ expect(md).toContain('Coffee subscription guide');+ expect(md).toContain('https://app.example.com/dashboard/content/o1');+ expect(md).toContain('https://acme.example/subscriptions');+ expect(md).toContain('Best coffee subscription?');+ expect(md).toContain('coffee subscription');+ expect(md).not.toContain('free coffee');+ });++ it("says the opportunity can't be read when it is gone", async () => {+ rows.actions = [actionRow({ kind: 'content_opportunity', payload: { opportunityId: 'o9' } })];+ const md = (await exportActionFor(auth, 'a1', 'markdown'))!.body;+ expect(md).toContain(+ 'Content opportunity: The opportunity this action was sent from is no longer available.',+ );+ expect(md).not.toContain('/dashboard/content/o9');+ });+});diff --git a/web/src/lib/mcp/action-export.ts b/web/src/lib/mcp/action-export.tsnew file mode 100644index 000000000..b01d39c51--- /dev/null+++ b/web/src/lib/mcp/action-export.ts@@ -0,0 +1,301 @@+import { createFormatter, createTranslator } from 'next-intl';+import messages from '../../../messages/en.json';+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { McpAuthContext } from '@/lib/mcp-auth';+import type { ActionDetail } from '@/lib/actions/action-center';+import type { ContentOpportunity, OpportunityBasket } from '@/types';+import { SIGNAL_ROW_COLUMNS, mapSignalRows, type SignalRow } from '@/lib/signals/map';+import { readPromptPlaces } from '@/lib/signals/prompt-places';+import { OPEN_SIGNAL_STATUSES, type SignalStatus } from '@/lib/signals/registry';+import { UNCOUNTED_TASK_STATUSES } from '@/lib/action-center/registry';+import { affectedOf, affectedSignals } from '@/lib/action-center/affected';+import { actionStory } from '@/lib/action-center/story';+import { readPromptDemand } from '@/lib/action-center/prompt-demand';+import { actionCsv, actionExportFileName, actionMarkdown } from '@/lib/action-center/export';+import {+ EXPORT_NAMESPACES,+ labelActionExport,+ sentFromOpportunityId,+ type ExportTranslators,+ type SentFromOpportunity,+} from '@/lib/action-center/export-labels';+import {+ ACTION_COLUMNS,+ EVENT_COLUMNS,+ TASK_COLUMNS,+ actionItemFromRow,+ eventFromRow,+ kpiFromRow,+ taskFromRow,+ type ActionRow,+} from '@/lib/action-center/rows';++/**+ * One action as Markdown or CSV for the API and MCP (AC-005): the drawer's+ * Copy Data and Export CSV, read through an API key. The same labelling as the+ * drawer, with the Affected list, its prompts' demand, the Why and Goal and a+ * Content action's opportunity read here instead of by the browser. Dates are+ * in UTC, labels in English.+ */++export type ActionExportFormat = 'markdown' | 'csv';++/** The app's address, for the links the export carries. */+function appOrigin(): string {+ return (process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000').replace(/\/$/, '');+}++type PlainTranslator = ExportTranslators[keyof ExportTranslators];++/** A namespace of en.json behind the plain (key, values) shape the export's helpers take. */+function translator(namespace: string): PlainTranslator {+ const t = createTranslator({ locale: 'en', messages, namespace: namespace as never });+ const plain = (key: string, values?: Record<string, string | number>) =>+ t(key as never, values as never);+ return Object.assign(plain, { has: (key: string) => t.has(key as never) });+}++let built: { labels: ExportTranslators; story: PlainTranslator } | null = null;++/** Every label the export reads, from en.json as the drawer reads them; built once. */+function translators() {+ built ??= {+ labels: Object.fromEntries(+ Object.entries(EXPORT_NAMESPACES).map(([key, namespace]) => [key, translator(namespace)]),+ ) as ExportTranslators,+ story: translator('actionCenter.actionsPage.drawer.story'),+ };+ return built;+}++/**+ * A Content action's opportunity and the prompts and queries it answers, as+ * the Content API returns them for the drawer. 'unavailable' when it is gone.+ */+async function sentFromOpportunity(+ brandId: string,+ opportunityId: string,+): Promise<SentFromOpportunity> {+ const { data: row, error } = await supabaseAdmin+ .from('content_opportunities')+ .select('id, title, decision, brief, source_data, cluster_id, related_cluster_ids, prompt_id')+ .eq('id', opportunityId)+ .eq('brand_id', brandId)+ .maybeSingle();+ if (error || !row) return 'unavailable';++ const opportunity: Pick<+ ContentOpportunity,+ 'id' | 'title' | 'decision' | 'brief' | 'sourceData'+ > = {+ id: row.id as string,+ title: row.title as string,+ decision: (row.decision ?? null) as ContentOpportunity['decision'],+ brief: (row.brief ?? null) as ContentOpportunity['brief'],+ sourceData: (row.source_data ?? {}) as ContentOpportunity['sourceData'],+ };+ const clusterIds = [+ row.cluster_id,+ ...((row.related_cluster_ids as string[] | null) ?? []),+ ].filter((id): id is string => typeof id === 'string');++ // One from the per-prompt generator rests on its one prompt.+ if (clusterIds.length === 0) {+ if (!row.prompt_id) return { opportunity, basket: { clusters: [], queries: [] } };+ const { data: prompt } = await supabaseAdmin+ .from('prompts')+ .select('id, text')+ .eq('id', row.prompt_id)+ .maybeSingle();+ const basket: OpportunityBasket = {+ clusters: prompt+ ? [+ {+ id: `prompt:${prompt.id}`,+ label: prompt.text as string,+ need: '',+ topicName: null,+ prompts: [{ id: prompt.id as string, text: prompt.text as string }],+ },+ ]+ : [],+ queries: [],+ };+ return { opportunity, basket };+ }++ const [membersRes, queriesRes] = await Promise.all([+ supabaseAdmin+ .from('prompt_cluster_members')+ .select('cluster_id, prompts(id, text)')+ .in('cluster_id', clusterIds),+ supabaseAdmin+ .from('prompt_cluster_queries')+ .select('query, times_searched, included, reason')+ .in('cluster_id', clusterIds),+ ]);+ if (membersRes.error || queriesRes.error) return 'unavailable';++ // A query searched for several of its clusters is listed once, kept if any keeps it.+ const queries = new Map<string, OpportunityBasket['queries'][number]>();+ for (const q of queriesRes.data ?? []) {+ const prior = queries.get(q.query as string);+ queries.set(q.query as string, {+ query: q.query as string,+ timesSearched: (prior?.timesSearched ?? 0) + Number(q.times_searched ?? 0),+ included: Boolean(prior?.included || q.included),+ reason: prior?.included ? prior.reason : ((q.reason as string | null) ?? ''),+ });+ }+ const promptOf = (m: { prompts: unknown }) =>+ (Array.isArray(m.prompts) ? m.prompts[0] : m.prompts) as { id: string; text: string } | null;+ const basket: OpportunityBasket = {+ clusters: clusterIds.map((id) => ({+ id,+ label: '',+ need: '',+ topicName: null,+ prompts: (membersRes.data ?? [])+ .filter((m) => m.cluster_id === id)+ .map(promptOf)+ .filter((p): p is { id: string; text: string } => p !== null),+ })),+ queries: [...queries.values()].sort((a, b) => b.timesSearched - a.timesSearched),+ };+ return { opportunity, basket };+}++/**+ * The action as the drawer's Copy Data (Markdown) or Export CSV writes it, or+ * null when it isn't the caller's organization's.+ */+export async function exportActionFor(+ auth: McpAuthContext,+ actionId: string,+ format: ActionExportFormat,+): Promise<{ body: string; fileName: string } | null> {+ if (!auth.organizationId) return null;++ const { data: row, error } = await supabaseAdmin+ .from('actions')+ .select(`${ACTION_COLUMNS}, brand_id, brands!inner(organization_id)`)+ .eq('id', actionId)+ .eq('brands.organization_id', auth.organizationId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!row) return null;+ const brandId = row.brand_id as string;+ const opportunityId = sentFromOpportunityId({+ kind: row.kind as string,+ payload: (row.payload ?? {}) as Record<string, unknown>,+ });++ const [tasksRes, signalsRes, eventsRes, kpisRes, places, assigneeRes, openRes, sentFrom] =+ await Promise.all([+ supabaseAdmin+ .from('action_tasks')+ .select(TASK_COLUMNS)+ .eq('action_id', actionId)+ .order('position'),+ // Every signal the action has taken as evidence (AC-007), as the drawer reads them.+ supabaseAdmin+ .from('signals')+ .select(`${SIGNAL_ROW_COLUMNS}, action_signals!inner(action_id)`)+ .eq('brand_id', brandId)+ .eq('action_signals.action_id', actionId)+ .order('detected_at', { ascending: false }),+ supabaseAdmin+ .from('action_events')+ .select(EVENT_COLUMNS)+ .eq('action_id', actionId)+ .order('created_at'),+ supabaseAdmin+ .from('kpi_definitions')+ .select('kpi_key, target, timeframe')+ .eq('brand_id', brandId)+ .eq('is_active', true),+ readPromptPlaces(supabaseAdmin, brandId),+ row.assignee_id+ ? supabaseAdmin+ .from('profiles')+ .select('id, full_name, avatar_url')+ .eq('id', row.assignee_id)+ .maybeSingle()+ : Promise.resolve({ data: null, error: null }),+ // The signals that support it now, as the list counts them (AC-007): its "n signals" tag.+ supabaseAdmin+ .from('signals')+ .select('id', { count: 'exact', head: true })+ .eq('brand_id', brandId)+ .eq('action_id', actionId)+ .in('status', OPEN_SIGNAL_STATUSES as SignalStatus[]),+ opportunityId ? sentFromOpportunity(brandId, opportunityId) : Promise.resolve(null),+ ]);+ for (const res of [tasksRes, signalsRes, eventsRes, kpisRes, assigneeRes, openRes]) {+ if (res.error) throw new Error(res.error.message);+ }++ const profile = assigneeRes.data as {+ id: string;+ full_name: string | null;+ avatar_url: string | null;+ } | null;+ const tasks = (tasksRes.data ?? []).map(taskFromRow);+ // Skipped and failed tasks leave the count, as on the list.+ const counted = tasks.filter(+ (task) => !(UNCOUNTED_TASK_STATUSES as readonly string[]).includes(task.status),+ );+ const action = actionItemFromRow(row as unknown as ActionRow, {+ assignee: profile+ ? { id: profile.id, fullName: profile.full_name, avatarUrl: profile.avatar_url }+ : null,+ taskTotal: counted.length,+ taskCompleted: counted.filter((task) => task.status === 'completed').length,+ signalCount: openRes.count ?? 0,+ });+ const detail: ActionDetail = {+ tasks,+ signals: mapSignalRows((signalsRes.data ?? []) as unknown as SignalRow[], places),+ events: (eventsRes.data ?? []).map(eventFromRow),+ kpis: (kpisRes.data ?? []).map(kpiFromRow),+ // Not part of the export.+ positionOutcome: null,+ };++ // What the drawer works out from them: the Affected list, its prompts'+ // demand, and the Why and Goal in the action's own terms (AC-003).+ const evidence = affectedSignals(detail.signals, action.id);+ const affected = affectedOf(evidence, action.payload ?? {});+ const promptIds = affected.prompts.map((p) => p.id).filter((id): id is string => !!id);+ // Best effort, as in the drawer: without it the Volume column is left out.+ const volumes = promptIds.length+ ? await readPromptDemand(supabaseAdmin, brandId, promptIds).catch(() => null)+ : null;+ const t = translators();+ const format_ = createFormatter({ locale: 'en', timeZone: 'UTC' });+ const story = actionStory(+ { signals: evidence, volumes, createdAt: action.createdAt, dueDate: action.dueDate },+ t.story,+ {+ day: (date) => format_.dateTime(date, { month: 'short', day: 'numeric' }),+ list: (items) => format_.list(items, { type: 'conjunction' }),+ },+ );++ const data = labelActionExport(+ {+ action,+ detail,+ affected,+ volumes,+ story,+ sentFrom,+ origin: appOrigin(),+ timeZone: 'UTC',+ },+ t.labels,+ );+ return format === 'markdown'+ ? { body: actionMarkdown(data, t.labels.export), fileName: actionExportFileName(data, 'md') }+ : { body: actionCsv(data), fileName: actionExportFileName(data, 'csv') };+}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex d08f69acb..86345e9bd 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -38,6 +38,7 @@ import {IMPROVE_SOURCE_TYPES,createImproveActionFor,} from './data';+import { exportActionFor } from './action-export';/*** Build a fresh MCP server bound to a single authenticated request.@@ -938,12 +939,26 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'get_action',{description:- '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`. `details` says what the task carries beyond that, or null: `where` (the page, prompt, platform, domain or competitor), `why` (the evidence), `how` (the steps), `done_when` (the check that closes it), `type` (content, on_page, technical, outreach, pr or product), `effort` and `role`; a task sent from the Improve tab also carries `body`, `platform`, `platform_label` and `sources`; `sent_to_content` (the opportunity it became) and `sent_to_webhook` say where it was sent.',+ '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`. `details` says what the task carries beyond that, or null: `where` (the page, prompt, platform, domain or competitor), `why` (the evidence), `how` (the steps), `done_when` (the check that closes it), `type` (content, on_page, technical, outreach, pr or product), `effort` and `role`; a task sent from the Improve tab also carries `body`, `platform`, `platform_label` and `sources`; `sent_to_content` (the opportunity it became) and `sent_to_webhook` say where it was sent. With `format` "markdown" or "csv" it returns the action as the dashboard\'s Copy Data and Export CSV write it instead (everything its tabs show, labelled in English, dates in UTC): Markdown to paste into a doc, ticket or another agent, CSV with a row per affected item, task and signal.',inputSchema: {action_id: relaxedUuid.describe('Action UUID, from list_actions or list_action_history.'),+ format: z+ .enum(['json', 'markdown', 'csv'])+ .optional()+ .describe('json (default): the fields above. markdown or csv: the export, as text.'),},},async (args) => {+ if (args.format === 'markdown' || args.format === 'csv') {+ const exported = await exportActionFor(auth, args.action_id, args.format);+ if (!exported) {+ return {+ content: [{ type: 'text', text: 'Action not found' }],+ isError: true,+ };+ }+ return { content: [{ type: 'text', text: exported.body }] };+ }const action = await getActionFor(auth, args.action_id);if (!action) {return {diff --git a/web/src/lib/signals/display.ts b/web/src/lib/signals/display.tsindex b30cbb634..89a432056 100644--- a/web/src/lib/signals/display.ts+++ b/web/src/lib/signals/display.ts@@ -209,3 +209,12 @@ export function signalAffected(}}}++/**+ * A signal the engine closed because its subject moved to another kind — a+ * topic that went from slipping to dropped — reads "Changed", not "Resolved":+ * nothing was fixed, the finding became a different one.+ */+export function isSuperseded(signal: Pick<Signal, 'status' | 'payload'>): boolean {+ return signal.status === 'resolved' && typeof signal.payload?.supersededBy === 'string';+}