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): keep an action's prompts, pages and competitors once, as its count (AC-009, 1/3) (#1388)
Cihana394c2dc966f
diff --git a/server/src/lib/action-center/definitions/_helpers.js b/server/src/lib/action-center/definitions/_helpers.jsindex 5d1aa9961..4298a4bb6 100644--- a/server/src/lib/action-center/definitions/_helpers.js+++ b/server/src/lib/action-center/definitions/_helpers.js@@ -13,6 +13,8 @@* predate that, so their targets are read off the fields they do carry.*/+import { targetKeys } from '../../target-ids.js';+function legacyTargets(signal) {const p = signal.payload ?? {};if (Array.isArray(p.targets)) return p.targets;@@ -20,20 +22,41 @@ function legacyTargets(signal) {if (p.competitorName)return [{ id: p.competitorId ?? p.competitorName, label: p.competitorName }];if (p.landingPage) return [{ id: p.landingPage, label: p.landingPage }];- if (Array.isArray(p.urls)) return p.urls.map((url) => ({ id: url, label: url }));+ // Site Audit's low scores carry { url, score }; older signals plain addresses.+ if (Array.isArray(p.urls)) {+ return p.urls+ .map((entry) => (typeof entry === 'string' ? entry : entry?.url))+ .filter(Boolean)+ .map((url) => ({ id: url, label: url }));+ }if (p.platform) return [{ id: p.platform, label: p.platform }];return [];}-/** Every target across the matched signals, once each. */+/** A target's key: its id, or its label where it has none. */+export function targetKey(target) {+ return String(target.id ?? target.label ?? '');+}++/**+ * Every target across the matched signals, once each: the ones the signals+ * name first, with their labels, then those a bigger group lists only by id+ * (`targetIds`, AC-009), so the count is the whole group's.+ */export function collectTargets(byKind) {const seen = new Map();- for (const signals of byKind.values()) {- for (const signal of signals) {- for (const target of legacyTargets(signal)) {- const key = String(target.id ?? target.label ?? '');- if (key && !seen.has(key)) seen.set(key, target);- }+ const signals = [...byKind.values()].flat();+ for (const signal of signals) {+ for (const target of legacyTargets(signal)) {+ const key = targetKey(target);+ if (key && !seen.has(key)) seen.set(key, target);+ }+ }+ for (const signal of signals) {+ const ids = signal.payload?.targetIds;+ for (const id of Array.isArray(ids) ? ids : []) {+ const key = String(id ?? '');+ if (key && !seen.has(key)) seen.set(key, { id: key });}}return [...seen.values()];@@ -51,10 +74,22 @@ export function collectTargets(byKind) {export function targetPayload(byKind, entity, extra = {}) {const targets = collectTargets(byKind);const mapped = targets.filter((t) => typeof t.mapped === 'boolean');+ // The ones a signal named, to show; every target's key once there are more+ // (AC-009: the action keeps the whole list it counts, in action_entities).+ const named = targets.filter((t) => t.label !== undefined || Object.keys(t).length > 1);+ // The count is the list's, as the action keeps it (targetKeys): signals+ // each capped at MAX_TARGET_IDS can add up past it.+ const keys = targetKeys(targets.map(targetKey));+ const shown = named.slice(0, 50);+ // Listed whenever the names shown aren't exactly those keys: more of them,+ // or names whose keys the action keeps otherwise (trimmed, once).+ const shownKeys = shown.map(targetKey);+ const listed = keys.length !== shownKeys.length || keys.some((k, i) => k !== shownKeys[i]);return {targetEntity: entity,- targetCount: targets.length,- targets: targets.slice(0, 50),+ targetCount: keys.length,+ targets: shown,+ ...(listed ? { targetIds: keys } : {}),...(mapped.length > 0 ? { contentExists: mapped.some((t) => t.mapped) } : {}),...extra,};diff --git a/server/src/lib/action-center/definitions/_helpers.test.js b/server/src/lib/action-center/definitions/_helpers.test.jsnew file mode 100644index 000000000..767313caf--- /dev/null+++ b/server/src/lib/action-center/definitions/_helpers.test.js@@ -0,0 +1,113 @@+import { describe, expect, it } from 'vitest';+import { collectTargets, targetPayload } from './_helpers.js';+import f01 from './f01-fix-low-scores.js';+import g02 from './g02-convert-mentions.js';++/**+ * An action counts the whole group its signals found and keeps that list+ * (AC-009): a group signal names its first 50 targets and lists every id.+ */++const byKind = (...signals) => new Map(signals.map((s, i) => [`kind${i}`, [s]]));+const prompt = (i) => ({ id: `p${i}`, label: `Prompt ${i}` });++describe('collectTargets', () => {+ it('counts a group past the 50 it names, the named ones first', () => {+ const big = {+ payload: {+ targets: Array.from({ length: 50 }, (_, i) => prompt(i)),+ targetIds: Array.from({ length: 80 }, (_, i) => `p${i}`),+ },+ };+ const small = { payload: { targets: [prompt(100)] } };+ const targets = collectTargets(byKind(big, small));+ expect(targets).toHaveLength(81);+ // Every named one before the ones known only by id.+ expect(targets.slice(0, 51).every((t) => t.label)).toBe(true);+ expect(targets[51]).toEqual({ id: 'p50' });+ });++ it('reads Site Audit’s low pages by their address', () => {+ const audit = {+ payload: { urls: [{ url: 'https://a.example/x', score: 31 }, 'https://a.example/y'] },+ };+ expect(collectTargets(byKind(audit))).toEqual([+ { id: 'https://a.example/x', label: 'https://a.example/x' },+ { id: 'https://a.example/y', label: 'https://a.example/y' },+ ]);+ });+});++describe('targetPayload', () => {+ it('keeps every key once there are more targets than it names', () => {+ const big = {+ payload: {+ targets: Array.from({ length: 50 }, (_, i) => prompt(i)),+ targetIds: Array.from({ length: 80 }, (_, i) => `p${i}`),+ },+ };+ const payload = targetPayload(byKind(big), 'prompts');+ expect(payload.targetCount).toBe(80);+ expect(payload.targets).toHaveLength(50);+ expect(payload.targetIds).toHaveLength(80);+ });++ it('counts no more than the action keeps, however many the signals add up to', () => {+ const big = (from) => ({+ payload: {+ targets: [prompt(from)],+ targetIds: Array.from({ length: 1000 }, (_, i) => `p${from + i}`),+ },+ });+ const payload = targetPayload(byKind(big(0), big(1000)), 'prompts');+ expect(payload.targetCount).toBe(1000);+ expect(payload.targetIds).toHaveLength(1000);+ });++ it('lists the keys when a name shown isn’t one the action keeps as it is', () => {+ const payload = targetPayload(+ byKind({ payload: { targets: [{ id: 'p1 ', label: 'Prompt 1' }, prompt(2)] } }),+ 'prompts',+ );+ expect(payload).toMatchObject({ targetCount: 2, targetIds: ['p1', 'p2'] });+ });++ it('names them all and lists no ids when it can', () => {+ const payload = targetPayload(+ byKind({ payload: { targets: [prompt(1), prompt(2)] } }),+ 'prompts',+ );+ expect(payload).toMatchObject({ targetCount: 2, targets: [prompt(1), prompt(2)] });+ expect(payload).not.toHaveProperty('targetIds');+ });+});++describe('f01 (low audit scores)', () => {+ it('counts the pages the action keeps, not the signal’s raw number', () => {+ const audit = {+ current_value: 3,+ payload: {+ urls: [+ { url: 'https://a.example/x', score: 31 },+ { url: 'https://a.example/x', score: 31 },+ ],+ },+ };+ const payload = f01.payload(new Map([['audit_low_score', [audit]]]));+ expect(payload).toMatchObject({ targetCount: 1, pageCount: 1 });+ });+});++describe('g02 (uncited mentions)', () => {+ it('counts the uncited prompts the signal lists, and keeps them', () => {+ const mentions = { current_value: 3, payload: { promptIds: ['a', 'b', 'c'] } };+ const payload = g02.payload(new Map([['uncited_mentions', [mentions]]]));+ expect(payload).toMatchObject({ targetCount: 3, targetIds: ['a', 'b', 'c'], promptCount: 3 });+ // A prompt listed twice is kept, and counted, once.+ const twice = { current_value: 3, payload: { promptIds: ['a', 'b', 'a'] } };+ expect(g02.payload(new Map([['uncited_mentions', [twice]]]))).toMatchObject({+ targetCount: 2,+ targetIds: ['a', 'b'],+ });+ });+});diff --git a/server/src/lib/action-center/definitions/f01-fix-low-scores.js b/server/src/lib/action-center/definitions/f01-fix-low-scores.jsindex f051d4331..85ebc3a87 100644--- a/server/src/lib/action-center/definitions/f01-fix-low-scores.js+++ b/server/src/lib/action-center/definitions/f01-fix-low-scores.js@@ -7,7 +7,7 @@* payload names its targets.*/-import { first, targetPayload } from './_helpers.js';+import { targetPayload } from './_helpers.js';export default {id: 'fix_low_scores',@@ -28,8 +28,8 @@ export default {],payload(byKind) {- const audit = first(byKind, 'audit_low_score');- const pageCount = Number(audit?.current_value ?? 0);- return { ...targetPayload(byKind, 'pages'), targetCount: pageCount, pageCount };+ // The count is the list the action keeps (AC-009), as g01's.+ const base = targetPayload(byKind, 'pages');+ return { ...base, pageCount: base.targetCount };},};diff --git a/server/src/lib/action-center/definitions/g02-convert-mentions.js b/server/src/lib/action-center/definitions/g02-convert-mentions.jsindex caa81125f..f31dfd777 100644--- a/server/src/lib/action-center/definitions/g02-convert-mentions.js+++ b/server/src/lib/action-center/definitions/g02-convert-mentions.js@@ -7,6 +7,7 @@* payload names its targets.*/+import { targetKeys } from '../../target-ids.js';import { first, targetPayload } from './_helpers.js';export default {@@ -32,6 +33,19 @@ export default {payload(byKind) {const mentions = first(byKind, 'uncited_mentions');const promptCount = Number(mentions?.current_value ?? 0);+ // The uncited prompts themselves are the targets (AC-009): the count is+ // their list's, which the action keeps.+ const ids = targetKeys(+ Array.isArray(mentions?.payload?.promptIds) ? mentions.payload.promptIds : [],+ );+ if (ids.length > 0) {+ return {+ ...targetPayload(byKind, 'prompts'),+ targetIds: ids,+ targetCount: ids.length,+ promptCount,+ };+ }return { ...targetPayload(byKind, 'prompts'), targetCount: promptCount, promptCount };},};diff --git a/server/src/lib/action-center/from-opportunity.js b/server/src/lib/action-center/from-opportunity.jsindex dd48488e6..b57133733 100644--- a/server/src/lib/action-center/from-opportunity.js+++ b/server/src/lib/action-center/from-opportunity.js@@ -10,6 +10,7 @@* measured like any other action's.*/+import { targetKeys } from '../target-ids.js';import supabaseAdmin from '../../config/supabase.js';import { resolveBrandSources } from './sources.js';import { planTasks } from './tasks/plan.js';@@ -97,6 +98,22 @@ export function actionPromptScope(opportunity, memberPromptIds) {return { promptIds: [opportunity.prompt_id], prompts: sd.promptText ? [sd.promptText] : [] };}+/**+ * The count and keys an opportunity's action keeps (AC-009): the prompts it+ * is scoped to when it has them, else the ones the opportunity names (by+ * id, or by text), each once (targetKeys). The first 50 named are shown as+ * before.+ */+export function actionTargets(promptIds, prompts) {+ const keyOf = (p) => (typeof p === 'string' ? p : String(p?.id ?? p?.text ?? p?.label ?? ''));+ const keys = targetKeys(promptIds.length ? promptIds : prompts.map(keyOf));+ return {+ targetCount: keys.length,+ targets: prompts.slice(0, 50),+ ...(keys.length ? { targetIds: keys } : {}),+ };+}+/*** A task's status when the action opens. The brief task starts completed when* the opportunity already has a brief: the work is done, and the brief is@@ -178,8 +195,9 @@ export async function sendToActionCenter(pages: [...new Set(chosen.flatMap((a) => (a.pages || []).map((p) => p.url)))],promptIds,targetEntity: 'prompts',- targetCount: prompts.length,- targets: prompts.slice(0, 50),+ // What the action counts is the list it keeps (AC-009): its prompts when+ // it has them, else the prompts the opportunity names.+ ...actionTargets(promptIds, prompts),contentExists: chosen.some((a) => a.decision !== 'create'),};diff --git a/server/src/lib/action-center/from-opportunity.test.js b/server/src/lib/action-center/from-opportunity.test.jsindex c2bcc3170..c37e9ac37 100644--- a/server/src/lib/action-center/from-opportunity.test.js+++ b/server/src/lib/action-center/from-opportunity.test.js@@ -2,8 +2,14 @@ import { describe, expect, it, vi } from 'vitest';vi.mock('../../config/supabase.js', () => ({ default: {} }));-const { actionPromptScope, assetTasks, combinedTasks, initialTaskStatus, opportunityAssets } =- await import('./from-opportunity.js');+const {+ actionPromptScope,+ actionTargets,+ assetTasks,+ combinedTasks,+ initialTaskStatus,+ opportunityAssets,+} = await import('./from-opportunity.js');const { getTask } = await import('./tasks/registry.js');const owned = (decision) => ({ type: 'blog_post', channel: 'owned', decision });@@ -147,3 +153,30 @@ describe('an opportunity a task was sent as (AC-004)', () => {).toEqual({ actionId: 'a1', created: false });});});++describe('actionTargets (AC-009)', () => {+ it('counts and keeps the prompts the action is scoped to', () => {+ expect(actionTargets(['p1', 'p2', 'p3'], ['A', 'B'])).toEqual({+ targetCount: 3,+ targets: ['A', 'B'],+ targetIds: ['p1', 'p2', 'p3'],+ });+ });++ it('keeps the ones the opportunity names when it has no prompts', () => {+ expect(actionTargets([], ['A', { id: 'p9', text: 'B' }])).toEqual({+ targetCount: 2,+ targets: ['A', { id: 'p9', text: 'B' }],+ targetIds: ['A', 'p9'],+ });+ expect(actionTargets([], [])).toEqual({ targetCount: 0, targets: [] });+ });++ it('counts a prompt named twice once, as the action keeps it', () => {+ expect(actionTargets([], ['A', 'B', 'A ', ''])).toEqual({+ targetCount: 2,+ targets: ['A', 'B', 'A ', ''],+ targetIds: ['A', 'B'],+ });+ });+});diff --git a/server/src/lib/action-center/from-topic-gap.js b/server/src/lib/action-center/from-topic-gap.jsindex 3fcea80a5..927cd53b0 100644--- a/server/src/lib/action-center/from-topic-gap.js+++ b/server/src/lib/action-center/from-topic-gap.js@@ -11,6 +11,7 @@import supabaseAdmin from '../../config/supabase.js';import { computeAiVisibilityScore } from '../../config/visibility-score.js';+import { targetKeys } from '../target-ids.js';import { resolveBrandSources } from './sources.js';import { planTasks } from './tasks/plan.js';@@ -153,7 +154,8 @@ export async function sendTopicGapToActionCenter(window: { dayFrom: dayFrom ?? null, dayTo: dayTo ?? null },promptIds: (prompts || []).map((p) => p.id),targetEntity: 'prompts',- targetCount: (prompts || []).length,+ // As many as the action keeps of them (AC-009).+ targetCount: targetKeys((prompts || []).map((p) => p.id)).length,targets: (prompts || []).slice(0, 50).map((p) => p.text),};diff --git a/server/src/lib/action-center/from-topic-opportunity.js b/server/src/lib/action-center/from-topic-opportunity.jsindex 907b90210..2c55ba6da 100644--- a/server/src/lib/action-center/from-topic-opportunity.js+++ b/server/src/lib/action-center/from-topic-opportunity.js@@ -14,6 +14,7 @@import supabaseAdmin from '../../config/supabase.js';import { RELEVANCE_THRESHOLD } from '../suggestion-relevance.js';+import { targetKeys } from '../target-ids.js';import expandTopicVisibility from './definitions/g05-expand-topic-visibility.js';import createContentForTopics from './definitions/g16-create-content-for-topics.js';import { resolveBrandSources } from './sources.js';@@ -103,6 +104,11 @@ export async function sendTopicOpportunityToActionCenter(topic, { suggestionIds,if (promptsErr) throw new Error(promptsErr.message);const tracked = prompts || [];const definition = topicOpportunityPlan(tracked.length);+ // What it counts is the suggestions, kept by their text, each once+ // (AC-009): not the topic's tracked prompts, which it measures.+ const keys = targetKeys(suggestions.map((s) => s.suggested_text));+ // None with words: its list would fall back to the tracked prompts.+ if (!keys.length) throw httpError('No open suggestions for this topic', 409);const payload = {source: TOPIC_OPPORTUNITY_ACTION_KIND,@@ -118,8 +124,9 @@ export async function sendTopicOpportunityToActionCenter(topic, { suggestionIds,trackedPrompts: tracked.length,promptIds: tracked.map((p) => p.id),targetEntity: 'prompts',- targetCount: suggestions.length,+ targetCount: keys.length,targets: suggestions.slice(0, 50).map((s) => s.suggested_text),+ targetIds: keys,};const { data: action, error } = await supabaseAdmindiff --git a/server/src/lib/action-center/from-topic-opportunity.test.js b/server/src/lib/action-center/from-topic-opportunity.test.jsindex e65d318a7..4ae0a38cb 100644--- a/server/src/lib/action-center/from-topic-opportunity.test.js+++ b/server/src/lib/action-center/from-topic-opportunity.test.js@@ -186,6 +186,25 @@ describe('sendTopicOpportunityToActionCenter', () => {expect(action.payload.demand).toBe(30_000);});+ it('counts the suggestions as the action keeps them: each text once, none empty', async () => {+ db.rows.prompt_suggestions = () => [+ suggestionRow('s1', 30_000),+ { ...suggestionRow('s2', 20_000), suggested_text: 'prompt s1' },+ { ...suggestionRow('s3', 10_000), suggested_text: '' },+ ];++ await send(['s1', 's2', 's3']);++ const action = db.inserts.find((i) => i.table === 'actions').row;+ expect(action.payload).toMatchObject({ targetCount: 1, targetIds: ['prompt s1'] });+ });++ it('refuses suggestions with no words, which it couldn’t keep', async () => {+ db.rows.prompt_suggestions = () => [{ ...suggestionRow('s1', 30_000), suggested_text: ' ' }];+ await expect(send(['s1'])).rejects.toMatchObject({ status: 409 });+ expect(db.inserts.find((i) => i.table === 'actions')).toBeUndefined();+ });+it('refuses when none of the suggestions is still open in this topic', async () => {db.rows.prompt_suggestions = () => [];await expect(send()).rejects.toMatchObject({ status: 409 });diff --git a/server/src/lib/action-center/from-traffic-pages.js b/server/src/lib/action-center/from-traffic-pages.jsindex e417af825..83d5a798c 100644--- a/server/src/lib/action-center/from-traffic-pages.js+++ b/server/src/lib/action-center/from-traffic-pages.js@@ -209,6 +209,8 @@ export async function sendTrafficPagesToActionCenter(brandId, { pages, reason, fpages: host ? found.map((p) => `https://${host}${p.page === '/' ? '' : p.page}`) : [],targetEntity: 'pages',targetCount: found.length,+ // The pages it counts, by path (AC-009): `pages` is empty without a domain.+ targetIds: found.map((p) => p.page),targets: found.map((p) => ({id: p.page,label: p.page,diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.jsindex be337bdb6..e42a8b5ba 100644--- a/server/src/lib/action-center/priority.js+++ b/server/src/lib/action-center/priority.js@@ -213,7 +213,9 @@ export function promptIdsOf(payloads) {for (const p of payloads) {if (!p) continue;if (typeof p.promptId === 'string') ids.add(p.promptId);- for (const id of Array.isArray(p.promptIds) ? p.promptIds : []) {+ // The first 50, as signals named them before they listed every prompt+ // (AC-009): demand is read for the prompts an action leads with.+ for (const id of Array.isArray(p.promptIds) ? p.promptIds.slice(0, 50) : []) {if (typeof id === 'string') ids.add(id);}const entity = p.entity ?? p.targetEntity;diff --git a/server/src/lib/signals/audit-low-score.test.js b/server/src/lib/signals/audit-low-score.test.jsnew file mode 100644index 000000000..0e29971d8--- /dev/null+++ b/server/src/lib/signals/audit-low-score.test.js@@ -0,0 +1,55 @@+import { describe, expect, it, vi } from 'vitest';++// record.js reaches the admin client at import time, whose config hard-exits+// without SUPABASE_* env (as in CI). Its `from` is replaced per test below.+vi.mock('../../config/supabase.js', () => ({ default: { rpc: vi.fn(), from: vi.fn() } }));+vi.mock('../logger.js', () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));+vi.mock('../pulse/metrics.js', () => ({ computePulseMetrics: vi.fn() }));++import supabaseAdmin from '../../config/supabase.js';+import { auditCandidates } from './record.js';+import { ENGINE_THRESHOLDS } from '../../config/action-engine.js';++const { auditLowScore } = ENGINE_THRESHOLDS.detection;++const now = new Date('2026-10-23T06:00:00.000Z');++/** site_audits in miniature: every chained filter passes, the rows come back as given. */+function serve(rows) {+ const query = new Proxy(+ {},+ {+ get: (_, key) =>+ key === 'then'+ ? (resolve, reject) => Promise.resolve({ data: rows, error: null }).then(resolve, reject)+ : () => query,+ },+ );+ supabaseAdmin.from.mockReturnValue(query);+}++const audit = (i, score) => ({+ url: `https://acme.example/p${i}`,+ total_score: score,+ completed_at: now.toISOString(),+});++/** Site Audit's low pages (AC-009): the ten lowest to show, every address past them. */+describe('auditCandidates', () => {+ it('lists no addresses beside the ten it shows', async () => {+ serve(Array.from({ length: 10 }, (_, i) => audit(i, auditLowScore - 1 - i)));+ const [signal] = await auditCandidates('b1', now);+ expect(signal.payload.urls).toHaveLength(10);+ expect(signal.payload).not.toHaveProperty('targetIds');+ });++ it('lists every low page’s address past them', async () => {+ serve(Array.from({ length: 12 }, (_, i) => audit(i, auditLowScore - 1 - i)));+ const [signal] = await auditCandidates('b1', now);+ expect(signal.payload.urls).toHaveLength(10);+ expect(signal.payload.targetIds).toHaveLength(12);+ expect(signal.currentValue).toBe(12);+ });+});diff --git a/server/src/lib/signals/library/detect.js b/server/src/lib/signals/library/detect.jsindex 175c4f18b..3118c497a 100644--- a/server/src/lib/signals/library/detect.js+++ b/server/src/lib/signals/library/detect.js@@ -19,6 +19,7 @@* nothing — which is right — but only by accident.*/+import { MAX_TARGET_IDS } from '../../target-ids.js';import supabaseAdmin from '../../../config/supabase.js';import { logger } from '../../logger.js';import { resolve } from '../../../config/action-engine.js';@@ -99,13 +100,27 @@ async function selectAll(build) {}}-/** A finding about a group — prompts, pages, queries — as one signal. */-function group(kind, entity, rows, toTarget, source, extra = {}) {+/**+ * A finding about a group — prompts, pages, queries — as one signal. It+ * names its first 50 targets; a bigger group lists every target's id too+ * (`targetIds`), so the action it starts counts and keeps the whole group+ * (AC-009: one count everywhere).+ */+export function group(kind, entity, rows, toTarget, source, extra = {}) {+ const ids =+ rows.length > 50+ ? {+ targetIds: rows.slice(0, MAX_TARGET_IDS).map((row) => {+ const target = toTarget(row);+ return String(target.id ?? target.label ?? '');+ }),+ }+ : {};return {kind,dedupKey: kind,source,- payload: { entity, targets: rows.slice(0, 50).map(toTarget), ...extra },+ payload: { entity, targets: rows.slice(0, 50).map(toTarget), ...ids, ...extra },previousValue: null,currentValue: rows.length,changeValue: null,diff --git a/server/src/lib/signals/library/group.test.js b/server/src/lib/signals/library/group.test.jsnew file mode 100644index 000000000..f989b11e2--- /dev/null+++ b/server/src/lib/signals/library/group.test.js@@ -0,0 +1,29 @@+import { describe, expect, it, vi } from 'vitest';++/**+ * A group signal names its first 50 targets and, past that, lists every+ * target's id (AC-009), so the action it starts counts the whole group.+ */++vi.mock('../../../config/supabase.js', () => ({ default: {} }));++const { group } = await import('./detect.js');++const toTarget = (row) => ({ id: row.id, label: row.text });+const rows = (n) => Array.from({ length: n }, (_, i) => ({ id: `p${i}`, text: `Prompt ${i}` }));++describe('group', () => {+ it('names 50 and lists every id past that', () => {+ const signal = group('k', 'prompts', rows(80), toTarget, ['ai_results']);+ expect(signal.currentValue).toBe(80);+ expect(signal.payload.targets).toHaveLength(50);+ expect(signal.payload.targetIds).toHaveLength(80);+ expect(signal.payload.targetIds[79]).toBe('p79');+ });++ it('lists no ids when it names them all', () => {+ const signal = group('k', 'prompts', rows(3), toTarget, ['ai_results']);+ expect(signal.payload.targets).toHaveLength(3);+ expect(signal.payload).not.toHaveProperty('targetIds');+ });+});diff --git a/server/src/lib/signals/record.js b/server/src/lib/signals/record.jsindex f9df573ff..ff262cdc2 100644--- a/server/src/lib/signals/record.js+++ b/server/src/lib/signals/record.js@@ -26,6 +26,7 @@* they never auto-resolve and simply age until triaged.*/+import { MAX_TARGET_IDS } from '../target-ids.js';import supabaseAdmin from '../../config/supabase.js';import { computePulseMetrics, LOST_CITATION_WINDOW_DAYS } from '../pulse/metrics.js';import { lostCitationEvidence } from './lost-citation-evidence.js';@@ -283,7 +284,8 @@ export async function uncitedMentionCandidates(brandId, now) {kind: 'uncited_mentions',dedupKey: 'uncited_mentions',source: ['ai_results'],- payload: { promptIds: uncited.map((row) => row.prompt_id).slice(0, 50) },+ // Every uncited prompt, so the action counts and keeps them all (AC-009).+ payload: { promptIds: uncited.map((row) => row.prompt_id).slice(0, MAX_TARGET_IDS) },previousValue: null,currentValue: uncited.length,changeValue: null,@@ -302,7 +304,7 @@ export async function uncitedMentionCandidates(brandId, now) {* drowning every other category. The worst pages ride in the payload for* the drawer; the full list lives on the Site Audit page.*/-async function auditCandidates(brandId, now) {+export async function auditCandidates(brandId, now) {const since = new Date(now.getTime() - detection.auditMaxAgeDays * DAY_MS).toISOString();const { data, error } = await supabaseAdmin.from('site_audits')@@ -331,7 +333,14 @@ async function auditCandidates(brandId, now) {kind: 'audit_low_score',dedupKey: 'audit_low_score',source: ['site_audit'],- payload: { urls: low.slice(0, 10) },+ // The ten lowest to show; past them, every low page's address for the+ // action's count (AC-009), as group signals list theirs past 50.+ payload: {+ urls: low.slice(0, 10),+ ...(low.length > 10+ ? { targetIds: low.slice(0, MAX_TARGET_IDS).map((audit) => audit.url) }+ : {}),+ },previousValue: null,currentValue: low.length,changeValue: null,diff --git a/server/src/lib/signals/uncited-mentions.test.js b/server/src/lib/signals/uncited-mentions.test.jsindex 7be5791d5..f8c4630fe 100644--- a/server/src/lib/signals/uncited-mentions.test.js+++ b/server/src/lib/signals/uncited-mentions.test.js@@ -78,7 +78,8 @@ describe('uncitedMentionCandidates', () => {const [signal] = await uncitedMentionCandidates('brand-1', now);expect(signal).toMatchObject({ kind: 'uncited_mentions', currentValue: 1500 });- expect(signal.payload.promptIds).toEqual(Array.from({ length: 50 }, (_, i) => uuid(i)));+ // Every uncited prompt the action will count, up to 1000 (AC-009).+ expect(signal.payload.promptIds).toEqual(Array.from({ length: 1000 }, (_, i) => uuid(i)));expect(calls.map((c) => c.range)).toEqual([[0, 999],[1000, 1999],diff --git a/server/src/lib/target-ids.js b/server/src/lib/target-ids.jsnew file mode 100644index 000000000..08dbece49--- /dev/null+++ b/server/src/lib/target-ids.js@@ -0,0 +1,25 @@+/**+ * The most target keys a signal or an action lists beyond the targets it+ * names (AC-009). A group signal names 50 targets with their labels and+ * lists every one's id up to this, so the action it starts counts and keeps+ * the whole group (action_entities, 00244); bigger groups count up to here.+ */+export const MAX_TARGET_IDS = 1000;++/**+ * The keys an action keeps, as action_entities keeps them (00244): each+ * trimmed of spaces, once, in order, up to MAX_TARGET_IDS; none empty, no+ * object or list, and no text that starts with "{" or "[" (00244 reads those+ * as an object's text, e.g. old signals' { url, score }). An action's+ * targetCount is their number, so its payload and its list agree.+ */+export function targetKeys(values) {+ const keys = new Set();+ for (const value of values) {+ if (keys.size >= MAX_TARGET_IDS) break;+ if (value !== null && typeof value === 'object') continue;+ const key = String(value ?? '').replace(/^ +| +$/g, '');+ if (key && key[0] !== '{' && key[0] !== '[') keys.add(key);+ }+ return [...keys];+}diff --git a/server/src/lib/target-ids.test.js b/server/src/lib/target-ids.test.jsnew file mode 100644index 000000000..782cc0598--- /dev/null+++ b/server/src/lib/target-ids.test.js@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';+import { MAX_TARGET_IDS, targetKeys } from './target-ids.js';++/** The keys an action keeps, as action_entities (00244) keeps them, so its count agrees. */+describe('targetKeys', () => {+ it('keeps each key once, trimmed, in order, none empty and none an object', () => {+ expect(targetKeys([' a', 'b', 'a ', '', null, 'c', { url: 'x' }, '[1]', 'b'])).toEqual([+ 'a',+ 'b',+ 'c',+ ]);+ });++ it('takes no object or list as a key', () => {+ expect(targetKeys([['x'], { id: 'y' }, 'z'])).toEqual(['z']);+ });++ it('stops at the most an action keeps', () => {+ const keys = targetKeys(Array.from({ length: MAX_TARGET_IDS + 5 }, (_, i) => `k${i}`));+ expect(keys).toHaveLength(MAX_TARGET_IDS);+ expect(keys.at(-1)).toBe(`k${MAX_TARGET_IDS - 1}`);+ });+});diff --git a/supabase/migrations/00244_action_entities.sql b/supabase/migrations/00244_action_entities.sqlnew file mode 100644index 000000000..660dcbe0c--- /dev/null+++ b/supabase/migrations/00244_action_entities.sql@@ -0,0 +1,332 @@+-- AC-009: one count source for an action's prompts, pages, competitors…+--+-- One action showed 13 prompts in its title, 12 in its detail and 13 in a+-- task: the title and the tasks read the count saved in the payload when the+-- action was created, the detail, Copy all and the exports re-counted the+-- signals the nightly pass rewrites, and nothing changed when a prompt was+-- deleted or paused.+--+-- An action now keeps the list of what it is about, once, when it is created:+-- one action_entities row per prompt, page, competitor… (its payload's+-- targetEntity), written by a trigger on actions so every way an action is+-- made (the engine, Send to Action Center from content, prompts, mentions,+-- topics, traffic) keeps it the same way. A prompt deleted or paused, or a+-- competitor deleted, marks its rows removed (a prompt resumed is back), so+-- every place can say "12 prompts (1 removed since this action was+-- created)" and name the one removed.+--+-- Actions made before this keep what their payload still names: the first 50+-- of a bigger group (their count stays the payload's).++create table if not exists public.action_entities (+ action_id uuid not null references public.actions(id) on delete cascade,+ -- The payload's targetEntity: prompts, pages, competitors, platforms…+ entity_type text not null,+ -- The target's id (a prompt or competitor id, an address, a platform).+ entity_key text not null,+ label text,+ removed_at timestamptz,+ removed_reason text+ constraint action_entities_removed_reason_check+ check (removed_reason is null or removed_reason in ('deleted', 'paused')),+ -- When the list was written: as the action was created, or by this+ -- migration's backfill for one made before (the nightly check, AC-009+ -- part 3, judges only lists kept at creation).+ kept_at timestamptz not null default now(),+ primary key (action_id, entity_type, entity_key)+);++-- A prompt or competitor going: every action naming it, at once.+create index if not exists action_entities_entity_idx+ on public.action_entities (entity_type, entity_key)+ where entity_type in ('prompts', 'competitors');++comment on table public.action_entities is+ 'AC-009: what an action is about (its payload''s targetEntity: prompts, pages, competitors…), kept once when the action is created; removed_at marks a prompt deleted or paused, or a competitor deleted, since. Every count of the action reads this list.';++alter table public.action_entities enable row level security;++drop policy if exists "action_entities: member select" on public.action_entities;+create policy "action_entities: member select" on public.action_entities+ for select using (+ action_id in (+ select a.id from public.actions a+ join public.brands b on b.id = a.brand_id+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ )+ );++revoke all on table public.action_entities from anon, authenticated;+grant select on table public.action_entities to authenticated;+grant all on table public.action_entities to service_role;++-- An action's list from its payload: every key it lists (targetIds; a+-- person-sent action's promptIds or pages), else the targets it names+-- (`targets`, or the list under its targetEntity, as Improve's `platforms`),+-- with the names it gives. A prompt is named by its text where the payload+-- gives none. Empty lists name nothing: the next one down is read.+create or replace function public.snapshot_action_entities(+ p_action_id uuid,+ p_brand_id uuid,+ p_payload jsonb,+ -- Mark a prompt already deleted or paused, a competitor already deleted, as+ -- removed: for actions kept before 00244, whose list is written now. A new+ -- action's list is what it was made from: nothing is removed yet.+ p_mark_gone boolean default false+)+returns void+language plpgsql+security definer+set search_path = public+as $$+declare+ v_type text := nullif(btrim(coalesce(p_payload->>'targetEntity', '')), '');+ v_keys jsonb;+ v_named jsonb;+begin+ if v_type is null then+ return;+ end if;+ v_named := case+ when jsonb_typeof(p_payload->'targets') = 'array' then p_payload->'targets'+ when jsonb_typeof(p_payload->v_type) = 'array' then p_payload->v_type+ else '[]'::jsonb+ end;+ v_keys := case+ when jsonb_typeof(p_payload->'targetIds') = 'array'+ and jsonb_array_length(p_payload->'targetIds') > 0 then p_payload->'targetIds'+ when v_type = 'prompts' and jsonb_typeof(p_payload->'promptIds') = 'array'+ and jsonb_array_length(p_payload->'promptIds') > 0 then p_payload->'promptIds'+ when v_type = 'pages' and jsonb_typeof(p_payload->'pages') = 'array'+ and jsonb_array_length(p_payload->'pages') > 0 then p_payload->'pages'+ end;++ insert into public.action_entities (+ action_id, entity_type, entity_key, label, removed_at, removed_reason)+ select p_action_id, v_type, k.key,+ coalesce(n.label, pr.text),+ case when p_mark_gone then+ case+ when v_type = 'prompts' and k.uid is not null and pr.id is null then now()+ when v_type = 'prompts' and pr.id is not null and not coalesce(pr.is_active, true) then now()+ when v_type = 'competitors' and co.id is null then now()+ end+ end,+ case when p_mark_gone then+ case+ when v_type = 'prompts' and k.uid is not null and pr.id is null then 'deleted'+ when v_type = 'prompts' and pr.id is not null and not coalesce(pr.is_active, true) then 'paused'+ when v_type = 'competitors' and co.id is null then 'deleted'+ end+ end+ from (+ -- Listed keys when the payload has them, else the named targets' keys,+ -- once each, in the payload's order. A uuid key is cast here, never in a+ -- join: a key that is a prompt's text would fail the cast there.+ select key, min(ord) as ord,+ case when key ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' then key::uuid end as uid+ from (+ select btrim(x.value) as key, x.ord+ from jsonb_array_elements_text(coalesce(v_keys, '[]'::jsonb)) with ordinality as x(value, ord)+ union all+ select coalesce(t->>'id', t->>'label', case when jsonb_typeof(t) = 'string' then t #>> '{}' end),+ t_ord + 1000000+ from jsonb_array_elements(+ case when v_keys is null then v_named else '[]'::jsonb end+ ) with ordinality as y(t, t_ord)+ ) keys+ -- An object where an id belongs (old signals' { url, score }) is no key.+ where coalesce(key, '') <> '' and left(key, 1) not in ('{', '[')+ group by key+ order by min(ord)+ limit 1000+ ) k+ -- The names the payload gives.+ left join lateral (+ select case when jsonb_typeof(t) = 'string' then t #>> '{}' else nullif(t->>'label', '') end as label+ from jsonb_array_elements(v_named) as z(t)+ where coalesce(t->>'id', t->>'label', case when jsonb_typeof(t) = 'string' then t #>> '{}' end) = k.key+ limit 1+ ) n on true+ left join public.prompts pr+ on v_type = 'prompts' and pr.id = k.uid+ left join public.competitors co+ on v_type = 'competitors' and co.brand_id = p_brand_id+ and (co.id::text = k.key or co.name = k.key)+ on conflict do nothing;+end;+$$;++revoke all on function public.snapshot_action_entities(uuid, uuid, jsonb, boolean) from public, anon, authenticated;++create or replace function public.actions_snapshot_entities()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+begin+ begin+ perform public.snapshot_action_entities(new.id, new.brand_id, new.payload);+ -- The list is kept here now: the payload doesn't carry a thousand keys+ -- to every read of the action.+ if new.payload ? 'targetIds' then+ update public.actions set payload = payload - 'targetIds' where id = new.id;+ end if;+ exception when others then+ -- An action is never refused for its list: the nightly check finds one+ -- kept without it.+ raise warning 'action % kept no entities: %', new.id, sqlerrm;+ end;+ return null;+end;+$$;++revoke all on function public.actions_snapshot_entities() from public, anon, authenticated;++drop trigger if exists actions_snapshot_entities on public.actions;+create trigger actions_snapshot_entities+ after insert on public.actions+ for each row execute function public.actions_snapshot_entities();++-- A prompt deleted: removed from every action that names it.+create or replace function public.action_entities_prompts_deleted()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+begin+ update public.action_entities e+ set removed_at = now(), removed_reason = 'deleted'+ from deleted_prompts d+ where e.entity_type = 'prompts'+ and e.entity_key = d.id::text+ and e.removed_reason is distinct from 'deleted';+ return null;+end;+$$;++revoke all on function public.action_entities_prompts_deleted() from public, anon, authenticated;++drop trigger if exists prompts_remove_from_actions on public.prompts;+create trigger prompts_remove_from_actions+ after delete on public.prompts+ referencing old table as deleted_prompts+ for each statement execute function public.action_entities_prompts_deleted();++-- A prompt paused is removed until it is resumed. (Transition tables can't+-- name columns, so every prompt update passes here; only an is_active change+-- touches a row.)+create or replace function public.action_entities_prompts_paused()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+begin+ update public.action_entities e+ set removed_at = now(), removed_reason = 'paused'+ from changed_prompts n+ join earlier_prompts o on o.id = n.id+ where e.entity_type = 'prompts'+ and e.entity_key = n.id::text+ and coalesce(o.is_active, true) and not coalesce(n.is_active, true)+ and e.removed_at is null;++ update public.action_entities e+ set removed_at = null, removed_reason = null+ from changed_prompts n+ join earlier_prompts o on o.id = n.id+ where e.entity_type = 'prompts'+ and e.entity_key = n.id::text+ and not coalesce(o.is_active, true) and coalesce(n.is_active, true)+ and e.removed_reason = 'paused';+ return null;+end;+$$;++revoke all on function public.action_entities_prompts_paused() from public, anon, authenticated;++drop trigger if exists prompts_pause_in_actions on public.prompts;+create trigger prompts_pause_in_actions+ after update on public.prompts+ referencing old table as earlier_prompts new table as changed_prompts+ for each statement execute function public.action_entities_prompts_paused();++-- A competitor deleted: removed from its brand's actions, by id or by name+-- (older signals name competitors by name).+create or replace function public.action_entities_competitors_deleted()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+begin+ update public.action_entities e+ set removed_at = now(), removed_reason = 'deleted'+ from deleted_competitors d+ join public.actions a on a.brand_id = d.brand_id+ where e.action_id = a.id+ and e.entity_type = 'competitors'+ and (e.entity_key = d.id::text or e.entity_key = d.name)+ and e.removed_at is null;+ return null;+end;+$$;++revoke all on function public.action_entities_competitors_deleted() from public, anon, authenticated;++drop trigger if exists competitors_remove_from_actions on public.competitors;+create trigger competitors_remove_from_actions+ after delete on public.competitors+ referencing old table as deleted_competitors+ for each statement execute function public.action_entities_competitors_deleted();++-- Each action's list in one read, for every place that shows a count: per+-- entity type, how many it was made with, how many are removed since, the names+-- of the removed (up to 20, for the hover) and their keys (to leave them out+-- of a list). Read through the member's policy: only their brands' actions+-- answer.+create or replace function public.action_entity_counts(p_action_ids uuid[])+returns table (+ action_id uuid,+ entity_type text,+ total integer,+ removed integer,+ removed_labels text[],+ removed_keys text[]+)+language sql+stable+security invoker+set search_path = public+as $$+ select e.action_id,+ e.entity_type,+ count(*)::integer,+ count(*) filter (where e.removed_at is not null)::integer,+ (array_agg(coalesce(e.label, e.entity_key) order by e.removed_at, e.entity_key)+ filter (where e.removed_at is not null))[1:20],+ array_agg(e.entity_key order by e.removed_at, e.entity_key)+ filter (where e.removed_at is not null)+ from public.action_entities e+ where e.action_id = any (p_action_ids[1:500])+ group by e.action_id, e.entity_type;+$$;++revoke execute on function public.action_entity_counts(uuid[]) from public, anon;+grant execute on function public.action_entity_counts(uuid[]) to authenticated, service_role;++-- The actions made before: their list from what their payload still names.+-- A topic opportunity counts its suggestions (targets), not the tracked+-- prompts it measures (promptIds). An action that names nothing a list can+-- hold keeps none; the web then shows its saved count (part 2).+select public.snapshot_action_entities(+ a.id,+ a.brand_id,+ case when a.kind = 'topic_opportunity' then a.payload - 'promptIds' else a.payload end,+ true)+from public.actions a+where a.deleted_at is null;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 13d9ec64a..e9c5ffd86 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -36496,3 +36496,339 @@ revoke all on function public.reserve_ai_usage(uuid, timestamptz, numeric, numergrant execute on function public.reserve_ai_usage(uuid, timestamptz, numeric, numeric, text, text, uuid, uuid, uuid)to service_role;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00244_action_entities.sql+-- ─────────────────────────────────────────────────────────────────────────+-- AC-009: one count source for an action's prompts, pages, competitors…+--+-- One action showed 13 prompts in its title, 12 in its detail and 13 in a+-- task: the title and the tasks read the count saved in the payload when the+-- action was created, the detail, Copy all and the exports re-counted the+-- signals the nightly pass rewrites, and nothing changed when a prompt was+-- deleted or paused.+--+-- An action now keeps the list of what it is about, once, when it is created:+-- one action_entities row per prompt, page, competitor… (its payload's+-- targetEntity), written by a trigger on actions so every way an action is+-- made (the engine, Send to Action Center from content, prompts, mentions,+-- topics, traffic) keeps it the same way. A prompt deleted or paused, or a+-- competitor deleted, marks its rows removed (a prompt resumed is back), so+-- every place can say "12 prompts (1 removed since this action was+-- created)" and name the one removed.+--+-- Actions made before this keep what their payload still names: the first 50+-- of a bigger group (their count stays the payload's).++create table if not exists public.action_entities (+ action_id uuid not null references public.actions(id) on delete cascade,+ -- The payload's targetEntity: prompts, pages, competitors, platforms…+ entity_type text not null,+ -- The target's id (a prompt or competitor id, an address, a platform).+ entity_key text not null,+ label text,+ removed_at timestamptz,+ removed_reason text+ constraint action_entities_removed_reason_check+ check (removed_reason is null or removed_reason in ('deleted', 'paused')),+ -- When the list was written: as the action was created, or by this+ -- migration's backfill for one made before (the nightly check, AC-009+ -- part 3, judges only lists kept at creation).+ kept_at timestamptz not null default now(),+ primary key (action_id, entity_type, entity_key)+);++-- A prompt or competitor going: every action naming it, at once.+create index if not exists action_entities_entity_idx+ on public.action_entities (entity_type, entity_key)+ where entity_type in ('prompts', 'competitors');++comment on table public.action_entities is+ 'AC-009: what an action is about (its payload''s targetEntity: prompts, pages, competitors…), kept once when the action is created; removed_at marks a prompt deleted or paused, or a competitor deleted, since. Every count of the action reads this list.';++alter table public.action_entities enable row level security;++drop policy if exists "action_entities: member select" on public.action_entities;+create policy "action_entities: member select" on public.action_entities+ for select using (+ action_id in (+ select a.id from public.actions a+ join public.brands b on b.id = a.brand_id+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ )+ );++revoke all on table public.action_entities from anon, authenticated;+grant select on table public.action_entities to authenticated;+grant all on table public.action_entities to service_role;++-- An action's list from its payload: every key it lists (targetIds; a+-- person-sent action's promptIds or pages), else the targets it names+-- (`targets`, or the list under its targetEntity, as Improve's `platforms`),+-- with the names it gives. A prompt is named by its text where the payload+-- gives none. Empty lists name nothing: the next one down is read.+create or replace function public.snapshot_action_entities(+ p_action_id uuid,+ p_brand_id uuid,+ p_payload jsonb,+ -- Mark a prompt already deleted or paused, a competitor already deleted, as+ -- removed: for actions kept before 00244, whose list is written now. A new+ -- action's list is what it was made from: nothing is removed yet.+ p_mark_gone boolean default false+)+returns void+language plpgsql+security definer+set search_path = public+as $$+declare+ v_type text := nullif(btrim(coalesce(p_payload->>'targetEntity', '')), '');+ v_keys jsonb;+ v_named jsonb;+begin+ if v_type is null then+ return;+ end if;+ v_named := case+ when jsonb_typeof(p_payload->'targets') = 'array' then p_payload->'targets'+ when jsonb_typeof(p_payload->v_type) = 'array' then p_payload->v_type+ else '[]'::jsonb+ end;+ v_keys := case+ when jsonb_typeof(p_payload->'targetIds') = 'array'+ and jsonb_array_length(p_payload->'targetIds') > 0 then p_payload->'targetIds'+ when v_type = 'prompts' and jsonb_typeof(p_payload->'promptIds') = 'array'+ and jsonb_array_length(p_payload->'promptIds') > 0 then p_payload->'promptIds'+ when v_type = 'pages' and jsonb_typeof(p_payload->'pages') = 'array'+ and jsonb_array_length(p_payload->'pages') > 0 then p_payload->'pages'+ end;++ insert into public.action_entities (+ action_id, entity_type, entity_key, label, removed_at, removed_reason)+ select p_action_id, v_type, k.key,+ coalesce(n.label, pr.text),+ case when p_mark_gone then+ case+ when v_type = 'prompts' and k.uid is not null and pr.id is null then now()+ when v_type = 'prompts' and pr.id is not null and not coalesce(pr.is_active, true) then now()+ when v_type = 'competitors' and co.id is null then now()+ end+ end,+ case when p_mark_gone then+ case+ when v_type = 'prompts' and k.uid is not null and pr.id is null then 'deleted'+ when v_type = 'prompts' and pr.id is not null and not coalesce(pr.is_active, true) then 'paused'+ when v_type = 'competitors' and co.id is null then 'deleted'+ end+ end+ from (+ -- Listed keys when the payload has them, else the named targets' keys,+ -- once each, in the payload's order. A uuid key is cast here, never in a+ -- join: a key that is a prompt's text would fail the cast there.+ select key, min(ord) as ord,+ case when key ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' then key::uuid end as uid+ from (+ select btrim(x.value) as key, x.ord+ from jsonb_array_elements_text(coalesce(v_keys, '[]'::jsonb)) with ordinality as x(value, ord)+ union all+ select coalesce(t->>'id', t->>'label', case when jsonb_typeof(t) = 'string' then t #>> '{}' end),+ t_ord + 1000000+ from jsonb_array_elements(+ case when v_keys is null then v_named else '[]'::jsonb end+ ) with ordinality as y(t, t_ord)+ ) keys+ -- An object where an id belongs (old signals' { url, score }) is no key.+ where coalesce(key, '') <> '' and left(key, 1) not in ('{', '[')+ group by key+ order by min(ord)+ limit 1000+ ) k+ -- The names the payload gives.+ left join lateral (+ select case when jsonb_typeof(t) = 'string' then t #>> '{}' else nullif(t->>'label', '') end as label+ from jsonb_array_elements(v_named) as z(t)+ where coalesce(t->>'id', t->>'label', case when jsonb_typeof(t) = 'string' then t #>> '{}' end) = k.key+ limit 1+ ) n on true+ left join public.prompts pr+ on v_type = 'prompts' and pr.id = k.uid+ left join public.competitors co+ on v_type = 'competitors' and co.brand_id = p_brand_id+ and (co.id::text = k.key or co.name = k.key)+ on conflict do nothing;+end;+$$;++revoke all on function public.snapshot_action_entities(uuid, uuid, jsonb, boolean) from public, anon, authenticated;++create or replace function public.actions_snapshot_entities()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+begin+ begin+ perform public.snapshot_action_entities(new.id, new.brand_id, new.payload);+ -- The list is kept here now: the payload doesn't carry a thousand keys+ -- to every read of the action.+ if new.payload ? 'targetIds' then+ update public.actions set payload = payload - 'targetIds' where id = new.id;+ end if;+ exception when others then+ -- An action is never refused for its list: the nightly check finds one+ -- kept without it.+ raise warning 'action % kept no entities: %', new.id, sqlerrm;+ end;+ return null;+end;+$$;++revoke all on function public.actions_snapshot_entities() from public, anon, authenticated;++drop trigger if exists actions_snapshot_entities on public.actions;+create trigger actions_snapshot_entities+ after insert on public.actions+ for each row execute function public.actions_snapshot_entities();++-- A prompt deleted: removed from every action that names it.+create or replace function public.action_entities_prompts_deleted()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+begin+ update public.action_entities e+ set removed_at = now(), removed_reason = 'deleted'+ from deleted_prompts d+ where e.entity_type = 'prompts'+ and e.entity_key = d.id::text+ and e.removed_reason is distinct from 'deleted';+ return null;+end;+$$;++revoke all on function public.action_entities_prompts_deleted() from public, anon, authenticated;++drop trigger if exists prompts_remove_from_actions on public.prompts;+create trigger prompts_remove_from_actions+ after delete on public.prompts+ referencing old table as deleted_prompts+ for each statement execute function public.action_entities_prompts_deleted();++-- A prompt paused is removed until it is resumed. (Transition tables can't+-- name columns, so every prompt update passes here; only an is_active change+-- touches a row.)+create or replace function public.action_entities_prompts_paused()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+begin+ update public.action_entities e+ set removed_at = now(), removed_reason = 'paused'+ from changed_prompts n+ join earlier_prompts o on o.id = n.id+ where e.entity_type = 'prompts'+ and e.entity_key = n.id::text+ and coalesce(o.is_active, true) and not coalesce(n.is_active, true)+ and e.removed_at is null;++ update public.action_entities e+ set removed_at = null, removed_reason = null+ from changed_prompts n+ join earlier_prompts o on o.id = n.id+ where e.entity_type = 'prompts'+ and e.entity_key = n.id::text+ and not coalesce(o.is_active, true) and coalesce(n.is_active, true)+ and e.removed_reason = 'paused';+ return null;+end;+$$;++revoke all on function public.action_entities_prompts_paused() from public, anon, authenticated;++drop trigger if exists prompts_pause_in_actions on public.prompts;+create trigger prompts_pause_in_actions+ after update on public.prompts+ referencing old table as earlier_prompts new table as changed_prompts+ for each statement execute function public.action_entities_prompts_paused();++-- A competitor deleted: removed from its brand's actions, by id or by name+-- (older signals name competitors by name).+create or replace function public.action_entities_competitors_deleted()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+begin+ update public.action_entities e+ set removed_at = now(), removed_reason = 'deleted'+ from deleted_competitors d+ join public.actions a on a.brand_id = d.brand_id+ where e.action_id = a.id+ and e.entity_type = 'competitors'+ and (e.entity_key = d.id::text or e.entity_key = d.name)+ and e.removed_at is null;+ return null;+end;+$$;++revoke all on function public.action_entities_competitors_deleted() from public, anon, authenticated;++drop trigger if exists competitors_remove_from_actions on public.competitors;+create trigger competitors_remove_from_actions+ after delete on public.competitors+ referencing old table as deleted_competitors+ for each statement execute function public.action_entities_competitors_deleted();++-- Each action's list in one read, for every place that shows a count: per+-- entity type, how many it was made with, how many are removed since, the names+-- of the removed (up to 20, for the hover) and their keys (to leave them out+-- of a list). Read through the member's policy: only their brands' actions+-- answer.+create or replace function public.action_entity_counts(p_action_ids uuid[])+returns table (+ action_id uuid,+ entity_type text,+ total integer,+ removed integer,+ removed_labels text[],+ removed_keys text[]+)+language sql+stable+security invoker+set search_path = public+as $$+ select e.action_id,+ e.entity_type,+ count(*)::integer,+ count(*) filter (where e.removed_at is not null)::integer,+ (array_agg(coalesce(e.label, e.entity_key) order by e.removed_at, e.entity_key)+ filter (where e.removed_at is not null))[1:20],+ array_agg(e.entity_key order by e.removed_at, e.entity_key)+ filter (where e.removed_at is not null)+ from public.action_entities e+ where e.action_id = any (p_action_ids[1:500])+ group by e.action_id, e.entity_type;+$$;++revoke execute on function public.action_entity_counts(uuid[]) from public, anon;+grant execute on function public.action_entity_counts(uuid[]) to authenticated, service_role;++-- The actions made before: their list from what their payload still names.+-- A topic opportunity counts its suggestions (targets), not the tracked+-- prompts it measures (promptIds). An action that names nothing a list can+-- hold keeps none; the web then shows its saved count (part 2).+select public.snapshot_action_entities(+ a.id,+ a.brand_id,+ case when a.kind = 'topic_opportunity' then a.payload - 'promptIds' else a.payload end,+ true)+from public.actions a+where a.deleted_at is null;+