Skip to content

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.

feat(action-center): make a definition a file, not a line in the engine (#828)

Gökhan Geyika425a91289f4
diff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.js
index 58e9a4d47..640b34be0 100644
--- a/server/src/config/action-engine.js
+++ b/server/src/config/action-engine.js
@@ -137,6 +137,22 @@ export const ENGINE_THRESHOLDS = Object.freeze({
*/
restAfterCloseDays: 14,
+ /**
+ * How many new actions one brand may be given in a day.
+ *
+ * A ceiling, not a target. Today it binds on nothing: eight definitions
+ * produce at most three actions on a brand's busiest day, because a brand
+ * rarely has more than a couple of distinct conditions firing at once.
+ * The ceiling is the definition count, and the plan takes that to sixty —
+ * at which point a bad night could hand someone a list nobody reads, and
+ * the engine would have talked its way out of being believed.
+ *
+ * Five is what one person can plausibly start on in a week. Anything over
+ * it is not lost: the condition is still firing, so the slot opens again
+ * tomorrow, in priority order.
+ */
+ maxNewActionsPerDay: 5,
+
/**
* Platform-wide result volume collapsing to this fraction of its trailing
* daily average is a collection incident on our side, not a visibility
diff --git a/server/src/lib/action-center/definitions/capture-ai-traffic.js b/server/src/lib/action-center/definitions/capture-ai-traffic.js
new file mode 100644
index 000000000..ef0d97da4
--- /dev/null
+++ b/server/src/lib/action-center/definitions/capture-ai-traffic.js
@@ -0,0 +1,20 @@
+/**
+ * Growth — pages already earning traffic that AI answers do not cite.
+ *
+ * The only definition whose evidence comes from outside our own tracking:
+ * page opportunities are landing pages read from the brand's analytics
+ * connection, so without one the definition has nothing to stand on.
+ */
+export default {
+ id: 'capture_ai_traffic',
+ version: 1,
+ category: 'growth',
+ signalKinds: ['page_opportunity'],
+ requires: ['analytics'],
+ optional: ['site_audits'],
+ tasks: ['review_pages', 'coverage_gaps', 'optimize_content', 'validate'],
+
+ payload(byKind) {
+ return { pageCount: (byKind.get('page_opportunity') ?? []).length };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/close-citation-gap.js b/server/src/lib/action-center/definitions/close-citation-gap.js
new file mode 100644
index 000000000..5e439f272
--- /dev/null
+++ b/server/src/lib/action-center/definitions/close-citation-gap.js
@@ -0,0 +1,26 @@
+/**
+ * Compete — a competitor is cited far more often than the brand.
+ *
+ * Distinct from close_competitor_gap, which is about visibility: this one is
+ * about who gets referenced, and the work is earning sources rather than
+ * ranking answers.
+ */
+export default {
+ id: 'close_citation_gap',
+ version: 1,
+ category: 'compete',
+ signalKinds: ['competitor_citation_gap'],
+ requires: ['tracking', 'competitors'],
+ optional: [],
+ tasks: ['compare_citations', 'identify_sources', 'strengthen_sources', 'validate'],
+
+ payload(byKind) {
+ const gap = (byKind.get('competitor_citation_gap') ?? [])[0];
+ if (!gap) return {};
+ return {
+ competitorNames: gap.payload?.competitorName ? [gap.payload.competitorName] : [],
+ citationCount: gap.current_value,
+ competitorCitations: gap.payload?.competitorCitations,
+ };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/close-competitor-gap.js b/server/src/lib/action-center/definitions/close-competitor-gap.js
new file mode 100644
index 000000000..baf7a961d
--- /dev/null
+++ b/server/src/lib/action-center/definitions/close-competitor-gap.js
@@ -0,0 +1,26 @@
+/**
+ * Compete — a competitor is gaining visibility, or has passed the brand.
+ *
+ * One action per cycle however many competitors moved: the response is the
+ * same piece of work, and three rows would be three copies of it.
+ */
+export default {
+ id: 'close_competitor_gap',
+ version: 1,
+ category: 'compete',
+ signalKinds: ['competitor_surge', 'competitor_crossed'],
+ requires: ['tracking', 'competitors'],
+ optional: [],
+ tasks: ['analyze_competitor', 'coverage_gaps', 'strengthen_content', 'validate'],
+
+ payload(byKind) {
+ const names = new Set();
+ for (const signals of byKind.values()) {
+ for (const signal of signals) {
+ const name = signal.payload?.competitorName;
+ if (name) names.add(name);
+ }
+ }
+ return { competitorNames: [...names].slice(0, 3) };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/convert-mentions.js b/server/src/lib/action-center/definitions/convert-mentions.js
new file mode 100644
index 000000000..e76101499
--- /dev/null
+++ b/server/src/lib/action-center/definitions/convert-mentions.js
@@ -0,0 +1,21 @@
+/**
+ * Growth — the brand is named in answers but not linked from them.
+ *
+ * A mention without a citation is recognition the brand earns nothing from:
+ * the reader has no route back. The work is making the claim citable, not
+ * winning more answers.
+ */
+export default {
+ id: 'convert_mentions',
+ version: 1,
+ category: 'growth',
+ signalKinds: ['uncited_mentions'],
+ requires: ['tracking'],
+ optional: [],
+ tasks: ['identify_prompts', 'create_citable_content', 'strengthen_sources'],
+
+ payload(byKind) {
+ const mentions = (byKind.get('uncited_mentions') ?? [])[0];
+ return { promptCount: Number(mentions?.current_value ?? 0) };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/expand-platform-visibility.js b/server/src/lib/action-center/definitions/expand-platform-visibility.js
new file mode 100644
index 000000000..1f3d5d61a
--- /dev/null
+++ b/server/src/lib/action-center/definitions/expand-platform-visibility.js
@@ -0,0 +1,27 @@
+/**
+ * Growth — the brand ranks on one engine and is absent on another.
+ *
+ * It is the engine, not the material, that differs: content that already
+ * ranks somewhere proves the content can rank, which is what separates this
+ * from a brand that is simply weak everywhere.
+ */
+export default {
+ id: 'expand_platform_visibility',
+ version: 1,
+ category: 'growth',
+ signalKinds: ['platform_gap'],
+ requires: ['tracking'],
+ optional: [],
+ tasks: ['compare_platforms', 'coverage_gaps', 'optimize_content', 'validate'],
+
+ payload(byKind) {
+ const gap = (byKind.get('platform_gap') ?? [])[0];
+ if (!gap) return {};
+ return {
+ platform: gap.payload?.platform,
+ bestPlatform: gap.payload?.bestPlatform,
+ dropFrom: gap.previous_value,
+ dropTo: gap.current_value,
+ };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/fix-low-scores.js b/server/src/lib/action-center/definitions/fix-low-scores.js
new file mode 100644
index 000000000..29d9d12f3
--- /dev/null
+++ b/server/src/lib/action-center/definitions/fix-low-scores.js
@@ -0,0 +1,21 @@
+/**
+ * Fix — pages whose Site Audit score is low enough to be the reason.
+ *
+ * Requires audits for the same reason the traffic definition requires
+ * analytics: without them there is no evidence, and a definition with no
+ * possible evidence should not be offered to the brand at all.
+ */
+export default {
+ id: 'fix_low_scores',
+ version: 1,
+ category: 'fix',
+ signalKinds: ['audit_low_score'],
+ requires: ['site_audits'],
+ optional: [],
+ tasks: ['review_audits', 'fix_issues', 'revalidate'],
+
+ payload(byKind) {
+ const audit = (byKind.get('audit_low_score') ?? [])[0];
+ return { pageCount: Number(audit?.current_value ?? 0) };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/index.js b/server/src/lib/action-center/definitions/index.js
new file mode 100644
index 000000000..61029ad9f
--- /dev/null
+++ b/server/src/lib/action-center/definitions/index.js
@@ -0,0 +1,133 @@
+/**
+ * The action definition registry (#818, phase 4).
+ *
+ * A definition says what condition deserves an action, what work it implies,
+ * and what data a brand must have for it to apply. Until now the eight of
+ * them lived in one array inside the generator, with their payload shaping
+ * in a switch beside it. That is fine at eight and impossible at sixty-two:
+ * every new definition would mean editing the engine, and a mistake in one
+ * would break the others.
+ *
+ * So the engine no longer knows any definition by name. Each one is a file
+ * in this directory; the registry finds them, checks them, and hands the
+ * engine a list. Adding a definition means adding a file — nothing in
+ * generate.js, nothing in another definition.
+ *
+ * Discovery is by directory listing rather than a manifest of imports on
+ * purpose: a manifest is one more place to forget, and forgetting it fails
+ * silently (the definition simply never fires) where a malformed file fails
+ * loudly, at startup, with the filename in the message.
+ *
+ * ## Versions
+ *
+ * `version` is the definition's own, bumped by whoever changes what it means
+ * — different thresholds, a different task list, a different scope. Every
+ * action records the version that created it, so an action raised in March
+ * can still be read against the rules that raised it. Nothing reads the
+ * version yet; recording it costs a column, and reconstructing it later
+ * would cost the history.
+ */
+
+import { readdirSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { SOURCES } from '../sources.js';
+
+const DIR = dirname(fileURLToPath(import.meta.url));
+
+/** Mirrors the actions.category check constraint. */
+export const CATEGORIES = Object.freeze(['growth', 'protect', 'recover', 'fix', 'compete']);
+
+const ID_PATTERN = /^[a-z][a-z0-9_]*$/;
+
+function fail(file, message) {
+ throw new Error(`[action definitions] ${file}: ${message}`);
+}
+
+function assertStringList(value, { file, field, allowed, allowEmpty = false }) {
+ if (!Array.isArray(value)) fail(file, `${field} must be an array`);
+ if (value.length === 0 && !allowEmpty) fail(file, `${field} must not be empty`);
+ for (const entry of value) {
+ if (typeof entry !== 'string' || entry.length === 0) {
+ fail(file, `${field} contains a non-string entry`);
+ }
+ if (allowed && !allowed.includes(entry)) {
+ fail(file, `${field} names an unknown source "${entry}"`);
+ }
+ }
+ if (new Set(value).size !== value.length) fail(file, `${field} contains duplicates`);
+}
+
+/**
+ * Everything a definition must get right to be loaded at all.
+ *
+ * Strict on purpose. A definition that is half-wrong is worse than one that
+ * is missing: it produces actions nobody can present, or claims a signal
+ * kind nothing emits and quietly never fires.
+ */
+function validate(definition, file) {
+ if (!definition || typeof definition !== 'object') fail(file, 'must default-export an object');
+
+ const { id, version, category, signalKinds, requires, optional, tasks, payload } = definition;
+
+ if (typeof id !== 'string' || !ID_PATTERN.test(id)) {
+ fail(file, 'id must be a lower_snake_case string');
+ }
+ if (!Number.isInteger(version) || version < 1) fail(file, 'version must be a positive integer');
+ if (!CATEGORIES.includes(category)) fail(file, `category "${category}" is not a known family`);
+
+ assertStringList(signalKinds, { file, field: 'signalKinds' });
+ assertStringList(tasks, { file, field: 'tasks' });
+ assertStringList(requires, { file, field: 'requires', allowed: SOURCES });
+ assertStringList(optional ?? [], { file, field: 'optional', allowed: SOURCES, allowEmpty: true });
+
+ const overlap = (optional ?? []).filter((source) => requires.includes(source));
+ if (overlap.length > 0) fail(file, `${overlap.join(', ')} is both required and optional`);
+
+ if (typeof payload !== 'function') fail(file, 'payload must be a function');
+
+ return Object.freeze({ ...definition, optional: Object.freeze([...(optional ?? [])]) });
+}
+
+let cache = null;
+
+/**
+ * Every definition, ordered by id so a run is reproducible.
+ *
+ * @returns {Promise<readonly object[]>}
+ */
+export async function loadDefinitions() {
+ if (cache) return cache;
+
+ const files = readdirSync(DIR)
+ .filter((file) => file.endsWith('.js') && file !== 'index.js' && !file.endsWith('.test.js'))
+ .sort();
+
+ const definitions = [];
+ const seen = new Set();
+ for (const file of files) {
+ const module = await import(pathToFileURL(join(DIR, file)).href);
+ const definition = validate(module.default, file);
+ if (seen.has(definition.id)) fail(file, `id "${definition.id}" is already taken`);
+ seen.add(definition.id);
+ definitions.push(definition);
+ }
+
+ cache = Object.freeze(definitions.sort((a, b) => a.id.localeCompare(b.id)));
+ return cache;
+}
+
+/**
+ * Does this brand have what the definition needs?
+ *
+ * Belt and braces today — a brand with no competitors never gets a
+ * competitor signal, so the definition would not have matched anyway — but
+ * it makes the data contract a declaration rather than a coincidence, and
+ * phase 5 reads the same answer to decide which tasks a plan can contain.
+ *
+ * @param {{ requires: readonly string[] }} definition
+ * @param {Set<string>} available
+ */
+export function isEligible(definition, available) {
+ return definition.requires.every((source) => available.has(source));
+}
diff --git a/server/src/lib/action-center/definitions/protect-visibility.js b/server/src/lib/action-center/definitions/protect-visibility.js
new file mode 100644
index 000000000..7879df2b6
--- /dev/null
+++ b/server/src/lib/action-center/definitions/protect-visibility.js
@@ -0,0 +1,23 @@
+/**
+ * Protect — a real position losing ground, caught before it collapses.
+ *
+ * The Protect family's first definition (#823). Its trigger is the relative
+ * slip detector rather than the collapse, so the two grades differ in
+ * severity and in the work they ask for, not in how they are measured.
+ */
+export default {
+ id: 'protect_visibility',
+ version: 1,
+ category: 'protect',
+ signalKinds: ['visibility_slipping'],
+ requires: ['tracking'],
+ // Who is taking the ground is context, not a precondition.
+ optional: ['competitors'],
+ tasks: ['diagnose_slip', 'review_responses', 'reinforce_content', 'validate'],
+
+ payload(byKind) {
+ const slip = (byKind.get('visibility_slipping') ?? [])[0];
+ if (!slip) return {};
+ return { dropFrom: slip.previous_value, dropTo: slip.current_value };
+ },
+};
diff --git a/server/src/lib/action-center/definitions/recover-visibility.js b/server/src/lib/action-center/definitions/recover-visibility.js
new file mode 100644
index 000000000..75eee17c6
--- /dev/null
+++ b/server/src/lib/action-center/definitions/recover-visibility.js
@@ -0,0 +1,28 @@
+/**
+ * Recover — the brand held a position and lost it.
+ *
+ * Kept apart from protect_visibility on purpose: the work differs. Recovering
+ * asks what was lost and how to win it back; protecting asks what is slipping
+ * and how to hold it, while the position still exists to hold.
+ */
+export default {
+ id: 'recover_visibility',
+ version: 1,
+ category: 'recover',
+ signalKinds: ['sharp_drop', 'lost_citations'],
+ requires: ['tracking'],
+ // Traffic is not needed to raise the action, but with it connected the plan
+ // can show what the drop cost in sessions rather than only in points.
+ optional: ['analytics'],
+ tasks: ['analyze_losses', 'coverage_gaps', 'update_content', 'internal_links', 'validate'],
+
+ payload(byKind) {
+ const out = { promptCount: (byKind.get('lost_citations') ?? []).length };
+ const drop = (byKind.get('sharp_drop') ?? [])[0];
+ if (drop) {
+ out.dropFrom = drop.previous_value;
+ out.dropTo = drop.current_value;
+ }
+ return out;
+ },
+};
diff --git a/server/src/lib/action-center/definitions/registry.test.js b/server/src/lib/action-center/definitions/registry.test.js
new file mode 100644
index 000000000..385b43a36
--- /dev/null
+++ b/server/src/lib/action-center/definitions/registry.test.js
@@ -0,0 +1,107 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// The signal registry reaches the admin client at import time, whose config
+// hard-exits without SUPABASE_* env (as in CI). Nothing under test touches it.
+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 { CATEGORIES, isEligible, loadDefinitions } from './index.js';
+import { SOURCES } from '../sources.js';
+import { KIND_META } from '../../signals/record.js';
+
+const definitions = await loadDefinitions();
+
+/**
+ * The registry's whole promise is that a definition can be added by dropping
+ * a file in the directory. That only holds if a bad file is caught, so these
+ * are the checks the loader makes, asserted against what is actually there.
+ */
+describe('the definition registry', () => {
+ it('finds every definition file in the directory', () => {
+ expect(definitions.length).toBeGreaterThan(0);
+ });
+
+ it('gives each definition a unique id', () => {
+ const ids = definitions.map((definition) => definition.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it('orders them reproducibly, so two runs agree', () => {
+ const ids = definitions.map((definition) => definition.id);
+ expect(ids).toEqual([...ids].sort());
+ });
+
+ it.each(definitions.map((definition) => [definition.id, definition]))(
+ '%s is a well-formed definition',
+ (_id, definition) => {
+ expect(CATEGORIES).toContain(definition.category);
+ expect(Number.isInteger(definition.version)).toBe(true);
+ expect(definition.version).toBeGreaterThanOrEqual(1);
+ expect(definition.signalKinds.length).toBeGreaterThan(0);
+ expect(definition.tasks.length).toBeGreaterThan(0);
+ expect(typeof definition.payload).toBe('function');
+ for (const source of [...definition.requires, ...definition.optional]) {
+ expect(SOURCES).toContain(source);
+ }
+ },
+ );
+
+ /**
+ * A definition naming a signal kind nothing emits cannot fire, and nothing
+ * would say so — it would simply be quiet forever. Cheaper to fail here
+ * than to wonder in three months why a family never produced an action.
+ */
+ it.each(definitions.map((definition) => [definition.id, definition]))(
+ '%s only listens for signal kinds a detector emits',
+ (_id, definition) => {
+ for (const kind of definition.signalKinds) {
+ expect(Object.keys(KIND_META)).toContain(kind);
+ }
+ },
+ );
+
+ /**
+ * Two definitions consuming the same signal kind would both fire on it,
+ * giving the brand two actions for one condition.
+ */
+ it('gives each signal kind at most one definition', () => {
+ const owner = new Map();
+ for (const definition of definitions) {
+ for (const kind of definition.signalKinds) {
+ expect(owner.get(kind) ?? definition.id).toBe(definition.id);
+ owner.set(kind, definition.id);
+ }
+ }
+ });
+
+ it('shapes a payload from the signals it was given', () => {
+ for (const definition of definitions) {
+ const byKind = new Map(definition.signalKinds.map((kind) => [kind, []]));
+ expect(typeof definition.payload(byKind)).toBe('object');
+ }
+ });
+
+ /** An empty map is what an ineligible or signal-less brand looks like. */
+ it('survives being asked for a payload with nothing to shape', () => {
+ for (const definition of definitions) {
+ expect(() => definition.payload(new Map())).not.toThrow();
+ }
+ });
+});
+
+describe('isEligible', () => {
+ const definition = { requires: ['tracking', 'analytics'] };
+
+ it('passes when the brand has every required source', () => {
+ expect(isEligible(definition, new Set(['tracking', 'analytics', 'competitors']))).toBe(true);
+ });
+
+ it('fails when one is missing', () => {
+ expect(isEligible(definition, new Set(['tracking']))).toBe(false);
+ });
+
+ it('ignores optional sources entirely', () => {
+ expect(isEligible({ requires: [], optional: ['analytics'] }, new Set())).toBe(true);
+ });
+});
diff --git a/server/src/lib/action-center/generate.js b/server/src/lib/action-center/generate.js
index e028911f9..a88bbd7e6 100644
--- a/server/src/lib/action-center/generate.js
+++ b/server/src/lib/action-center/generate.js
@@ -2,13 +2,17 @@
* Action generation (Action Center, prioritization layer).
*
* Consolidates a brand's OPEN signals into a handful of actions — many
- * signals → one action, deterministically. Each rule below names the signal
+ * signals → one action, deterministically. A definition names the signal
* kinds that constitute one outcome; if a brand has six open page
* opportunities they become ONE "capture AI traffic" action with six linked
* signals, never six rows. The count of actions therefore follows what the
* detectors actually found: four important things yield four actions, per
- * the quality-over-quantity rule. A future scoring/clustering engine can
- * replace this module without touching the schema.
+ * the quality-over-quantity rule.
+ *
+ * This module is the matching engine and knows no definition by name. What
+ * exists, what it needs, and what it puts in its payload is each definition's
+ * own business — see definitions/index.js. The engine's job is the part every
+ * definition shares: match, decide whether a new cycle may open, and write.
*
* Lifecycle across nights, mirroring signals:
* - an ACTIVE action keeps its scope. Newly detected signals are linked to
@@ -18,17 +22,24 @@
* - a CLOSED action — completed or dismissed — is finished. It is never
* written to again and never resurrected; it is the historical record of
* one execution cycle;
- * - closing frees the kind's slot. Once the rest window has passed, a still
- * firing condition opens a NEW action beside the old one, with its own
- * baseline, tasks and outcome.
+ * - closing frees the definition's slot. Once the rest window has passed, a
+ * still firing condition opens a NEW action beside the old one, with its
+ * own baseline, tasks and outcome.
+ *
+ * Three things stop an action being raised, and they are counted separately
+ * so a quiet night is legible: the brand lacks the data the definition needs
+ * (`ineligible`), the last cycle closed too recently (`resting`), or the
+ * brand has already had its day's worth (`capped`).
*
* `baseline` snapshots the linked signals' measured values at creation —
- * the "before" half of the future validation comparison (#818, phase 2).
+ * the "before" half of the validation comparison (#818, phase 2).
*/
import supabaseAdmin from '../../config/supabase.js';
import { logger } from '../logger.js';
import { resolve } from '../../config/action-engine.js';
+import { isEligible, loadDefinitions } from './definitions/index.js';
+import { resolveBrandSources } from './sources.js';
const DAY_MS = 86_400_000;
@@ -37,137 +48,6 @@ const { noise } = resolve();
const IMPACT_RANK = { high: 3, medium: 2, low: 1 };
-/**
- * The consolidation rules. `kind` keys the i18n templates and task list
- * web-side (web/src/lib/action-center/registry.ts); `signalKinds` decides
- * which open signals constitute the action.
- */
-const ACTION_RULES = [
- {
- kind: 'recover_visibility',
- category: 'recover',
- signalKinds: ['sharp_drop', 'lost_citations'],
- taskKeys: ['analyze_losses', 'coverage_gaps', 'update_content', 'internal_links', 'validate'],
- },
- // The Protect family's first definition. Kept apart from recover_visibility
- // on purpose: the work differs. Recovering asks what was lost and how to
- // win it back; protecting asks what is slipping and how to hold it, while
- // the position still exists to hold.
- {
- kind: 'protect_visibility',
- category: 'protect',
- signalKinds: ['visibility_slipping'],
- taskKeys: ['diagnose_slip', 'review_responses', 'reinforce_content', 'validate'],
- },
- {
- kind: 'capture_ai_traffic',
- category: 'growth',
- signalKinds: ['page_opportunity'],
- taskKeys: ['review_pages', 'coverage_gaps', 'optimize_content', 'validate'],
- },
- // Growth's second definition: the brand ranks somewhere, so the content can
- // rank — it is the engine, not the material, that differs.
- {
- kind: 'expand_platform_visibility',
- category: 'growth',
- signalKinds: ['platform_gap'],
- taskKeys: ['compare_platforms', 'coverage_gaps', 'optimize_content', 'validate'],
- },
- {
- kind: 'convert_mentions',
- category: 'growth',
- signalKinds: ['uncited_mentions'],
- taskKeys: ['identify_prompts', 'create_citable_content', 'strengthen_sources'],
- },
- {
- kind: 'fix_low_scores',
- category: 'fix',
- signalKinds: ['audit_low_score'],
- taskKeys: ['review_audits', 'fix_issues', 'revalidate'],
- },
- // Compete's second definition. Distinct from close_competitor_gap, which is
- // about visibility: this one is about who gets cited, and the work is
- // earning references rather than ranking answers.
- {
- kind: 'close_citation_gap',
- category: 'compete',
- signalKinds: ['competitor_citation_gap'],
- taskKeys: ['compare_citations', 'identify_sources', 'strengthen_sources', 'validate'],
- },
- {
- kind: 'close_competitor_gap',
- category: 'compete',
- signalKinds: ['competitor_surge', 'competitor_crossed'],
- taskKeys: ['analyze_competitor', 'coverage_gaps', 'strengthen_content', 'validate'],
- },
-];
-
-function buildPayload(rule, signals) {
- const byKind = new Map();
- for (const signal of signals) {
- byKind.set(signal.kind, [...(byKind.get(signal.kind) ?? []), signal]);
- }
- const payload = { signalCount: signals.length };
-
- switch (rule.kind) {
- case 'recover_visibility': {
- payload.promptCount = (byKind.get('lost_citations') ?? []).length;
- const drop = (byKind.get('sharp_drop') ?? [])[0];
- if (drop) {
- payload.dropFrom = drop.previous_value;
- payload.dropTo = drop.current_value;
- }
- break;
- }
- case 'expand_platform_visibility': {
- const gap = (byKind.get('platform_gap') ?? [])[0];
- if (gap) {
- payload.platform = gap.payload?.platform;
- payload.bestPlatform = gap.payload?.bestPlatform;
- payload.dropFrom = gap.previous_value;
- payload.dropTo = gap.current_value;
- }
- break;
- }
- case 'close_citation_gap': {
- const gap = (byKind.get('competitor_citation_gap') ?? [])[0];
- if (gap) {
- payload.competitorNames = gap.payload?.competitorName ? [gap.payload.competitorName] : [];
- payload.citationCount = gap.current_value;
- payload.competitorCitations = gap.payload?.competitorCitations;
- }
- break;
- }
- case 'protect_visibility': {
- const slip = (byKind.get('visibility_slipping') ?? [])[0];
- if (slip) {
- payload.dropFrom = slip.previous_value;
- payload.dropTo = slip.current_value;
- }
- break;
- }
- case 'capture_ai_traffic':
- payload.pageCount = (byKind.get('page_opportunity') ?? []).length;
- break;
- case 'convert_mentions':
- payload.promptCount = Number((byKind.get('uncited_mentions') ?? [])[0]?.current_value ?? 0);
- break;
- case 'fix_low_scores':
- payload.pageCount = Number((byKind.get('audit_low_score') ?? [])[0]?.current_value ?? 0);
- break;
- case 'close_competitor_gap': {
- const names = new Set();
- for (const signal of signals) {
- const name = signal.payload?.competitorName;
- if (name) names.add(name);
- }
- payload.competitorNames = [...names].slice(0, 3);
- break;
- }
- }
- return payload;
-}
-
function buildBaseline(signals) {
return {
capturedAt: new Date().toISOString(),
@@ -181,6 +61,14 @@ function buildBaseline(signals) {
};
}
+function groupByKind(signals) {
+ const byKind = new Map();
+ for (const signal of signals) {
+ byKind.set(signal.kind, [...(byKind.get(signal.kind) ?? []), signal]);
+ }
+ return byKind;
+}
+
async function logEvent(actionId, event, data = {}) {
const { error } = await supabaseAdmin
.from('action_events')
@@ -202,7 +90,65 @@ async function linkSignals(actionId, signals) {
return unlinked.length;
}
-export async function generateActionsForBrand(brandId, { now = new Date() } = {}) {
+/**
+ * Which candidate gets the day's remaining room.
+ *
+ * The same order the Action Center sorts by: impact, then weight of
+ * evidence, then something stable. Phase 6 replaces this with scoring across
+ * candidates; until definitions compete for the room there is nothing for a
+ * score to say that this does not.
+ */
+function comparePriority(a, b) {
+ return (
+ IMPACT_RANK[b.impact] - IMPACT_RANK[a.impact] ||
+ b.signals.length - a.signals.length ||
+ a.definition.id.localeCompare(b.definition.id)
+ );
+}
+
+function startOfUtcDay(now) {
+ return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
+}
+
+async function openCycle({ brandId, definition, signals, impact }) {
+ const { data: inserted, error } = await supabaseAdmin
+ .from('actions')
+ .insert({
+ brand_id: brandId,
+ category: definition.category,
+ kind: definition.id,
+ definition_version: definition.version,
+ impact,
+ payload: { signalCount: signals.length, ...definition.payload(groupByKind(signals)) },
+ kpi_keys: [...new Set(signals.flatMap((signal) => signal.kpi_keys ?? []))],
+ baseline: buildBaseline(signals),
+ dedup_key: definition.id,
+ })
+ .select('id')
+ .single();
+ if (error) throw new Error(error.message);
+
+ const { error: tasksErr } = await supabaseAdmin.from('action_tasks').insert(
+ definition.tasks.map((taskKey, index) => ({
+ action_id: inserted.id,
+ position: index + 1,
+ task_key: taskKey,
+ })),
+ );
+ if (tasksErr) throw new Error(tasksErr.message);
+
+ await logEvent(inserted.id, 'created', {
+ impact,
+ signalCount: signals.length,
+ definitionVersion: definition.version,
+ });
+ await linkSignals(inserted.id, signals);
+}
+
+export async function generateActionsForBrand(brandId, { now = new Date(), sources } = {}) {
+ const definitions = await loadDefinitions();
+ const available = sources ?? (await resolveBrandSources(brandId));
+
const { data: openSignals, error: signalsErr } = await supabaseAdmin
.from('signals')
.select(
@@ -218,18 +164,18 @@ export async function generateActionsForBrand(brandId, { now = new Date() } = {}
// has no bearing on what happens tonight beyond the rest window below.
const { data: activeRows, error: actionsErr } = await supabaseAdmin
.from('actions')
- .select('id, dedup_key, status')
+ .select('id, dedup_key, status, created_at')
.eq('brand_id', brandId)
.not('status', 'in', '("completed","dismissed")')
.limit(1000);
if (actionsErr) throw new Error(actionsErr.message);
const active = new Map((activeRows ?? []).map((row) => [row.dedup_key, row]));
- // How recently each kind was closed, so a condition that is still firing
- // does not reopen as a fresh action the very next night.
+ // How recently each definition was closed, so a condition that is still
+ // firing does not reopen as a fresh action the very next night.
const { data: closedRows, error: closedErr } = await supabaseAdmin
.from('actions')
- .select('dedup_key, completed_at, updated_at')
+ .select('dedup_key, completed_at, updated_at, created_at')
.eq('brand_id', brandId)
.in('status', ['completed', 'dismissed'])
.order('created_at', { ascending: false })
@@ -243,79 +189,84 @@ export async function generateActionsForBrand(brandId, { now = new Date() } = {}
}
}
+ // The day's budget, counted from rows already fetched rather than asked
+ // for separately. An action raised this morning and dismissed by lunch
+ // still spent its slot: the brand was told about it.
+ const dayStart = startOfUtcDay(now);
+ const createdToday = [...(activeRows ?? []), ...(closedRows ?? [])].filter(
+ (row) => (Date.parse(row.created_at ?? '') || 0) >= dayStart,
+ ).length;
+
const nowIso = now.toISOString();
- let created = 0;
+ const candidates = [];
let refreshed = 0;
let resting = 0;
+ let ineligible = 0;
- for (const rule of ACTION_RULES) {
- const matched = (openSignals ?? []).filter((signal) => rule.signalKinds.includes(signal.kind));
+ for (const definition of definitions) {
+ const matched = (openSignals ?? []).filter((signal) =>
+ definition.signalKinds.includes(signal.kind),
+ );
if (matched.length === 0) continue;
- const impact = matched
- .map((signal) => signal.impact)
- .sort((a, b) => IMPACT_RANK[b] - IMPACT_RANK[a])[0];
- const kpiKeys = [...new Set(matched.flatMap((signal) => signal.kpi_keys ?? []))];
- const payload = buildPayload(rule, matched);
- const current = active.get(rule.kind);
-
- if (!current) {
- // The slot is open. Leave it open a while after a cycle closed, so a
- // condition that is still firing does not produce a fresh action every
- // night — the same restraint the old reopen window provided, minus the
- // resurrection.
- const closedAt = lastClosedAt.get(rule.kind) ?? 0;
- if (closedAt && now.getTime() - closedAt < noise.restAfterCloseDays * DAY_MS) {
- resting += 1;
- continue;
+ const current = active.get(definition.id);
+ if (current) {
+ // An active action (new / in_progress / on_hold) keeps the scope it was
+ // created with. Signals that arrived since are linked as evidence —
+ // they are why this action exists — but `payload` is the work package
+ // someone may already be executing against, and rewriting it nightly
+ // turned a recovery for six prompts into a recovery for a different
+ // nine without telling anyone. New targets wait for the next cycle.
+ const linked = await linkSignals(current.id, matched);
+ if (linked > 0) {
+ await supabaseAdmin.from('actions').update({ updated_at: nowIso }).eq('id', current.id);
+ await logEvent(current.id, 'signals_linked', { count: linked });
}
+ refreshed += 1;
+ continue;
+ }
- const { data: inserted, error } = await supabaseAdmin
- .from('actions')
- .insert({
- brand_id: brandId,
- category: rule.category,
- kind: rule.kind,
- impact,
- payload,
- kpi_keys: kpiKeys,
- baseline: buildBaseline(matched),
- dedup_key: rule.kind,
- })
- .select('id')
- .single();
- if (error) throw new Error(error.message);
-
- const { error: tasksErr } = await supabaseAdmin.from('action_tasks').insert(
- rule.taskKeys.map((taskKey, index) => ({
- action_id: inserted.id,
- position: index + 1,
- task_key: taskKey,
- })),
- );
- if (tasksErr) throw new Error(tasksErr.message);
-
- await logEvent(inserted.id, 'created', { impact, signalCount: matched.length });
- await linkSignals(inserted.id, matched);
- created += 1;
+ // Eligibility gates opening a cycle, not maintaining one: a brand that
+ // disconnects an integration mid-cycle keeps the action it was given.
+ if (!isEligible(definition, available)) {
+ ineligible += 1;
continue;
}
- // An active action (new / in_progress / on_hold) keeps the scope it was
- // created with. Signals that arrived since are linked as evidence — they
- // are why this action exists — but `payload` is the work package someone
- // may already be executing against, and rewriting it nightly turned a
- // recovery for six prompts into a recovery for a different nine without
- // telling anyone. New targets wait for the next cycle.
- const linked = await linkSignals(current.id, matched);
- if (linked > 0) {
- await supabaseAdmin.from('actions').update({ updated_at: nowIso }).eq('id', current.id);
- await logEvent(current.id, 'signals_linked', { count: linked });
+ // The slot is open. Leave it open a while after a cycle closed, so a
+ // condition that is still firing does not produce a fresh action every
+ // night — the same restraint the old reopen window provided, minus the
+ // resurrection.
+ const closedAt = lastClosedAt.get(definition.id) ?? 0;
+ if (closedAt && now.getTime() - closedAt < noise.restAfterCloseDays * DAY_MS) {
+ resting += 1;
+ continue;
}
- refreshed += 1;
+
+ candidates.push({
+ definition,
+ signals: matched,
+ impact: matched
+ .map((signal) => signal.impact)
+ .sort((a, b) => IMPACT_RANK[b] - IMPACT_RANK[a])[0],
+ });
}
- const summary = { created, refreshed, resting };
+ const room = Math.max(0, noise.maxNewActionsPerDay - createdToday);
+ candidates.sort(comparePriority);
+ const opening = candidates.slice(0, room);
+
+ for (const candidate of opening) {
+ await openCycle({ brandId, ...candidate });
+ }
+
+ const summary = {
+ created: opening.length,
+ refreshed,
+ resting,
+ ineligible,
+ capped: candidates.length - opening.length,
+ };
logger.info({ brandId, ...summary }, '[actions] generated');
return summary;
}
diff --git a/server/src/lib/action-center/generate.test.js b/server/src/lib/action-center/generate.test.js
index d590c62f0..b58d4e94f 100644
--- a/server/src/lib/action-center/generate.test.js
+++ b/server/src/lib/action-center/generate.test.js
@@ -9,8 +9,14 @@ vi.mock('../logger.js', () => ({
}));
import { generateActionsForBrand } from './generate.js';
+import { ENGINE_THRESHOLDS } from '../../config/action-engine.js';
+
+const { maxNewActionsPerDay } = ENGINE_THRESHOLDS.noise;
const BRAND = 'brand-1';
+/** A brand with everything connected, so eligibility is not what a test is
+ * measuring unless it says so. */
+const ALL_SOURCES = new Set(['tracking', 'competitors', 'site_audits', 'analytics']);
const NOW = new Date('2026-09-16T04:00:00Z');
/**
@@ -219,7 +225,162 @@ describe('generateActionsForBrand', () => {
const summary = await generateActionsForBrand(BRAND, { now: NOW });
- expect(summary).toEqual({ created: 0, refreshed: 0, resting: 0 });
+ expect(summary).toEqual({
+ created: 0,
+ refreshed: 0,
+ resting: 0,
+ ineligible: 0,
+ capped: 0,
+ });
expect(writes.inserted).toHaveLength(0);
});
});
+
+/**
+ * Phase 4 (#818): the engine stopped knowing any definition by name. What is
+ * tested here is the part it still owns — whether a brand may have this
+ * definition at all, and how many it may have in one day.
+ */
+describe('eligibility', () => {
+ it('does not raise a definition the brand has no data for', async () => {
+ const writes = mockDb({ signals: [signal({ kind: 'page_opportunity', impact: 'medium' })] });
+
+ // Page opportunities are landing pages read from an analytics connection.
+ const summary = await generateActionsForBrand(BRAND, {
+ now: NOW,
+ sources: new Set(['tracking']),
+ });
+
+ expect(summary.created).toBe(0);
+ expect(summary.ineligible).toBe(1);
+ expect(writes.inserted.find((w) => w.table === 'actions')).toBeUndefined();
+ });
+
+ it('raises it once the source is connected', async () => {
+ const writes = mockDb({ signals: [signal({ kind: 'page_opportunity', impact: 'medium' })] });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(summary.created).toBe(1);
+ expect(summary.ineligible).toBe(0);
+ expect(writes.inserted.find((w) => w.table === 'actions').rows[0]).toMatchObject({
+ kind: 'capture_ai_traffic',
+ category: 'growth',
+ });
+ });
+
+ /**
+ * Losing a source mid-cycle must not orphan work already handed out: the
+ * action stays, and evidence keeps attaching to it.
+ */
+ it('keeps maintaining an active action whose source went away', async () => {
+ const writes = mockDb({
+ signals: [signal({ id: 's9', kind: 'page_opportunity', impact: 'medium' })],
+ activeActions: [{ id: 'a9', dedup_key: 'capture_ai_traffic', status: 'in_progress' }],
+ });
+
+ const summary = await generateActionsForBrand(BRAND, {
+ now: NOW,
+ sources: new Set(['tracking']),
+ });
+
+ expect(summary.refreshed).toBe(1);
+ expect(summary.ineligible).toBe(0);
+ expect(writes.updated.some((w) => w.table === 'signals')).toBe(true);
+ });
+});
+
+describe('the daily cap', () => {
+ /** One open signal for every definition that exists. */
+ const oneOfEachKind = () =>
+ [
+ 'sharp_drop',
+ 'visibility_slipping',
+ 'platform_gap',
+ 'uncited_mentions',
+ 'page_opportunity',
+ 'audit_low_score',
+ 'competitor_citation_gap',
+ 'competitor_surge',
+ ].map((kind, index) => signal({ id: `s${index}`, kind, impact: 'medium' }));
+
+ it('stops at the configured number of new actions a day', async () => {
+ const writes = mockDb({ signals: oneOfEachKind() });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(summary.created).toBe(maxNewActionsPerDay);
+ expect(summary.capped).toBe(8 - maxNewActionsPerDay);
+ expect(writes.inserted.filter((w) => w.table === 'actions')).toHaveLength(maxNewActionsPerDay);
+ });
+
+ /**
+ * The budget is the day's, not the run's. An action raised this morning
+ * and dismissed by lunch still spent its slot — the brand was told.
+ */
+ it('counts what the brand was already given today', async () => {
+ const spent = Array.from({ length: maxNewActionsPerDay - 1 }, (_, i) => ({
+ id: `spent-${i}`,
+ dedup_key: `unrelated-${i}`,
+ status: 'new',
+ created_at: NOW.toISOString(),
+ }));
+ const writes = mockDb({ signals: oneOfEachKind(), activeActions: spent });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(summary.created).toBe(1);
+ expect(writes.inserted.filter((w) => w.table === 'actions')).toHaveLength(1);
+ });
+
+ it('ignores actions raised on earlier days', async () => {
+ const yesterday = Array.from({ length: maxNewActionsPerDay }, (_, i) => ({
+ id: `old-${i}`,
+ dedup_key: `unrelated-${i}`,
+ status: 'new',
+ created_at: daysAgo(1),
+ }));
+ mockDb({ signals: oneOfEachKind(), activeActions: yesterday });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(summary.created).toBe(maxNewActionsPerDay);
+ });
+
+ /** When there is room for one, it goes to the one that matters most. */
+ it('spends the last slot on the highest impact candidate', async () => {
+ const spent = Array.from({ length: maxNewActionsPerDay - 1 }, (_, i) => ({
+ id: `spent-${i}`,
+ dedup_key: `unrelated-${i}`,
+ status: 'new',
+ created_at: NOW.toISOString(),
+ }));
+ const writes = mockDb({
+ signals: [
+ signal({ id: 'low', kind: 'platform_gap', impact: 'low' }),
+ signal({ id: 'high', kind: 'sharp_drop', impact: 'high' }),
+ ],
+ activeActions: spent,
+ });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(summary.created).toBe(1);
+ expect(summary.capped).toBe(1);
+ expect(writes.inserted.find((w) => w.table === 'actions').rows[0].kind).toBe(
+ 'recover_visibility',
+ );
+ });
+});
+
+describe('the definition version', () => {
+ it('is stamped on the action that the definition raised', async () => {
+ const writes = mockDb({ signals: [signal()] });
+
+ await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ const row = writes.inserted.find((w) => w.table === 'actions').rows[0];
+ expect(row.definition_version).toBeGreaterThanOrEqual(1);
+ expect(Number.isInteger(row.definition_version)).toBe(true);
+ });
+});
diff --git a/server/src/lib/action-center/sources.js b/server/src/lib/action-center/sources.js
new file mode 100644
index 000000000..a0803741f
--- /dev/null
+++ b/server/src/lib/action-center/sources.js
@@ -0,0 +1,74 @@
+/**
+ * What a brand actually has to work with (#818, phase 4).
+ *
+ * A definition declares the data it needs; this module answers whether a
+ * given brand has it. Today that answer only gates generation — a brand with
+ * no analytics connection is not offered the traffic definition — but the
+ * same answer is what phase 5's task planner needs in order to give two
+ * brands different plans for the same action kind, so it is computed once
+ * here rather than inferred twice.
+ *
+ * Deliberately coarse. "Does this brand have competitors configured" is a
+ * stable fact about the workspace; "are there competitor rows in the last
+ * seven days" is a detector's question, and detectors already ask it.
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+
+/**
+ * Every source a definition may declare. Validation rejects anything else,
+ * so a typo in a definition file fails at load rather than silently making
+ * that definition ineligible for every brand forever.
+ */
+export const SOURCES = Object.freeze([
+ /** Our own prompt tracking. Every brand has it — a brand without it is not
+ * a brand yet — so it is the source a definition declares when it needs
+ * nothing beyond what the product collects by itself. */
+ 'tracking',
+ /** Competitors configured on the brand. */
+ 'competitors',
+ /** Site Audit runs. */
+ 'site_audits',
+ /** An analytics integration connected for the brand's organization. */
+ 'analytics',
+]);
+
+/**
+ * The sources available to one brand.
+ *
+ * @param {string} brandId
+ * @returns {Promise<Set<string>>}
+ */
+export async function resolveBrandSources(brandId) {
+ const available = new Set(['tracking']);
+
+ const [competitors, audits, brand] = await Promise.all([
+ supabaseAdmin.from('competitors').select('id').eq('brand_id', brandId).limit(1),
+ supabaseAdmin.from('site_audits').select('id').eq('brand_id', brandId).limit(1),
+ supabaseAdmin.from('brands').select('organization_id').eq('id', brandId).limit(1),
+ ]);
+
+ if (competitors.error) throw new Error(competitors.error.message);
+ if (audits.error) throw new Error(audits.error.message);
+ if (brand.error) throw new Error(brand.error.message);
+
+ if ((competitors.data ?? []).length > 0) available.add('competitors');
+ if ((audits.data ?? []).length > 0) available.add('site_audits');
+
+ // Integrations are connected per organization, not per brand: every brand
+ // in a workspace sees the same analytics connection.
+ const organizationId = (brand.data ?? [])[0]?.organization_id;
+ if (organizationId) {
+ const { data, error } = await supabaseAdmin
+ .from('integration_connections')
+ .select('id')
+ .eq('organization_id', organizationId)
+ .eq('provider', 'google-analytics')
+ .eq('status', 'connected')
+ .limit(1);
+ if (error) throw new Error(error.message);
+ if ((data ?? []).length > 0) available.add('analytics');
+ }
+
+ return available;
+}
diff --git a/server/src/lib/action-center/sources.test.js b/server/src/lib/action-center/sources.test.js
new file mode 100644
index 000000000..39e0c0379
--- /dev/null
+++ b/server/src/lib/action-center/sources.test.js
@@ -0,0 +1,63 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const from = vi.fn();
+vi.mock('../../config/supabase.js', () => ({ default: { from: (...a) => from(...a) } }));
+
+import { resolveBrandSources } from './sources.js';
+
+const BRAND = 'brand-1';
+
+/**
+ * Answers one row per table that has something, nothing for the rest.
+ *
+ * `tables` is what the brand HAS; anything absent answers empty, which is
+ * what a brand without competitors or audits looks like.
+ */
+function mockDb(tables) {
+ from.mockImplementation((table) => {
+ const builder = {
+ select: () => builder,
+ eq: () => builder,
+ limit: () => builder,
+ then: (resolve, reject) =>
+ Promise.resolve({ data: tables[table] ?? [], error: null }).then(resolve, reject),
+ };
+ return builder;
+ });
+}
+
+beforeEach(() => from.mockReset());
+
+describe('resolveBrandSources', () => {
+ it('always includes tracking — a brand without it is not a brand yet', async () => {
+ mockDb({});
+ expect([...(await resolveBrandSources(BRAND))]).toEqual(['tracking']);
+ });
+
+ it('reports the competitors and audits the brand has', async () => {
+ mockDb({ competitors: [{ id: 'c1' }], site_audits: [{ id: 'a1' }] });
+
+ const sources = await resolveBrandSources(BRAND);
+
+ expect(sources.has('competitors')).toBe(true);
+ expect(sources.has('site_audits')).toBe(true);
+ expect(sources.has('analytics')).toBe(false);
+ });
+
+ /** Integrations are connected per organization, so the brand has to be
+ * resolved to one before the connection can be found. */
+ it('finds an analytics connection through the brand’s organization', async () => {
+ mockDb({
+ brands: [{ organization_id: 'org-1' }],
+ integration_connections: [{ id: 'i1' }],
+ });
+
+ expect((await resolveBrandSources(BRAND)).has('analytics')).toBe(true);
+ });
+
+ it('claims no analytics for a brand with no organization', async () => {
+ mockDb({ integration_connections: [{ id: 'i1' }] });
+
+ expect((await resolveBrandSources(BRAND)).has('analytics')).toBe(false);
+ });
+});
diff --git a/server/src/lib/signals/record.js b/server/src/lib/signals/record.js
index 00f03431f..67d9e2f31 100644
--- a/server/src/lib/signals/record.js
+++ b/server/src/lib/signals/record.js
@@ -43,7 +43,7 @@ const { detection } = resolve();
* this side owns what gets STORED: category, impact, sources, KPI links,
* and whether the condition persists.
*/
-const KIND_META = {
+export const KIND_META = {
sharp_drop: {
category: 'visibility',
impact: 'high',
diff --git a/supabase/migrations/00086_action_definition_version.sql b/supabase/migrations/00086_action_definition_version.sql
new file mode 100644
index 000000000..faf080ee7
--- /dev/null
+++ b/supabase/migrations/00086_action_definition_version.sql
@@ -0,0 +1,25 @@
+-- Action Engine, phase 4 (#818): an action remembers the rule that raised it.
+--
+-- Definitions move out of the generator into their own registry, where each
+-- one carries a version its author bumps when what it means changes — a
+-- different threshold, a different task list, a different scope. Without the
+-- version stored on the action, an action raised in March can only ever be
+-- read against today's rules, and the History tab quietly rewrites its own
+-- past every time a definition is tuned. The same reasoning as resolving a
+-- task's text at creation (00083): the record says what happened, not what
+-- would happen now.
+--
+-- Existing rows get 1, which is what every definition is on today.
+
+alter table public.actions
+ add column if not exists definition_version integer not null default 1;
+
+alter table public.actions
+ drop constraint if exists actions_definition_version_check;
+
+alter table public.actions
+ add constraint actions_definition_version_check
+ check (definition_version >= 1);
+
+comment on column public.actions.definition_version is
+ 'Version of the action definition (server/src/lib/action-center/definitions) that raised this action. Historical rows keep the rules they were raised under.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 91cf650ac..9a4375a5f 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -10420,3 +10420,32 @@ create index if not exists actions_pending_validation_idx
on public.actions (completed_at)
where outcome = 'pending_measurement' and status = 'completed';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00086_action_definition_version.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Action Engine, phase 4 (#818): an action remembers the rule that raised it.
+--
+-- Definitions move out of the generator into their own registry, where each
+-- one carries a version its author bumps when what it means changes — a
+-- different threshold, a different task list, a different scope. Without the
+-- version stored on the action, an action raised in March can only ever be
+-- read against today's rules, and the History tab quietly rewrites its own
+-- past every time a definition is tuned. The same reasoning as resolving a
+-- task's text at creation (00083): the record says what happened, not what
+-- would happen now.
+--
+-- Existing rows get 1, which is what every definition is on today.
+
+alter table public.actions
+ add column if not exists definition_version integer not null default 1;
+
+alter table public.actions
+ drop constraint if exists actions_definition_version_check;
+
+alter table public.actions
+ add constraint actions_definition_version_check
+ check (definition_version >= 1);
+
+comment on column public.actions.definition_version is
+ 'Version of the action definition (server/src/lib/action-center/definitions) that raised this action. Historical rows keep the rules they were raised under.';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index f71645727..0175d7fbb 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -539,6 +539,10 @@
"description": "You reach {bestRate}% of {best} answers but {rate}% on {platform} — the content ranks, this engine does not surface it.",
"goal": "Close the gap between your strongest engine and your weakest."
},
+ "unknown": {
+ "description": "This action comes from a detection rule newer than this release of the app. Its tasks, evidence and measurement are complete — only the written description is missing.",
+ "goal": "Work through the tasks below; they carry what this action is for."
+ },
"close_citation_gap": {
"title": "Close the citation gap",
"description": "A competitor is cited far more often than you are.",
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index ab860da46..29f13552b 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -46,18 +46,19 @@ import {
type ActionStatus,
type TaskStatus,
} from '@/lib/action-center/registry';
-import { actionContextTags, actionTexts, memberLabel, taskText } from '@/lib/action-center/display';
+import {
+ actionContextTags,
+ actionGoal,
+ actionTexts,
+ memberLabel,
+ taskText,
+} from '@/lib/action-center/display';
import { signalTexts } from '@/lib/signals/display';
import { isKpiKey } from '@/lib/kpis/registry';
import { ImpactDots, SignalStatusBadge } from './signal-table';
-import { KIND_ICONS } from './action-table';
+import { ActionIcon } from './action-table';
import { cn } from '@/lib/utils';
-function ActionHeaderIcon({ kind }: { kind: ActionItem['kind'] }) {
- const Icon = KIND_ICONS[kind];
- return <Icon className="h-4 w-4 text-muted-foreground" />;
-}
-
type DrawerTab = 'overview' | 'tasks' | 'signals' | 'history';
const TABS: DrawerTab[] = ['overview', 'tasks', 'signals', 'history'];
@@ -156,7 +157,11 @@ export function ActionDrawer({
</div>
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-muted/40">
- <ActionHeaderIcon kind={action.kind} />
+ <ActionIcon
+ kind={action.kind}
+ category={action.category}
+ className="h-4 w-4 text-muted-foreground"
+ />
</div>
<div className="min-w-0">
<SheetTitle>{texts.title}</SheetTitle>
@@ -208,7 +213,7 @@ export function ActionDrawer({
<Separator />
<section>
<p className="text-xs font-medium text-muted-foreground">{t('drawer.goal')}</p>
- <p className="mt-1">{tTexts(`${action.kind}.goal`)}</p>
+ <p className="mt-1">{actionGoal(action.kind, tTexts)}</p>
</section>
<Separator />
<section>
diff --git a/web/src/components/action-center/action-table.tsx b/web/src/components/action-center/action-table.tsx
index b2a2019a2..0437c8f68 100644
--- a/web/src/components/action-center/action-table.tsx
+++ b/web/src/components/action-center/action-table.tsx
@@ -10,6 +10,8 @@ import {
ShieldCheck,
Layers,
Quote,
+ Sparkles,
+ Target,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
@@ -22,13 +24,15 @@ import {
TableRow,
} from '@/components/ui/table';
import type { ActionItem } from '@/lib/actions/action-center';
-import type { ActionKind, ActionStatus } from '@/lib/action-center/registry';
+import type { ActionCategory, ActionKind, ActionStatus } from '@/lib/action-center/registry';
import { actionContextTags, actionTexts } from '@/lib/action-center/display';
import { ImpactDots } from './signal-table';
import { formatRelative } from '@/lib/format-relative';
import { cn } from '@/lib/utils';
-export const KIND_ICONS: Record<ActionKind, React.ComponentType<{ className?: string }>> = {
+type IconComponent = React.ComponentType<{ className?: string }>;
+
+const KIND_ICONS: Record<ActionKind, IconComponent> = {
recover_visibility: BarChart3,
protect_visibility: ShieldCheck,
expand_platform_visibility: Layers,
@@ -39,6 +43,36 @@ export const KIND_ICONS: Record<ActionKind, React.ComponentType<{ className?: st
close_competitor_gap: Swords,
};
+/** What a kind we have no icon for falls back to — every definition belongs
+ * to a family, and the family says enough to orient a reader. */
+const CATEGORY_ICONS: Record<ActionCategory, IconComponent> = {
+ growth: Sparkles,
+ protect: ShieldCheck,
+ recover: BarChart3,
+ fix: Wrench,
+ compete: Swords,
+};
+
+/**
+ * The icon for an action, whatever kind it turns out to be.
+ *
+ * A component rather than a lookup helper so the resolution happens in one
+ * place: callers that only render it should not have to hold a component in
+ * a variable to do so.
+ */
+export function ActionIcon({
+ kind,
+ category,
+ className,
+}: {
+ kind: string;
+ category: ActionCategory;
+ className?: string;
+}) {
+ const Icon = KIND_ICONS[kind as ActionKind] ?? CATEGORY_ICONS[category] ?? Target;
+ return <Icon className={className} />;
+}
+
export const ACTION_STATUS_BADGE: Record<ActionStatus, string> = {
new: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',
in_progress: 'border-indigo-500/30 bg-indigo-500/10 text-indigo-600 dark:text-indigo-400',
@@ -100,7 +134,6 @@ export function ActionTable({
</TableHeader>
<TableBody>
{actions.map((action) => {
- const Icon = KIND_ICONS[action.kind];
const texts = actionTexts(action, tTexts);
const tags = actionContextTags(action, t);
return (
@@ -108,7 +141,11 @@ export function ActionTable({
<TableCell className="max-w-[380px]">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-muted/40">
- <Icon className="h-4 w-4 text-muted-foreground" />
+ <ActionIcon
+ kind={action.kind}
+ category={action.category}
+ className="h-4 w-4 text-muted-foreground"
+ />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-medium">{texts.title}</p>
diff --git a/web/src/components/action-center/history-drawer.tsx b/web/src/components/action-center/history-drawer.tsx
index d3dc1cf1b..275a2ebef 100644
--- a/web/src/components/action-center/history-drawer.tsx
+++ b/web/src/components/action-center/history-drawer.tsx
@@ -12,11 +12,11 @@ import {
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet';
-import { actionTexts } from '@/lib/action-center/display';
+import { actionGoal, actionTexts } from '@/lib/action-center/display';
import type { ActionHistoryItem } from '@/lib/action-center/history';
import { UNCOUNTED_TASK_STATUSES } from '@/lib/action-center/registry';
import { ImpactDots } from './signal-table';
-import { KIND_ICONS } from './action-table';
+import { ActionIcon } from './action-table';
import { HistoryStatusBadge } from './history-table';
import { cn } from '@/lib/utils';
@@ -89,7 +89,6 @@ export function HistoryDrawer({
if (!item) return null;
- const Icon = KIND_ICONS[item.kind as keyof typeof KIND_ICONS];
const texts = actionTexts(
{ kind: item.kind, payload: item.payload } as Parameters<typeof actionTexts>[0],
tTexts,
@@ -118,7 +117,11 @@ export function HistoryDrawer({
</div>
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-muted/40">
- {Icon && <Icon className="h-4 w-4 text-muted-foreground" />}
+ <ActionIcon
+ kind={item.kind}
+ category={item.type}
+ className="h-4 w-4 text-muted-foreground"
+ />
</div>
<div className="min-w-0">
<SheetTitle>{texts.title}</SheetTitle>
@@ -139,7 +142,7 @@ export function HistoryDrawer({
<div className="flex-1 space-y-5 overflow-y-auto px-6 py-4 text-sm">
<section>
<p className="text-xs font-medium text-muted-foreground">{t('drawer.goal')}</p>
- <p className="mt-1">{tTexts(`${item.kind}.goal`)}</p>
+ <p className="mt-1">{actionGoal(item.kind, tTexts)}</p>
</section>
<Separator />
diff --git a/web/src/components/action-center/history-table.tsx b/web/src/components/action-center/history-table.tsx
index afa1f74b9..f3e630d43 100644
--- a/web/src/components/action-center/history-table.tsx
+++ b/web/src/components/action-center/history-table.tsx
@@ -14,7 +14,7 @@ import { actionTexts } from '@/lib/action-center/display';
import type { ActionHistoryItem } from '@/lib/action-center/history';
import type { ActionStatus } from '@/lib/action-center/registry';
import { ImpactDots } from './signal-table';
-import { KIND_ICONS } from './action-table';
+import { ActionIcon } from './action-table';
import { cn } from '@/lib/utils';
/** Low-saturation per type, the way the Signals table tints its categories —
@@ -119,7 +119,6 @@ export function HistoryTable({
</TableHeader>
<TableBody>
{items.map((item) => {
- const Icon = KIND_ICONS[item.kind as keyof typeof KIND_ICONS];
const texts = actionTexts(
{ kind: item.kind, payload: item.payload } as Parameters<typeof actionTexts>[0],
tTexts,
@@ -134,7 +133,11 @@ export function HistoryTable({
<TableCell className="max-w-[360px]">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-muted/40">
- {Icon && <Icon className="h-4 w-4 text-muted-foreground" />}
+ <ActionIcon
+ kind={item.kind}
+ category={item.type}
+ className="h-4 w-4 text-muted-foreground"
+ />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-medium">{texts.title}</p>
diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.ts
new file mode 100644
index 000000000..7e2e0ed6a
--- /dev/null
+++ b/web/src/lib/action-center/display.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest';
+import { actionGoal, actionTexts, humanizeKind } from './display';
+import { ACTION_KINDS } from './registry';
+import type { ActionItem } from '@/lib/actions/action-center';
+import messages from '../../../messages/en.json';
+
+/** Resolves an actionCenter.actionTexts key the way next-intl would, minus
+ * the ICU formatting — enough to prove a key exists and is reached. */
+const t = (key: string) => {
+ const value = key
+ .split('.')
+ .reduce<unknown>(
+ (node, part) => (node as Record<string, unknown> | undefined)?.[part],
+ messages.actionCenter.actionTexts,
+ );
+ if (typeof value !== 'string') throw new Error(`missing message: ${key}`);
+ return value;
+};
+
+const action = (over: Partial<ActionItem>) =>
+ ({
+ kind: 'recover_visibility',
+ category: 'recover',
+ payload: {},
+ signalCount: 1,
+ ...over,
+ }) as ActionItem;
+
+describe('actionTexts', () => {
+ it.each(ACTION_KINDS)('has written copy for %s', (kind) => {
+ expect(() => actionTexts(action({ kind }), t)).not.toThrow();
+ expect(() => actionGoal(kind, t)).not.toThrow();
+ });
+
+ /**
+ * The server's definition registry grows on its own release cycle, so the
+ * web will meet kinds it has never heard of. Hiding them was the old
+ * behaviour and the wrong one: the work is real, and a row nobody can read
+ * still beats a row nobody sees.
+ */
+ it('presents a kind it has never heard of rather than failing on it', () => {
+ const texts = actionTexts(action({ kind: 'seize_the_means', category: 'growth' }), t);
+
+ expect(texts.title).toBe('Seize the means');
+ expect(texts.description).toBe(messages.actionCenter.actionTexts.unknown.description);
+ expect(actionGoal('seize_the_means', t)).toBe(messages.actionCenter.actionTexts.unknown.goal);
+ });
+});
+
+describe('humanizeKind', () => {
+ it('reads a definition id as the phrase it was written to be', () => {
+ expect(humanizeKind('expand_platform_visibility')).toBe('Expand platform visibility');
+ });
+
+ it('leaves a single word alone but for its capital', () => {
+ expect(humanizeKind('recover')).toBe('Recover');
+ });
+});
diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.ts
index f298672ba..dee77dd44 100644
--- a/web/src/lib/action-center/display.ts
+++ b/web/src/lib/action-center/display.ts
@@ -1,10 +1,16 @@
import type { ActionItem } from '@/lib/actions/action-center';
+import { isActionKind } from '@/lib/action-center/registry';
/**
* Composes what an action row shows from `kind` + `payload`, mirroring the
* signals display helper: templates live in i18n
* (actionCenter.actionTexts.<kind>), this module prepares the values and
* picks the right variant when a payload part is optional.
+ *
+ * The server can raise a kind this build has never heard of — that is the
+ * point of the definition registry, which grows on its own release cycle.
+ * Such an action is presented generically rather than hidden: the work is
+ * real, and a row nobody can read is still better than a row nobody sees.
*/
type Translator = (key: string, values?: Record<string, string | number>) => string;
@@ -18,12 +24,30 @@ function num(payload: Record<string, unknown>, key: string): number {
return Number(payload[key] ?? 0);
}
+/**
+ * `expand_platform_visibility` → "Expand platform visibility".
+ *
+ * Definition ids are written to be read — they are verb phrases naming the
+ * work — so the id itself is a better title than any generic string.
+ */
+export function humanizeKind(kind: string): string {
+ const words = kind.replace(/_/g, ' ').trim();
+ return words.charAt(0).toUpperCase() + words.slice(1);
+}
+
export function actionTexts(
action: ActionItem,
t: Translator,
): { title: string; description: string } {
const p = action.payload;
- switch (action.kind) {
+ const kind = action.kind;
+ if (!isActionKind(kind)) {
+ return {
+ title: humanizeKind(kind),
+ description: t('unknown.description'),
+ };
+ }
+ switch (kind) {
case 'recover_visibility': {
const hasDrop = p.dropFrom !== undefined && p.dropFrom !== null;
return {
@@ -100,11 +124,23 @@ export function actionTexts(
}
}
+/**
+ * What the drawer shows under "Goal".
+ *
+ * Its own helper rather than an inline `t(`${kind}.goal`)` in two components,
+ * because an unknown kind has no goal key and next-intl would render the key
+ * itself into the drawer.
+ */
+export function actionGoal(kind: string, t: Translator): string {
+ return isActionKind(kind) ? t(`${kind}.goal`) : t('unknown.goal');
+}
+
/** Compact evidence chips under the title: signal count plus the kind's own
* count (pages, prompts, competitors). */
export function actionContextTags(action: ActionItem, t: Translator): string[] {
const p = action.payload;
const tags = [t('tags.signals', { count: action.signalCount })];
+ if (!isActionKind(action.kind)) return tags;
switch (action.kind) {
case 'recover_visibility':
if (num(p, 'promptCount') > 0) tags.push(t('tags.prompts', { count: num(p, 'promptCount') }));
diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.ts
index 803269de3..ecb7b8580 100644
--- a/web/src/lib/action-center/registry.ts
+++ b/web/src/lib/action-center/registry.ts
@@ -1,9 +1,16 @@
/**
- * The action registry — static product knowledge about every action kind
- * the generator can produce. Same division of labor as signals: the server
- * (server/src/lib/action-center/generate.js ACTION_RULES) owns what gets
- * stored; this file owns display — i18n template keys, task lists, and the
- * context tags a row shows.
+ * The action registry — what this build knows how to present.
+ *
+ * Same division of labor as signals, with one asymmetry worth naming: the
+ * server's definition registry (server/src/lib/action-center/definitions) is
+ * the source of truth for which actions EXIST, and it is meant to grow
+ * without this file following. So the list below is not a contract — it is
+ * the set of kinds we have written copy and an icon for. Anything the server
+ * raises that is not here still reaches the user, presented from its
+ * category and its id; see lib/action-center/display.ts.
+ *
+ * Dropping a kind from this list therefore degrades an action; it never
+ * hides one.
*/
export type ActionCategory = 'growth' | 'protect' | 'recover' | 'fix' | 'compete';
@@ -29,6 +36,7 @@ export type ActionOutcome =
| 'declined'
| 'not_measurable';
+/** A kind this build has copy and an icon for. */
export type ActionKind =
| 'recover_visibility'
| 'protect_visibility'
@@ -88,49 +96,25 @@ export const TASK_STATUSES: readonly TaskStatus[] = [
/** Statuses that leave the progress denominator — the work is not outstanding. */
export const UNCOUNTED_TASK_STATUSES: readonly TaskStatus[] = ['skipped', 'failed'];
-export interface ActionKindMeta {
- kind: ActionKind;
- /** Ordered task template keys — the DB rows carry the same keys. */
- taskKeys: string[];
-}
-
-export const ACTION_KINDS: Record<ActionKind, ActionKindMeta> = {
- recover_visibility: {
- kind: 'recover_visibility',
- taskKeys: ['analyze_losses', 'coverage_gaps', 'update_content', 'internal_links', 'validate'],
- },
- protect_visibility: {
- kind: 'protect_visibility',
- taskKeys: ['diagnose_slip', 'review_responses', 'reinforce_content', 'validate'],
- },
- expand_platform_visibility: {
- kind: 'expand_platform_visibility',
- taskKeys: ['compare_platforms', 'coverage_gaps', 'optimize_content', 'validate'],
- },
- close_citation_gap: {
- kind: 'close_citation_gap',
- taskKeys: ['compare_citations', 'identify_sources', 'strengthen_sources', 'validate'],
- },
- capture_ai_traffic: {
- kind: 'capture_ai_traffic',
- taskKeys: ['review_pages', 'coverage_gaps', 'optimize_content', 'validate'],
- },
- convert_mentions: {
- kind: 'convert_mentions',
- taskKeys: ['identify_prompts', 'create_citable_content', 'strengthen_sources'],
- },
- fix_low_scores: {
- kind: 'fix_low_scores',
- taskKeys: ['review_audits', 'fix_issues', 'revalidate'],
- },
- close_competitor_gap: {
- kind: 'close_competitor_gap',
- taskKeys: ['analyze_competitor', 'coverage_gaps', 'strengthen_content', 'validate'],
- },
-};
+export const ACTION_KINDS: readonly ActionKind[] = [
+ 'recover_visibility',
+ 'protect_visibility',
+ 'expand_platform_visibility',
+ 'close_citation_gap',
+ 'capture_ai_traffic',
+ 'convert_mentions',
+ 'fix_low_scores',
+ 'close_competitor_gap',
+];
+/**
+ * Is this one of the kinds we have copy for?
+ *
+ * A guard, not a filter. Callers use it to choose between the written
+ * presentation and the generic one — never to decide whether a row is real.
+ */
export function isActionKind(value: string): value is ActionKind {
- return value in ACTION_KINDS;
+ return (ACTION_KINDS as readonly string[]).includes(value);
}
/** Sort orders the toolbar offers. Priority is impact-weighted evidence. */
diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.ts
index c402e64ee..81ebb960b 100644
--- a/web/src/lib/actions/action-center.ts
+++ b/web/src/lib/actions/action-center.ts
@@ -12,10 +12,8 @@
import { createClient } from '@/lib/supabase/server';
import {
- isActionKind,
type ActionCategory,
type ActionImpact,
- type ActionKind,
UNCOUNTED_TASK_STATUSES,
type ActionStatus,
type TaskStatus,
@@ -33,7 +31,12 @@ export interface ActionItem {
id: string;
actionNo: number;
category: ActionCategory;
- kind: ActionKind;
+ /**
+ * The server definition's id. Not narrowed to the kinds this build has copy
+ * for: the definition registry grows on its own release cycle, and an
+ * action we cannot name is still an action someone has to do.
+ */
+ kind: string;
impact: ActionImpact;
status: ActionStatus;
payload: Record<string, unknown>;
@@ -73,7 +76,7 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {
.eq('brand_id', brandId)
.limit(1000);
if (error) throw new Error(error.message);
- const rows = ((data ?? []) as ActionRow[]).filter((row) => isActionKind(row.kind));
+ const rows = (data ?? []) as ActionRow[];
if (rows.length === 0) return [];
const actionIds = rows.map((row) => row.id);
@@ -124,7 +127,7 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {
id: row.id,
actionNo: Number(row.action_no),
category: row.category as ActionCategory,
- kind: row.kind as ActionKind,
+ kind: row.kind,
impact: row.impact as ActionImpact,
status: row.status as ActionStatus,
payload: row.payload ?? {},
diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.ts
index 3e0b87493..0d2fbd919 100644
--- a/web/src/lib/actions/action-history.ts
+++ b/web/src/lib/actions/action-history.ts
@@ -15,7 +15,7 @@
*/
import { createClient } from '@/lib/supabase/server';
-import { isActionKind, type ActionCategory, type ActionImpact } from '@/lib/action-center/registry';
+import type { ActionCategory, ActionImpact } from '@/lib/action-center/registry';
import type { ActionOutcome, ActionStatus, TaskStatus } from '@/lib/action-center/registry';
import { SIGNAL_SOURCES, type SignalSource } from '@/lib/signals/registry';
import {
@@ -168,7 +168,7 @@ export async function getActionHistory(
const { data, error } = await query;
if (error) throw new Error(error.message);
- const rows = ((data ?? []) as HistoryRow[]).filter((row) => isActionKind(row.kind));
+ const rows = (data ?? []) as HistoryRow[];
if (rows.length === 0) return [];
const actionIds = rows.map((row) => row.id);