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
fix(action-center): list an action's Affected rows from what it kept, as its count does (AC-009) (#1409)
Cihan17f1924f676c
diff --git a/web/src/components/action-center/action-drawer.test.tsx b/web/src/components/action-center/action-drawer.test.tsxindex 611c4e2ce..a9689366e 100644--- a/web/src/components/action-center/action-drawer.test.tsx+++ b/web/src/components/action-center/action-drawer.test.tsx@@ -3,6 +3,8 @@ import { createRoot, type Root } from 'react-dom/client';import { NextIntlClientProvider } from 'next-intl';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { ActionItem } from '@/lib/actions/action-center';+import type { Signal } from '@/lib/signals/map';+import { promptVolumeEstimate } from '@/lib/volume-estimate';import messages from '../../../messages/en.json';/**@@ -16,6 +18,7 @@ const server = vi.hoisted(() => ({assignAction: vi.fn(),deleteTask: vi.fn(),getActionDetail: vi.fn(),+ getPromptDemand: vi.fn(),setActionDueDate: vi.fn(),updateActionStatus: vi.fn(),updateTaskStatus: vi.fn(),@@ -126,6 +129,55 @@ describe('ActionDrawer', () => {);});+ it("gives the Why the demand of a signal's prompt the action didn't keep", async () => {+ const lost = (id: string, promptId: string, promptText: string) =>+ ({+ id,+ category: 'citation',+ kind: 'lost_citations',+ impact: 'high',+ status: 'new',+ source: ['ai_results'],+ detectedAt: '2026-10-09T00:00:00Z',+ lastDetectedAt: '2026-10-09T00:00:00Z',+ resolvedAt: null,+ previousValue: null,+ currentValue: null,+ changeValue: null,+ payload: { promptId, promptText },+ kpiKeys: [],+ actionId: 'a1',+ where: { platforms: ['chatgpt-web'], regions: [], topics: [] },+ }) as Signal;+ const estimate = promptVolumeEstimate({+ estAiVolume: 5500,+ googleVolumes: { a: 10_000, b: 12_200, c: 14_000 },+ aiVolumeMultiplier: 0.45,+ keywords: ['a', 'b', 'c'],+ fetchedAt: new Date().toISOString(),+ });+ server.getActionDetail.mockResolvedValue({+ ...emptyDetail,+ // p2 is named by a signal the nightly pass added, never kept by the action.+ signals: [+ lost('s1', 'p1', 'Best coffee subscription?'),+ lost('s2', 'p2', 'Coffee delivery near me'),+ ],+ entities: [+ { type: 'prompts', key: 'p1', label: 'Best coffee subscription?', removed: false },+ ],+ });+ server.getPromptDemand.mockResolvedValue({ p1: estimate, p2: estimate });++ await renderDrawer({ ...action, payload: { targetEntity: 'prompts', targetCount: 1 } });++ expect(server.getPromptDemand).toHaveBeenCalledWith('b1', ['p1', 'p2']);+ // Both prompts' demand, not the kept one's alone (4.1–6.9k).+ expect(document.body.querySelector('[role="dialog"]')!.textContent).toContain(+ '2 prompts (8.2–13.8k AI searches a month, estimated)',+ );+ });+describe('changes', () => {beforeEach(() => vi.useFakeTimers());afterEach(() => vi.useRealTimers());diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex bf4b84cf1..50a7efdb1 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -224,6 +224,7 @@ export function ActionDrawer({brandId,action,detail?.signals ?? null,+ detail?.entities ?? null,);if (!action) return null;diff --git a/web/src/components/action-center/use-action-story.ts b/web/src/components/action-center/use-action-story.tsindex c7524196f..578f48d48 100644--- a/web/src/components/action-center/use-action-story.ts+++ b/web/src/components/action-center/use-action-story.ts@@ -4,7 +4,13 @@ import { useEffect, useMemo, useState } from 'react';import { useFormatter, useTranslations } from 'next-intl';import { getPromptDemand } from '@/lib/actions/action-center';import type { Signal } from '@/lib/signals/map';-import { affectedOf, affectedSignals, type Affected } from '@/lib/action-center/affected';+import {+ affectedOf,+ affectedSignals,+ demandPromptIds,+ type Affected,+ type KeptEntity,+} from '@/lib/action-center/affected';import { actionStory, type ActionStory } from '@/lib/action-center/story';import type { VolumeEstimate } from '@/lib/volume-estimate';@@ -28,6 +34,8 @@ export function useActionStory(brandId: string,action: StoryAction | null,signals: Signal[] | null,+ /** What the action kept when it was created (00244): its Affected rows, when read. */+ kept: KeptEntity[] | null = null,): {affected: Affected | null;volumes: Map<string, VolumeEstimate> | null;@@ -42,17 +50,21 @@ export function useActionStory([action, signals],);const affected = useMemo(- () => (action && evidence ? affectedOf(evidence, action.payload ?? {}) : null),- [action, evidence],+ () => (action && evidence ? affectedOf(evidence, action.payload ?? {}, kept) : null),+ [action, evidence, kept],);- // Each affected prompt's demand. Best effort: without it the column is left- // out. Kept with the prompts it was read for, so a read still under way is- // told apart from one that failed.- const promptIdsKey = (affected?.prompts ?? [])- .map((row) => row.id)- .filter(Boolean)- .join(',');+ // Each affected prompt's demand, and that of the prompts the Why names from+ // the signals (some the action didn't keep). Best effort: without it the+ // column is left out. Kept with the prompts it was read for, so a read+ // still under way is told apart from one that failed.+ const promptIdsKey = useMemo(+ () =>+ action && evidence && affected+ ? demandPromptIds(affected, evidence, action.payload ?? {}).join(',')+ : '',+ [action, evidence, affected],+ );const demandKey = `${brandId}:${promptIdsKey}`;const [demand, setDemand] = useState<{key: string;diff --git a/web/src/lib/action-center/affected.test.ts b/web/src/lib/action-center/affected.test.tsindex ebdefddbf..b21d24b00 100644--- a/web/src/lib/action-center/affected.test.ts+++ b/web/src/lib/action-center/affected.test.ts@@ -6,6 +6,7 @@ import {affectedOf,affectedSummary,affectedTotal,+ demandPromptIds,leaderText,type Affected,} from './affected';@@ -202,6 +203,159 @@ describe('affectedOf', () => {expect(left.promptTotal).toBe(1);});+ const P1 = '11111111-1111-4111-8111-111111111111';+ const P2 = '22222222-2222-4222-8222-222222222222';+ const P9 = '99999999-9999-4999-8999-999999999999';+ const keptPrompt = (key: string, label: string, removed = false) => ({+ type: 'prompts',+ key,+ label,+ removed,+ });++ it('lists what the action kept, with what the signals say of each, as its count says', () => {+ const signals = [+ signal({+ payload: { promptId: P1, promptText: 'Which tools track AI search?' },+ where: { platforms: ['chatgpt-web'], regions: [], topics: [] },+ }),+ // A signal the nightly pass added later, about a prompt the action never had.+ signal({+ id: 's2',+ payload: { promptId: P9, promptText: 'Cheapest AI rank tracker?' },+ where: { platforms: ['gemini-web'], regions: [], topics: [] },+ }),+ ];+ const kept = [+ keptPrompt(P1, 'Which tools track AI search?'),+ // Kept, but no signal names it now: a plain row.+ keptPrompt(P2, 'Best AI rank tracker?'),+ ];+ const affected = affectedOf(signals, { targetEntity: 'prompts', targetCount: 2 }, kept);+ expect(affected.prompts.map((p) => [p.id, p.text, p.platforms])).toEqual([+ [P1, 'Which tools track AI search?', ['chatgpt-web']],+ [P2, 'Best AI rank tracker?', []],+ ]);+ // The heading and the rows agree.+ expect(affected.promptTotal).toBe(2);++ // An action made before 00244 kept its first ones: the count says the rest.+ expect(+ affectedOf(signals, { targetEntity: 'prompts', targetCount: 60 }, kept).promptTotal,+ ).toBe(60);+ });++ it('lists none the action lost since, even when it lost them all', () => {+ const signals = [signal({ payload: { promptId: P9, promptText: 'Not the action’s?' } })];+ const affected = affectedOf(signals, { targetEntity: 'prompts', targetCount: 0 }, [+ keptPrompt(P1, 'Paused one?', true),+ ]);+ expect(affected.prompts).toEqual([]);+ expect(affected.promptTotal).toBe(0);+ });++ it('keeps a prompt kept by its text without an id, and matches a text only to a row without one', () => {+ // A topic opportunity keeps its prompts' texts: no id, no link, no volume read.+ const byText = affectedOf(+ [],+ { targetEntity: 'prompts', targetCount: 2, targets: ['Best beans?'] },+ [keptPrompt('Best beans?', 'Best beans?'), keptPrompt('Best grinder?', 'Best grinder?')],+ );+ expect(byText.prompts.map((p) => [p.id, p.text])).toEqual([+ [null, 'Best beans?'],+ [null, 'Best grinder?'],+ ]);++ // A copy of a kept prompt's text in another topic is another prompt.+ const copies = affectedOf(+ [signal({ payload: { promptId: P9, promptText: 'Best beans?' } })],+ { targetEntity: 'prompts', targetCount: 1 },+ [keptPrompt(P1, 'Best beans?')],+ );+ expect(copies.prompts.map((p) => p.id)).toEqual([P1]);+ });++ it('merges a prompt named by its id and by its text into one row', () => {+ const affected = affectedOf(+ [+ signal({+ payload: { promptId: P1, promptText: 'Best beans?' },+ where: { platforms: ['chatgpt-web'], regions: [], topics: [] },+ }),+ signal({+ id: 's2',+ payload: { promptText: 'Best beans?' },+ where: { platforms: ['gemini-web'], regions: [], topics: [] },+ }),+ ],+ { targetEntity: 'prompts', targetCount: 1 },+ [keptPrompt(P1, 'Best beans?')],+ );+ expect(affected.prompts.map((p) => [p.id, p.platforms])).toEqual([+ [P1, ['chatgpt-web', 'gemini-web']],+ ]);+ });++ it('matches pages by address and keeps competitors by name', () => {+ const pages = affectedOf(+ [],+ {+ targetEntity: 'pages',+ targetCount: 2,+ targets: [{ label: 'https://acme.example/a/' }, { label: 'https://acme.example/old' }],+ },+ [+ { type: 'pages', key: 'https://acme.example/a', label: null, removed: false },+ { type: 'pages', key: 'https://acme.example/b', label: null, removed: false },+ { type: 'pages', key: 'https://acme.example/old', label: null, removed: true },+ ],+ );+ expect(pages.pages.map((p) => p.url)).toEqual([+ 'https://acme.example/a/',+ 'https://acme.example/b',+ ]);+ expect(pages.pageTotal).toBe(2);++ const competitors = affectedOf(+ [],+ { targetEntity: 'competitors', targets: ['Profound', 'Gone Inc'] },+ [+ { type: 'competitors', key: 'c1', label: 'Profound', removed: false },+ { type: 'competitors', key: 'c2', label: 'Gone Inc', removed: true },+ ],+ );+ expect(competitors.competitors).toEqual(['Profound']);+ });++ it('builds from the signals when there is no kept list of its kind, or none can be read', () => {+ const signals = [signal({ payload: { promptId: P1, promptText: 'Which tools?' } })];+ const payload = { targetEntity: 'prompts', targetCount: 1 };+ expect(affectedOf(signals, payload, null).prompts).toHaveLength(1);+ expect(affectedOf(signals, payload, []).prompts).toHaveLength(1);+ expect(+ affectedOf(signals, payload, [+ { type: 'competitors', key: 'c1', label: 'Profound', removed: false },+ ]).prompts,+ ).toHaveLength(1);+ });++ it("reads demand for the rows' prompts and those the signals name outside the kept list", () => {+ const signals = [+ signal({ payload: { promptId: P1, promptText: 'Which tools track AI search?' } }),+ // Named by the signals (and so by the Why), never kept by the action.+ signal({ id: 's2', payload: { promptId: P9, promptText: 'Cheapest AI rank tracker?' } }),+ // Removed since: in neither.+ signal({ id: 's3', payload: { promptId: P2, promptText: 'Best AI rank tracker?' } }),+ ];+ const payload = { targetEntity: 'prompts', targetCount: 1, removedKeys: [P2] };+ const affected = affectedOf(signals, payload, [+ keptPrompt(P1, 'Which tools track AI search?'),+ keptPrompt(P2, 'Best AI rank tracker?', true),+ ]);+ expect(affected.prompts.map((p) => p.id)).toEqual([P1]);+ expect(demandPromptIds(affected, signals, payload)).toEqual([P1, P9]);+ });+it('is empty for an action with nothing to list', () => {expect(affectedOf([], {})).toMatchObject({ prompts: [], pages: [], promptTotal: 0 });});diff --git a/web/src/lib/action-center/affected.ts b/web/src/lib/action-center/affected.tsindex 73ed0a8d1..61303e68a 100644--- a/web/src/lib/action-center/affected.ts+++ b/web/src/lib/action-center/affected.ts@@ -80,15 +80,49 @@ const urlsOf = (value: WhereValue | null): string[] =>? [...value.items]: [];+/** One of the things an action kept when it was created (action_entities, 00244). */+export interface KeptEntity {+ type: string;+ /** A prompt's id (or its text, for an action that kept texts), a page's address, a competitor's id… */+ key: string;+ label: string | null;+ /** Deleted or paused since: counted out, never listed. */+ removed: boolean;+}++/** A key that is a row's id: a prompt kept by its text has none. */+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const idOf = (key: string) => (UUID_RE.test(key) ? key : null);+/*** The action's affected items, from the signals that support it. With none* (an action a person sent), from what it was sent about. Its prompts or* pages count as the action counts them (AC-009): the list it kept when it* was created, less what was removed since, not the signals the nightly* pass rewrites; the rows still show what the signals say about each.+ *+ * With `kept` (that list, read from action_entities), the rows are its+ * items still there: each with what the signals say of it, one the signals+ * no longer name as a plain row, and none the action never had (or had and+ * lost since). The heading and the rows then agree.*/-export function affectedOf(signals: Signal[], payload: Record<string, unknown> = {}): Affected {+export function affectedOf(+ signals: Signal[],+ payload: Record<string, unknown> = {},+ kept: KeptEntity[] | null = null,+): Affected {const out = signals.length === 0 ? affectedFromPayload(payload) : affectedOfSignals(signals);+ const entity = typeof payload.targetEntity === 'string' ? payload.targetEntity : null;+ const keptOnes = entity ? (kept ?? []).filter((e) => e.type === entity) : [];+ // Any kept of its kind, removed ones too: an action that lost all of them lists none.+ if (keptOnes.length > 0) {+ return keptRows(+ out,+ entity!,+ keptOnes.filter((e) => !e.removed),+ payload,+ );+ }// What was removed since (withEntityCounts) isn't listed: by its key (a// prompt's id, or its text where it has none), a competitor by its name.const strings = (value: unknown) =>@@ -122,6 +156,92 @@ export function affectedOf(signals: Signal[], payload: Record<string, unknown> =return out;}+/**+ * The prompts whose demand a drawer reads: its Affected rows' (the kept+ * list's), and those its signals name. The Why is told from the signals+ * (actionStory), and they can name prompts the action didn't keep: read for+ * the rows alone, its range would leave those out.+ */+export function demandPromptIds(+ affected: Affected,+ signals: Signal[],+ payload: Record<string, unknown> = {},+): string[] {+ const ids = [...affected.prompts, ...affectedOf(signals, payload).prompts].map((row) => row.id);+ return [...new Set(ids.filter((id): id is string => !!id))];+}++/** The rows as the action's kept list has them (affectedOf). */+function keptRows(+ out: Affected,+ entity: string,+ kept: KeptEntity[],+ payload: Record<string, unknown>,+): Affected {+ const count = typeof payload.targetCount === 'number' ? payload.targetCount : 0;+ if (entity === 'prompts') {+ const byKey = new Map(kept.map((e) => [e.key, e]));+ // A prompt listed by its text alone matches the label kept for it; one+ // with an id only its own (copies of a text live in other topics).+ const byLabel = new Map(kept.flatMap((e) => (e.label ? [[e.label, e] as const] : [])));+ const merged = new Map<string, AffectedPrompt>();+ const rows: AffectedPrompt[] = [];+ for (const row of out.prompts) {+ const match = row.id ? byKey.get(row.id) : (byKey.get(row.text) ?? byLabel.get(row.text));+ if (!match) continue;+ const first = merged.get(match.key);+ if (first) {+ // The same prompt by its id and by its text: one row, with all it says.+ add(first.platforms, ...row.platforms);+ add(first.lostPages, ...row.lostPages);+ add(first.citedInstead, ...row.citedInstead);+ add(first.topics, ...row.topics);+ first.leaders.push(...row.leaders);+ continue;+ }+ // A key is an id only when it is one: an action that kept texts has none.+ if (!row.id) row.id = idOf(match.key);+ merged.set(match.key, row);+ rows.push(row);+ }+ for (const e of kept) {+ if (merged.has(e.key)) continue;+ rows.push({+ id: idOf(e.key),+ text: e.label ?? e.key,+ platforms: [],+ lostPages: [],+ citedInstead: [],+ leaders: [],+ topics: [],+ });+ }+ out.prompts = rows;+ // An action made before 00244 kept its first 50: the count says the rest.+ out.promptTotal = Math.max(count, rows.length);+ } else if (entity === 'pages') {+ // An address as compared: its trailing slash aside.+ const pageKey = (url: string) => bareUrl(url).replace(/\/+$/, '');+ const keys = new Set(kept.map((e) => pageKey(e.key)));+ const listed = new Set<string>();+ const rows = out.pages.filter((row) => {+ const key = pageKey(row.url);+ if (!keys.has(key) || listed.has(key)) return false;+ listed.add(key);+ return true;+ });+ for (const e of kept) {+ if (listed.has(pageKey(e.key))) continue;+ rows.push({ url: e.key, sessions: null, before: null, platforms: [], issues: [] });+ }+ out.pages = rows;+ out.pageTotal = Math.max(count, rows.length);+ } else if (entity === 'competitors') {+ out.competitors = kept.map((e) => e.label ?? e.key);+ }+ return out;+}+function affectedOfSignals(signals: Signal[]): Affected {const prompts = new Map<string, AffectedPrompt>();const pages = new Map<string, AffectedPage>();diff --git a/web/src/lib/action-center/entity-counts.ts b/web/src/lib/action-center/entity-counts.tsindex 7ae9c193f..075220d7e 100644--- a/web/src/lib/action-center/entity-counts.ts+++ b/web/src/lib/action-center/entity-counts.ts@@ -1,4 +1,5 @@import type { SupabaseClient } from '@supabase/supabase-js';+import type { KeptEntity } from './affected';/*** AC-009: one count for an action, everywhere.@@ -179,3 +180,100 @@ export async function readEntityCounts(}return byAction;}++/** A row of action_entities as a list reads it. */+interface KeptRow {+ entity_type: string;+ entity_key: string;+ label: string | null;+ removed_at: string | null;+}++const keptOf = (row: KeptRow): KeptEntity => ({+ type: row.entity_type,+ key: row.entity_key,+ label: row.label,+ removed: row.removed_at !== null,+});++/** A failed read of the lists: quiet on a database without 00244, logged otherwise. */+function keptReadFailed(error: { code?: string; message: string }) {+ // A database without 00244 has no list: the rows come from the signals, quietly.+ if (error.code !== 'PGRST205' && error.code !== '42P01') {+ console.error('Failed to read an action’s list:', error.message);+ }+}++/**+ * What an action kept when it was created, removed ones marked+ * (action_entities, 00244, members may read it): the rows of its Affected+ * list (affectedOf). Null when it can't be read, so the list is built from+ * the signals as before.+ */+export async function readKeptEntities(+ client: SupabaseClient,+ actionId: string,+): Promise<KeptEntity[] | null> {+ try {+ const { data, error } = await client+ .from('action_entities')+ .select('entity_type, entity_key, label, removed_at')+ .eq('action_id', actionId)+ // A steady order: the rows don't move between opens.+ .order('label')+ .order('entity_key')+ .limit(1000);+ if (error) {+ keptReadFailed(error);+ return null;+ }+ return ((data ?? []) as KeptRow[]).map(keptOf);+ } catch (err) {+ console.error('Failed to read an action’s list:', err);+ return null;+ }+}++/** Kept rows per page when many actions' lists are read at once. */+const KEPT_PAGE_SIZE = 1000;++/**+ * Many actions' lists (readKeptEntities) in one read, by action, for the+ * actions list's Export CSV: page by page, as their rows together can be+ * more than one response returns. An action with none is left out. Null+ * when they can't be read, so their rows come from the signals as before.+ */+export async function readKeptEntityLists(+ client: SupabaseClient,+ actionIds: string[],+): Promise<Map<string, KeptEntity[]> | null> {+ const byAction = new Map<string, KeptEntity[]>();+ try {+ for (let from = 0; ; from += KEPT_PAGE_SIZE) {+ const { data, error } = await client+ .from('action_entities')+ .select('action_id, entity_type, entity_key, label, removed_at')+ .in('action_id', actionIds)+ // Each action's rows in the drawer's order, made whole so pages don't shuffle.+ .order('action_id')+ .order('label')+ .order('entity_key')+ .order('entity_type')+ .range(from, from + KEPT_PAGE_SIZE - 1);+ if (error) {+ keptReadFailed(error);+ return null;+ }+ const batch = (data ?? []) as (KeptRow & { action_id: string })[];+ for (const row of batch) {+ const list = byAction.get(row.action_id) ?? [];+ list.push(keptOf(row));+ byAction.set(row.action_id, list);+ }+ if (batch.length < KEPT_PAGE_SIZE) return byAction;+ }+ } catch (err) {+ console.error('Failed to read an action’s list:', err);+ return null;+ }+}diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex 5ec693f9b..2701887d1 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -22,13 +22,20 @@ import {import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';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 {+ affectedOf,+ affectedSignals,+ affectedSummary,+ type KeptEntity,+} from '@/lib/action-center/affected';import { readPromptDemand } from '@/lib/action-center/prompt-demand';import type { VolumeEstimate } from '@/lib/volume-estimate';import { readAssignees } from '@/lib/action-center/assignees';import {currentTaskParams,readEntityCounts,+ readKeptEntities,+ readKeptEntityLists,withEntityCounts,withoutTargetIds,} from '@/lib/action-center/entity-counts';@@ -184,6 +191,8 @@ export interface ActionKpiRef {export interface ActionDetail {tasks: ActionTask[];signals: Signal[];+ /** What it kept when it was created and still has (00244): its Affected rows; null unread. */+ entities?: KeptEntity[] | null;events: ActionEvent[];kpis: ActionKpiRef[];/** Improve actions only: positions now next to the baseline (PROMPT-008). */@@ -232,27 +241,33 @@ export async function getActionSignals(brandId: string, actionId: string): Promi* action's kpi_keys — evidence of which goals this work serves. */export async function getActionDetail(brandId: string, actionId: string): Promise<ActionDetail> {const supabase = await createClient();- const [tasksRes, signals, eventsRes, kpisRes, outcomeRes, entityCounts] = await Promise.all([- supabase.from('action_tasks').select(TASK_COLUMNS).eq('action_id', actionId).order('position'),- readActionSignals(supabase, brandId, actionId),- supabase- .from('action_events')- .select(EVENT_COLUMNS)- .eq('action_id', actionId)- .order('created_at'),- supabase- .from('kpi_definitions')- .select('kpi_key, target, timeframe')- .eq('brand_id', brandId)- .eq('is_active', true),- supabase- .from('actions')- .select('position_outcome, payload')- .eq('brand_id', brandId)- .eq('id', actionId)- .maybeSingle(),- readEntityCounts(supabase, [actionId]),- ]);+ const [tasksRes, signals, eventsRes, kpisRes, outcomeRes, entityCounts, entities] =+ await Promise.all([+ supabase+ .from('action_tasks')+ .select(TASK_COLUMNS)+ .eq('action_id', actionId)+ .order('position'),+ readActionSignals(supabase, brandId, actionId),+ supabase+ .from('action_events')+ .select(EVENT_COLUMNS)+ .eq('action_id', actionId)+ .order('created_at'),+ supabase+ .from('kpi_definitions')+ .select('kpi_key, target, timeframe')+ .eq('brand_id', brandId)+ .eq('is_active', true),+ supabase+ .from('actions')+ .select('position_outcome, payload')+ .eq('brand_id', brandId)+ .eq('id', actionId)+ .maybeSingle(),+ readEntityCounts(supabase, [actionId]),+ readKeptEntities(supabase, actionId),+ ]);if (tasksRes.error) throw new Error(tasksRes.error.message);if (eventsRes.error) throw new Error(eventsRes.error.message);if (kpisRes.error) throw new Error(kpisRes.error.message);@@ -268,6 +283,7 @@ export async function getActionDetail(brandId: string, actionId: string): PromistitleParams: currentTaskParams(task.titleParams, payload) ?? task.titleParams,})),signals,+ entities,events: (eventsRes.data ?? []).map(eventFromRow),kpis: (kpisRes.data ?? []).map(kpiFromRow),positionOutcome: parseImproveOutcome(outcomeRes.data?.position_outcome ?? null),@@ -553,9 +569,10 @@ const AFFECTED_PAGE_SIZE = 1000;/*** Each action's affected items, for the actions list's Export CSV (AC-005):- * the count and names the drawer's Affected tab shows, from the signals the- * action rests on — or, for one a person sent, from what it was sent about.- * Read page by page, so a brand with many signals is read whole.+ * the count and names the drawer's Affected tab shows, from what the action+ * kept (00244) and the signals it rests on — or, for one a person sent, from+ * what it was sent about. Read page by page, so a brand with many signals is+ * read whole.*/export async function getActionsAffected(brandId: string,@@ -597,9 +614,12 @@ export async function getActionsAffected(return (data ?? []) as { id: string; payload: Record<string, unknown> | null }[];};- const [signalChunks, payloadChunks, places, entityCounts] = await Promise.all([+ const [signalChunks, payloadChunks, keptChunks, places, entityCounts] = await Promise.all([Promise.all(chunks.map(readSignals)),Promise.all(chunks.map(readPayloads)),+ // What each kept (00244): its rows, as in the drawer. Without them (a+ // database before 00244), the signals'.+ Promise.all(chunks.map((chunk) => readKeptEntityLists(supabase, chunk))),readPromptPlaces(supabase, brandId),// The count each action shows (AC-009), so the CSV's agrees with its title.readEntityCounts(supabase, ids),@@ -613,6 +633,10 @@ export async function getActionsAffected(rowsByAction.set(link.action_id, list);}}+ const keptByAction = new Map<string, KeptEntity[]>();+ for (const lists of keptChunks) {+ for (const [actionId, kept] of lists ?? []) keptByAction.set(actionId, kept);+ }const summaries: Record<string, { count: number; items: string[] }> = {};for (const action of payloadChunks.flat()) {const signals = mapSignalRows(rowsByAction.get(action.id) ?? [], places);@@ -620,6 +644,7 @@ export async function getActionsAffected(affectedOf(affectedSignals(signals, action.id),withEntityCounts(action.payload ?? {}, entityCounts.get(action.id)),+ keptByAction.get(action.id) ?? null,),);}diff --git a/web/src/lib/actions/actions-affected.test.ts b/web/src/lib/actions/actions-affected.test.tsindex 1457ac199..90e214703 100644--- a/web/src/lib/actions/actions-affected.test.ts+++ b/web/src/lib/actions/actions-affected.test.ts@@ -35,6 +35,8 @@ function answer(table: string, calls: Call[]): Row[] {}let entityCounts: unknown[] = [];+/** Tables whose reads fail, and how. */+let errors: Record<string, { code: string; message: string }>;vi.mock('@/lib/supabase/server', () => ({createClient: vi.fn(async () => ({from: (table: string) => {@@ -48,7 +50,11 @@ vi.mock('@/lib/supabase/server', () => ({};}chain.then = (resolve: (value: unknown) => unknown) =>- resolve({ data: answer(table, query.calls), error: null });+ resolve(+ errors[table]+ ? { data: null, error: errors[table] }+ : { data: answer(table, query.calls), error: null },+ );return chain;},// The actions' list counts (AC-009): nothing removed here.@@ -78,9 +84,19 @@ const lost = (id: string, promptId: string, promptText: string, actions: string[action_signals: actions.map((action_id) => ({ action_id })),});+/** A prompt an action kept when it was created (action_entities, 00244). */+const kept = (actionId: string, key: string, label: string, removed = false): Row => ({+ action_id: actionId,+ entity_type: 'prompts',+ entity_key: key,+ label,+ removed_at: removed ? '2026-10-12T00:00:00Z' : null,+});+beforeEach(() => {queries = [];entityCounts = [];+ errors = {};rows = {actions: [{ id: 'a1', payload: {} },@@ -117,6 +133,86 @@ describe('getActionsAffected', () => {expect(result.a1.count).toBe(12);});+ it('lists what an action kept, so its count and names agree (00244)', async () => {+ rows.actions[0].payload = { targetEntity: 'prompts', targetCount: 4 };+ entityCounts = [+ {+ action_id: 'a1',+ entity_type: 'prompts',+ total: 4,+ removed: 1,+ removed_labels: ['Old coffee prompt'],+ removed_keys: ['p4'],+ },+ ];+ // A signal the nightly pass added later, about a prompt a1 never kept.+ rows.signals.push(lost('s4', 'p3', 'Cheapest coffee beans?', ['a1']));+ rows.action_entities = [+ kept('a1', 'p1', 'Best coffee subscription?'),+ kept('a1', 'p2', 'Coffee delivery near me'),+ // Kept, but no signal names it now: listed by its label.+ kept('a1', 'p5', 'Coffee grinder reviews'),+ // Paused since: counted out, not listed.+ kept('a1', 'p4', 'Old coffee prompt', true),+ ];++ const result = await getActionsAffected('b1', ['a1', 'a2']);+ expect(result.a1).toEqual({+ count: 3,+ items: ['Best coffee subscription?', 'Coffee delivery near me', 'Coffee grinder reviews'],+ });+ expect(result.a1.items).toHaveLength(result.a1.count);+ // An action with no list reads its signals, as before.+ expect(result.a2).toEqual({ count: 1, items: ['Coffee delivery near me'] });+ // One read of the lists for the chunk, not one per action.+ const reads = queries.filter((q) => q.table === 'action_entities');+ expect(reads).toHaveLength(1);+ expect(reads[0].calls).toContainEqual(['in', 'action_id', ['a1', 'a2']]);+ });++ it("reads the kept lists past one response's rows, a page at a time", async () => {+ rows.actions[0].payload = { targetEntity: 'prompts', targetCount: 1001 };+ rows.signals = [];+ rows.action_entities = Array.from({ length: 1001 }, (_, i) =>+ kept('a1', `p${i}`, `Prompt ${i}`),+ );+ const result = await getActionsAffected('b1', ['a1']);++ expect(result.a1.count).toBe(1001);+ expect(result.a1.items).toHaveLength(1001);+ const ranges = queries+ .filter((q) => q.table === 'action_entities')+ .map((q) => q.calls.find(([method]) => method === 'range'));+ expect(ranges).toEqual([+ ['range', 0, 999],+ ['range', 1000, 1999],+ ]);+ });++ it('reads the signals, quietly, on a database without the kept lists (before 00244)', async () => {+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ rows.actions[0].payload = { targetEntity: 'prompts', targetCount: 2 };+ // What a read would have listed: one of the two.+ rows.action_entities = [kept('a1', 'p1', 'Best coffee subscription?')];+ for (const code of ['PGRST205', '42P01']) {+ errors.action_entities = { code, message: 'relation "action_entities" does not exist' };+ expect((await getActionsAffected('b1', ['a1'])).a1).toEqual({+ count: 2,+ items: ['Best coffee subscription?', 'Coffee delivery near me'],+ });+ }+ expect(logged).not.toHaveBeenCalled();++ // Any other failure is logged, and the export still reads the signals.+ errors.action_entities = { code: '57014', message: 'canceling statement' };+ expect((await getActionsAffected('b1', ['a1'])).a1.count).toBe(2);+ expect(logged).toHaveBeenCalledTimes(1);+ } finally {+ logged.mockRestore();+ }+ });+it("reads past one response's rows, a page at a time", async () => {rows.signals = Array.from({ length: 1001 }, (_, i) =>lost(`s${i}`, `p${i}`, `Prompt ${i}`, ['a1']),diff --git a/web/src/lib/mcp/action-export.test.ts b/web/src/lib/mcp/action-export.test.tsindex 818fd1d6d..bda6a98f4 100644--- a/web/src/lib/mcp/action-export.test.ts+++ b/web/src/lib/mcp/action-export.test.ts@@ -45,6 +45,7 @@ function table(name: string) {return chain;},order: () => chain,+ limit: () => chain,is: () => chain,range: (from: number, to: number) => {range = [from, to];@@ -210,6 +211,40 @@ describe('exportActionFor', () => {expect(md).toMatch(/Why: .*Oct 9/);});+ it("gives the Why the demand of a signal's prompt the action didn't keep", async () => {+ rows.actions = [actionRow({ payload: { targetEntity: 'prompts', targetCount: 1 } })];+ // What the action kept (00244): p1 alone.+ rows.action_entities = [+ {+ action_id: 'a1',+ entity_type: 'prompts',+ entity_key: 'p1',+ label: 'Best coffee subscription?',+ removed_at: null,+ },+ ];+ // A signal about a prompt the action never kept: not listed, but the Why names it.+ const [first] = rows.signals;+ rows.signals.push({+ ...first,+ id: 's2',+ payload: {+ promptId: 'p2',+ promptText: 'Coffee delivery near me',+ lostUrls: [{ url: 'https://acme.example/delivery', position: 3 }],+ },+ });+ rows.prompts.push({ ...rows.prompts[0], id: 'p2', text: 'Coffee delivery near me' });+ rows.prompt_volumes.push({ ...rows.prompt_volumes[0], prompt_id: 'p2' });++ const md = (await exportActionFor(auth, 'a1', 'markdown'))!.body;+ // The list is what it kept…+ expect(md).toContain('## Affected (1)\n- Best coffee subscription? · 4.1–6.9k');+ expect(md).not.toMatch(/^- Coffee delivery near me/m);+ // …and the Why, told from both signals, sums both prompts' demand.+ expect(md).toMatch(/^Why: 2 prompts \(8\.2–13\.8k AI searches a month, estimated\)/m);+ });+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;diff --git a/web/src/lib/mcp/action-export.ts b/web/src/lib/mcp/action-export.tsindex 6ff5db643..befc61739 100644--- a/web/src/lib/mcp/action-export.ts+++ b/web/src/lib/mcp/action-export.ts@@ -8,10 +8,11 @@ import { SIGNAL_ROW_COLUMNS, mapSignalRows, type SignalRow } from '@/lib/signalsimport { 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 { affectedOf, affectedSignals, demandPromptIds } from '@/lib/action-center/affected';import {currentTaskParams,readEntityCounts,+ readKeptEntities,withEntityCounts,} from '@/lib/action-center/entity-counts';import { actionStory } from '@/lib/action-center/story';@@ -207,6 +208,7 @@ export async function exportActionFor(openRes,sentFrom,entityCounts,+ kept,] = await Promise.all([supabaseAdmin.from('action_tasks')@@ -246,8 +248,9 @@ export async function exportActionFor(.eq('action_id', actionId).in('status', OPEN_SIGNAL_STATUSES as SignalStatus[]),opportunityId ? sentFromOpportunity(brandId, opportunityId) : Promise.resolve(null),- // Its list (AC-009): the count it shows, as on the page.+ // Its list (AC-009): the count it shows, as on the page, and its rows.readEntityCounts(supabaseAdmin, [actionId]),+ readKeptEntities(supabaseAdmin, actionId),]);for (const res of [tasksRes, signalsRes, eventsRes, kpisRes, assigneeRes, openRes]) {if (res.error) throw new Error(res.error.message);@@ -280,6 +283,7 @@ export async function exportActionFor(const detail: ActionDetail = {tasks,signals: mapSignalRows((signalsRes.data ?? []) as unknown as SignalRow[], places),+ entities: kept,events: (eventsRes.data ?? []).map(eventFromRow),kpis: (kpisRes.data ?? []).map(kpiFromRow),// Not part of the export.@@ -289,8 +293,9 @@ export async function exportActionFor(// 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);+ const affected = affectedOf(evidence, action.payload ?? {}, kept);+ // The rows' prompts and those the Why names from the signals, as in the drawer.+ const promptIds = demandPromptIds(affected, evidence, action.payload ?? {});// 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)