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): KPIs, Signals and Actions — the goal, observation and prioritization layers (#808)

Gökhan Geyikce7204a0f3a2
diff --git a/server/src/lib/action-center/generate.js b/server/src/lib/action-center/generate.js
new file mode 100644
index 000000000..a21930dd9
--- /dev/null
+++ b/server/src/lib/action-center/generate.js
@@ -0,0 +1,250 @@
+/**
+ * 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
+ * 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.
+ *
+ * Lifecycle across nights, mirroring signals:
+ * - an OPEN action is refreshed: payload recounted, newly detected signals
+ * linked (logged as a signals_linked event);
+ * - a DISMISSED action stays dismissed;
+ * - a COMPLETED action stays completed while fresh — but if its condition
+ * is still (or again) firing REOPEN_AFTER_DAYS after completion, it
+ * reopens: the outcome did not hold, and hiding that would be lying.
+ *
+ * `baseline` snapshots the linked signals' measured values at creation —
+ * the "before" half of the future validation comparison.
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+import { logger } from '../logger.js';
+
+const REOPEN_AFTER_DAYS = 14;
+const DAY_MS = 86_400_000;
+
+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'],
+ },
+ {
+ kind: 'capture_ai_traffic',
+ category: 'growth',
+ signalKinds: ['page_opportunity'],
+ taskKeys: ['review_pages', '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'],
+ },
+ {
+ 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 '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(),
+ signals: signals.map((signal) => ({
+ id: signal.id,
+ kind: signal.kind,
+ previousValue: signal.previous_value,
+ currentValue: signal.current_value,
+ changeValue: signal.change_value,
+ })),
+ };
+}
+
+async function logEvent(actionId, event, data = {}) {
+ const { error } = await supabaseAdmin
+ .from('action_events')
+ .insert({ action_id: actionId, event, data });
+ if (error) throw new Error(error.message);
+}
+
+async function linkSignals(actionId, signals) {
+ const unlinked = signals.filter((signal) => !signal.action_id);
+ if (unlinked.length === 0) return 0;
+ const { error } = await supabaseAdmin
+ .from('signals')
+ .update({ action_id: actionId })
+ .in(
+ 'id',
+ unlinked.map((signal) => signal.id),
+ );
+ if (error) throw new Error(error.message);
+ return unlinked.length;
+}
+
+export async function generateActionsForBrand(brandId, { now = new Date() } = {}) {
+ const { data: openSignals, error: signalsErr } = await supabaseAdmin
+ .from('signals')
+ .select(
+ 'id, kind, impact, kpi_keys, payload, previous_value, current_value, change_value, action_id',
+ )
+ .eq('brand_id', brandId)
+ .in('status', ['new', 'acknowledged'])
+ .limit(1000);
+ if (signalsErr) throw new Error(signalsErr.message);
+
+ const { data: existingRows, error: actionsErr } = await supabaseAdmin
+ .from('actions')
+ .select('id, dedup_key, status, completed_at')
+ .eq('brand_id', brandId)
+ .limit(1000);
+ if (actionsErr) throw new Error(actionsErr.message);
+ const existing = new Map((existingRows ?? []).map((row) => [row.dedup_key, row]));
+
+ const nowIso = now.toISOString();
+ let created = 0;
+ let refreshed = 0;
+ let reopened = 0;
+
+ for (const rule of ACTION_RULES) {
+ const matched = (openSignals ?? []).filter((signal) => rule.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 = existing.get(rule.kind);
+
+ if (!current) {
+ 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;
+ continue;
+ }
+
+ if (current.status === 'dismissed') continue;
+
+ if (current.status === 'completed') {
+ const completedAt = current.completed_at ? Date.parse(current.completed_at) : 0;
+ if (now.getTime() - completedAt < REOPEN_AFTER_DAYS * DAY_MS) continue;
+ const { error } = await supabaseAdmin
+ .from('actions')
+ .update({
+ status: 'new',
+ impact,
+ payload,
+ kpi_keys: kpiKeys,
+ completed_at: null,
+ updated_at: nowIso,
+ })
+ .eq('id', current.id);
+ if (error) throw new Error(error.message);
+ await logEvent(current.id, 'reopened', { signalCount: matched.length });
+ await linkSignals(current.id, matched);
+ reopened += 1;
+ continue;
+ }
+
+ // Open in some form (new / in_progress / on_hold / no_improvement):
+ // refresh the measured context, quietly — an event only when the
+ // evidence actually grew.
+ const { error } = await supabaseAdmin
+ .from('actions')
+ .update({ impact, payload, kpi_keys: kpiKeys, updated_at: nowIso })
+ .eq('id', current.id);
+ if (error) throw new Error(error.message);
+ const linked = await linkSignals(current.id, matched);
+ if (linked > 0) await logEvent(current.id, 'signals_linked', { count: linked });
+ refreshed += 1;
+ }
+
+ const summary = { created, refreshed, reopened };
+ logger.info({ brandId, ...summary }, '[actions] generated');
+ return summary;
+}
diff --git a/server/src/lib/job-runner.js b/server/src/lib/job-runner.js
index 772d3bde8..8a7b81b1a 100644
--- a/server/src/lib/job-runner.js
+++ b/server/src/lib/job-runner.js
@@ -16,6 +16,8 @@ import {
import { processTrackingJob } from '../workers/tracking-worker.js';
import { processContentJob } from '../workers/content-worker.js';
import { generatePulseForBrand } from './pulse/engine.js';
+import { recordSignalsForBrand } from './signals/record.js';
+import { generateActionsForBrand } from './action-center/generate.js';
import logger from './logger.js';
// Concurrency counters (the default of 2 per queue is inherited from the Bull
@@ -94,6 +96,16 @@ export async function runTrackingJob(jobId, io) {
generatePulseForBrand(brandId).catch((err) => {
logger.error({ err, brandId }, 'daily pulse trigger failed');
});
+ // Signal recording (Action Center) rides the same trigger but is
+ // deliberately NOT inside the pulse engine: signals are a product
+ // surface, so a brand with pulse emails off still gets them. Action
+ // generation chains after it — it consolidates the signals the
+ // recording just wrote, so running concurrently would read stale.
+ recordSignalsForBrand(brandId)
+ .then(() => generateActionsForBrand(brandId))
+ .catch((err) => {
+ logger.error({ err, brandId }, '[signals] recording or action generation failed');
+ });
} else {
logger.warn(
{ brandId, resultCount: result?.resultCount },
diff --git a/server/src/lib/signals/record.js b/server/src/lib/signals/record.js
new file mode 100644
index 000000000..3b4238500
--- /dev/null
+++ b/server/src/lib/signals/record.js
@@ -0,0 +1,404 @@
+/**
+ * Signal recording (Action Center, observation layer).
+ *
+ * Converts what the production detectors already find into `signals` rows
+ * with a lifecycle. Two inputs, one writer:
+ *
+ * - the Daily Pulse metric engine's highlights and warnings (#540) — its
+ * thresholds ARE the noise control: a visibility wobble below the
+ * sharp-drop floor or a one-run citation blip never reaches this module;
+ * - open page-opportunity findings (#719), read from their table.
+ *
+ * Runs after every stamped daily tracking run, before and independent of the
+ * pulse email's own gating — a brand with pulse emails off still gets
+ * signals, because the observation layer is a product surface, not a
+ * notification preference.
+ *
+ * Dedup: one row per ongoing condition, keyed by (brand, dedup_key). A
+ * re-detection updates last_detected_at and the measured values. A RESOLVED
+ * condition that fires again reopens as new; a DISMISSED one stays dismissed
+ * — the user said "not relevant", and re-raising it nightly would teach them
+ * to ignore the page.
+ *
+ * Resolution: persistent kinds (a drop, a surge, an open opportunity) are
+ * auto-resolved when a run no longer detects them — the condition ended.
+ * Event kinds (a first citation, a new engine appearance) describe moments;
+ * they never auto-resolve and simply age until triaged.
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+import { computePulseMetrics } from '../pulse/metrics.js';
+import { logger } from '../logger.js';
+
+const DETECTION_WINDOW_DAYS = 7;
+const DAY_MS = 86_400_000;
+
+/** A "mentioned but never cited" pattern needs at least this many prompts
+ * before it is a signal — one or two uncited mentions are normal noise. */
+const UNCITED_MIN_PROMPTS = 3;
+
+/** Audits older than this no longer describe the page (it may have been
+ * rewritten since); their findings age out instead of nagging forever. */
+const AUDIT_MAX_AGE_DAYS = 90;
+
+/** Latest completed audit below this total score raises a technical signal. */
+const AUDIT_LOW_SCORE = 50;
+
+/**
+ * Static knowledge per detector kind. Mirrored by the web registry
+ * (web/src/lib/signals/registry.ts) which owns the display templates —
+ * this side owns what gets STORED: category, impact, sources, KPI links,
+ * and whether the condition persists.
+ */
+const KIND_META = {
+ sharp_drop: {
+ category: 'visibility',
+ impact: 'high',
+ kpiKeys: ['ai_visibility'],
+ persistent: true,
+ },
+ prompt_gain: {
+ category: 'visibility',
+ impact: 'medium',
+ kpiKeys: ['ai_visibility'],
+ persistent: false,
+ },
+ new_engine: {
+ category: 'visibility',
+ impact: 'medium',
+ kpiKeys: ['ai_visibility'],
+ persistent: false,
+ },
+ lost_citations: {
+ category: 'citation',
+ impact: 'high',
+ kpiKeys: ['citations'],
+ persistent: true,
+ },
+ first_citation: {
+ category: 'citation',
+ impact: 'medium',
+ kpiKeys: ['citations'],
+ persistent: false,
+ },
+ competitor_surge: {
+ category: 'competitor',
+ impact: 'high',
+ kpiKeys: ['share_of_voice'],
+ persistent: true,
+ },
+ competitor_crossed: {
+ category: 'competitor',
+ impact: 'high',
+ kpiKeys: ['share_of_voice', 'ai_visibility'],
+ persistent: true,
+ },
+ competitor_overtaken: {
+ category: 'competitor',
+ impact: 'medium',
+ kpiKeys: ['share_of_voice'],
+ persistent: false,
+ },
+ page_opportunity: {
+ category: 'traffic',
+ impact: 'medium',
+ kpiKeys: ['ai_referral_traffic'],
+ persistent: true,
+ },
+ uncited_mentions: {
+ category: 'mention',
+ impact: 'medium',
+ kpiKeys: ['citations', 'mentions'],
+ persistent: true,
+ },
+ audit_low_score: {
+ category: 'technical',
+ impact: 'medium',
+ kpiKeys: [],
+ persistent: true,
+ },
+};
+
+/** Pulse highlight/warning → signal candidate. Returns null for entries that
+ * describe engine health rather than the brand (degraded platforms). */
+function fromPulseEntry(entry) {
+ const meta = KIND_META[entry.type];
+ if (!meta) return null;
+
+ const candidate = {
+ kind: entry.type,
+ dedupKey: entry.key,
+ source: ['ai_results'],
+ payload: {},
+ previousValue: null,
+ currentValue: null,
+ changeValue: null,
+ };
+
+ switch (entry.type) {
+ case 'sharp_drop':
+ candidate.previousValue = entry.from;
+ candidate.currentValue = entry.to;
+ candidate.changeValue = -entry.drop;
+ break;
+ case 'prompt_gain':
+ // The prompt's id lives in the dedup key (prompt_gain:<id>); surfaced
+ // in the payload so the drawer can link to the prompt itself.
+ candidate.payload = { promptText: entry.promptText, promptId: entry.key.split(':')[1] };
+ candidate.changeValue = entry.gain;
+ break;
+ case 'new_engine':
+ candidate.payload = { platform: entry.platform };
+ break;
+ case 'lost_citations':
+ candidate.payload = { promptText: entry.promptText, promptId: entry.key.split(':')[1] };
+ break;
+ case 'first_citation':
+ candidate.payload = { url: entry.url, label: entry.label, promptText: entry.promptText };
+ break;
+ case 'competitor_surge':
+ candidate.payload = { competitorName: entry.competitorName };
+ candidate.previousValue = entry.from;
+ candidate.currentValue = entry.to;
+ candidate.changeValue = Math.round((entry.to - entry.from) * 10) / 10;
+ break;
+ case 'competitor_crossed':
+ case 'competitor_overtaken':
+ candidate.payload = {
+ competitorName: entry.competitorName,
+ competitorRate: entry.competitorRate,
+ brandRate: entry.brandRate,
+ };
+ break;
+ default:
+ return null;
+ }
+ return candidate;
+}
+
+/**
+ * Mentioned-but-never-cited (brief §10's headline mention signal), from the
+ * same per-prompt aggregates the Prompts page reads. A prompt counts when
+ * the window's answers mention the brand at least once and cite it never —
+ * the brand is in the conversation but AI engines have nothing of its own
+ * to point at. One consolidated signal (brief §29), not one per prompt.
+ */
+async function uncitedMentionCandidates(brandId, now) {
+ const from = new Date(now.getTime() - DETECTION_WINDOW_DAYS * DAY_MS);
+ const { data, error } = await supabaseAdmin.rpc('prompt_visibility_summaries', {
+ p_brand_id: brandId,
+ p_date_from: from.toISOString(),
+ p_date_to: now.toISOString(),
+ });
+ if (error) throw new Error(error.message);
+
+ const uncited = (data ?? []).filter(
+ (row) =>
+ Number(row.runs) > 0 && Number(row.total_mentions) > 0 && Number(row.total_citations) === 0,
+ );
+ if (uncited.length < UNCITED_MIN_PROMPTS) return [];
+
+ return [
+ {
+ kind: 'uncited_mentions',
+ dedupKey: 'uncited_mentions',
+ source: ['ai_results'],
+ payload: { promptIds: uncited.map((row) => row.prompt_id).slice(0, 50) },
+ previousValue: null,
+ currentValue: uncited.length,
+ changeValue: null,
+ },
+ ];
+}
+
+/**
+ * Low AEO readiness from Site Audit's stored scores (brief §12). Only the
+ * LATEST completed audit of each URL speaks for it — an old bad score
+ * followed by a good re-audit is a fixed page — and audits past the age cap
+ * no longer describe the page at all.
+ *
+ * Consolidated into ONE signal per brand (§29): a brand that audits forty
+ * weak pages has one condition, "audited pages score low", not forty rows
+ * 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) {
+ const since = new Date(now.getTime() - AUDIT_MAX_AGE_DAYS * DAY_MS).toISOString();
+ const { data, error } = await supabaseAdmin
+ .from('site_audits')
+ .select('url, total_score, completed_at')
+ .eq('brand_id', brandId)
+ .eq('status', 'completed')
+ .not('total_score', 'is', null)
+ .gte('completed_at', since)
+ .order('completed_at', { ascending: false })
+ .limit(500);
+ if (error) throw new Error(error.message);
+
+ const latestByUrl = new Map();
+ for (const audit of data ?? []) {
+ if (!latestByUrl.has(audit.url)) latestByUrl.set(audit.url, audit);
+ }
+
+ const low = [...latestByUrl.values()]
+ .map((audit) => ({ url: audit.url, score: Number(audit.total_score) }))
+ .filter((audit) => audit.score < AUDIT_LOW_SCORE)
+ .sort((a, b) => a.score - b.score);
+ if (low.length === 0) return [];
+
+ return [
+ {
+ kind: 'audit_low_score',
+ dedupKey: 'audit_low_score',
+ source: ['site_audit'],
+ payload: { urls: low.slice(0, 10) },
+ previousValue: null,
+ currentValue: low.length,
+ changeValue: null,
+ },
+ ];
+}
+
+/** Open page-opportunity findings → signal candidates. */
+async function pageOpportunityCandidates(brandId) {
+ const { data, error } = await supabaseAdmin
+ .from('page_opportunities')
+ .select('landing_page, value_signal, value_rank, sessions, citation_state')
+ .eq('brand_id', brandId)
+ .is('resolved_at', null)
+ .limit(1000);
+ if (error) throw new Error(error.message);
+
+ return (data ?? []).map((row) => ({
+ kind: 'page_opportunity',
+ dedupKey: `page_opportunity:${row.landing_page}`,
+ source: ['ga4', 'ai_results'],
+ payload: {
+ landingPage: row.landing_page,
+ valueSignal: row.value_signal,
+ valueRank: row.value_rank,
+ citationState: row.citation_state,
+ },
+ previousValue: null,
+ currentValue: row.sessions,
+ changeValue: null,
+ }));
+}
+
+/**
+ * Detect and record signals for one brand. Best-effort by contract: callers
+ * fire-and-forget, and a failure here must never affect the tracking run.
+ */
+export async function recordSignalsForBrand(brandId, { now = new Date() } = {}) {
+ const metrics = await computePulseMetrics(brandId, {
+ windowDays: DETECTION_WINDOW_DAYS,
+ now,
+ });
+
+ // No fresh results means the detectors saw nothing, not that every
+ // condition ended — recording now would silently auto-resolve real
+ // signals. Same for a platform outage, during which the engine already
+ // suppresses drop/loss warnings: absence of a warning is not recovery.
+ if ((metrics.kpis?.totalResults ?? 0) === 0) {
+ logger.info({ brandId }, '[signals] skipped — no fresh results in window');
+ return { skipped: 'no_fresh_results' };
+ }
+ const outage = (metrics.degradedPlatforms?.length ?? 0) > 0;
+
+ const candidates = [];
+ for (const entry of [...(metrics.highlights ?? []), ...(metrics.warnings ?? [])]) {
+ const candidate = fromPulseEntry(entry);
+ if (candidate) candidates.push(candidate);
+ }
+ candidates.push(...(await pageOpportunityCandidates(brandId)));
+ candidates.push(...(await uncitedMentionCandidates(brandId, now)));
+ candidates.push(...(await auditCandidates(brandId, now)));
+
+ // Existing rows decide insert vs update vs reopen. A brand's signal set is
+ // small (tens), so reading it whole is cheaper than being clever.
+ const { data: existingRows, error: readErr } = await supabaseAdmin
+ .from('signals')
+ .select('id, dedup_key, kind, status')
+ .eq('brand_id', brandId)
+ .limit(1000);
+ if (readErr) throw new Error(readErr.message);
+ const existing = new Map((existingRows ?? []).map((row) => [row.dedup_key, row]));
+
+ const nowIso = now.toISOString();
+ let inserted = 0;
+ let refreshed = 0;
+ let reopened = 0;
+
+ for (const candidate of candidates) {
+ const meta = KIND_META[candidate.kind];
+ const current = existing.get(candidate.dedupKey);
+
+ if (!current) {
+ const { error } = await supabaseAdmin.from('signals').insert({
+ brand_id: brandId,
+ category: meta.category,
+ kind: candidate.kind,
+ impact: meta.impact,
+ source: candidate.source,
+ dedup_key: candidate.dedupKey,
+ detected_at: nowIso,
+ last_detected_at: nowIso,
+ previous_value: candidate.previousValue,
+ current_value: candidate.currentValue,
+ change_value: candidate.changeValue,
+ payload: candidate.payload,
+ kpi_keys: meta.kpiKeys,
+ });
+ if (error) throw new Error(error.message);
+ inserted += 1;
+ continue;
+ }
+
+ if (current.status === 'dismissed') continue;
+
+ const patch = {
+ last_detected_at: nowIso,
+ previous_value: candidate.previousValue,
+ current_value: candidate.currentValue,
+ change_value: candidate.changeValue,
+ payload: candidate.payload,
+ updated_at: nowIso,
+ };
+ if (current.status === 'resolved') {
+ // The condition came back: this is a new observation, not a stale one.
+ patch.status = 'new';
+ patch.detected_at = nowIso;
+ patch.resolved_at = null;
+ reopened += 1;
+ } else {
+ refreshed += 1;
+ }
+ const { error } = await supabaseAdmin.from('signals').update(patch).eq('id', current.id);
+ if (error) throw new Error(error.message);
+ }
+
+ // Persistent conditions this run no longer detects have ended — close
+ // them. Not during an outage: the engine suppresses drop/loss warnings
+ // while a platform is degraded, and treating that silence as recovery
+ // would close real signals.
+ const detectedKeys = new Set(candidates.map((c) => c.dedupKey));
+ const toResolve = outage
+ ? []
+ : (existingRows ?? []).filter(
+ (row) =>
+ KIND_META[row.kind]?.persistent &&
+ (row.status === 'new' || row.status === 'acknowledged') &&
+ !detectedKeys.has(row.dedup_key),
+ );
+ for (const row of toResolve) {
+ const { error } = await supabaseAdmin
+ .from('signals')
+ .update({ status: 'resolved', resolved_at: nowIso, updated_at: nowIso })
+ .eq('id', row.id);
+ if (error) throw new Error(error.message);
+ }
+
+ const summary = { inserted, refreshed, reopened, autoResolved: toResolve.length };
+ logger.info({ brandId, ...summary }, '[signals] recorded');
+ return summary;
+}
diff --git a/server/src/scripts/backfill-signals.js b/server/src/scripts/backfill-signals.js
new file mode 100644
index 000000000..c80f7b174
--- /dev/null
+++ b/server/src/scripts/backfill-signals.js
@@ -0,0 +1,45 @@
+/**
+ * One-off signal backfill (Action Center).
+ *
+ * Runs the nightly signal recorder once for one brand or for every active
+ * brand, so the Signals page has real rows before the next tracking cycle.
+ * Safe to re-run: recording dedupes on (brand, dedup_key).
+ *
+ * Run: node src/scripts/backfill-signals.js [brandId|--all]
+ */
+import 'dotenv/config';
+import supabaseAdmin from '../config/supabase.js';
+import { recordSignalsForBrand } from '../lib/signals/record.js';
+import { generateActionsForBrand } from '../lib/action-center/generate.js';
+
+const arg = process.argv[2];
+if (!arg) {
+ console.error('Usage: node src/scripts/backfill-signals.js <brandId|--all>');
+ process.exit(1);
+}
+
+let brandIds;
+if (arg === '--all') {
+ const { data, error } = await supabaseAdmin
+ .from('brands')
+ .select('id')
+ .eq('is_active', true)
+ .limit(1000);
+ if (error) throw new Error(error.message);
+ brandIds = (data ?? []).map((b) => b.id);
+} else {
+ brandIds = [arg];
+}
+
+for (const brandId of brandIds) {
+ try {
+ const result = await recordSignalsForBrand(brandId);
+ const actions = result.skipped
+ ? { skipped: result.skipped }
+ : await generateActionsForBrand(brandId);
+ console.log(brandId, JSON.stringify({ signals: result, actions }));
+ } catch (err) {
+ console.error(brandId, 'FAILED:', err.message);
+ }
+}
+process.exit(0);
diff --git a/supabase/migrations/00078_kpi_definitions.sql b/supabase/migrations/00078_kpi_definitions.sql
new file mode 100644
index 000000000..b4f590eb5
--- /dev/null
+++ b/supabase/migrations/00078_kpi_definitions.sql
@@ -0,0 +1,85 @@
+-- Action Center: KPI definitions (issue: Action Center KPIs page).
+--
+-- One row per activated KPI per brand. Only the user's choices live here —
+-- the target, the timeframe, and whether the KPI is active. Everything a
+-- reader sees next to those (value, change, trend, status) is computed at
+-- read time from the tracking/GA aggregates, so a definition can never
+-- disagree with the surfaces it summarizes. Static product knowledge
+-- (name, unit, direction, category) lives in the code registry keyed by
+-- kpi_key; storing it here as well would let the two drift.
+
+create table public.kpi_definitions (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ -- Key into the code-side KPI registry (web/src/lib/kpis/registry.ts).
+ -- Not an enum: adding a KPI must not take a migration.
+ kpi_key text not null,
+ target numeric not null check (target > 0),
+ timeframe text not null default 'monthly'
+ check (timeframe in ('weekly', 'monthly', 'quarterly')),
+ is_active boolean not null default true,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (brand_id, kpi_key)
+);
+
+create index kpi_definitions_brand_idx
+ on public.kpi_definitions (brand_id) where is_active;
+
+-- ─── Row level security ──────────────────────────────────────────────────────
+-- Same shape as brand_domains: every org member reads, admins and managers
+-- write. Targets steer what the Action Center will prioritize, so changing
+-- them is a management decision, not a per-member preference.
+
+alter table public.kpi_definitions enable row level security;
+
+create policy "kpi_definitions: member select"
+ on public.kpi_definitions
+ for select
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "kpi_definitions: admin/manager insert"
+ on public.kpi_definitions
+ for insert
+ with check (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ and p.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ );
+
+create policy "kpi_definitions: admin/manager update"
+ on public.kpi_definitions
+ for update
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ and p.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ );
+
+create policy "kpi_definitions: admin/manager delete"
+ on public.kpi_definitions
+ for delete
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ and p.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ );
diff --git a/supabase/migrations/00079_signals.sql b/supabase/migrations/00079_signals.sql
new file mode 100644
index 000000000..1cf7b7804
--- /dev/null
+++ b/supabase/migrations/00079_signals.sql
@@ -0,0 +1,168 @@
+-- Action Center: signals (observation layer).
+--
+-- A signal is a meaningful detected change — not an action, not a task. The
+-- rows here are produced nightly by the server from detectors that already
+-- run in production (the Daily Pulse highlight/warning engine, #540, and the
+-- page-opportunity engine, #719); this table gives those detections what the
+-- pulse email cannot: a queryable lifecycle (new → acknowledged → resolved /
+-- dismissed), dedup across nights, and a stable identity that a future
+-- Action can reference (many signals → one action).
+--
+-- Display text is NOT stored: like the KPI registry, the signal kind maps to
+-- i18n templates code-side, and `payload` carries the values those templates
+-- interpolate. What IS stored is everything the page filters or aggregates
+-- on: category, impact, status, source, timestamps.
+
+create table public.signals (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+
+ -- Broad category (the page's tabs) and the specific detector kind.
+ -- Text, not enums: adding a detector must not take a migration.
+ category text not null
+ check (category in ('visibility', 'citation', 'mention', 'traffic', 'technical', 'competitor')),
+ kind text not null,
+
+ impact text not null check (impact in ('high', 'medium', 'low')),
+ status text not null default 'new'
+ check (status in ('new', 'acknowledged', 'resolved', 'dismissed')),
+
+ -- Producing systems, e.g. {ai_results}, {ga4,ai_results}.
+ source text[] not null default '{}',
+
+ -- One row per ongoing condition: re-detection updates last_detected_at
+ -- instead of inserting a sibling. The key encodes the condition's
+ -- identity (kind + entity), not the night it fired.
+ dedup_key text not null,
+ detected_at timestamptz not null default now(),
+ last_detected_at timestamptz not null default now(),
+ resolved_at timestamptz,
+
+ -- The measured movement, in the kind's own unit (points, counts).
+ previous_value numeric,
+ current_value numeric,
+ change_value numeric,
+
+ -- Interpolation values for the i18n templates plus affected entities
+ -- (prompts, urls, platforms, competitors) — shapes vary by kind.
+ payload jsonb not null default '{}'::jsonb,
+
+ -- Which configured KPIs this signal bears on (registry keys).
+ kpi_keys text[] not null default '{}',
+
+ -- Future Actions link (many signals → one action). Plain uuid until the
+ -- actions table exists; the FK arrives with it.
+ action_id uuid,
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+
+ unique (brand_id, dedup_key)
+);
+
+create index signals_brand_detected_idx
+ on public.signals (brand_id, detected_at desc);
+create index signals_brand_status_idx
+ on public.signals (brand_id, status);
+
+-- ─── Row level security ──────────────────────────────────────────────────────
+-- Members read and triage (status changes are lightweight review work, not a
+-- management decision); the service role writes detections.
+
+alter table public.signals enable row level security;
+
+create policy "signals: member select"
+ on public.signals
+ for select
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "signals: member update"
+ on public.signals
+ for update
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "Service role can insert signals"
+ on public.signals
+ for insert
+ with check (true);
+
+create policy "Service role can delete signals"
+ on public.signals
+ for delete
+ using (true);
+
+-- ─── Summary RPC ─────────────────────────────────────────────────────────────
+-- Everything the page's summary strip and tab counts need in one round trip,
+-- immune to the PostgREST 1000-row cap. Security invoker: RLS scopes the
+-- table to the caller's org, so the function needs no guard of its own.
+
+create or replace function public.signals_summary(
+ p_brand_id uuid,
+ p_from timestamptz,
+ p_to timestamptz
+) returns jsonb
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ with windowed as (
+ select * from public.signals
+ where brand_id = p_brand_id
+ and detected_at >= p_from
+ and detected_at < p_to
+ ),
+ prev as (
+ select count(*) as total
+ from public.signals
+ where brand_id = p_brand_id
+ and detected_at >= p_from - (p_to - p_from)
+ and detected_at < p_from
+ )
+ select jsonb_build_object(
+ 'total', (select count(*) from windowed),
+ 'prev_total', (select total from prev),
+ 'important', (select count(*) from windowed where impact = 'high'),
+ 'new', (select count(*) from windowed where status = 'new'),
+ 'resolved', (
+ select count(*) from public.signals
+ where brand_id = p_brand_id
+ and resolved_at >= p_from
+ and resolved_at < p_to
+ ),
+ 'by_day', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select detected_at::date as day, count(*) as cnt
+ from windowed
+ group by 1
+ ) d
+ ),
+ 'by_category', (
+ select coalesce(jsonb_object_agg(category, cnt), '{}'::jsonb)
+ from (
+ select category, count(*) as cnt from windowed group by 1
+ ) c
+ ),
+ 'by_source', (
+ select coalesce(jsonb_object_agg(src, cnt), '{}'::jsonb)
+ from (
+ select unnest(source) as src, count(*) as cnt from windowed group by 1
+ ) s
+ )
+ );
+$$;
diff --git a/supabase/migrations/00080_signals_summary_cards.sql b/supabase/migrations/00080_signals_summary_cards.sql
new file mode 100644
index 000000000..1df678ee3
--- /dev/null
+++ b/supabase/migrations/00080_signals_summary_cards.sql
@@ -0,0 +1,127 @@
+-- Signals summary v2: everything the five mockup cards show (issue: Action
+-- Center Signals page).
+--
+-- The first version conflated "total" with "new": both counted detected_at
+-- in the window, so the two cards could never differ. With the dedup model
+-- (one row per ongoing condition, re-detections bump last_detected_at) the
+-- honest semantics are:
+--
+-- total — conditions ACTIVE in the window: detected before its end and
+-- still open, or resolved inside it (i.e. lifetime overlaps).
+-- new — conditions FIRST detected inside the window.
+-- important — the high-impact subset of total.
+-- resolved — conditions resolved inside the window.
+--
+-- Every count carries its previous-window twin for the ↑/↓ deltas, and a
+-- per-day series for the card sparklines. Per-day "active" counts scan
+-- signals × days, which is fine at per-brand signal counts (tens).
+
+create or replace function public.signals_summary(
+ p_brand_id uuid,
+ p_from timestamptz,
+ p_to timestamptz
+) returns jsonb
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ with bounds as (
+ select p_from as cur_from, p_to as cur_to,
+ p_from - (p_to - p_from) as prev_from, p_from as prev_to
+ ),
+ active as (
+ select * from public.signals, bounds
+ where brand_id = p_brand_id
+ and detected_at < cur_to
+ and (resolved_at is null or resolved_at >= cur_from)
+ ),
+ prev_active as (
+ select * from public.signals, bounds
+ where brand_id = p_brand_id
+ and detected_at < prev_to
+ and (resolved_at is null or resolved_at >= prev_from)
+ ),
+ days as (
+ select generate_series(
+ (select cur_from from bounds)::date,
+ (select cur_to from bounds)::date - 1,
+ interval '1 day'
+ )::date as day
+ )
+ select jsonb_build_object(
+ 'total', (select count(*) from active),
+ 'prev_total', (select count(*) from prev_active),
+ 'important', (select count(*) from active where impact = 'high'),
+ 'prev_important', (select count(*) from prev_active where impact = 'high'),
+ 'new', (
+ select count(*) from public.signals, bounds
+ where brand_id = p_brand_id and detected_at >= cur_from and detected_at < cur_to
+ ),
+ 'prev_new', (
+ select count(*) from public.signals, bounds
+ where brand_id = p_brand_id and detected_at >= prev_from and detected_at < prev_to
+ ),
+ 'resolved', (
+ select count(*) from public.signals, bounds
+ where brand_id = p_brand_id and resolved_at >= cur_from and resolved_at < cur_to
+ ),
+ 'prev_resolved', (
+ select count(*) from public.signals, bounds
+ where brand_id = p_brand_id and resolved_at >= prev_from and resolved_at < prev_to
+ ),
+ 'by_day_active', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(s.id) as cnt
+ from days d
+ left join public.signals s
+ on s.brand_id = p_brand_id
+ and s.detected_at::date <= d.day
+ and (s.resolved_at is null or s.resolved_at::date >= d.day)
+ group by d.day
+ ) t
+ ),
+ 'by_day_important', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(s.id) as cnt
+ from days d
+ left join public.signals s
+ on s.brand_id = p_brand_id
+ and s.impact = 'high'
+ and s.detected_at::date <= d.day
+ and (s.resolved_at is null or s.resolved_at::date >= d.day)
+ group by d.day
+ ) t
+ ),
+ 'by_day_new', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(s.id) as cnt
+ from days d
+ left join public.signals s
+ on s.brand_id = p_brand_id and s.detected_at::date = d.day
+ group by d.day
+ ) t
+ ),
+ 'by_day_resolved', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(s.id) as cnt
+ from days d
+ left join public.signals s
+ on s.brand_id = p_brand_id and s.resolved_at::date = d.day
+ group by d.day
+ ) t
+ ),
+ 'by_category', (
+ select coalesce(jsonb_object_agg(category, cnt), '{}'::jsonb)
+ from (select category, count(*) as cnt from active group by 1) c
+ ),
+ 'by_source', (
+ select coalesce(jsonb_object_agg(src, cnt), '{}'::jsonb)
+ from (select unnest(source) as src, count(*) as cnt from active group by 1) s
+ )
+ );
+$$;
diff --git a/supabase/migrations/00081_actions.sql b/supabase/migrations/00081_actions.sql
new file mode 100644
index 000000000..e1e581bd3
--- /dev/null
+++ b/supabase/migrations/00081_actions.sql
@@ -0,0 +1,167 @@
+-- Action Center: actions, their tasks, and their event trail.
+--
+-- An action is a measurable outcome to achieve, produced by consolidating
+-- open signals (many signals → one action); a task is one execution step
+-- under it. The three concepts stay separate tables on purpose — the brief's
+-- rule that Signal, Action and Task are never interchangeable is enforced by
+-- the schema, not by convention.
+--
+-- Like signals, nothing display-shaped is stored: `kind` keys into i18n
+-- templates code-side, `payload` carries the interpolation values, and the
+-- category/impact/status columns exist because the page filters on them.
+--
+-- `baseline` snapshots the linked signals' measured values at creation time.
+-- Nothing reads it yet — it is the "before" half that the future validation
+-- layer (before → execution → after) will compare against, stored now
+-- because it cannot be reconstructed later.
+
+create table public.actions (
+ id uuid primary key default gen_random_uuid(),
+ -- Human-readable identity ("AC-1258") — a global counter, shown in the
+ -- drawer so people can refer to an action in conversation.
+ action_no bigint generated always as identity,
+ brand_id uuid not null references public.brands(id) on delete cascade,
+
+ category text not null
+ check (category in ('growth', 'protect', 'recover', 'fix', 'compete')),
+ kind text not null,
+ impact text not null check (impact in ('high', 'medium', 'low')),
+
+ -- Outcome-oriented lifecycle, not to-do/done: an executed action can fail
+ -- validation (no_improvement), and that result must stay visible.
+ status text not null default 'new'
+ check (status in ('new', 'in_progress', 'completed', 'on_hold', 'no_improvement', 'dismissed')),
+
+ payload jsonb not null default '{}'::jsonb,
+ kpi_keys text[] not null default '{}',
+ baseline jsonb not null default '{}'::jsonb,
+
+ assignee_id uuid references public.profiles(id) on delete set null,
+ due_date date,
+
+ dedup_key text not null,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ completed_at timestamptz,
+
+ unique (brand_id, dedup_key)
+);
+
+create index actions_brand_status_idx on public.actions (brand_id, status);
+
+create table public.action_tasks (
+ id uuid primary key default gen_random_uuid(),
+ action_id uuid not null references public.actions(id) on delete cascade,
+ position integer not null,
+ -- Key into the code-side task templates for this action's kind.
+ task_key text not null,
+ status text not null default 'todo'
+ check (status in ('todo', 'in_progress', 'completed', 'blocked')),
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (action_id, task_key)
+);
+
+create index action_tasks_action_idx on public.action_tasks (action_id);
+
+-- Append-only lifecycle trail: created, status changes, assignments, task
+-- completions. The drawer's History tab reads it verbatim; completed
+-- actions carry their whole story into the History page later.
+create table public.action_events (
+ id uuid primary key default gen_random_uuid(),
+ action_id uuid not null references public.actions(id) on delete cascade,
+ event text not null,
+ data jsonb not null default '{}'::jsonb,
+ -- Null for system events (the nightly generator); a profile id when a
+ -- person did it.
+ actor_id uuid references public.profiles(id) on delete set null,
+ created_at timestamptz not null default now()
+);
+
+create index action_events_action_idx on public.action_events (action_id, created_at);
+
+-- The signals column that waited for this table.
+alter table public.signals
+ add constraint signals_action_id_fkey
+ foreign key (action_id) references public.actions(id) on delete set null;
+
+-- ─── Row level security ──────────────────────────────────────────────────────
+-- Members read everything and do the work: change status, assign, set due
+-- dates, move tasks. The service role (nightly generator) inserts and
+-- deletes. Events are also member-insertable so user actions can log
+-- themselves through RLS rather than needing the admin client.
+
+alter table public.actions enable row level security;
+alter table public.action_tasks enable row level security;
+alter table public.action_events enable row level security;
+
+create policy "actions: member select" on public.actions
+ for select using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "actions: member update" on public.actions
+ for update using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "Service role can insert actions" on public.actions
+ for insert with check (true);
+create policy "Service role can delete actions" on public.actions
+ for delete using (true);
+
+create policy "action_tasks: member select" on public.action_tasks
+ 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()
+ )
+ );
+
+create policy "action_tasks: member update" on public.action_tasks
+ for update 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()
+ )
+ );
+
+create policy "Service role can insert action tasks" on public.action_tasks
+ for insert with check (true);
+create policy "Service role can delete action tasks" on public.action_tasks
+ for delete using (true);
+
+create policy "action_events: member select" on public.action_events
+ 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()
+ )
+ );
+
+create policy "action_events: member insert" on public.action_events
+ for insert with check (
+ 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()
+ )
+ );
+
+create policy "Service role can delete action events" on public.action_events
+ for delete using (true);
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 4ea22825e..5f1c9c728 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -9555,3 +9555,566 @@ comment on function public.citation_competitor_sources(
) is
'Per-competitor source domains for the Competitor Gaps tab (#777), keyed by the competitor id recorded in the mention. plpgsql + force_custom_plan so the arguments reach the planner.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00078_kpi_definitions.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Action Center: KPI definitions (issue: Action Center KPIs page).
+--
+-- One row per activated KPI per brand. Only the user's choices live here —
+-- the target, the timeframe, and whether the KPI is active. Everything a
+-- reader sees next to those (value, change, trend, status) is computed at
+-- read time from the tracking/GA aggregates, so a definition can never
+-- disagree with the surfaces it summarizes. Static product knowledge
+-- (name, unit, direction, category) lives in the code registry keyed by
+-- kpi_key; storing it here as well would let the two drift.
+
+create table public.kpi_definitions (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ -- Key into the code-side KPI registry (web/src/lib/kpis/registry.ts).
+ -- Not an enum: adding a KPI must not take a migration.
+ kpi_key text not null,
+ target numeric not null check (target > 0),
+ timeframe text not null default 'monthly'
+ check (timeframe in ('weekly', 'monthly', 'quarterly')),
+ is_active boolean not null default true,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (brand_id, kpi_key)
+);
+
+create index kpi_definitions_brand_idx
+ on public.kpi_definitions (brand_id) where is_active;
+
+-- ─── Row level security ──────────────────────────────────────────────────────
+-- Same shape as brand_domains: every org member reads, admins and managers
+-- write. Targets steer what the Action Center will prioritize, so changing
+-- them is a management decision, not a per-member preference.
+
+alter table public.kpi_definitions enable row level security;
+
+create policy "kpi_definitions: member select"
+ on public.kpi_definitions
+ for select
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "kpi_definitions: admin/manager insert"
+ on public.kpi_definitions
+ for insert
+ with check (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ and p.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ );
+
+create policy "kpi_definitions: admin/manager update"
+ on public.kpi_definitions
+ for update
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ and p.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ );
+
+create policy "kpi_definitions: admin/manager delete"
+ on public.kpi_definitions
+ for delete
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ and p.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ );
+
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00079_signals.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Action Center: signals (observation layer).
+--
+-- A signal is a meaningful detected change — not an action, not a task. The
+-- rows here are produced nightly by the server from detectors that already
+-- run in production (the Daily Pulse highlight/warning engine, #540, and the
+-- page-opportunity engine, #719); this table gives those detections what the
+-- pulse email cannot: a queryable lifecycle (new → acknowledged → resolved /
+-- dismissed), dedup across nights, and a stable identity that a future
+-- Action can reference (many signals → one action).
+--
+-- Display text is NOT stored: like the KPI registry, the signal kind maps to
+-- i18n templates code-side, and `payload` carries the values those templates
+-- interpolate. What IS stored is everything the page filters or aggregates
+-- on: category, impact, status, source, timestamps.
+
+create table public.signals (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+
+ -- Broad category (the page's tabs) and the specific detector kind.
+ -- Text, not enums: adding a detector must not take a migration.
+ category text not null
+ check (category in ('visibility', 'citation', 'mention', 'traffic', 'technical', 'competitor')),
+ kind text not null,
+
+ impact text not null check (impact in ('high', 'medium', 'low')),
+ status text not null default 'new'
+ check (status in ('new', 'acknowledged', 'resolved', 'dismissed')),
+
+ -- Producing systems, e.g. {ai_results}, {ga4,ai_results}.
+ source text[] not null default '{}',
+
+ -- One row per ongoing condition: re-detection updates last_detected_at
+ -- instead of inserting a sibling. The key encodes the condition's
+ -- identity (kind + entity), not the night it fired.
+ dedup_key text not null,
+ detected_at timestamptz not null default now(),
+ last_detected_at timestamptz not null default now(),
+ resolved_at timestamptz,
+
+ -- The measured movement, in the kind's own unit (points, counts).
+ previous_value numeric,
+ current_value numeric,
+ change_value numeric,
+
+ -- Interpolation values for the i18n templates plus affected entities
+ -- (prompts, urls, platforms, competitors) — shapes vary by kind.
+ payload jsonb not null default '{}'::jsonb,
+
+ -- Which configured KPIs this signal bears on (registry keys).
+ kpi_keys text[] not null default '{}',
+
+ -- Future Actions link (many signals → one action). Plain uuid until the
+ -- actions table exists; the FK arrives with it.
+ action_id uuid,
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+
+ unique (brand_id, dedup_key)
+);
+
+create index signals_brand_detected_idx
+ on public.signals (brand_id, detected_at desc);
+create index signals_brand_status_idx
+ on public.signals (brand_id, status);
+
+-- ─── Row level security ──────────────────────────────────────────────────────
+-- Members read and triage (status changes are lightweight review work, not a
+-- management decision); the service role writes detections.
+
+alter table public.signals enable row level security;
+
+create policy "signals: member select"
+ on public.signals
+ for select
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "signals: member update"
+ on public.signals
+ for update
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "Service role can insert signals"
+ on public.signals
+ for insert
+ with check (true);
+
+create policy "Service role can delete signals"
+ on public.signals
+ for delete
+ using (true);
+
+-- ─── Summary RPC ─────────────────────────────────────────────────────────────
+-- Everything the page's summary strip and tab counts need in one round trip,
+-- immune to the PostgREST 1000-row cap. Security invoker: RLS scopes the
+-- table to the caller's org, so the function needs no guard of its own.
+
+create or replace function public.signals_summary(
+ p_brand_id uuid,
+ p_from timestamptz,
+ p_to timestamptz
+) returns jsonb
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ with windowed as (
+ select * from public.signals
+ where brand_id = p_brand_id
+ and detected_at >= p_from
+ and detected_at < p_to
+ ),
+ prev as (
+ select count(*) as total
+ from public.signals
+ where brand_id = p_brand_id
+ and detected_at >= p_from - (p_to - p_from)
+ and detected_at < p_from
+ )
+ select jsonb_build_object(
+ 'total', (select count(*) from windowed),
+ 'prev_total', (select total from prev),
+ 'important', (select count(*) from windowed where impact = 'high'),
+ 'new', (select count(*) from windowed where status = 'new'),
+ 'resolved', (
+ select count(*) from public.signals
+ where brand_id = p_brand_id
+ and resolved_at >= p_from
+ and resolved_at < p_to
+ ),
+ 'by_day', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select detected_at::date as day, count(*) as cnt
+ from windowed
+ group by 1
+ ) d
+ ),
+ 'by_category', (
+ select coalesce(jsonb_object_agg(category, cnt), '{}'::jsonb)
+ from (
+ select category, count(*) as cnt from windowed group by 1
+ ) c
+ ),
+ 'by_source', (
+ select coalesce(jsonb_object_agg(src, cnt), '{}'::jsonb)
+ from (
+ select unnest(source) as src, count(*) as cnt from windowed group by 1
+ ) s
+ )
+ );
+$$;
+
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00080_signals_summary_cards.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Signals summary v2: everything the five mockup cards show (issue: Action
+-- Center Signals page).
+--
+-- The first version conflated "total" with "new": both counted detected_at
+-- in the window, so the two cards could never differ. With the dedup model
+-- (one row per ongoing condition, re-detections bump last_detected_at) the
+-- honest semantics are:
+--
+-- total — conditions ACTIVE in the window: detected before its end and
+-- still open, or resolved inside it (i.e. lifetime overlaps).
+-- new — conditions FIRST detected inside the window.
+-- important — the high-impact subset of total.
+-- resolved — conditions resolved inside the window.
+--
+-- Every count carries its previous-window twin for the ↑/↓ deltas, and a
+-- per-day series for the card sparklines. Per-day "active" counts scan
+-- signals × days, which is fine at per-brand signal counts (tens).
+
+create or replace function public.signals_summary(
+ p_brand_id uuid,
+ p_from timestamptz,
+ p_to timestamptz
+) returns jsonb
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ with bounds as (
+ select p_from as cur_from, p_to as cur_to,
+ p_from - (p_to - p_from) as prev_from, p_from as prev_to
+ ),
+ active as (
+ select * from public.signals, bounds
+ where brand_id = p_brand_id
+ and detected_at < cur_to
+ and (resolved_at is null or resolved_at >= cur_from)
+ ),
+ prev_active as (
+ select * from public.signals, bounds
+ where brand_id = p_brand_id
+ and detected_at < prev_to
+ and (resolved_at is null or resolved_at >= prev_from)
+ ),
+ days as (
+ select generate_series(
+ (select cur_from from bounds)::date,
+ (select cur_to from bounds)::date - 1,
+ interval '1 day'
+ )::date as day
+ )
+ select jsonb_build_object(
+ 'total', (select count(*) from active),
+ 'prev_total', (select count(*) from prev_active),
+ 'important', (select count(*) from active where impact = 'high'),
+ 'prev_important', (select count(*) from prev_active where impact = 'high'),
+ 'new', (
+ select count(*) from public.signals, bounds
+ where brand_id = p_brand_id and detected_at >= cur_from and detected_at < cur_to
+ ),
+ 'prev_new', (
+ select count(*) from public.signals, bounds
+ where brand_id = p_brand_id and detected_at >= prev_from and detected_at < prev_to
+ ),
+ 'resolved', (
+ select count(*) from public.signals, bounds
+ where brand_id = p_brand_id and resolved_at >= cur_from and resolved_at < cur_to
+ ),
+ 'prev_resolved', (
+ select count(*) from public.signals, bounds
+ where brand_id = p_brand_id and resolved_at >= prev_from and resolved_at < prev_to
+ ),
+ 'by_day_active', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(s.id) as cnt
+ from days d
+ left join public.signals s
+ on s.brand_id = p_brand_id
+ and s.detected_at::date <= d.day
+ and (s.resolved_at is null or s.resolved_at::date >= d.day)
+ group by d.day
+ ) t
+ ),
+ 'by_day_important', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(s.id) as cnt
+ from days d
+ left join public.signals s
+ on s.brand_id = p_brand_id
+ and s.impact = 'high'
+ and s.detected_at::date <= d.day
+ and (s.resolved_at is null or s.resolved_at::date >= d.day)
+ group by d.day
+ ) t
+ ),
+ 'by_day_new', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(s.id) as cnt
+ from days d
+ left join public.signals s
+ on s.brand_id = p_brand_id and s.detected_at::date = d.day
+ group by d.day
+ ) t
+ ),
+ 'by_day_resolved', (
+ select coalesce(jsonb_object_agg(day, cnt), '{}'::jsonb)
+ from (
+ select d.day, count(s.id) as cnt
+ from days d
+ left join public.signals s
+ on s.brand_id = p_brand_id and s.resolved_at::date = d.day
+ group by d.day
+ ) t
+ ),
+ 'by_category', (
+ select coalesce(jsonb_object_agg(category, cnt), '{}'::jsonb)
+ from (select category, count(*) as cnt from active group by 1) c
+ ),
+ 'by_source', (
+ select coalesce(jsonb_object_agg(src, cnt), '{}'::jsonb)
+ from (select unnest(source) as src, count(*) as cnt from active group by 1) s
+ )
+ );
+$$;
+
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00081_actions.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Action Center: actions, their tasks, and their event trail.
+--
+-- An action is a measurable outcome to achieve, produced by consolidating
+-- open signals (many signals → one action); a task is one execution step
+-- under it. The three concepts stay separate tables on purpose — the brief's
+-- rule that Signal, Action and Task are never interchangeable is enforced by
+-- the schema, not by convention.
+--
+-- Like signals, nothing display-shaped is stored: `kind` keys into i18n
+-- templates code-side, `payload` carries the interpolation values, and the
+-- category/impact/status columns exist because the page filters on them.
+--
+-- `baseline` snapshots the linked signals' measured values at creation time.
+-- Nothing reads it yet — it is the "before" half that the future validation
+-- layer (before → execution → after) will compare against, stored now
+-- because it cannot be reconstructed later.
+
+create table public.actions (
+ id uuid primary key default gen_random_uuid(),
+ -- Human-readable identity ("AC-1258") — a global counter, shown in the
+ -- drawer so people can refer to an action in conversation.
+ action_no bigint generated always as identity,
+ brand_id uuid not null references public.brands(id) on delete cascade,
+
+ category text not null
+ check (category in ('growth', 'protect', 'recover', 'fix', 'compete')),
+ kind text not null,
+ impact text not null check (impact in ('high', 'medium', 'low')),
+
+ -- Outcome-oriented lifecycle, not to-do/done: an executed action can fail
+ -- validation (no_improvement), and that result must stay visible.
+ status text not null default 'new'
+ check (status in ('new', 'in_progress', 'completed', 'on_hold', 'no_improvement', 'dismissed')),
+
+ payload jsonb not null default '{}'::jsonb,
+ kpi_keys text[] not null default '{}',
+ baseline jsonb not null default '{}'::jsonb,
+
+ assignee_id uuid references public.profiles(id) on delete set null,
+ due_date date,
+
+ dedup_key text not null,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ completed_at timestamptz,
+
+ unique (brand_id, dedup_key)
+);
+
+create index actions_brand_status_idx on public.actions (brand_id, status);
+
+create table public.action_tasks (
+ id uuid primary key default gen_random_uuid(),
+ action_id uuid not null references public.actions(id) on delete cascade,
+ position integer not null,
+ -- Key into the code-side task templates for this action's kind.
+ task_key text not null,
+ status text not null default 'todo'
+ check (status in ('todo', 'in_progress', 'completed', 'blocked')),
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (action_id, task_key)
+);
+
+create index action_tasks_action_idx on public.action_tasks (action_id);
+
+-- Append-only lifecycle trail: created, status changes, assignments, task
+-- completions. The drawer's History tab reads it verbatim; completed
+-- actions carry their whole story into the History page later.
+create table public.action_events (
+ id uuid primary key default gen_random_uuid(),
+ action_id uuid not null references public.actions(id) on delete cascade,
+ event text not null,
+ data jsonb not null default '{}'::jsonb,
+ -- Null for system events (the nightly generator); a profile id when a
+ -- person did it.
+ actor_id uuid references public.profiles(id) on delete set null,
+ created_at timestamptz not null default now()
+);
+
+create index action_events_action_idx on public.action_events (action_id, created_at);
+
+-- The signals column that waited for this table.
+alter table public.signals
+ add constraint signals_action_id_fkey
+ foreign key (action_id) references public.actions(id) on delete set null;
+
+-- ─── Row level security ──────────────────────────────────────────────────────
+-- Members read everything and do the work: change status, assign, set due
+-- dates, move tasks. The service role (nightly generator) inserts and
+-- deletes. Events are also member-insertable so user actions can log
+-- themselves through RLS rather than needing the admin client.
+
+alter table public.actions enable row level security;
+alter table public.action_tasks enable row level security;
+alter table public.action_events enable row level security;
+
+create policy "actions: member select" on public.actions
+ for select using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "actions: member update" on public.actions
+ for update using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "Service role can insert actions" on public.actions
+ for insert with check (true);
+create policy "Service role can delete actions" on public.actions
+ for delete using (true);
+
+create policy "action_tasks: member select" on public.action_tasks
+ 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()
+ )
+ );
+
+create policy "action_tasks: member update" on public.action_tasks
+ for update 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()
+ )
+ );
+
+create policy "Service role can insert action tasks" on public.action_tasks
+ for insert with check (true);
+create policy "Service role can delete action tasks" on public.action_tasks
+ for delete using (true);
+
+create policy "action_events: member select" on public.action_events
+ 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()
+ )
+ );
+
+create policy "action_events: member insert" on public.action_events
+ for insert with check (
+ 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()
+ )
+ );
+
+create policy "Service role can delete action events" on public.action_events
+ for delete using (true);
+
diff --git a/web/messages/en.json b/web/messages/en.json
index b5f2a73da..3beb749ff 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -47,6 +47,7 @@
"nav": {
"overview": "Overview",
"agent": "Agent",
+ "actionCenter": "Action Center",
"insights": "Visibility",
"traffic": "AI Traffic Analytics",
"prompts": "Prompts",
@@ -61,6 +62,476 @@
"analytics": "Analytics",
"optimization": "Optimization"
},
+ "actionCenter": {
+ "tabs": {
+ "label": "Action Center sections",
+ "kpis": "KPIs",
+ "actions": "Actions",
+ "signals": "Signals",
+ "history": "History"
+ },
+ "pages": {
+ "actions": "What should you do now, ranked by your KPI goals.",
+ "signals": "What changed across your AI visibility data.",
+ "history": "What was done, and what it moved."
+ },
+ "comingSoon": {
+ "title": "Coming soon",
+ "description": "This part of the Action Center is on its way. KPIs are live — start by setting your goals there."
+ },
+ "categories": {
+ "visibility": "Visibility",
+ "citations": "Citations",
+ "mentions": "Mentions",
+ "traffic": "Traffic",
+ "content": "Content"
+ },
+ "kpis": {
+ "title": "KPIs",
+ "subtitle": "Track the metrics that matter, aligned with your goals.",
+ "allKpis": "All KPIs",
+ "filters": "Filters",
+ "dateRangeAria": "Date range",
+ "table": {
+ "kpi": "KPI",
+ "value": "Value",
+ "change": "Change",
+ "trend": "Trend (7D)",
+ "status": "Status",
+ "goal": "Goal",
+ "vsGoal": "vs Goal",
+ "actions": "Actions"
+ },
+ "status": {
+ "on_track": "On Track",
+ "at_risk": "At Risk",
+ "off_track": "Off Track",
+ "goal_reached": "Goal Reached"
+ },
+ "pointsChange": "{value} pts",
+ "vsGoalAria": "{progress}% of goal",
+ "editKpis": "Edit KPIs",
+ "addKpi": "Add KPI",
+ "menu": {
+ "label": "Actions for {name}",
+ "edit": "Edit KPI",
+ "remove": "Remove KPI"
+ },
+ "empty": {
+ "title": "No KPIs configured yet",
+ "description": "Choose a KPI framework to define what Ansvisor should prioritize for this brand.",
+ "cta": "Configure KPIs"
+ },
+ "allInactive": "No active KPIs for this brand.",
+ "noResults": "No KPIs match this filter.",
+ "clearFilter": "Clear filter",
+ "removeFailed": "Couldn't remove the KPI. Only admins and managers can change KPIs.",
+ "error": {
+ "title": "We couldn't load your KPIs.",
+ "retry": "Try again"
+ },
+ "noBrand": {
+ "title": "No brand selected",
+ "description": "Select a brand to view its KPIs."
+ }
+ },
+ "drawer": {
+ "title": "Configure KPI Framework",
+ "description": "Customize the KPIs Ansvisor tracks for this brand.",
+ "steps": {
+ "template": {
+ "title": "1 · Choose KPI template",
+ "description": "Start with a template or build your own."
+ },
+ "goals": {
+ "title": "2 · Set goals & targets",
+ "description": "Define your targets and time period."
+ }
+ },
+ "templates": {
+ "ai_search_visibility": {
+ "name": "AI Search Visibility",
+ "description": "Core KPIs for AI visibility and citations."
+ },
+ "content_performance": {
+ "name": "Content Performance",
+ "description": "KPIs for content quality and impact."
+ },
+ "brand_monitoring": {
+ "name": "Brand Monitoring",
+ "description": "KPIs for mentions, sentiment and reputation."
+ },
+ "custom": {
+ "name": "Custom Framework",
+ "description": "Build your own KPI set from scratch."
+ },
+ "notAvailable": "Coming soon — its KPIs aren't measurable yet."
+ },
+ "timePeriod": "Time period",
+ "timeframes": {
+ "weekly": "Weekly",
+ "monthly": "Monthly",
+ "quarterly": "Quarterly"
+ },
+ "targets": "Targets",
+ "targetAria": "Target for {name}",
+ "invalidTarget": "Targets must be positive; percent targets can't exceed 100.",
+ "callout": {
+ "title": "This KPI framework will drive your Action Center.",
+ "description": "Actions and recommendations are prioritized based on your KPI goals."
+ },
+ "cancel": "Cancel",
+ "save": "Save & Apply",
+ "saved": "KPI framework applied.",
+ "saveFailed": "Couldn't save the framework. Only admins and managers can change KPIs.",
+ "loadFailed": "Couldn't load your current KPIs."
+ },
+ "registry": {
+ "ai_visibility": {
+ "name": "AI Visibility",
+ "description": "Share of tracked prompts where your brand appears"
+ },
+ "citations": {
+ "name": "Citations",
+ "description": "Total citations across all AI responses"
+ },
+ "mentions": {
+ "name": "Mentions",
+ "description": "Brand mentions in AI responses"
+ },
+ "share_of_voice": {
+ "name": "Share of Voice",
+ "description": "Your share of brand mentions vs competitors"
+ },
+ "ai_referral_traffic": {
+ "name": "AI Referral Traffic",
+ "description": "Visits arriving from AI platforms"
+ }
+ },
+ "signalCategories": {
+ "visibility": "Visibility",
+ "citation": "Citation",
+ "mention": "Mention",
+ "traffic": "Traffic",
+ "technical": "Technical",
+ "competitor": "Competitor"
+ },
+ "signalsPage": {
+ "title": "Signals",
+ "subtitle": "Real-time signals from AI Search, your site, and the web. These signals drive your Action Center.",
+ "cards": {
+ "total": "Total Signals",
+ "important": "Important Signals",
+ "new": "New Signals",
+ "resolved": "Resolved Signals",
+ "avgImpact": "Avg. Signal Impact",
+ "noPrev": "no previous data",
+ "vsRange": "vs {range}",
+ "impactSame": "Same as previous {days} days",
+ "impactHigher": "Higher than previous {days} days",
+ "impactLower": "Lower than previous {days} days"
+ },
+ "allSignals": "All",
+ "filters": {
+ "impact": "Impact",
+ "status": "Status",
+ "source": "Source",
+ "all": "All",
+ "search": "Search signals…",
+ "clear": "Clear filters"
+ },
+ "table": {
+ "signal": "Signal",
+ "type": "Type",
+ "impact": "Impact",
+ "source": "Source",
+ "affected": "Affected",
+ "detected": "Detected",
+ "status": "Status",
+ "actions": "Actions"
+ },
+ "status": {
+ "new": "New",
+ "acknowledged": "Acknowledged",
+ "resolved": "Resolved",
+ "dismissed": "Dismissed"
+ },
+ "impact": {
+ "high": "High",
+ "medium": "Medium",
+ "low": "Low"
+ },
+ "sources": {
+ "ai_results": "AI Results",
+ "ga4": "Google Analytics 4",
+ "gsc": "Google Search Console",
+ "site_audit": "Site Audit"
+ },
+ "states": {
+ "dropped": "Dropped",
+ "gained": "Gained",
+ "lost": "Lost",
+ "opportunity": "Opportunity",
+ "gain": "Gain",
+ "overtaken": "Overtaken",
+ "crossed": "Crossed",
+ "uncited": "Uncited",
+ "issue": "Issue"
+ },
+ "affected": {
+ "prompts": "{count, plural, one {1 prompt} other {# prompts}}",
+ "urls": "{count, plural, one {1 URL} other {# URLs}}",
+ "platform": "1 platform",
+ "competitor": "1 competitor",
+ "allPrompts": "All prompts"
+ },
+ "menu": {
+ "label": "Actions for this signal",
+ "acknowledge": "Acknowledge",
+ "resolve": "Mark resolved",
+ "dismiss": "Dismiss",
+ "reopen": "Reopen"
+ },
+ "statusChangeFailed": "Couldn't update the signal.",
+ "empty": {
+ "title": "No signals yet",
+ "description": "Signals are detected after your daily tracking runs. Meaningful changes across visibility, citations, competitors and traffic will appear here."
+ },
+ "noResults": "No signals match these filters.",
+ "error": {
+ "title": "We couldn't load your signals.",
+ "retry": "Try again"
+ },
+ "noBrand": {
+ "title": "No brand selected",
+ "description": "Select a brand to view its signals."
+ },
+ "drawer": {
+ "whatChanged": "What changed",
+ "affected": "Affected",
+ "relatedKpis": "Related KPIs",
+ "detected": "Detected",
+ "lastDetected": "Last detected",
+ "source": "Source",
+ "status": "Status",
+ "viewPrompt": "View prompt"
+ }
+ },
+ "signalTexts": {
+ "sharp_drop": {
+ "title": "Visibility dropped sharply",
+ "description": "You were visible in {from}% of responses, now {to}%."
+ },
+ "prompt_gain": {
+ "title": "Visibility gained for “{prompt}”",
+ "description": "This prompt's visibility score rose {gain} points over the past week."
+ },
+ "new_engine": {
+ "title": "New AI platform appearance",
+ "description": "Your brand appeared on {platform} for the first time."
+ },
+ "lost_citations": {
+ "title": "Citations lost for “{prompt}”",
+ "description": "Your pages are no longer cited in answers to this prompt."
+ },
+ "first_citation": {
+ "title": "First citation for {url}",
+ "description": "“{prompt}” now cites this page for the first time."
+ },
+ "competitor_surge": {
+ "title": "{name} visibility surged",
+ "description": "Across your tracked prompts, their 7-day visibility score rose from {from}% to {to}%."
+ },
+ "competitor_crossed": {
+ "title": "{name} passed your visibility",
+ "description": "Across your tracked prompts, their 7-day visibility score is now {competitorRate}% while yours is {brandRate}%."
+ },
+ "competitor_overtaken": {
+ "title": "You overtook {name}",
+ "description": "Across your tracked prompts, your 7-day visibility score moved above theirs ({brandRate}% vs {competitorRate}%)."
+ },
+ "page_opportunity": {
+ "title": "High-value page without AI traffic",
+ "description": "{page} ranks #{rank} on your site by {signal} but receives no AI referrals."
+ },
+ "uncited_mentions": {
+ "title": "Brand mentioned without citation",
+ "description": "Your brand is mentioned but never cited in {count} prompts."
+ },
+ "audit_low_score": {
+ "title": "Audited pages score low on AEO readiness",
+ "description": "{count, plural, one {1 audited page scores} other {# audited pages score}} below 50/100."
+ }
+ },
+ "actionCategories": {
+ "growth": "Growth",
+ "protect": "Protect",
+ "recover": "Recover",
+ "fix": "Fix",
+ "compete": "Compete"
+ },
+ "actionsPage": {
+ "title": "Actions",
+ "subtitle": "Know what changed, what matters, and what to do next.",
+ "cards": {
+ "top": "Top Actions",
+ "topSub": "Highest priority right now",
+ "atRisk": "At Risk",
+ "atRiskSub": "Visibility or traffic declining",
+ "opportunities": "Opportunities",
+ "opportunitiesSub": "High potential to grow",
+ "inProgress": "In Progress",
+ "inProgressSub": "Actions currently running",
+ "impact": "Potential Impact",
+ "impactSub": "Across open actions"
+ },
+ "allActions": "All",
+ "filters": {
+ "impact": "Impact",
+ "status": "Status",
+ "assignee": "Assignee",
+ "all": "All",
+ "unassigned": "Unassigned",
+ "search": "Search actions…",
+ "clear": "Clear filters"
+ },
+ "sort": {
+ "label": "Sort",
+ "priority": "Priority",
+ "impact": "Impact",
+ "newest": "Newest",
+ "due_date": "Due date",
+ "updated": "Recently updated"
+ },
+ "table": {
+ "action": "Action",
+ "impact": "Impact",
+ "status": "Status",
+ "assignee": "Assignee",
+ "dueDate": "Due date",
+ "updated": "Updated",
+ "actions": "Actions"
+ },
+ "status": {
+ "new": "New",
+ "in_progress": "In Progress",
+ "completed": "Completed",
+ "on_hold": "On Hold",
+ "no_improvement": "No Improvement",
+ "dismissed": "Dismissed"
+ },
+ "impact": {
+ "high": "High",
+ "medium": "Medium",
+ "low": "Low"
+ },
+ "taskProgress": "{completed}/{total} tasks",
+ "tags": {
+ "signals": "{count, plural, one {1 signal} other {# signals}}",
+ "prompts": "{count, plural, one {1 prompt} other {# prompts}}",
+ "pages": "{count, plural, one {1 page} other {# pages}}"
+ },
+ "menu": {
+ "label": "Actions for this item"
+ },
+ "empty": {
+ "title": "No actions yet",
+ "description": "Actions are generated from your signals after daily tracking runs. When meaningful work emerges, it will appear here — quality over quantity."
+ },
+ "noResults": "No actions match these filters.",
+ "error": {
+ "title": "We couldn't load your actions.",
+ "retry": "Try again"
+ },
+ "noBrand": {
+ "title": "No brand selected",
+ "description": "Select a brand to view its actions."
+ },
+ "updateFailed": "Couldn't update the action.",
+ "drawer": {
+ "actionId": "Action ID",
+ "tabs": {
+ "overview": "Overview",
+ "tasks": "Tasks",
+ "signals": "Signals",
+ "history": "History"
+ },
+ "why": "Why this action?",
+ "goal": "Goal",
+ "kpis": "KPIs",
+ "kpiTarget": "target {target}",
+ "noKpis": "No configured KPIs are linked to this action.",
+ "primarySignals": "Primary signals",
+ "tasksProgress": "{completed} / {total} tasks completed",
+ "noSignals": "No linked signals.",
+ "assignee": "Assignee",
+ "assignTo": "Assign to teammate",
+ "dueDate": "Due date",
+ "statusLabel": "Status",
+ "events": {
+ "created": "Action created",
+ "reopened": "Action reopened — its condition is firing again",
+ "signals_linked": "{count, plural, one {1 new signal} other {# new signals}} linked",
+ "status_changed": "Status changed to {to}",
+ "assigned": "Assignee changed",
+ "due_date_set": "Due date updated",
+ "task_status": "Task updated"
+ }
+ }
+ },
+ "actionTexts": {
+ "recover_visibility": {
+ "title": "Recover lost visibility and citations",
+ "description": "Citations were lost across {prompts, plural, one {1 prompt} other {# prompts}}.",
+ "descriptionWithDrop": "Visibility dropped from {from}% to {to}%; citations lost across {prompts, plural, one {1 prompt} other {# prompts}}.",
+ "goal": "Recover and grow visibility and citations for the affected prompts."
+ },
+ "capture_ai_traffic": {
+ "title": "Capture AI traffic for {pages, plural, one {1 high-value page} other {# high-value pages}}",
+ "description": "Pages with strong business value receive no AI referrals.",
+ "goal": "Make these pages visible and cited in AI answers so they start earning AI referrals."
+ },
+ "convert_mentions": {
+ "title": "Convert mentions into citations",
+ "description": "Your brand is mentioned but never cited in {prompts, plural, one {1 prompt} other {# prompts}}.",
+ "goal": "Give AI engines something of yours to cite where you are already part of the answer."
+ },
+ "fix_low_scores": {
+ "title": "Fix low-scoring pages",
+ "description": "{pages, plural, one {1 audited page scores} other {# audited pages score}} below 50/100 on AEO readiness.",
+ "goal": "Bring the audited pages above the readiness bar."
+ },
+ "close_competitor_gap": {
+ "title": "Close the gap with {name}",
+ "titleMany": "Close the gap with competitors",
+ "description": "Competitor visibility moved sharply against you across your tracked prompts.",
+ "goal": "Regain the visibility position lost to competitors."
+ }
+ },
+ "actionTasks": {
+ "analyze_losses": "Analyze lost citations and competitor sources",
+ "coverage_gaps": "Identify missing topic and entity coverage",
+ "update_content": "Update the target pages' content",
+ "internal_links": "Strengthen internal linking to affected pages",
+ "validate": "Validate across AI platforms",
+ "review_pages": "Review the affected high-value pages",
+ "optimize_content": "Optimize content for AI answer inclusion",
+ "identify_prompts": "Identify the prompts mentioning you without citation",
+ "create_citable_content": "Create or improve citable source content",
+ "strengthen_sources": "Strengthen the pages AI engines could cite",
+ "review_audits": "Review the failing audit findings",
+ "fix_issues": "Fix the highest-impact issues first",
+ "revalidate": "Re-run the audits to confirm the fixes",
+ "analyze_competitor": "Analyze what the competitor gained visibility with",
+ "strengthen_content": "Strengthen your content where they now win"
+ },
+ "taskStatus": {
+ "todo": "To Do",
+ "in_progress": "In Progress",
+ "completed": "Completed",
+ "blocked": "Blocked"
+ }
+ },
"agent": {
"newChat": "New chat",
"noConversations": "No conversations yet.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx
new file mode 100644
index 000000000..7d21f0386
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx
@@ -0,0 +1,478 @@
+'use client';
+
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import {
+ AlertCircle,
+ ArrowUpDown,
+ CircleDot,
+ ListChecks,
+ Search,
+ Shield,
+ Sparkles,
+ TrendingUp,
+ X,
+} from 'lucide-react';
+import { useBrandStore } from '@/stores/use-brand-store';
+import type { Brand } from '@/types';
+import { getActions, type ActionItem } from '@/lib/actions/action-center';
+import { listMembers, type TeamMember } from '@/lib/actions/team';
+import {
+ ACTION_CATEGORIES,
+ ACTION_IMPACTS,
+ ACTION_SORTS,
+ ACTION_STATUSES,
+ type ActionCategory,
+ type ActionImpact,
+ type ActionSort,
+ type ActionStatus,
+} from '@/lib/action-center/registry';
+import { actionContextTags, actionTexts, comparePriority } from '@/lib/action-center/display';
+import { ActionCenterTabs } from '@/components/action-center/action-center-tabs';
+import { ActionTable } from '@/components/action-center/action-table';
+import { ActionDrawer } from '@/components/action-center/action-drawer';
+import { Button } from '@/components/ui/button';
+import { Card, CardContent } from '@/components/ui/card';
+import { Input } from '@/components/ui/input';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { Skeleton } from '@/components/ui/skeleton';
+import { cn } from '@/lib/utils';
+
+const OPEN_STATUSES: ActionStatus[] = ['new', 'in_progress', 'on_hold', 'no_improvement'];
+
+export default function ActionCenterActionsPage() {
+ const brand = useBrandStore((s) => s.getActiveBrand());
+ const t = useTranslations('actionCenter.actionsPage');
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>
+ </div>
+ <ActionCenterTabs />
+ {brand ? (
+ <ActionsContent key={brand.id} brand={brand} />
+ ) : (
+ <div className="flex flex-col items-center justify-center py-20 text-center">
+ <h2 className="text-lg font-semibold">{t('noBrand.title')}</h2>
+ <p className="mt-1 text-sm text-muted-foreground">{t('noBrand.description')}</p>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ActionsContent({ brand }: { brand: Brand }) {
+ const t = useTranslations('actionCenter.actionsPage');
+ const tTexts = useTranslations('actionCenter.actionTexts');
+ const tCategories = useTranslations('actionCenter.actionCategories');
+
+ const [actions, setActions] = useState<ActionItem[] | null>(null);
+ const [members, setMembers] = useState<TeamMember[]>([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [loadFailed, setLoadFailed] = useState(false);
+
+ const [category, setCategory] = useState<ActionCategory | 'all'>('all');
+ const [impact, setImpact] = useState<ActionImpact | 'all'>('all');
+ const [status, setStatus] = useState<ActionStatus | 'all'>('all');
+ const [assignee, setAssignee] = useState<string>('all');
+ const [sort, setSort] = useState<ActionSort>('priority');
+ const [search, setSearch] = useState('');
+
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+
+ // The open drawer lives in the URL (?action=<id>) so that coming BACK from
+ // a signal's page — or refreshing — restores it. replaceState, not push:
+ // opening and closing the drawer must not grow the history stack.
+ const selectAction = (id: string | null) => {
+ setSelectedId(id);
+ const params = new URLSearchParams(window.location.search);
+ if (id) params.set('action', id);
+ else params.delete('action');
+ const query = params.toString();
+ window.history.replaceState(null, '', window.location.pathname + (query ? `?${query}` : ''));
+ };
+
+ const load = useCallback(async () => {
+ setLoadFailed(false);
+ try {
+ setActions(await getActions(brand.id));
+ } catch {
+ setLoadFailed(true);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [brand.id]);
+
+ useEffect(() => {
+ void load();
+ listMembers()
+ .then(setMembers)
+ .catch(() => setMembers([]));
+ }, [load]);
+
+ // Restore the drawer named by the URL once the list is in.
+ useEffect(() => {
+ if (!actions) return;
+ const id = new URLSearchParams(window.location.search).get('action');
+ if (id && actions.some((action) => action.id === id)) setSelectedId(id);
+ }, [actions]);
+
+ const selected = useMemo(
+ () => (actions ?? []).find((action) => action.id === selectedId) ?? null,
+ [actions, selectedId],
+ );
+
+ const visible = useMemo(() => {
+ const needle = search.trim().toLowerCase();
+ const filtered = (actions ?? []).filter((action) => {
+ if (category !== 'all' && action.category !== category) return false;
+ if (impact !== 'all' && action.impact !== impact) return false;
+ if (status !== 'all' && action.status !== status) return false;
+ if (assignee !== 'all') {
+ if (assignee === 'unassigned' ? action.assignee !== null : action.assignee?.id !== assignee)
+ return false;
+ }
+ if (needle) {
+ const texts = actionTexts(action, tTexts);
+ const tags = actionContextTags(action, t).join(' ');
+ if (!`${texts.title} ${texts.description} ${tags}`.toLowerCase().includes(needle))
+ return false;
+ }
+ return true;
+ });
+ return filtered.sort((a, b) => {
+ switch (sort) {
+ case 'impact':
+ return comparePriority(a, b);
+ case 'newest':
+ return b.createdAt.localeCompare(a.createdAt);
+ case 'due_date':
+ return (a.dueDate ?? '9999').localeCompare(b.dueDate ?? '9999');
+ case 'updated':
+ return b.updatedAt.localeCompare(a.updatedAt);
+ default:
+ return comparePriority(a, b);
+ }
+ });
+ }, [actions, category, impact, status, assignee, search, sort, tTexts, t]);
+
+ const categoryCounts = useMemo(() => {
+ const counts = new Map<ActionCategory, number>();
+ for (const action of actions ?? []) {
+ counts.set(action.category, (counts.get(action.category) ?? 0) + 1);
+ }
+ return counts;
+ }, [actions]);
+
+ const summary = useMemo(() => {
+ const open = (actions ?? []).filter((action) => OPEN_STATUSES.includes(action.status));
+ const impacts = open.map((action) => action.impact);
+ return {
+ top: open.filter((action) => action.impact === 'high').length,
+ atRisk: open.filter((action) => action.category === 'recover' || action.category === 'fix')
+ .length,
+ opportunities: open.filter((action) => action.category === 'growth').length,
+ inProgress: (actions ?? []).filter((action) => action.status === 'in_progress').length,
+ potential: impacts.includes('high') ? 'high' : impacts.includes('medium') ? 'medium' : 'low',
+ hasOpen: open.length > 0,
+ };
+ }, [actions]);
+
+ const hasActiveFilters =
+ category !== 'all' ||
+ impact !== 'all' ||
+ status !== 'all' ||
+ assignee !== 'all' ||
+ search !== '';
+
+ const clearFilters = () => {
+ setCategory('all');
+ setImpact('all');
+ setStatus('all');
+ setAssignee('all');
+ setSearch('');
+ };
+
+ if (isLoading) {
+ return (
+ <div className="space-y-4">
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
+ {[0, 1, 2, 3, 4].map((i) => (
+ <Skeleton key={i} className="h-24 w-full" />
+ ))}
+ </div>
+ <div className="space-y-2 rounded-lg border p-4">
+ {[0, 1, 2].map((i) => (
+ <Skeleton key={i} className="h-16 w-full" />
+ ))}
+ </div>
+ </div>
+ );
+ }
+
+ if (loadFailed) {
+ return (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">
+ <AlertCircle className="h-8 w-8 text-muted-foreground" />
+ <h2 className="mt-4 font-semibold">{t('error.title')}</h2>
+ <Button variant="outline" className="mt-4" onClick={() => void load()}>
+ {t('error.retry')}
+ </Button>
+ </div>
+ );
+ }
+
+ if (!actions?.length) {
+ return (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">
+ <ListChecks className="h-8 w-8 text-muted-foreground" />
+ <h2 className="mt-4 font-semibold">{t('empty.title')}</h2>
+ <p className="mt-1 max-w-md text-sm text-muted-foreground">{t('empty.description')}</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
+ <SummaryCard
+ icon={CircleDot}
+ label={t('cards.top')}
+ value={summary.top}
+ sub={t('cards.topSub')}
+ />
+ <SummaryCard
+ icon={Shield}
+ label={t('cards.atRisk')}
+ value={summary.atRisk}
+ sub={t('cards.atRiskSub')}
+ />
+ <SummaryCard
+ icon={Sparkles}
+ label={t('cards.opportunities')}
+ value={summary.opportunities}
+ sub={t('cards.opportunitiesSub')}
+ />
+ <SummaryCard
+ icon={ArrowUpDown}
+ label={t('cards.inProgress')}
+ value={summary.inProgress}
+ sub={t('cards.inProgressSub')}
+ />
+ <Card>
+ <CardContent className="p-4">
+ <div className="flex items-center gap-2">
+ <div className="flex h-7 w-7 items-center justify-center rounded-md border bg-muted/40">
+ <TrendingUp className="h-3.5 w-3.5 text-muted-foreground" />
+ </div>
+ <p className="text-xs font-medium text-muted-foreground">{t('cards.impact')}</p>
+ </div>
+ <p className="mt-2 text-2xl font-bold">
+ {summary.hasOpen ? t(`impact.${summary.potential}`) : '—'}
+ </p>
+ <p className="mt-0.5 text-xs text-muted-foreground">{t('cards.impactSub')}</p>
+ </CardContent>
+ </Card>
+ </div>
+
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <CategoryPill
+ label={t('allActions')}
+ count={actions.length}
+ isActive={category === 'all'}
+ onClick={() => setCategory('all')}
+ />
+ {ACTION_CATEGORIES.filter((key) => (categoryCounts.get(key) ?? 0) > 0).map((key) => (
+ <CategoryPill
+ key={key}
+ label={tCategories(key)}
+ count={categoryCounts.get(key) ?? 0}
+ isActive={category === key}
+ onClick={() => setCategory(key)}
+ />
+ ))}
+ </div>
+ <Select
+ value={sort}
+ onValueChange={(v) => setSort((v ?? 'priority') as ActionSort)}
+ items={ACTION_SORTS.map((key) => ({ value: key, label: t(`sort.${key}`) }))}
+ >
+ <SelectTrigger className="h-8 w-44 text-xs">
+ <span className="text-muted-foreground">{t('sort.label')}:</span>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {ACTION_SORTS.map((key) => (
+ <SelectItem key={key} value={key}>
+ {t(`sort.${key}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <FilterSelect
+ label={t('filters.impact')}
+ value={impact}
+ onChange={(v) => setImpact(v as ActionImpact | 'all')}
+ options={ACTION_IMPACTS.map((v) => ({ value: v, label: t(`impact.${v}`) }))}
+ allLabel={t('filters.all')}
+ />
+ <FilterSelect
+ label={t('filters.status')}
+ value={status}
+ onChange={(v) => setStatus(v as ActionStatus | 'all')}
+ options={ACTION_STATUSES.map((v) => ({ value: v, label: t(`status.${v}`) }))}
+ allLabel={t('filters.all')}
+ />
+ <FilterSelect
+ label={t('filters.assignee')}
+ value={assignee}
+ onChange={setAssignee}
+ options={[
+ { value: 'unassigned', label: t('filters.unassigned') },
+ ...members.map((member) => ({
+ value: member.userId,
+ label: member.fullName ?? member.userId.slice(0, 8),
+ })),
+ ]}
+ allLabel={t('filters.all')}
+ />
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={t('filters.search')}
+ className="h-8 w-56 pl-8 text-xs"
+ />
+ </div>
+ {hasActiveFilters && (
+ <Button variant="ghost" size="sm" className="text-xs" onClick={clearFilters}>
+ <X className="h-3.5 w-3.5" />
+ {t('filters.clear')}
+ </Button>
+ )}
+ </div>
+
+ {visible.length > 0 ? (
+ <ActionTable actions={visible} onSelect={(action) => selectAction(action.id)} />
+ ) : (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16 text-center">
+ <p className="text-sm text-muted-foreground">{t('noResults')}</p>
+ <Button variant="outline" size="sm" className="mt-3" onClick={clearFilters}>
+ {t('filters.clear')}
+ </Button>
+ </div>
+ )}
+
+ <ActionDrawer
+ brandId={brand.id}
+ action={selected}
+ members={members}
+ onOpenChange={(open) => {
+ if (!open) selectAction(null);
+ }}
+ onChanged={() => void load()}
+ />
+ </div>
+ );
+}
+
+function SummaryCard({
+ icon: Icon,
+ label,
+ value,
+ sub,
+}: {
+ icon: React.ComponentType<{ className?: string }>;
+ label: string;
+ value: number;
+ sub: string;
+}) {
+ return (
+ <Card>
+ <CardContent className="p-4">
+ <div className="flex items-center gap-2">
+ <div className="flex h-7 w-7 items-center justify-center rounded-md border bg-muted/40">
+ <Icon className="h-3.5 w-3.5 text-muted-foreground" />
+ </div>
+ <p className="text-xs font-medium text-muted-foreground">{label}</p>
+ </div>
+ <p className="mt-2 text-2xl font-bold tabular-nums">{value}</p>
+ <p className="mt-0.5 text-xs text-muted-foreground">{sub}</p>
+ </CardContent>
+ </Card>
+ );
+}
+
+function FilterSelect({
+ label,
+ value,
+ onChange,
+ options,
+ allLabel,
+}: {
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ options: { value: string; label: string }[];
+ allLabel: string;
+}) {
+ const items = [{ value: 'all', label: allLabel }, ...options];
+ return (
+ <Select value={value} onValueChange={(v) => onChange(v ?? 'all')} items={items}>
+ <SelectTrigger className="h-8 w-36 text-xs">
+ <span className="text-muted-foreground">{label}:</span>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{allLabel}</SelectItem>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+function CategoryPill({
+ label,
+ count,
+ isActive,
+ onClick,
+}: {
+ label: string;
+ count: number;
+ isActive: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-pressed={isActive}
+ className={cn(
+ 'flex h-8 items-center gap-1.5 rounded-md border px-3 text-xs font-medium transition-colors',
+ isActive
+ ? 'border-foreground/20 bg-muted text-foreground'
+ : 'text-muted-foreground hover:bg-muted/50 hover:text-foreground',
+ )}
+ >
+ {label}
+ <span className="text-xs text-muted-foreground">{count}</span>
+ </button>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx
new file mode 100644
index 000000000..4e191c260
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx
@@ -0,0 +1,5 @@
+import { ComingSoonPage } from '@/components/action-center/coming-soon-page';
+
+export default function ActionCenterHistoryPage() {
+ return <ComingSoonPage tab="history" />;
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsx
new file mode 100644
index 000000000..abdc46155
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsx
@@ -0,0 +1,340 @@
+'use client';
+
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { AlertCircle, ListFilter, Plus, Settings2, Target } from 'lucide-react';
+import { useBrandStore } from '@/stores/use-brand-store';
+import type { Brand } from '@/types';
+import {
+ getKpiSnapshots,
+ removeKpi,
+ type KpiSnapshotsResult,
+ type KpiWindow,
+} from '@/lib/actions/kpis';
+import type { KpiCategory, KpiKey } from '@/lib/kpis/registry';
+import type { KpiStatus } from '@/lib/kpis/status';
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { ActionCenterTabs } from '@/components/action-center/action-center-tabs';
+import { KpiFrameworkDrawer } from '@/components/action-center/kpi-framework-drawer';
+import { KpiTable } from '@/components/action-center/kpi-table';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import { cn } from '@/lib/utils';
+
+type KpiDatePreset = '7d' | '30d' | '90d';
+const KPI_DATE_PRESETS: readonly KpiDatePreset[] = ['7d', '30d', '90d'];
+const PRESET_DAYS: Record<KpiDatePreset, number> = { '7d': 7, '30d': 30, '90d': 90 };
+const KPI_STATUSES: readonly KpiStatus[] = ['on_track', 'at_risk', 'off_track', 'goal_reached'];
+const DAY_MS = 86_400_000;
+
+function utcDay(offset = 0): string {
+ return new Date(Date.now() - offset * DAY_MS).toISOString().slice(0, 10);
+}
+
+export default function ActionCenterKpisPage() {
+ const brand = useBrandStore((s) => s.getActiveBrand());
+ const t = useTranslations('actionCenter.kpis');
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>
+ </div>
+ <ActionCenterTabs />
+ {brand ? (
+ <KpisContent key={brand.id} brand={brand} />
+ ) : (
+ <div className="flex flex-col items-center justify-center py-20 text-center">
+ <h2 className="text-lg font-semibold">{t('noBrand.title')}</h2>
+ <p className="mt-1 text-sm text-muted-foreground">{t('noBrand.description')}</p>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function KpisContent({ brand }: { brand: Brand }) {
+ const t = useTranslations('actionCenter.kpis');
+ const tCategories = useTranslations('actionCenter.categories');
+
+ const [result, setResult] = useState<KpiSnapshotsResult | null>(null);
+ const [isLoading, setIsLoading] = useState(true);
+ const [loadFailed, setLoadFailed] = useState(false);
+ const [category, setCategory] = useState<KpiCategory | 'all'>('all');
+ const [busyKey, setBusyKey] = useState<KpiKey | null>(null);
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const [editKey, setEditKey] = useState<KpiKey | null>(null);
+ const [datePreset, setDatePreset] = useState<KpiDatePreset>('30d');
+ const [statusFilter, setStatusFilter] = useState<Set<KpiStatus>>(new Set());
+
+ const window = useMemo<KpiWindow>(() => {
+ const days = PRESET_DAYS[datePreset];
+ return { dayFrom: utcDay(days - 1), dayTo: utcDay() };
+ }, [datePreset]);
+
+ const openDrawer = (key: KpiKey | null = null) => {
+ setEditKey(key);
+ setIsDrawerOpen(true);
+ };
+
+ const load = useCallback(async () => {
+ setIsLoading(true);
+ setLoadFailed(false);
+ try {
+ setResult(await getKpiSnapshots(brand.id, window));
+ } catch {
+ setLoadFailed(true);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [brand.id, window]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const kpis = useMemo(() => result?.kpis ?? [], [result]);
+ const categories = useMemo(() => {
+ const counts = new Map<KpiCategory, number>();
+ for (const kpi of kpis) counts.set(kpi.category, (counts.get(kpi.category) ?? 0) + 1);
+ return [...counts.entries()];
+ }, [kpis]);
+ const visible = kpis.filter(
+ (k) =>
+ (category === 'all' || k.category === category) &&
+ (statusFilter.size === 0 || statusFilter.has(k.status)),
+ );
+
+ const toggleStatus = (status: KpiStatus) => {
+ setStatusFilter((prev) => {
+ const next = new Set(prev);
+ if (next.has(status)) next.delete(status);
+ else next.add(status);
+ return next;
+ });
+ };
+
+ const handleRemove = async (key: KpiKey) => {
+ setBusyKey(key);
+ try {
+ await removeKpi(brand.id, key);
+ await load();
+ } catch {
+ toast.error(t('removeFailed'));
+ } finally {
+ setBusyKey(null);
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <div className="space-y-3">
+ <div className="flex gap-2">
+ {[0, 1, 2].map((i) => (
+ <Skeleton key={i} className="h-8 w-24" />
+ ))}
+ </div>
+ <div className="space-y-2 rounded-lg border p-4">
+ {[0, 1, 2, 3, 4].map((i) => (
+ <Skeleton key={i} className="h-14 w-full" />
+ ))}
+ </div>
+ </div>
+ );
+ }
+
+ if (loadFailed) {
+ return (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">
+ <AlertCircle className="h-8 w-8 text-muted-foreground" />
+ <h2 className="mt-4 font-semibold">{t('error.title')}</h2>
+ <Button variant="outline" className="mt-4" onClick={() => void load()}>
+ {t('error.retry')}
+ </Button>
+ </div>
+ );
+ }
+
+ const drawer = (
+ <KpiFrameworkDrawer
+ brandId={brand.id}
+ open={isDrawerOpen}
+ onOpenChange={setIsDrawerOpen}
+ onSaved={() => void load()}
+ focusKpi={editKey}
+ />
+ );
+
+ if (!result?.configured) {
+ return (
+ <>
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">
+ <Target className="h-8 w-8 text-muted-foreground" />
+ <h2 className="mt-4 font-semibold">{t('empty.title')}</h2>
+ <p className="mt-1 max-w-md text-sm text-muted-foreground">{t('empty.description')}</p>
+ <Button className="mt-4" onClick={() => openDrawer()}>
+ <Plus className="h-4 w-4" />
+ {t('empty.cta')}
+ </Button>
+ </div>
+ {drawer}
+ </>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <CategoryPill
+ label={t('allKpis')}
+ count={kpis.length}
+ isActive={category === 'all'}
+ onClick={() => setCategory('all')}
+ />
+ {categories.map(([key, count]) => (
+ <CategoryPill
+ key={key}
+ label={tCategories(key)}
+ count={count}
+ isActive={category === key}
+ onClick={() => setCategory(key)}
+ />
+ ))}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className={cn(
+ 'flex h-8 items-center gap-1.5 rounded-md border px-3 text-xs font-medium transition-colors hover:bg-muted/50',
+ statusFilter.size > 0 && 'border-foreground/30 bg-muted',
+ )}
+ >
+ <ListFilter className="h-3.5 w-3.5" />
+ {t('filters')}
+ {statusFilter.size > 0 && (
+ <span className="text-xs text-muted-foreground">{statusFilter.size}</span>
+ )}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>{t('table.status')}</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ {KPI_STATUSES.map((status) => (
+ <DropdownMenuCheckboxItem
+ key={status}
+ checked={statusFilter.has(status)}
+ onCheckedChange={() => toggleStatus(status)}
+ >
+ {t(`status.${status}`)}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <div
+ className="flex h-8 overflow-hidden rounded-md border"
+ role="group"
+ aria-label={t('dateRangeAria')}
+ >
+ {KPI_DATE_PRESETS.map((preset) => (
+ <button
+ key={preset}
+ type="button"
+ onClick={() => setDatePreset(preset)}
+ aria-pressed={datePreset === preset}
+ className={cn(
+ 'px-3 text-xs font-medium transition-colors',
+ datePreset === preset
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-card text-foreground hover:bg-muted',
+ )}
+ >
+ {preset}
+ </button>
+ ))}
+ </div>
+ <Button variant="outline" size="sm" className="text-xs" onClick={() => openDrawer()}>
+ <Settings2 className="h-3.5 w-3.5" />
+ {t('editKpis')}
+ </Button>
+ <Button size="sm" className="text-xs" onClick={() => openDrawer()}>
+ <Plus className="h-3.5 w-3.5" />
+ {t('addKpi')}
+ </Button>
+ </div>
+ </div>
+
+ {visible.length > 0 ? (
+ <KpiTable
+ kpis={visible}
+ onEdit={(key) => openDrawer(key)}
+ onRemove={(key) => void handleRemove(key)}
+ busyKey={busyKey}
+ />
+ ) : kpis.length > 0 ? (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16 text-center">
+ <p className="text-sm text-muted-foreground">{t('noResults')}</p>
+ <Button
+ variant="outline"
+ size="sm"
+ className="mt-3"
+ onClick={() => {
+ setCategory('all');
+ setStatusFilter(new Set());
+ }}
+ >
+ {t('clearFilter')}
+ </Button>
+ </div>
+ ) : (
+ // Configured but nothing active/computable — distinct from the
+ // never-configured empty state.
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16 text-center">
+ <p className="text-sm text-muted-foreground">{t('allInactive')}</p>
+ <Button variant="outline" size="sm" className="mt-3" onClick={() => openDrawer()}>
+ {t('editKpis')}
+ </Button>
+ </div>
+ )}
+
+ {drawer}
+ </div>
+ );
+}
+
+function CategoryPill({
+ label,
+ count,
+ isActive,
+ onClick,
+}: {
+ label: string;
+ count: number;
+ isActive: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-pressed={isActive}
+ className={cn(
+ 'flex h-8 items-center gap-1.5 rounded-md border px-3 text-xs font-medium transition-colors',
+ isActive
+ ? 'border-foreground/20 bg-muted text-foreground'
+ : 'text-muted-foreground hover:bg-muted/50 hover:text-foreground',
+ )}
+ >
+ {label}
+ <span className="text-xs text-muted-foreground">{count}</span>
+ </button>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/page.tsx
new file mode 100644
index 000000000..8d23500b7
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/page.tsx
@@ -0,0 +1,5 @@
+import { redirect } from 'next/navigation';
+
+export default function ActionCenterPage() {
+ redirect('/dashboard/action-center/kpis');
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx
new file mode 100644
index 000000000..988e0fbde
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/signals/page.tsx
@@ -0,0 +1,569 @@
+'use client';
+
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import dynamic from 'next/dynamic';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { AlertCircle, Radar, Search, TrendingDown, TrendingUp, X } from 'lucide-react';
+import { useBrandStore } from '@/stores/use-brand-store';
+import type { Brand } from '@/types';
+import {
+ getSignals,
+ getSignalsSummary,
+ updateSignalStatus,
+ type Signal,
+ type SignalsSummary,
+} from '@/lib/actions/signals';
+import {
+ SIGNAL_CATEGORIES,
+ SIGNAL_IMPACTS,
+ SIGNAL_SOURCES,
+ SIGNAL_STATUSES,
+ type SignalCategory,
+ type SignalImpact,
+ type SignalSource,
+ type SignalStatus,
+} from '@/lib/signals/registry';
+import { signalAffected, signalTexts } from '@/lib/signals/display';
+import { ActionCenterTabs } from '@/components/action-center/action-center-tabs';
+import { SignalTable } from '@/components/action-center/signal-table';
+import { SignalDrawer } from '@/components/action-center/signal-drawer';
+import { Button } from '@/components/ui/button';
+import { Card, CardContent } from '@/components/ui/card';
+import { Input } from '@/components/ui/input';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { Skeleton } from '@/components/ui/skeleton';
+import { cn } from '@/lib/utils';
+import type { KpiTrendPoint } from '@/lib/actions/kpis';
+
+const KpiSparkline = dynamic(() => import('@/components/action-center/kpi-sparkline'), {
+ ssr: false,
+ loading: () => <Skeleton className="h-8 w-[110px]" />,
+});
+
+type SignalDatePreset = '7d' | '30d' | '90d';
+const DATE_PRESETS: readonly SignalDatePreset[] = ['7d', '30d', '90d'];
+const PRESET_DAYS: Record<SignalDatePreset, number> = { '7d': 7, '30d': 30, '90d': 90 };
+const DAY_MS = 86_400_000;
+
+function utcDay(offset = 0): string {
+ return new Date(Date.now() - offset * DAY_MS).toISOString().slice(0, 10);
+}
+
+export default function ActionCenterSignalsPage() {
+ const brand = useBrandStore((s) => s.getActiveBrand());
+ const t = useTranslations('actionCenter.signalsPage');
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>
+ </div>
+ <ActionCenterTabs />
+ {brand ? (
+ <SignalsContent key={brand.id} brand={brand} />
+ ) : (
+ <div className="flex flex-col items-center justify-center py-20 text-center">
+ <h2 className="text-lg font-semibold">{t('noBrand.title')}</h2>
+ <p className="mt-1 text-sm text-muted-foreground">{t('noBrand.description')}</p>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function SignalsContent({ brand }: { brand: Brand }) {
+ const t = useTranslations('actionCenter.signalsPage');
+ const tTexts = useTranslations('actionCenter.signalTexts');
+ const tCategories = useTranslations('actionCenter.signalCategories');
+
+ const [signals, setSignals] = useState<Signal[] | null>(null);
+ const [summary, setSummary] = useState<SignalsSummary | null>(null);
+ const [isLoading, setIsLoading] = useState(true);
+ const [loadFailed, setLoadFailed] = useState(false);
+
+ const [datePreset, setDatePreset] = useState<SignalDatePreset>('30d');
+ const [category, setCategory] = useState<SignalCategory | 'all'>('all');
+ const [impact, setImpact] = useState<SignalImpact | 'all'>('all');
+ const [status, setStatus] = useState<SignalStatus | 'all'>('all');
+ const [source, setSource] = useState<SignalSource | 'all'>('all');
+ const [search, setSearch] = useState('');
+
+ const [selected, setSelected] = useState<Signal | null>(null);
+ const [busyId, setBusyId] = useState<string | null>(null);
+
+ // The open drawer lives in the URL (?signal=<id>), mirroring the Actions
+ // page: back from a prompt page — or a refresh — restores it, and the
+ // action drawer's evidence links land here with the drawer already open.
+ const selectSignal = (signal: Signal | null) => {
+ setSelected(signal);
+ const params = new URLSearchParams(window.location.search);
+ if (signal) params.set('signal', signal.id);
+ else params.delete('signal');
+ const query = params.toString();
+ window.history.replaceState(null, '', window.location.pathname + (query ? `?${query}` : ''));
+ };
+
+ const windowDays = PRESET_DAYS[datePreset];
+ const dayFrom = utcDay(windowDays - 1);
+ const dayTo = utcDay();
+
+ const load = useCallback(async () => {
+ setIsLoading(true);
+ setLoadFailed(false);
+ try {
+ const [rows, sums] = await Promise.all([
+ getSignals(brand.id, { dayFrom, dayTo }),
+ getSignalsSummary(brand.id, dayFrom, dayTo),
+ ]);
+ setSignals(rows);
+ setSummary(sums);
+ } catch {
+ setLoadFailed(true);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [brand.id, dayFrom, dayTo]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ // Restore the drawer named by the URL once the list is in. Read via
+ // window.location rather than useSearchParams to keep the page out of a
+ // Suspense boundary; the param stays while the drawer is open.
+ useEffect(() => {
+ if (!signals) return;
+ const signalId = new URLSearchParams(window.location.search).get('signal');
+ if (!signalId) return;
+ const match = signals.find((signal) => signal.id === signalId);
+ if (match) setSelected(match);
+ }, [signals]);
+
+ // Category/impact/status/source/search all narrow client-side: the whole
+ // window is already loaded (per-brand signal counts are tens), and search
+ // must match the composed titles, which only exist here.
+ const visible = useMemo(() => {
+ const needle = search.trim().toLowerCase();
+ return (signals ?? []).filter((signal) => {
+ if (category !== 'all' && signal.category !== category) return false;
+ if (impact !== 'all' && signal.impact !== impact) return false;
+ if (status !== 'all' && signal.status !== status) return false;
+ if (source !== 'all' && !signal.source.includes(source)) return false;
+ if (needle) {
+ const texts = signalTexts(signal, tTexts);
+ const affected = signalAffected(signal, t);
+ const haystack =
+ `${texts.title} ${texts.description} ${affected.detail ?? ''}`.toLowerCase();
+ if (!haystack.includes(needle)) return false;
+ }
+ return true;
+ });
+ }, [signals, category, impact, status, source, search, tTexts, t]);
+
+ const categoryCounts = useMemo(() => {
+ const counts = new Map<SignalCategory, number>();
+ for (const signal of signals ?? []) {
+ counts.set(signal.category, (counts.get(signal.category) ?? 0) + 1);
+ }
+ return counts;
+ }, [signals]);
+
+ // One sparkline series per card, over the window's days (capped at 30
+ // points so 90d stays legible at sparkline size).
+ const sparkSeries = useCallback(
+ (byDay: Record<string, number>): KpiTrendPoint[] => {
+ const points = Math.min(windowDays, 30);
+ return Array.from({ length: points }, (_, i) => {
+ const day = utcDay(points - 1 - i);
+ return { date: day, value: byDay[day] ?? 0 };
+ });
+ },
+ [windowDays],
+ );
+
+ // "vs Aug 20 – Aug 26" — the previous equal-length window, spelled out
+ // like the mockup rather than as a relative phrase.
+ const prevRangeLabel = useMemo(() => {
+ const fmt = (day: string) =>
+ new Date(`${day}T00:00:00Z`).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ timeZone: 'UTC',
+ });
+ return `${fmt(utcDay(windowDays * 2 - 1))} – ${fmt(utcDay(windowDays))}`;
+ }, [windowDays]);
+
+ const hasActiveFilters =
+ category !== 'all' || impact !== 'all' || status !== 'all' || source !== 'all' || search !== '';
+
+ const clearFilters = () => {
+ setCategory('all');
+ setImpact('all');
+ setStatus('all');
+ setSource('all');
+ setSearch('');
+ };
+
+ const handleStatusChange = async (signal: Signal, nextStatus: SignalStatus) => {
+ setBusyId(signal.id);
+ try {
+ await updateSignalStatus(brand.id, signal.id, nextStatus);
+ const patch = (s: Signal) =>
+ s.id === signal.id
+ ? {
+ ...s,
+ status: nextStatus,
+ resolvedAt: nextStatus === 'resolved' ? new Date().toISOString() : null,
+ }
+ : s;
+ setSignals((prev) => (prev ?? []).map(patch));
+ setSelected((prev) => (prev && prev.id === signal.id ? patch(prev) : prev));
+ } catch {
+ toast.error(t('statusChangeFailed'));
+ } finally {
+ setBusyId(null);
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <div className="space-y-4">
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
+ {[0, 1, 2, 3, 4].map((i) => (
+ <Skeleton key={i} className="h-24 w-full" />
+ ))}
+ </div>
+ <div className="space-y-2 rounded-lg border p-4">
+ {[0, 1, 2, 3, 4, 5].map((i) => (
+ <Skeleton key={i} className="h-12 w-full" />
+ ))}
+ </div>
+ </div>
+ );
+ }
+
+ if (loadFailed) {
+ return (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">
+ <AlertCircle className="h-8 w-8 text-muted-foreground" />
+ <h2 className="mt-4 font-semibold">{t('error.title')}</h2>
+ <Button variant="outline" className="mt-4" onClick={() => void load()}>
+ {t('error.retry')}
+ </Button>
+ </div>
+ );
+ }
+
+ if (!signals?.length && !hasActiveFilters) {
+ return (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">
+ <Radar className="h-8 w-8 text-muted-foreground" />
+ <h2 className="mt-4 font-semibold">{t('empty.title')}</h2>
+ <p className="mt-1 max-w-md text-sm text-muted-foreground">{t('empty.description')}</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ {summary && (
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
+ <SummaryCard
+ label={t('cards.total')}
+ value={summary.total}
+ prev={summary.prevTotal}
+ rangeLabel={prevRangeLabel}
+ spark={sparkSeries(summary.byDayActive)}
+ />
+ <SummaryCard
+ label={t('cards.important')}
+ value={summary.important}
+ prev={summary.prevImportant}
+ rangeLabel={prevRangeLabel}
+ spark={sparkSeries(summary.byDayImportant)}
+ />
+ <SummaryCard
+ label={t('cards.new')}
+ value={summary.newCount}
+ prev={summary.prevNew}
+ rangeLabel={prevRangeLabel}
+ spark={sparkSeries(summary.byDayNew)}
+ />
+ <SummaryCard
+ label={t('cards.resolved')}
+ value={summary.resolved}
+ prev={summary.prevResolved}
+ rangeLabel={prevRangeLabel}
+ spark={sparkSeries(summary.byDayResolved)}
+ />
+ <AvgImpactCard summary={summary} days={windowDays} />
+ </div>
+ )}
+
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <CategoryPill
+ label={t('allSignals')}
+ count={signals?.length ?? 0}
+ isActive={category === 'all'}
+ onClick={() => setCategory('all')}
+ />
+ {SIGNAL_CATEGORIES.filter((key) => (categoryCounts.get(key) ?? 0) > 0).map((key) => (
+ <CategoryPill
+ key={key}
+ label={tCategories(key)}
+ count={categoryCounts.get(key) ?? 0}
+ isActive={category === key}
+ onClick={() => setCategory(key)}
+ />
+ ))}
+ </div>
+ <div
+ className="flex h-8 overflow-hidden rounded-md border"
+ role="group"
+ aria-label={t('table.detected')}
+ >
+ {DATE_PRESETS.map((preset) => (
+ <button
+ key={preset}
+ type="button"
+ onClick={() => setDatePreset(preset)}
+ aria-pressed={datePreset === preset}
+ className={cn(
+ 'px-3 text-xs font-medium transition-colors',
+ datePreset === preset
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-card text-foreground hover:bg-muted',
+ )}
+ >
+ {preset}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <FilterSelect
+ label={t('filters.impact')}
+ value={impact}
+ onChange={(v) => setImpact(v as SignalImpact | 'all')}
+ options={SIGNAL_IMPACTS.map((v) => ({ value: v, label: t(`impact.${v}`) }))}
+ allLabel={t('filters.all')}
+ />
+ <FilterSelect
+ label={t('filters.status')}
+ value={status}
+ onChange={(v) => setStatus(v as SignalStatus | 'all')}
+ options={SIGNAL_STATUSES.map((v) => ({ value: v, label: t(`status.${v}`) }))}
+ allLabel={t('filters.all')}
+ />
+ <FilterSelect
+ label={t('filters.source')}
+ value={source}
+ onChange={(v) => setSource(v as SignalSource | 'all')}
+ options={SIGNAL_SOURCES.map((v) => ({ value: v, label: t(`sources.${v}`) }))}
+ allLabel={t('filters.all')}
+ />
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={t('filters.search')}
+ className="h-8 w-56 pl-8 text-xs"
+ />
+ </div>
+ {hasActiveFilters && (
+ <Button variant="ghost" size="sm" className="text-xs" onClick={clearFilters}>
+ <X className="h-3.5 w-3.5" />
+ {t('filters.clear')}
+ </Button>
+ )}
+ </div>
+
+ {visible.length > 0 ? (
+ <SignalTable
+ signals={visible}
+ onSelect={selectSignal}
+ onStatusChange={(signal, next) => void handleStatusChange(signal, next)}
+ busyId={busyId}
+ />
+ ) : (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16 text-center">
+ <p className="text-sm text-muted-foreground">{t('noResults')}</p>
+ <Button variant="outline" size="sm" className="mt-3" onClick={clearFilters}>
+ {t('filters.clear')}
+ </Button>
+ </div>
+ )}
+
+ <SignalDrawer
+ signal={selected}
+ onOpenChange={(open) => {
+ if (!open) selectSignal(null);
+ }}
+ onStatusChange={(signal, next) => void handleStatusChange(signal, next)}
+ isBusy={busyId === selected?.id}
+ />
+ </div>
+ );
+}
+
+function SummaryCard({
+ label,
+ value,
+ prev,
+ rangeLabel,
+ spark,
+}: {
+ label: string;
+ value: number;
+ prev: number;
+ rangeLabel: string;
+ spark: KpiTrendPoint[];
+}) {
+ const t = useTranslations('actionCenter.signalsPage');
+ const change = prev > 0 ? Math.round(((value - prev) / prev) * 100) : null;
+ return (
+ <Card>
+ <CardContent className="p-4">
+ <p className="text-xs font-medium text-muted-foreground">{label}</p>
+ <div className="mt-1 flex items-end justify-between gap-2">
+ <span className="text-2xl font-bold tabular-nums">{value}</span>
+ {spark.length > 1 && (
+ <span className="text-muted-foreground/60">
+ <KpiSparkline points={spark} />
+ </span>
+ )}
+ </div>
+ <p className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">
+ {change !== null ? (
+ <>
+ <span
+ className={cn(
+ 'flex items-center gap-0.5 font-medium',
+ change >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-500',
+ )}
+ >
+ {change >= 0 ? (
+ <TrendingUp className="h-3 w-3" />
+ ) : (
+ <TrendingDown className="h-3 w-3" />
+ )}
+ {Math.abs(change)}%
+ </span>
+ {t('cards.vsRange', { range: rangeLabel })}
+ </>
+ ) : (
+ t('cards.noPrev')
+ )}
+ </p>
+ </CardContent>
+ </Card>
+ );
+}
+
+function AvgImpactCard({ summary, days }: { summary: SignalsSummary; days: number }) {
+ const t = useTranslations('actionCenter.signalsPage');
+ const levelOf = (important: number, total: number) => {
+ const ratio = total > 0 ? important / total : 0;
+ return ratio >= 0.5 ? 'high' : ratio >= 0.2 ? 'medium' : 'low';
+ };
+ const level = levelOf(summary.important, summary.total);
+ const prevLevel = levelOf(summary.prevImportant, summary.prevTotal);
+ const comparison =
+ summary.prevTotal === 0
+ ? t('cards.noPrev')
+ : level === prevLevel
+ ? t('cards.impactSame', { days })
+ : level === 'high' || (level === 'medium' && prevLevel === 'low')
+ ? t('cards.impactHigher', { days })
+ : t('cards.impactLower', { days });
+ const filled = level === 'high' ? 10 : level === 'medium' ? 6 : 3;
+ return (
+ <Card>
+ <CardContent className="p-4">
+ <p className="text-xs font-medium text-muted-foreground">{t('cards.avgImpact')}</p>
+ <p className="mt-1 text-2xl font-bold">{t(`impact.${level}`)}</p>
+ <div className="mt-1.5 flex gap-0.5" aria-hidden="true">
+ {Array.from({ length: 12 }, (_, i) => (
+ <span
+ key={i}
+ className={cn('h-2.5 w-1 rounded-sm', i < filled ? 'bg-foreground/70' : 'bg-muted')}
+ />
+ ))}
+ </div>
+ <p className="mt-1 text-xs text-muted-foreground">{comparison}</p>
+ </CardContent>
+ </Card>
+ );
+}
+
+function FilterSelect({
+ label,
+ value,
+ onChange,
+ options,
+ allLabel,
+}: {
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ options: { value: string; label: string }[];
+ allLabel: string;
+}) {
+ const items = [{ value: 'all', label: allLabel }, ...options];
+ return (
+ <Select value={value} onValueChange={(v) => onChange(v ?? 'all')} items={items}>
+ <SelectTrigger className="h-8 w-36 text-xs">
+ <span className="text-muted-foreground">{label}:</span>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{allLabel}</SelectItem>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+function CategoryPill({
+ label,
+ count,
+ isActive,
+ onClick,
+}: {
+ label: string;
+ count: number;
+ isActive: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-pressed={isActive}
+ className={cn(
+ 'flex h-8 items-center gap-1.5 rounded-md border px-3 text-xs font-medium transition-colors',
+ isActive
+ ? 'border-foreground/20 bg-muted text-foreground'
+ : 'text-muted-foreground hover:bg-muted/50 hover:text-foreground',
+ )}
+ >
+ {label}
+ <span className="text-xs text-muted-foreground">{count}</span>
+ </button>
+ );
+}
diff --git a/web/src/components/action-center/action-center-tabs.tsx b/web/src/components/action-center/action-center-tabs.tsx
new file mode 100644
index 000000000..88a1206a6
--- /dev/null
+++ b/web/src/components/action-center/action-center-tabs.tsx
@@ -0,0 +1,70 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Link, usePathname } from '@/i18n/navigation';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { getNewSignalCount } from '@/lib/actions/signals';
+import { cn } from '@/lib/utils';
+
+const TABS = [
+ { key: 'kpis', href: '/dashboard/action-center/kpis' },
+ { key: 'actions', href: '/dashboard/action-center/actions' },
+ { key: 'signals', href: '/dashboard/action-center/signals' },
+ { key: 'history', href: '/dashboard/action-center/history' },
+] as const;
+
+/**
+ * The Action Center's section nav: KPIs | Actions | Signals | History.
+ * Route-backed rather than state-backed tabs so each section is linkable
+ * and the browser back button works across them.
+ */
+export function ActionCenterTabs() {
+ const pathname = usePathname();
+ const t = useTranslations('actionCenter.tabs');
+
+ // Untriaged-signal count on the Signals tab: information ("something new
+ // is waiting"), not decoration. Best-effort — a failed count shows nothing.
+ const brandId = useBrandStore((s) => s.activeBrandId);
+ const [newSignals, setNewSignals] = useState(0);
+ useEffect(() => {
+ if (!brandId) return;
+ let cancelled = false;
+ getNewSignalCount(brandId)
+ .then((count) => {
+ if (!cancelled) setNewSignals(count);
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, pathname]);
+
+ return (
+ <nav className="flex gap-6 border-b" aria-label={t('label')}>
+ {TABS.map((tab) => {
+ const isActive = pathname.startsWith(tab.href);
+ return (
+ <Link
+ key={tab.key}
+ href={tab.href}
+ aria-current={isActive ? 'page' : undefined}
+ className={cn(
+ '-mb-px border-b-2 pb-2 text-sm font-medium transition-colors',
+ isActive
+ ? 'border-foreground text-foreground'
+ : 'border-transparent text-muted-foreground hover:text-foreground',
+ )}
+ >
+ {t(tab.key)}
+ {tab.key === 'signals' && newSignals > 0 && (
+ <span className="ml-1.5 rounded-full bg-blue-500/10 px-1.5 py-0.5 text-[10px] font-medium text-blue-600 dark:text-blue-400">
+ {newSignals}
+ </span>
+ )}
+ </Link>
+ );
+ })}
+ </nav>
+ );
+}
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
new file mode 100644
index 000000000..ce3795982
--- /dev/null
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -0,0 +1,427 @@
+'use client';
+
+import { useCallback, useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { useRouter } from '@/i18n/navigation';
+import { toast } from 'sonner';
+import { Badge } from '@/components/ui/badge';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { Separator } from '@/components/ui/separator';
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet';
+import { Skeleton } from '@/components/ui/skeleton';
+import {
+ assignAction,
+ getActionDetail,
+ setActionDueDate,
+ updateActionStatus,
+ updateTaskStatus,
+ type ActionDetail,
+ type ActionItem,
+} from '@/lib/actions/action-center';
+import type { TeamMember } from '@/lib/actions/team';
+import {
+ ACTION_STATUSES,
+ TASK_STATUSES,
+ type ActionStatus,
+ type TaskStatus,
+} from '@/lib/action-center/registry';
+import { actionContextTags, actionTexts } 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 { 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'];
+
+/**
+ * Action detail: evidence, execution, trail. Tabs are local state, not
+ * routes — the drawer overlays the list, per the brief. Assignment and due
+ * date live at the bottom of every tab; "Assign to Agent" is deliberately
+ * absent until agent execution exists.
+ */
+export function ActionDrawer({
+ brandId,
+ action,
+ members,
+ onOpenChange,
+ onChanged,
+}: {
+ brandId: string;
+ action: ActionItem | null;
+ members: TeamMember[];
+ onOpenChange: (open: boolean) => void;
+ /** Fired after any mutation so the list refetches. */
+ onChanged: () => void;
+}) {
+ const t = useTranslations('actionCenter.actionsPage');
+ const tTexts = useTranslations('actionCenter.actionTexts');
+ const tSignalTexts = useTranslations('actionCenter.signalTexts');
+ const tCategories = useTranslations('actionCenter.actionCategories');
+ const tRegistry = useTranslations('actionCenter.registry');
+ const tTasks = useTranslations('actionCenter.actionTasks');
+ const tTaskStatus = useTranslations('actionCenter.taskStatus');
+
+ const router = useRouter();
+ const [tab, setTab] = useState<DrawerTab>('overview');
+ const [detail, setDetail] = useState<ActionDetail | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [isBusy, setIsBusy] = useState(false);
+
+ // Traceability: a signal card jumps to the Signals page with that signal's
+ // drawer open — the evidence must be one click from the action it created.
+ const openSignal = (signalId: string) => {
+ router.push(`/dashboard/action-center/signals?signal=${signalId}`);
+ };
+
+ const load = useCallback(async () => {
+ if (!action) return;
+ setIsLoading(true);
+ try {
+ setDetail(await getActionDetail(brandId, action.id));
+ } catch {
+ toast.error(t('error.title'));
+ } finally {
+ setIsLoading(false);
+ }
+ }, [brandId, action, t]);
+
+ useEffect(() => {
+ setTab('overview');
+ setDetail(null);
+ if (action) void load();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [action?.id]);
+
+ if (!action) return null;
+ const texts = actionTexts(action, tTexts);
+ const tags = actionContextTags(action, t);
+ const relatedKpis: string[] = action.kpiKeys.filter(isKpiKey);
+
+ const mutate = async (fn: () => Promise<void>) => {
+ setIsBusy(true);
+ try {
+ await fn();
+ await load();
+ onChanged();
+ } catch {
+ toast.error(t('updateFailed'));
+ } finally {
+ setIsBusy(false);
+ }
+ };
+
+ return (
+ <Sheet open={Boolean(action)} onOpenChange={onOpenChange}>
+ <SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-lg">
+ <SheetHeader className="border-b px-6 py-4">
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ <Badge variant="outline" className="text-[10px]">
+ {tCategories(action.category)}
+ </Badge>
+ <span className="flex items-center gap-1.5 text-muted-foreground">
+ <ImpactDots impact={action.impact} />
+ {t(`impact.${action.impact}`)}
+ </span>
+ <span className="ml-auto text-muted-foreground">
+ {t('drawer.actionId')}: AC-{action.actionNo}
+ </span>
+ </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} />
+ </div>
+ <div className="min-w-0">
+ <SheetTitle>{texts.title}</SheetTitle>
+ <SheetDescription>{texts.description}</SheetDescription>
+ </div>
+ </div>
+ <div className="flex flex-wrap gap-1">
+ {tags.map((tag) => (
+ <Badge key={tag} variant="outline" className="text-[10px]">
+ {tag}
+ </Badge>
+ ))}
+ </div>
+ </SheetHeader>
+
+ <nav className="flex gap-4 border-b px-6" aria-label={t('table.action')}>
+ {TABS.map((key) => (
+ <button
+ key={key}
+ type="button"
+ onClick={() => setTab(key)}
+ aria-current={tab === key ? 'page' : undefined}
+ className={cn(
+ '-mb-px border-b-2 py-2 text-xs font-medium transition-colors',
+ tab === key
+ ? 'border-foreground text-foreground'
+ : 'border-transparent text-muted-foreground hover:text-foreground',
+ )}
+ >
+ {t(`drawer.tabs.${key}`)}
+ {key === 'tasks' && detail ? ` (${detail.tasks.length})` : ''}
+ </button>
+ ))}
+ </nav>
+
+ <div className="flex-1 space-y-5 overflow-y-auto px-6 py-4 text-sm">
+ {isLoading || !detail ? (
+ <div className="space-y-3">
+ {[0, 1, 2].map((i) => (
+ <Skeleton key={i} className="h-16 w-full" />
+ ))}
+ </div>
+ ) : tab === 'overview' ? (
+ <>
+ <section>
+ <p className="text-xs font-medium text-muted-foreground">{t('drawer.why')}</p>
+ <p className="mt-1">{texts.description}</p>
+ </section>
+ <Separator />
+ <section>
+ <p className="text-xs font-medium text-muted-foreground">{t('drawer.goal')}</p>
+ <p className="mt-1">{tTexts(`${action.kind}.goal`)}</p>
+ </section>
+ <Separator />
+ <section>
+ <p className="text-xs font-medium text-muted-foreground">{t('drawer.kpis')}</p>
+ {detail.kpis.filter((kpi) => relatedKpis.includes(kpi.kpiKey)).length > 0 ? (
+ <div className="mt-2 flex flex-wrap gap-2">
+ {detail.kpis
+ .filter((kpi) => relatedKpis.includes(kpi.kpiKey) && isKpiKey(kpi.kpiKey))
+ .map((kpi) => (
+ <div key={kpi.kpiKey} className="rounded-md border px-3 py-2">
+ <p className="text-xs font-medium">{tRegistry(`${kpi.kpiKey}.name`)}</p>
+ <p className="text-xs text-muted-foreground">
+ {t('drawer.kpiTarget', { target: kpi.target })}
+ </p>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="mt-1 text-xs text-muted-foreground">{t('drawer.noKpis')}</p>
+ )}
+ </section>
+ <Separator />
+ <section>
+ <p className="text-xs font-medium text-muted-foreground">
+ {t('drawer.primarySignals')}
+ </p>
+ <div className="mt-2 space-y-2">
+ {detail.signals.slice(0, 3).map((signal) => {
+ const st = signalTexts(signal, tSignalTexts);
+ return (
+ <button
+ key={signal.id}
+ type="button"
+ onClick={() => openSignal(signal.id)}
+ className="block w-full rounded-md border px-3 py-2 text-left transition-colors hover:bg-muted/40"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <p className="truncate text-xs font-medium">{st.title}</p>
+ <ImpactDots impact={signal.impact} />
+ </div>
+ <p className="truncate text-xs text-muted-foreground">{st.description}</p>
+ </button>
+ );
+ })}
+ </div>
+ </section>
+ </>
+ ) : tab === 'tasks' ? (
+ <section>
+ <p className="text-xs text-muted-foreground">
+ {t('drawer.tasksProgress', {
+ completed: detail.tasks.filter((task) => task.status === 'completed').length,
+ total: detail.tasks.length,
+ })}
+ </p>
+ <div className="mt-3 space-y-2">
+ {detail.tasks.map((task) => (
+ <div
+ key={task.id}
+ className="flex items-center justify-between gap-3 rounded-md border px-3 py-2"
+ >
+ <p
+ className={cn(
+ 'min-w-0 flex-1 text-sm',
+ task.status === 'completed' && 'text-muted-foreground line-through',
+ )}
+ >
+ {task.position}. {tTasks(task.taskKey)}
+ </p>
+ <Select
+ value={task.status}
+ onValueChange={(value) =>
+ void mutate(() =>
+ updateTaskStatus(brandId, action.id, task.id, value as TaskStatus),
+ )
+ }
+ disabled={isBusy}
+ items={TASK_STATUSES.map((status) => ({
+ value: status,
+ label: tTaskStatus(status),
+ }))}
+ >
+ <SelectTrigger className="h-7 w-32 text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {TASK_STATUSES.map((status) => (
+ <SelectItem key={status} value={status}>
+ {tTaskStatus(status)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ ))}
+ </div>
+ </section>
+ ) : tab === 'signals' ? (
+ <section className="space-y-2">
+ {detail.signals.length === 0 && (
+ <p className="text-xs text-muted-foreground">{t('drawer.noSignals')}</p>
+ )}
+ {detail.signals.map((signal) => {
+ const st = signalTexts(signal, tSignalTexts);
+ return (
+ <button
+ key={signal.id}
+ type="button"
+ onClick={() => openSignal(signal.id)}
+ className="block w-full rounded-md border px-3 py-2 text-left transition-colors hover:bg-muted/40"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <p className="truncate text-xs font-medium">{st.title}</p>
+ <SignalStatusBadge status={signal.status} />
+ </div>
+ <p className="truncate text-xs text-muted-foreground">{st.description}</p>
+ </button>
+ );
+ })}
+ </section>
+ ) : (
+ <section className="space-y-3">
+ {detail.events.map((event) => (
+ <div key={event.id} className="flex gap-3">
+ <div className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-foreground/50" />
+ <div>
+ <p className="text-xs font-medium">
+ {t(`drawer.events.${event.event}`, {
+ to: String(event.data.to ?? ''),
+ count: Number(event.data.count ?? 0),
+ })}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {new Date(event.createdAt).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ })}
+ </p>
+ </div>
+ </div>
+ ))}
+ </section>
+ )}
+ </div>
+
+ <div className="space-y-3 border-t px-6 py-4">
+ <div className="grid grid-cols-2 gap-3">
+ <div>
+ <Label className="text-xs text-muted-foreground">{t('drawer.statusLabel')}</Label>
+ <Select
+ value={action.status}
+ onValueChange={(value) =>
+ void mutate(() => updateActionStatus(brandId, action.id, value as ActionStatus))
+ }
+ disabled={isBusy}
+ items={ACTION_STATUSES.map((status) => ({
+ value: status,
+ label: t(`status.${status}`),
+ }))}
+ >
+ <SelectTrigger className="mt-1 h-8 w-full text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {ACTION_STATUSES.map((status) => (
+ <SelectItem key={status} value={status}>
+ {t(`status.${status}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div>
+ <Label className="text-xs text-muted-foreground">{t('drawer.dueDate')}</Label>
+ <Input
+ type="date"
+ className="mt-1 h-8 text-xs"
+ value={action.dueDate ?? ''}
+ disabled={isBusy}
+ onChange={(e) =>
+ void mutate(() => setActionDueDate(brandId, action.id, e.target.value || null))
+ }
+ />
+ </div>
+ </div>
+ <div>
+ <Label className="text-xs text-muted-foreground">{t('drawer.assignee')}</Label>
+ <Select
+ value={action.assignee?.id ?? 'unassigned'}
+ onValueChange={(value) =>
+ void mutate(() =>
+ assignAction(brandId, action.id, value === 'unassigned' ? null : value),
+ )
+ }
+ disabled={isBusy}
+ items={[
+ { value: 'unassigned', label: t('filters.unassigned') },
+ ...members.map((member) => ({
+ value: member.userId,
+ label: member.fullName ?? member.userId.slice(0, 8),
+ })),
+ ]}
+ >
+ <SelectTrigger className="mt-1 h-8 w-full text-xs">
+ <SelectValue placeholder={t('drawer.assignTo')} />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="unassigned">{t('filters.unassigned')}</SelectItem>
+ {members.map((member) => (
+ <SelectItem key={member.userId} value={member.userId}>
+ {member.fullName ?? member.userId.slice(0, 8)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/web/src/components/action-center/action-table.tsx b/web/src/components/action-center/action-table.tsx
new file mode 100644
index 000000000..888949543
--- /dev/null
+++ b/web/src/components/action-center/action-table.tsx
@@ -0,0 +1,168 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { BarChart3, MessageSquare, MousePointerClick, Swords, Wrench } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import type { ActionItem } from '@/lib/actions/action-center';
+import type { 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 }>> = {
+ recover_visibility: BarChart3,
+ capture_ai_traffic: MousePointerClick,
+ convert_mentions: MessageSquare,
+ fix_low_scores: Wrench,
+ close_competitor_gap: Swords,
+};
+
+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',
+ completed: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',
+ on_hold: 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
+ no_improvement: 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400',
+ dismissed: 'border-border bg-muted/50 text-muted-foreground',
+};
+
+export function ActionStatusBadge({ status }: { status: ActionStatus }) {
+ const t = useTranslations('actionCenter.actionsPage');
+ return (
+ <Badge variant="outline" className={ACTION_STATUS_BADGE[status]}>
+ <span aria-hidden="true" className="h-1.5 w-1.5 rounded-full bg-current opacity-70" />
+ {t(`status.${status}`)}
+ </Badge>
+ );
+}
+
+export function AssigneeAvatar({ assignee }: { assignee: ActionItem['assignee'] }) {
+ if (!assignee) return <span className="text-xs text-muted-foreground">—</span>;
+ const initials = (assignee.fullName ?? '?')
+ .split(/\s+/)
+ .map((part) => part[0])
+ .slice(0, 2)
+ .join('')
+ .toUpperCase();
+ return (
+ <Avatar className="h-6 w-6" title={assignee.fullName ?? undefined}>
+ {assignee.avatarUrl && <AvatarImage src={assignee.avatarUrl} alt="" />}
+ <AvatarFallback className="text-[10px]">{initials}</AvatarFallback>
+ </Avatar>
+ );
+}
+
+export function ActionTable({
+ actions,
+ onSelect,
+}: {
+ actions: ActionItem[];
+ onSelect: (action: ActionItem) => void;
+}) {
+ const t = useTranslations('actionCenter.actionsPage');
+ const tTexts = useTranslations('actionCenter.actionTexts');
+ const tCategories = useTranslations('actionCenter.actionCategories');
+ const tCommon = useTranslations('common');
+
+ return (
+ <div className="overflow-x-auto rounded-lg border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="text-xs">{t('table.action')}</TableHead>
+ <TableHead className="text-xs">{t('table.impact')}</TableHead>
+ <TableHead className="text-xs">{t('table.status')}</TableHead>
+ <TableHead className="text-xs">{t('table.assignee')}</TableHead>
+ <TableHead className="text-xs">{t('table.dueDate')}</TableHead>
+ <TableHead className="text-xs">{t('table.updated')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {actions.map((action) => {
+ const Icon = KIND_ICONS[action.kind];
+ const texts = actionTexts(action, tTexts);
+ const tags = actionContextTags(action, t);
+ return (
+ <TableRow key={action.id} className="cursor-pointer" onClick={() => onSelect(action)}>
+ <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" />
+ </div>
+ <div className="min-w-0">
+ <p className="truncate text-sm font-medium">{texts.title}</p>
+ <p className="truncate text-xs text-muted-foreground">{texts.description}</p>
+ <div className="mt-1 flex flex-wrap gap-1">
+ <Badge variant="outline" className="text-[10px]">
+ {tCategories(action.category)}
+ </Badge>
+ {tags.map((tag) => (
+ <Badge key={tag} variant="outline" className="text-[10px]">
+ {tag}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ </div>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-1.5">
+ <span className="text-xs">{t(`impact.${action.impact}`)}</span>
+ <ImpactDots impact={action.impact} />
+ </div>
+ </TableCell>
+ <TableCell>
+ <ActionStatusBadge status={action.status} />
+ {action.taskTotal > 0 && (
+ <div className="mt-1.5 w-24">
+ <p className="text-[10px] text-muted-foreground">
+ {t('taskProgress', {
+ completed: action.taskCompleted,
+ total: action.taskTotal,
+ })}
+ </p>
+ <div className="mt-0.5 h-1 w-full overflow-hidden rounded-full bg-muted">
+ <div
+ className={cn('h-full rounded-full bg-foreground/60')}
+ style={{
+ width: `${Math.round((action.taskCompleted / action.taskTotal) * 100)}%`,
+ }}
+ />
+ </div>
+ </div>
+ )}
+ </TableCell>
+ <TableCell>
+ <AssigneeAvatar assignee={action.assignee} />
+ </TableCell>
+ <TableCell className="text-xs tabular-nums text-muted-foreground">
+ {action.dueDate
+ ? new Date(`${action.dueDate}T00:00:00Z`).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ timeZone: 'UTC',
+ })
+ : '—'}
+ </TableCell>
+ <TableCell className="text-xs text-muted-foreground">
+ {formatRelative(action.updatedAt, tCommon)}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
diff --git a/web/src/components/action-center/coming-soon-page.tsx b/web/src/components/action-center/coming-soon-page.tsx
new file mode 100644
index 000000000..23ce3afda
--- /dev/null
+++ b/web/src/components/action-center/coming-soon-page.tsx
@@ -0,0 +1,30 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { Hourglass } from 'lucide-react';
+import { ActionCenterTabs } from './action-center-tabs';
+
+/**
+ * Shared shell for the Action Center sections that exist in navigation but
+ * not yet in function (Actions, Signals, History). Honest placeholder over a
+ * dead tab: the route works, the nav highlights, and the body says exactly
+ * where things stand.
+ */
+export function ComingSoonPage({ tab }: { tab: 'actions' | 'signals' | 'history' }) {
+ const t = useTranslations('actionCenter');
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">{t(`tabs.${tab}`)}</h1>
+ <p className="mt-1 text-sm text-muted-foreground">{t(`pages.${tab}`)}</p>
+ </div>
+ <ActionCenterTabs />
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">
+ <Hourglass className="h-8 w-8 text-muted-foreground" />
+ <h2 className="mt-4 font-semibold">{t('comingSoon.title')}</h2>
+ <p className="mt-1 max-w-md text-sm text-muted-foreground">{t('comingSoon.description')}</p>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/components/action-center/kpi-framework-drawer.tsx b/web/src/components/action-center/kpi-framework-drawer.tsx
new file mode 100644
index 000000000..894109578
--- /dev/null
+++ b/web/src/components/action-center/kpi-framework-drawer.tsx
@@ -0,0 +1,394 @@
+'use client';
+
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import {
+ BarChart3,
+ CheckCircle2,
+ FileText,
+ Info,
+ Loader2,
+ Megaphone,
+ PencilRuler,
+} from 'lucide-react';
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { Skeleton } from '@/components/ui/skeleton';
+import { getKpiDefinitions, saveKpiFramework } from '@/lib/actions/kpis';
+import {
+ KPI_KEYS,
+ KPI_REGISTRY,
+ KPI_TEMPLATES,
+ TIMEFRAME_DAYS,
+ isValidKpiTarget,
+ type KpiKey,
+ type KpiTemplateKey,
+ type KpiTimeframe,
+} from '@/lib/kpis/registry';
+import { scaleTargetToWindow } from '@/lib/kpis/status';
+import { cn } from '@/lib/utils';
+
+const TEMPLATE_ICONS: Record<KpiTemplateKey, React.ComponentType<{ className?: string }>> = {
+ ai_search_visibility: BarChart3,
+ content_performance: FileText,
+ brand_monitoring: Megaphone,
+ custom: PencilRuler,
+};
+
+const TEMPLATE_ORDER: KpiTemplateKey[] = [
+ 'ai_search_visibility',
+ 'content_performance',
+ 'brand_monitoring',
+ 'custom',
+];
+
+const TIMEFRAMES: KpiTimeframe[] = ['weekly', 'monthly', 'quarterly'];
+
+const UNIT_SUFFIX: Record<string, string> = {
+ percent: '%',
+ count: '#',
+ sessions: '#',
+};
+
+interface DraftEntry {
+ enabled: boolean;
+ /** Kept as the raw input string so a half-typed number isn't clobbered. */
+ target: string;
+}
+
+type Draft = Record<KpiKey, DraftEntry>;
+
+function templateDraft(template: KpiTemplateKey, previous?: Draft): Draft {
+ const inTemplate = new Set(KPI_TEMPLATES[template]);
+ return Object.fromEntries(
+ KPI_KEYS.map((key) => [
+ key,
+ {
+ enabled: template === 'custom' ? (previous?.[key]?.enabled ?? false) : inTemplate.has(key),
+ // A target someone already typed survives switching templates —
+ // presets decide what is checked, not what was written.
+ target: previous?.[key]?.target ?? String(KPI_REGISTRY[key].defaultTarget),
+ },
+ ]),
+ ) as Draft;
+}
+
+/**
+ * Configure KPI Framework: pick a template, set targets and a time period,
+ * Save & Apply. Two steps, not the mockup's three — frameworks are
+ * brand-scoped and the brand is already selected in the app shell, so there
+ * is nothing to assign.
+ *
+ * State resets on every open by refetching the brand's definitions, so a
+ * cancelled edit leaves nothing behind.
+ */
+export function KpiFrameworkDrawer({
+ brandId,
+ open,
+ onOpenChange,
+ onSaved,
+ focusKpi,
+}: {
+ brandId: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSaved: () => void;
+ /** Set when opened from a row's Edit action: that KPI's target input is
+ * scrolled into view and focused once the prefill lands. */
+ focusKpi?: KpiKey | null;
+}) {
+ const t = useTranslations('actionCenter.drawer');
+ const tRegistry = useTranslations('actionCenter.registry');
+
+ const [isLoading, setIsLoading] = useState(false);
+ const [isSaving, setIsSaving] = useState(false);
+ const [template, setTemplate] = useState<KpiTemplateKey>('ai_search_visibility');
+ const [timeframe, setTimeframe] = useState<KpiTimeframe>('monthly');
+ const [draft, setDraft] = useState<Draft>(() => templateDraft('ai_search_visibility'));
+
+ const prefill = useCallback(async () => {
+ setIsLoading(true);
+ try {
+ const definitions = await getKpiDefinitions(brandId);
+ if (definitions.length === 0) {
+ setTemplate('ai_search_visibility');
+ setTimeframe('monthly');
+ setDraft(templateDraft('ai_search_visibility'));
+ return;
+ }
+ // An existing framework opens as what it is — the user's own set —
+ // rather than snapping back to a template's checkboxes.
+ const byKey = new Map(definitions.map((d) => [d.kpiKey, d]));
+ setTemplate('custom');
+ setTimeframe(definitions.find((d) => d.isActive)?.timeframe ?? 'monthly');
+ setDraft(
+ Object.fromEntries(
+ KPI_KEYS.map((key) => {
+ const existing = byKey.get(key);
+ return [
+ key,
+ {
+ enabled: existing?.isActive ?? false,
+ target: String(existing?.target ?? KPI_REGISTRY[key].defaultTarget),
+ },
+ ];
+ }),
+ ) as Draft,
+ );
+ } catch {
+ toast.error(t('loadFailed'));
+ onOpenChange(false);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [brandId, onOpenChange, t]);
+
+ useEffect(() => {
+ if (open) void prefill();
+ }, [open, prefill]);
+
+ useEffect(() => {
+ if (!open || isLoading || !focusKpi) return;
+ const input = document.getElementById(`kpi-target-${focusKpi}`);
+ if (input instanceof HTMLInputElement) {
+ input.scrollIntoView({ block: 'center' });
+ input.focus();
+ input.select();
+ }
+ }, [open, isLoading, focusKpi]);
+
+ const entries = useMemo(
+ () =>
+ KPI_KEYS.filter((key) => draft[key]?.enabled).map((key) => ({
+ key,
+ target: Number(draft[key].target),
+ })),
+ [draft],
+ );
+ const invalidKeys = useMemo(
+ () => new Set(entries.filter((e) => !isValidKpiTarget(e.key, e.target)).map((e) => e.key)),
+ [entries],
+ );
+ const canSave = !isLoading && !isSaving && entries.length > 0 && invalidKeys.size === 0;
+
+ // Switching the period rescales flow targets to the new cadence (weekly
+ // 23 citations becomes monthly ~99) so the numbers keep meaning the same
+ // goal; percent targets are levels and stay as typed. A non-numeric
+ // half-typed value is left alone rather than clobbered.
+ const handleTimeframeChange = (next: KpiTimeframe) => {
+ setDraft((prev) => {
+ const fromDays = TIMEFRAME_DAYS[timeframe];
+ const toDays = TIMEFRAME_DAYS[next];
+ return Object.fromEntries(
+ KPI_KEYS.map((key) => {
+ const entry = prev[key];
+ const num = Number(entry.target);
+ const scaled =
+ Number.isFinite(num) && num > 0
+ ? scaleTargetToWindow(num, KPI_REGISTRY[key].unit, toDays, fromDays)
+ : null;
+ return [key, scaled === null ? entry : { ...entry, target: String(scaled) }];
+ }),
+ ) as Draft;
+ });
+ setTimeframe(next);
+ };
+
+ const handleSave = async () => {
+ setIsSaving(true);
+ try {
+ await saveKpiFramework(brandId, timeframe, entries);
+ onOpenChange(false);
+ onSaved();
+ toast.success(t('saved'));
+ } catch {
+ toast.error(t('saveFailed'));
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-md">
+ <SheetHeader className="border-b px-6 py-4">
+ <SheetTitle>{t('title')}</SheetTitle>
+ <SheetDescription>{t('description')}</SheetDescription>
+ </SheetHeader>
+
+ {isLoading ? (
+ <div className="flex-1 space-y-3 overflow-y-auto px-6 py-4">
+ {[0, 1, 2, 3].map((i) => (
+ <Skeleton key={i} className="h-16 w-full" />
+ ))}
+ </div>
+ ) : (
+ <div className="flex-1 space-y-6 overflow-y-auto px-6 py-4">
+ <section>
+ <h3 className="text-sm font-semibold">{t('steps.template.title')}</h3>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {t('steps.template.description')}
+ </p>
+ <div className="mt-3 space-y-2">
+ {TEMPLATE_ORDER.map((key) => {
+ const Icon = TEMPLATE_ICONS[key];
+ const isAvailable = key === 'custom' || KPI_TEMPLATES[key].length > 0;
+ const isSelected = template === key;
+ return (
+ <button
+ key={key}
+ type="button"
+ disabled={!isAvailable}
+ aria-pressed={isSelected}
+ onClick={() => {
+ setTemplate(key);
+ setDraft((prev) => templateDraft(key, prev));
+ }}
+ className={cn(
+ 'flex w-full items-start gap-3 rounded-lg border p-3 text-left transition-colors',
+ isSelected
+ ? 'border-foreground bg-muted/60 ring-1 ring-foreground'
+ : 'hover:bg-muted/40 disabled:cursor-not-allowed disabled:opacity-50',
+ )}
+ >
+ <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-background">
+ <Icon className="h-4 w-4 text-muted-foreground" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium">{t(`templates.${key}.name`)}</p>
+ <p className="text-xs text-muted-foreground">
+ {isAvailable
+ ? t(`templates.${key}.description`)
+ : t('templates.notAvailable')}
+ </p>
+ </div>
+ {isSelected && (
+ <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-foreground" />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </section>
+
+ <section>
+ <h3 className="text-sm font-semibold">{t('steps.goals.title')}</h3>
+ <p className="mt-0.5 text-xs text-muted-foreground">{t('steps.goals.description')}</p>
+
+ <div className="mt-3">
+ <Label htmlFor="kpi-timeframe" className="text-xs text-muted-foreground">
+ {t('timePeriod')}
+ </Label>
+ <Select
+ value={timeframe}
+ onValueChange={(v) => handleTimeframeChange(v as KpiTimeframe)}
+ items={TIMEFRAMES.map((tf) => ({ value: tf, label: t(`timeframes.${tf}`) }))}
+ >
+ <SelectTrigger id="kpi-timeframe" className="mt-1 h-9 w-full text-sm">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {TIMEFRAMES.map((tf) => (
+ <SelectItem key={tf} value={tf}>
+ {t(`timeframes.${tf}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ <p className="mt-4 text-xs font-medium text-muted-foreground">{t('targets')}</p>
+ {/* Every registry KPI is always listed: picking a template must
+ visibly toggle checkmarks, not make rows silently vanish. */}
+ <div className="mt-2 space-y-2">
+ {KPI_KEYS.map((key) => {
+ const entry = draft[key];
+ const isInvalid = entry.enabled && invalidKeys.has(key);
+ return (
+ <div key={key} className="flex items-center gap-3">
+ <Checkbox
+ id={`kpi-enable-${key}`}
+ checked={entry.enabled}
+ onCheckedChange={(checked) =>
+ setDraft((prev) => ({
+ ...prev,
+ [key]: { ...prev[key], enabled: checked === true },
+ }))
+ }
+ />
+ <Label
+ htmlFor={`kpi-enable-${key}`}
+ className="min-w-0 flex-1 truncate text-sm font-normal"
+ >
+ {tRegistry(`${key}.name`)}
+ </Label>
+ <div className="relative w-28">
+ <Input
+ id={`kpi-target-${key}`}
+ type="number"
+ inputMode="decimal"
+ value={entry.target}
+ disabled={!entry.enabled}
+ aria-label={t('targetAria', { name: tRegistry(`${key}.name`) })}
+ aria-invalid={isInvalid || undefined}
+ onChange={(e) =>
+ setDraft((prev) => ({
+ ...prev,
+ [key]: { ...prev[key], target: e.target.value },
+ }))
+ }
+ className={cn('h-9 pr-7 text-sm', isInvalid && 'border-destructive')}
+ />
+ <span className="pointer-events-none absolute inset-y-0 right-2.5 flex items-center text-xs text-muted-foreground">
+ {UNIT_SUFFIX[KPI_REGISTRY[key].unit]}
+ </span>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ {invalidKeys.size > 0 && (
+ <p className="mt-2 text-xs text-destructive">{t('invalidTarget')}</p>
+ )}
+ </section>
+
+ <div className="flex gap-2.5 rounded-lg border bg-muted/40 p-3">
+ <Info className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div>
+ <p className="text-xs font-medium">{t('callout.title')}</p>
+ <p className="mt-0.5 text-xs text-muted-foreground">{t('callout.description')}</p>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <div className="flex justify-end gap-2 border-t px-6 py-4">
+ <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving}>
+ {t('cancel')}
+ </Button>
+ <Button onClick={() => void handleSave()} disabled={!canSave}>
+ {isSaving && <Loader2 className="h-4 w-4 animate-spin" />}
+ {t('save')}
+ </Button>
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/web/src/components/action-center/kpi-sparkline.tsx b/web/src/components/action-center/kpi-sparkline.tsx
new file mode 100644
index 000000000..3d7c24f56
--- /dev/null
+++ b/web/src/components/action-center/kpi-sparkline.tsx
@@ -0,0 +1,43 @@
+'use client';
+
+import { Line, LineChart } from 'recharts';
+import type { KpiTrendPoint } from '@/lib/actions/kpis';
+
+/**
+ * Micro trend indicator for a KPI table row: a bare 2px line, no axes, no
+ * grid, no tooltip. It answers only "which way is this heading" — the value
+ * and change columns beside it carry the numbers, and the status badge's
+ * text carries the state, so the sparkline is decorative and hidden from
+ * assistive tech.
+ *
+ * `stroke="currentColor"` inherits the wrapper's text color, which the table
+ * sets from the KPI's status — the same soft palette as the badge, so color
+ * never says two different things in one row, and dark mode follows the
+ * existing `text-*-600 dark:text-*-400` tokens for free.
+ */
+export default function KpiSparkline({ points }: { points: KpiTrendPoint[] }) {
+ if (points.length < 2) {
+ return <span className="text-xs text-muted-foreground">—</span>;
+ }
+ // A div, not a span: recharts renders a block wrapper and a div inside a
+ // span is invalid nesting.
+ return (
+ <div aria-hidden="true" className="inline-block">
+ <LineChart
+ width={110}
+ height={32}
+ data={points}
+ margin={{ top: 2, right: 2, bottom: 2, left: 2 }}
+ >
+ <Line
+ type="monotone"
+ dataKey="value"
+ stroke="currentColor"
+ strokeWidth={2}
+ dot={false}
+ isAnimationActive={false}
+ />
+ </LineChart>
+ </div>
+ );
+}
diff --git a/web/src/components/action-center/kpi-table.tsx b/web/src/components/action-center/kpi-table.tsx
new file mode 100644
index 000000000..69dabd55c
--- /dev/null
+++ b/web/src/components/action-center/kpi-table.tsx
@@ -0,0 +1,232 @@
+'use client';
+
+import dynamic from 'next/dynamic';
+import { useTranslations } from 'next-intl';
+import {
+ Eye,
+ MessageSquare,
+ MoreHorizontal,
+ MousePointerClick,
+ Pencil,
+ PieChart,
+ Quote,
+ TrendingDown,
+ TrendingUp,
+ Trash2,
+} from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { Skeleton } from '@/components/ui/skeleton';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import type { KpiSnapshot } from '@/lib/actions/kpis';
+import type { KpiKey } from '@/lib/kpis/registry';
+import type { KpiStatus } from '@/lib/kpis/status';
+import { isImprovement } from '@/lib/kpis/status';
+import { formatCompactNumber } from '@/lib/format';
+import { cn } from '@/lib/utils';
+
+const KpiSparkline = dynamic(() => import('./kpi-sparkline'), {
+ ssr: false,
+ loading: () => <Skeleton className="h-8 w-[110px]" />,
+});
+
+const KPI_ICONS: Record<KpiKey, React.ComponentType<{ className?: string }>> = {
+ ai_visibility: Eye,
+ citations: Quote,
+ mentions: MessageSquare,
+ share_of_voice: PieChart,
+ ai_referral_traffic: MousePointerClick,
+};
+
+/**
+ * One soft color per status, shared by the badge, the sparkline and the
+ * progress bar so a row's color always says one thing. Status is never
+ * carried by color alone — the badge text is the accessible signal.
+ */
+const STATUS_BADGE: Record<KpiStatus, string> = {
+ on_track: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',
+ at_risk: 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
+ off_track: 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400',
+ goal_reached: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
+};
+
+const STATUS_TEXT: Record<KpiStatus, string> = {
+ on_track: 'text-green-600 dark:text-green-400',
+ at_risk: 'text-amber-600 dark:text-amber-400',
+ off_track: 'text-red-600 dark:text-red-400',
+ goal_reached: 'text-emerald-600 dark:text-emerald-400',
+};
+
+const STATUS_BAR: Record<KpiStatus, string> = {
+ on_track: 'bg-green-500',
+ at_risk: 'bg-amber-500',
+ off_track: 'bg-red-500',
+ goal_reached: 'bg-emerald-500',
+};
+
+function formatKpiValue(value: number, unit: KpiSnapshot['unit']): string {
+ if (unit === 'percent') {
+ return `${Math.round(value * 10) / 10}%`;
+ }
+ return formatCompactNumber(value);
+}
+
+function KpiChange({ snapshot }: { snapshot: KpiSnapshot }) {
+ const t = useTranslations('actionCenter.kpis');
+ if (snapshot.change === null) {
+ return <span className="text-xs text-muted-foreground">—</span>;
+ }
+ const improving = isImprovement(snapshot.change, snapshot.direction);
+ const Arrow = snapshot.change > 0 ? TrendingUp : TrendingDown;
+ const magnitude = Math.abs(snapshot.change);
+ return (
+ <span
+ className={cn(
+ 'flex items-center gap-1 text-xs font-medium tabular-nums',
+ improving ? 'text-green-600 dark:text-green-400' : 'text-red-500',
+ )}
+ >
+ <Arrow className="h-3.5 w-3.5" />
+ {snapshot.changeKind === 'points' ? t('pointsChange', { value: magnitude }) : `${magnitude}%`}
+ </span>
+ );
+}
+
+function GoalProgress({ snapshot }: { snapshot: KpiSnapshot }) {
+ const t = useTranslations('actionCenter.kpis');
+ return (
+ <div className="w-24">
+ <span className="text-xs font-medium tabular-nums">{snapshot.progress}%</span>
+ <div
+ role="progressbar"
+ aria-valuenow={Math.min(snapshot.progress, 100)}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-label={t('vsGoalAria', { progress: snapshot.progress })}
+ className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-muted"
+ >
+ <div
+ className={cn('h-full rounded-full', STATUS_BAR[snapshot.status])}
+ style={{ width: `${Math.min(snapshot.progress, 100)}%` }}
+ />
+ </div>
+ </div>
+ );
+}
+
+export function KpiTable({
+ kpis,
+ onEdit,
+ onRemove,
+ busyKey,
+}: {
+ kpis: KpiSnapshot[];
+ onEdit: (key: KpiKey) => void;
+ onRemove: (key: KpiKey) => void;
+ busyKey: KpiKey | null;
+}) {
+ const t = useTranslations('actionCenter.kpis');
+ const tRegistry = useTranslations('actionCenter.registry');
+
+ return (
+ <div className="overflow-x-auto rounded-lg border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="text-xs">{t('table.kpi')}</TableHead>
+ <TableHead className="text-xs">{t('table.value')}</TableHead>
+ <TableHead className="text-xs">{t('table.change')}</TableHead>
+ <TableHead className="text-xs">{t('table.trend')}</TableHead>
+ <TableHead className="text-xs">{t('table.status')}</TableHead>
+ <TableHead className="text-xs">{t('table.goal')}</TableHead>
+ <TableHead className="text-xs">{t('table.vsGoal')}</TableHead>
+ <TableHead className="w-10">
+ <span className="sr-only">{t('table.actions')}</span>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {kpis.map((kpi) => {
+ const Icon = KPI_ICONS[kpi.key];
+ return (
+ <TableRow key={kpi.key}>
+ <TableCell>
+ <div className="flex items-center gap-3">
+ <div className="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" />
+ </div>
+ <div className="min-w-0">
+ <p className="text-sm font-medium">{tRegistry(`${kpi.key}.name`)}</p>
+ <p className="truncate text-xs text-muted-foreground">
+ {tRegistry(`${kpi.key}.description`)}
+ </p>
+ </div>
+ </div>
+ </TableCell>
+ <TableCell className="text-sm font-semibold tabular-nums">
+ {formatKpiValue(kpi.value, kpi.unit)}
+ </TableCell>
+ <TableCell>
+ <KpiChange snapshot={kpi} />
+ </TableCell>
+ <TableCell>
+ <div className={STATUS_TEXT[kpi.status]}>
+ <KpiSparkline points={kpi.trend} />
+ </div>
+ </TableCell>
+ <TableCell>
+ <Badge variant="outline" className={STATUS_BADGE[kpi.status]}>
+ <span
+ aria-hidden="true"
+ className="h-1.5 w-1.5 rounded-full bg-current opacity-70"
+ />
+ {t(`status.${kpi.status}`)}
+ </Badge>
+ </TableCell>
+ <TableCell className="text-xs text-muted-foreground tabular-nums">
+ {formatKpiValue(kpi.target, kpi.unit)}
+ </TableCell>
+ <TableCell>
+ <GoalProgress snapshot={kpi} />
+ </TableCell>
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className="rounded p-1 text-muted-foreground hover:bg-muted disabled:pointer-events-none disabled:opacity-50"
+ disabled={busyKey === kpi.key}
+ aria-label={t('menu.label', { name: tRegistry(`${kpi.key}.name`) })}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => onEdit(kpi.key)}>
+ <Pencil className="h-4 w-4" />
+ {t('menu.edit')}
+ </DropdownMenuItem>
+ <DropdownMenuItem variant="destructive" onClick={() => onRemove(kpi.key)}>
+ <Trash2 className="h-4 w-4" />
+ {t('menu.remove')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
diff --git a/web/src/components/action-center/signal-drawer.tsx b/web/src/components/action-center/signal-drawer.tsx
new file mode 100644
index 000000000..53ceb7d81
--- /dev/null
+++ b/web/src/components/action-center/signal-drawer.tsx
@@ -0,0 +1,230 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { ArrowUpRight, Check, Eye, RotateCcw, X } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Separator } from '@/components/ui/separator';
+import type { Signal } from '@/lib/actions/signals';
+import { SIGNAL_KINDS, type SignalStatus } from '@/lib/signals/registry';
+import { signalAffected, signalTexts } from '@/lib/signals/display';
+import { isKpiKey } from '@/lib/kpis/registry';
+import { ImpactDots, SIGNAL_ICONS, SignalStatusBadge, SourceList } from './signal-table';
+
+/**
+ * Signal detail: the evidence view. Deliberately light in v1 — identity,
+ * the measured change, affected entities, related KPIs, and triage. The
+ * "Create Action" CTA belongs to the Actions iteration and is absent rather
+ * than dead.
+ */
+export function SignalDrawer({
+ signal,
+ onOpenChange,
+ onStatusChange,
+ isBusy,
+}: {
+ signal: Signal | null;
+ onOpenChange: (open: boolean) => void;
+ onStatusChange: (signal: Signal, status: SignalStatus) => void;
+ isBusy: boolean;
+}) {
+ const t = useTranslations('actionCenter.signalsPage');
+ const tTexts = useTranslations('actionCenter.signalTexts');
+ const tCategories = useTranslations('actionCenter.signalCategories');
+ const tRegistry = useTranslations('actionCenter.registry');
+
+ if (!signal) return null;
+ const texts = signalTexts(signal, tTexts);
+ const affected = signalAffected(signal, t);
+ const stateKey = SIGNAL_KINDS[signal.kind].stateKey;
+ const relatedKpis = signal.kpiKeys.filter(isKpiKey);
+
+ const formatStamp = (iso: string) =>
+ new Date(iso).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ });
+
+ return (
+ <Sheet open={Boolean(signal)} onOpenChange={onOpenChange}>
+ <SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-md">
+ <SheetHeader className="border-b px-6 py-4">
+ <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ <span>{tCategories(signal.category)}</span>
+ <span>·</span>
+ <span>{t(`states.${stateKey}`)}</span>
+ <span className="flex items-center gap-1.5">
+ <ImpactDots impact={signal.impact} />
+ {t(`impact.${signal.impact}`)}
+ </span>
+ </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">
+ <HeaderIcon kind={signal.kind} />
+ </div>
+ <div className="min-w-0">
+ <SheetTitle>{texts.title}</SheetTitle>
+ <SheetDescription>{texts.description}</SheetDescription>
+ </div>
+ </div>
+ </SheetHeader>
+
+ <div className="flex-1 space-y-5 overflow-y-auto px-6 py-4 text-sm">
+ <div className="grid grid-cols-2 gap-x-4 gap-y-3">
+ <DetailItem label={t('drawer.status')}>
+ <SignalStatusBadge status={signal.status} />
+ </DetailItem>
+ <DetailItem label={t('drawer.source')}>
+ <SourceList sources={signal.source} />
+ </DetailItem>
+ <DetailItem label={t('drawer.detected')}>
+ <span className="text-xs tabular-nums">{formatStamp(signal.detectedAt)}</span>
+ </DetailItem>
+ <DetailItem label={t('drawer.lastDetected')}>
+ <span className="text-xs tabular-nums">{formatStamp(signal.lastDetectedAt)}</span>
+ </DetailItem>
+ </div>
+
+ {(signal.previousValue !== null || signal.changeValue !== null) && (
+ <>
+ <Separator />
+ <div>
+ <p className="text-xs font-medium text-muted-foreground">
+ {t('drawer.whatChanged')}
+ </p>
+ <div className="mt-2 flex items-baseline gap-3 tabular-nums">
+ {signal.previousValue !== null && (
+ <span className="text-sm text-muted-foreground line-through">
+ {signal.previousValue}
+ </span>
+ )}
+ {signal.currentValue !== null && (
+ <span className="text-lg font-semibold">{signal.currentValue}</span>
+ )}
+ {signal.changeValue !== null && (
+ <span
+ className={
+ signal.changeValue >= 0 === SIGNAL_KINDS[signal.kind].positive
+ ? 'text-xs font-medium text-green-600 dark:text-green-400'
+ : 'text-xs font-medium text-red-500'
+ }
+ >
+ {signal.changeValue > 0 ? '+' : ''}
+ {signal.changeValue}
+ </span>
+ )}
+ </div>
+ </div>
+ </>
+ )}
+
+ <Separator />
+ <div>
+ <p className="text-xs font-medium text-muted-foreground">{t('drawer.affected')}</p>
+ <p className="mt-1 text-sm">{affected.label}</p>
+ {affected.detail && (
+ <p className="break-all text-xs text-muted-foreground">{affected.detail}</p>
+ )}
+ {typeof signal.payload.promptId === 'string' && (
+ <Link
+ href={`/dashboard/prompts/${signal.payload.promptId}`}
+ className="mt-2 inline-flex items-center gap-1 text-xs font-medium text-foreground underline-offset-2 hover:underline"
+ >
+ {t('drawer.viewPrompt')}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
+ )}
+ </div>
+
+ {relatedKpis.length > 0 && (
+ <>
+ <Separator />
+ <div>
+ <p className="text-xs font-medium text-muted-foreground">
+ {t('drawer.relatedKpis')}
+ </p>
+ <div className="mt-2 flex flex-wrap gap-1.5">
+ {relatedKpis.map((key) => (
+ <Badge key={key} variant="outline" className="text-xs">
+ {tRegistry(`${key}.name`)}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+
+ <div className="flex flex-wrap justify-end gap-2 border-t px-6 py-4">
+ {signal.status === 'new' && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={isBusy}
+ onClick={() => onStatusChange(signal, 'acknowledged')}
+ >
+ <Eye className="h-3.5 w-3.5" />
+ {t('menu.acknowledge')}
+ </Button>
+ )}
+ {(signal.status === 'new' || signal.status === 'acknowledged') && (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={isBusy}
+ onClick={() => onStatusChange(signal, 'dismissed')}
+ >
+ <X className="h-3.5 w-3.5" />
+ {t('menu.dismiss')}
+ </Button>
+ <Button
+ size="sm"
+ disabled={isBusy}
+ onClick={() => onStatusChange(signal, 'resolved')}
+ >
+ <Check className="h-3.5 w-3.5" />
+ {t('menu.resolve')}
+ </Button>
+ </>
+ )}
+ {(signal.status === 'resolved' || signal.status === 'dismissed') && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={isBusy}
+ onClick={() => onStatusChange(signal, 'new')}
+ >
+ <RotateCcw className="h-3.5 w-3.5" />
+ {t('menu.reopen')}
+ </Button>
+ )}
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function HeaderIcon({ kind }: { kind: Signal['kind'] }) {
+ const Icon = SIGNAL_ICONS[kind];
+ return <Icon className="h-4 w-4 text-muted-foreground" />;
+}
+
+function DetailItem({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div>
+ <p className="text-xs font-medium text-muted-foreground">{label}</p>
+ <div className="mt-1">{children}</div>
+ </div>
+ );
+}
diff --git a/web/src/components/action-center/signal-table.tsx b/web/src/components/action-center/signal-table.tsx
new file mode 100644
index 000000000..e6cac7306
--- /dev/null
+++ b/web/src/components/action-center/signal-table.tsx
@@ -0,0 +1,279 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import {
+ BarChart3,
+ Check,
+ Eye,
+ Gauge,
+ Link2,
+ MessageSquare,
+ MoreHorizontal,
+ MousePointerClick,
+ RotateCcw,
+ Search,
+ Sparkles,
+ Swords,
+ TrendingDown,
+ TrendingUp,
+ Trophy,
+ Unlink,
+ X,
+} from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import type { Signal } from '@/lib/actions/signals';
+import {
+ SIGNAL_KINDS,
+ type SignalImpact,
+ type SignalKind,
+ type SignalSource,
+ type SignalStatus,
+} from '@/lib/signals/registry';
+import { signalAffected, signalTexts } from '@/lib/signals/display';
+import { formatRelative } from '@/lib/format-relative';
+import { cn } from '@/lib/utils';
+
+export const SIGNAL_ICONS: Record<SignalKind, React.ComponentType<{ className?: string }>> = {
+ sharp_drop: TrendingDown,
+ prompt_gain: TrendingUp,
+ new_engine: Sparkles,
+ lost_citations: Unlink,
+ first_citation: Link2,
+ competitor_surge: Swords,
+ competitor_crossed: Swords,
+ competitor_overtaken: Trophy,
+ page_opportunity: MousePointerClick,
+ uncited_mentions: MessageSquare,
+ audit_low_score: Gauge,
+};
+
+const SOURCE_ICONS: Record<SignalSource, React.ComponentType<{ className?: string }>> = {
+ ai_results: Sparkles,
+ ga4: BarChart3,
+ gsc: Search,
+ site_audit: Gauge,
+};
+
+/** Data sources as icon + name pairs — icons carry recognition, the text
+ * stays the accessible signal. */
+export function SourceList({ sources }: { sources: SignalSource[] }) {
+ const t = useTranslations('actionCenter.signalsPage');
+ return (
+ <span className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
+ {sources.map((source) => {
+ const Icon = SOURCE_ICONS[source];
+ return (
+ <span key={source} className="flex items-center gap-1 text-xs text-muted-foreground">
+ {Icon && <Icon className="h-3 w-3" />}
+ {t(`sources.${source}`)}
+ </span>
+ );
+ })}
+ </span>
+ );
+}
+
+/**
+ * Impact as the mockup's multi-dot meter. Never color alone: the dots sit
+ * beside the impact word, which carries the meaning for assistive tech.
+ */
+export function ImpactDots({ impact }: { impact: SignalImpact }) {
+ const filled = impact === 'high' ? 3 : impact === 'medium' ? 2 : 1;
+ const color =
+ impact === 'high' ? 'bg-red-500' : impact === 'medium' ? 'bg-amber-500' : 'bg-muted-foreground';
+ return (
+ <span className="flex items-center gap-0.5" aria-hidden="true">
+ {[0, 1, 2].map((i) => (
+ <span key={i} className={cn('h-1.5 w-1.5 rounded-full', i < filled ? color : 'bg-muted')} />
+ ))}
+ </span>
+ );
+}
+
+export const STATUS_BADGE: Record<SignalStatus, string> = {
+ new: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400',
+ acknowledged: 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400',
+ resolved: 'border-green-500/30 bg-green-500/10 text-green-600 dark:text-green-400',
+ dismissed: 'border-border bg-muted/50 text-muted-foreground',
+};
+
+const STATE_TEXT: Record<string, string> = {
+ dropped: 'text-red-600 dark:text-red-400',
+ lost: 'text-red-600 dark:text-red-400',
+ crossed: 'text-red-600 dark:text-red-400',
+ gain: 'text-red-600 dark:text-red-400',
+ gained: 'text-green-600 dark:text-green-400',
+ overtaken: 'text-green-600 dark:text-green-400',
+ opportunity: 'text-emerald-600 dark:text-emerald-400',
+};
+
+export function SignalStatusBadge({ status }: { status: SignalStatus }) {
+ const t = useTranslations('actionCenter.signalsPage');
+ return (
+ <Badge variant="outline" className={STATUS_BADGE[status]}>
+ <span aria-hidden="true" className="h-1.5 w-1.5 rounded-full bg-current opacity-70" />
+ {t(`status.${status}`)}
+ </Badge>
+ );
+}
+
+function detectedLabel(iso: string, tCommon: ReturnType<typeof useTranslations>): string {
+ return formatRelative(iso, tCommon);
+}
+
+function KindIcon({ kind }: { kind: SignalKind }) {
+ const Icon = SIGNAL_ICONS[kind];
+ return <Icon className="h-4 w-4 text-muted-foreground" />;
+}
+
+export function SignalTable({
+ signals,
+ onSelect,
+ onStatusChange,
+ busyId,
+}: {
+ signals: Signal[];
+ onSelect: (signal: Signal) => void;
+ onStatusChange: (signal: Signal, status: SignalStatus) => void;
+ busyId: string | null;
+}) {
+ const t = useTranslations('actionCenter.signalsPage');
+ const tTexts = useTranslations('actionCenter.signalTexts');
+ const tCategories = useTranslations('actionCenter.signalCategories');
+ const tCommon = useTranslations('common');
+
+ return (
+ <div className="overflow-x-auto rounded-lg border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="text-xs">{t('table.signal')}</TableHead>
+ <TableHead className="text-xs">{t('table.type')}</TableHead>
+ <TableHead className="text-xs">{t('table.impact')}</TableHead>
+ <TableHead className="text-xs">{t('table.source')}</TableHead>
+ <TableHead className="text-xs">{t('table.affected')}</TableHead>
+ <TableHead className="text-xs">{t('table.detected')}</TableHead>
+ <TableHead className="text-xs">{t('table.status')}</TableHead>
+ <TableHead className="w-10">
+ <span className="sr-only">{t('table.actions')}</span>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {signals.map((signal) => {
+ const texts = signalTexts(signal, tTexts);
+ const affected = signalAffected(signal, t);
+ const stateKey = SIGNAL_KINDS[signal.kind].stateKey;
+ const detected = new Date(signal.detectedAt);
+ return (
+ <TableRow key={signal.id} className="cursor-pointer" onClick={() => onSelect(signal)}>
+ <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">
+ <KindIcon kind={signal.kind} />
+ </div>
+ <div className="min-w-0">
+ <p className="truncate text-sm font-medium">{texts.title}</p>
+ <p className="truncate text-xs text-muted-foreground">{texts.description}</p>
+ </div>
+ </div>
+ </TableCell>
+ <TableCell>
+ <p className="text-xs font-medium">{tCategories(signal.category)}</p>
+ <p className={cn('text-xs', STATE_TEXT[stateKey] ?? 'text-muted-foreground')}>
+ {t(`states.${stateKey}`)}
+ </p>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-1.5">
+ <span className="text-xs">{t(`impact.${signal.impact}`)}</span>
+ <ImpactDots impact={signal.impact} />
+ </div>
+ </TableCell>
+ <TableCell>
+ <SourceList sources={signal.source} />
+ </TableCell>
+ <TableCell className="max-w-[180px]">
+ <p className="text-xs font-medium">{affected.label}</p>
+ {affected.detail && (
+ <p className="truncate text-xs text-muted-foreground">{affected.detail}</p>
+ )}
+ </TableCell>
+ <TableCell>
+ <p className="text-xs tabular-nums">
+ {detected.toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ })}
+ {', '}
+ {detected.toLocaleTimeString('en-US', {
+ hour: 'numeric',
+ minute: '2-digit',
+ })}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {detectedLabel(signal.detectedAt, tCommon)}
+ </p>
+ </TableCell>
+ <TableCell>
+ <SignalStatusBadge status={signal.status} />
+ </TableCell>
+ <TableCell onClick={(e) => e.stopPropagation()}>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className="rounded p-1 text-muted-foreground hover:bg-muted disabled:pointer-events-none disabled:opacity-50"
+ disabled={busyId === signal.id}
+ aria-label={t('menu.label')}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {signal.status === 'new' && (
+ <DropdownMenuItem onClick={() => onStatusChange(signal, 'acknowledged')}>
+ <Eye className="h-4 w-4" />
+ {t('menu.acknowledge')}
+ </DropdownMenuItem>
+ )}
+ {(signal.status === 'new' || signal.status === 'acknowledged') && (
+ <>
+ <DropdownMenuItem onClick={() => onStatusChange(signal, 'resolved')}>
+ <Check className="h-4 w-4" />
+ {t('menu.resolve')}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => onStatusChange(signal, 'dismissed')}>
+ <X className="h-4 w-4" />
+ {t('menu.dismiss')}
+ </DropdownMenuItem>
+ </>
+ )}
+ {(signal.status === 'resolved' || signal.status === 'dismissed') && (
+ <DropdownMenuItem onClick={() => onStatusChange(signal, 'new')}>
+ <RotateCcw className="h-4 w-4" />
+ {t('menu.reopen')}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
diff --git a/web/src/components/ui/select.tsx b/web/src/components/ui/select.tsx
index decf8d1d8..1e3fe6743 100644
--- a/web/src/components/ui/select.tsx
+++ b/web/src/components/ui/select.tsx
@@ -6,7 +6,37 @@ import { Select as SelectPrimitive } from '@base-ui/react/select';
import { cn } from '@/lib/utils';
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from 'lucide-react';
-const Select = SelectPrimitive.Root;
+/**
+ * RULE — always pass `items` (value/label pairs) to the Select root.
+ *
+ * Base UI's Select.Value renders the RAW VALUE in the trigger unless the
+ * root receives `items` to map values to labels. A select over enum-ish
+ * values ("in_progress", model ids, timeframe keys) therefore reads fine in
+ * the dropdown but shows the bare value once picked — a bug that has
+ * slipped into first implementations repeatedly. Passing `items` even when
+ * value === label costs one line and can never be wrong.
+ *
+ * Development builds warn once per page load when a Select renders without
+ * items, so the mistake is caught at first render instead of in review.
+ */
+let warnedMissingItems = false;
+
+function Select<Value, Multiple extends boolean | undefined = false>(
+ props: SelectPrimitive.Root.Props<Value, Multiple>,
+) {
+ const missingItems = props.items === undefined;
+ React.useEffect(() => {
+ if (process.env.NODE_ENV !== 'production' && missingItems && !warnedMissingItems) {
+ warnedMissingItems = true;
+ console.warn(
+ '[ui/select] A Select rendered without `items`. Base UI shows the raw value in the ' +
+ 'trigger unless the root gets {value, label} items — pass them (see select.tsx). ' +
+ 'Warning shown once per page load; more selects may be affected.',
+ );
+ }
+ }, [missingItems]);
+ return <SelectPrimitive.Root {...props} />;
+}
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
return (
diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.ts
index df9f4eb44..f893bf29b 100644
--- a/web/src/config/dashboard.ts
+++ b/web/src/config/dashboard.ts
@@ -10,6 +10,7 @@ import {
ShoppingBag,
Sparkles,
Tag,
+ Target,
} from 'lucide-react';
import type { Feature } from '@/config/plans';
@@ -52,6 +53,11 @@ export const dashboardNav: NavGroup[] = [
icon: Sparkles,
requiredFeature: 'ai_agent',
},
+ {
+ title: 'Action Center',
+ href: '/dashboard/action-center',
+ icon: Target,
+ },
],
},
{
diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.ts
new file mode 100644
index 000000000..9c6bb1158
--- /dev/null
+++ b/web/src/lib/action-center/display.ts
@@ -0,0 +1,100 @@
+import type { ActionItem } from '@/lib/actions/action-center';
+
+/**
+ * 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.
+ */
+
+type Translator = (key: string, values?: Record<string, string | number>) => string;
+
+function num(payload: Record<string, unknown>, key: string): number {
+ return Number(payload[key] ?? 0);
+}
+
+export function actionTexts(
+ action: ActionItem,
+ t: Translator,
+): { title: string; description: string } {
+ const p = action.payload;
+ switch (action.kind) {
+ case 'recover_visibility': {
+ const hasDrop = p.dropFrom !== undefined && p.dropFrom !== null;
+ return {
+ title: t('recover_visibility.title'),
+ description: hasDrop
+ ? t('recover_visibility.descriptionWithDrop', {
+ from: num(p, 'dropFrom'),
+ to: num(p, 'dropTo'),
+ prompts: num(p, 'promptCount'),
+ })
+ : t('recover_visibility.description', { prompts: num(p, 'promptCount') }),
+ };
+ }
+ case 'capture_ai_traffic':
+ return {
+ title: t('capture_ai_traffic.title', { pages: num(p, 'pageCount') }),
+ description: t('capture_ai_traffic.description'),
+ };
+ case 'convert_mentions':
+ return {
+ title: t('convert_mentions.title'),
+ description: t('convert_mentions.description', { prompts: num(p, 'promptCount') }),
+ };
+ case 'fix_low_scores':
+ return {
+ title: t('fix_low_scores.title'),
+ description: t('fix_low_scores.description', { pages: num(p, 'pageCount') }),
+ };
+ case 'close_competitor_gap': {
+ const names = Array.isArray(p.competitorNames) ? (p.competitorNames as string[]) : [];
+ return {
+ title:
+ names.length === 1
+ ? t('close_competitor_gap.title', { name: names[0] })
+ : t('close_competitor_gap.titleMany'),
+ description: t('close_competitor_gap.description'),
+ };
+ }
+ }
+}
+
+/** 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 })];
+ switch (action.kind) {
+ case 'recover_visibility':
+ if (num(p, 'promptCount') > 0) tags.push(t('tags.prompts', { count: num(p, 'promptCount') }));
+ break;
+ case 'capture_ai_traffic':
+ tags.push(t('tags.pages', { count: num(p, 'pageCount') }));
+ break;
+ case 'convert_mentions':
+ tags.push(t('tags.prompts', { count: num(p, 'promptCount') }));
+ break;
+ case 'fix_low_scores':
+ tags.push(t('tags.pages', { count: num(p, 'pageCount') }));
+ break;
+ case 'close_competitor_gap': {
+ const names = Array.isArray(p.competitorNames) ? (p.competitorNames as string[]) : [];
+ if (names[0]) tags.push(names[0]);
+ break;
+ }
+ }
+ return tags;
+}
+
+const IMPACT_RANK: Record<ActionItem['impact'], number> = { high: 3, medium: 2, low: 1 };
+
+/** Priority: impact first, then weight of evidence, then recency. The
+ * scoring formula stays out of the UI per the brief — this order IS it. */
+export function comparePriority(a: ActionItem, b: ActionItem): number {
+ return (
+ IMPACT_RANK[b.impact] - IMPACT_RANK[a.impact] ||
+ b.signalCount - a.signalCount ||
+ b.updatedAt.localeCompare(a.updatedAt)
+ );
+}
diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.ts
new file mode 100644
index 000000000..24ebc501a
--- /dev/null
+++ b/web/src/lib/action-center/registry.ts
@@ -0,0 +1,92 @@
+/**
+ * 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.
+ */
+
+export type ActionCategory = 'growth' | 'protect' | 'recover' | 'fix' | 'compete';
+
+export type ActionImpact = 'high' | 'medium' | 'low';
+
+export type ActionStatus =
+ | 'new'
+ | 'in_progress'
+ | 'completed'
+ | 'on_hold'
+ | 'no_improvement'
+ | 'dismissed';
+
+export type ActionKind =
+ | 'recover_visibility'
+ | 'capture_ai_traffic'
+ | 'convert_mentions'
+ | 'fix_low_scores'
+ | 'close_competitor_gap';
+
+export type TaskStatus = 'todo' | 'in_progress' | 'completed' | 'blocked';
+
+export const ACTION_CATEGORIES: readonly ActionCategory[] = [
+ 'growth',
+ 'protect',
+ 'recover',
+ 'fix',
+ 'compete',
+];
+
+export const ACTION_STATUSES: readonly ActionStatus[] = [
+ 'new',
+ 'in_progress',
+ 'completed',
+ 'on_hold',
+ 'no_improvement',
+ 'dismissed',
+];
+
+export const ACTION_IMPACTS: readonly ActionImpact[] = ['high', 'medium', 'low'];
+
+export const TASK_STATUSES: readonly TaskStatus[] = ['todo', 'in_progress', 'completed', 'blocked'];
+
+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'],
+ },
+ 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 function isActionKind(value: string): value is ActionKind {
+ return value in ACTION_KINDS;
+}
+
+/** Sort orders the toolbar offers. Priority is impact-weighted evidence. */
+export type ActionSort = 'priority' | 'impact' | 'newest' | 'due_date' | 'updated';
+export const ACTION_SORTS: readonly ActionSort[] = [
+ 'priority',
+ 'impact',
+ 'newest',
+ 'due_date',
+ 'updated',
+];
diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.ts
new file mode 100644
index 000000000..cab5b7675
--- /dev/null
+++ b/web/src/lib/actions/action-center.ts
@@ -0,0 +1,305 @@
+'use server';
+
+/**
+ * Action Center actions — reads and execution writes.
+ *
+ * Rows are produced nightly by the server's generator (consolidating open
+ * signals); this module reads them and carries the user's execution work:
+ * status changes, assignment, due dates, task progress. Every mutation logs
+ * an action_event, which is what the drawer's History tab shows — the trail
+ * is written as it happens, not reconstructed.
+ */
+
+import { createClient } from '@/lib/supabase/server';
+import {
+ isActionKind,
+ type ActionCategory,
+ type ActionImpact,
+ type ActionKind,
+ type ActionStatus,
+ type TaskStatus,
+} from '@/lib/action-center/registry';
+import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';
+import type { KpiTimeframe } from '@/lib/kpis/registry';
+
+export interface ActionAssignee {
+ id: string;
+ fullName: string | null;
+ avatarUrl: string | null;
+}
+
+export interface ActionItem {
+ id: string;
+ actionNo: number;
+ category: ActionCategory;
+ kind: ActionKind;
+ impact: ActionImpact;
+ status: ActionStatus;
+ payload: Record<string, unknown>;
+ kpiKeys: string[];
+ assignee: ActionAssignee | null;
+ dueDate: string | null;
+ createdAt: string;
+ updatedAt: string;
+ taskTotal: number;
+ taskCompleted: number;
+ signalCount: number;
+}
+
+interface ActionRow {
+ id: string;
+ action_no: number;
+ category: string;
+ kind: string;
+ impact: string;
+ status: string;
+ payload: Record<string, unknown>;
+ kpi_keys: string[];
+ assignee_id: string | null;
+ due_date: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+const ACTION_COLUMNS =
+ 'id, action_no, category, kind, impact, status, payload, kpi_keys, assignee_id, due_date, created_at, updated_at';
+
+export async function getActions(brandId: string): Promise<ActionItem[]> {
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('actions')
+ .select(ACTION_COLUMNS)
+ .eq('brand_id', brandId)
+ .limit(1000);
+ if (error) throw new Error(error.message);
+ const rows = ((data ?? []) as ActionRow[]).filter((row) => isActionKind(row.kind));
+ if (rows.length === 0) return [];
+
+ const actionIds = rows.map((row) => row.id);
+ const assigneeIds = [...new Set(rows.map((row) => row.assignee_id).filter(Boolean))] as string[];
+
+ const [tasksRes, signalsRes, profilesRes] = await Promise.all([
+ supabase.from('action_tasks').select('action_id, status').in('action_id', actionIds),
+ supabase
+ .from('signals')
+ .select('action_id')
+ .eq('brand_id', brandId)
+ .not('action_id', 'is', null),
+ assigneeIds.length > 0
+ ? supabase.from('profiles').select('id, full_name, avatar_url').in('id', assigneeIds)
+ : Promise.resolve({ data: [], error: null }),
+ ]);
+ if (tasksRes.error) throw new Error(tasksRes.error.message);
+ if (signalsRes.error) throw new Error(signalsRes.error.message);
+ if (profilesRes.error) throw new Error(profilesRes.error.message);
+
+ const taskTotals = new Map<string, { total: number; completed: number }>();
+ for (const task of tasksRes.data ?? []) {
+ const acc = taskTotals.get(task.action_id) ?? { total: 0, completed: 0 };
+ acc.total += 1;
+ if (task.status === 'completed') acc.completed += 1;
+ taskTotals.set(task.action_id, acc);
+ }
+ const signalCounts = new Map<string, number>();
+ for (const signal of signalsRes.data ?? []) {
+ if (!signal.action_id) continue;
+ signalCounts.set(signal.action_id, (signalCounts.get(signal.action_id) ?? 0) + 1);
+ }
+ const profiles = new Map(
+ (profilesRes.data ?? []).map((p) => [
+ p.id as string,
+ {
+ id: p.id as string,
+ fullName: (p.full_name as string | null) ?? null,
+ avatarUrl: (p.avatar_url as string | null) ?? null,
+ },
+ ]),
+ );
+
+ return rows.map((row) => ({
+ id: row.id,
+ actionNo: Number(row.action_no),
+ category: row.category as ActionCategory,
+ kind: row.kind as ActionKind,
+ impact: row.impact as ActionImpact,
+ status: row.status as ActionStatus,
+ payload: row.payload ?? {},
+ kpiKeys: row.kpi_keys ?? [],
+ assignee: row.assignee_id ? (profiles.get(row.assignee_id) ?? null) : null,
+ dueDate: row.due_date,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ taskTotal: taskTotals.get(row.id)?.total ?? 0,
+ taskCompleted: taskTotals.get(row.id)?.completed ?? 0,
+ signalCount: signalCounts.get(row.id) ?? 0,
+ }));
+}
+
+export interface ActionTask {
+ id: string;
+ position: number;
+ taskKey: string;
+ status: TaskStatus;
+}
+
+export interface ActionEvent {
+ id: string;
+ event: string;
+ data: Record<string, unknown>;
+ actorId: string | null;
+ createdAt: string;
+}
+
+export interface ActionKpiRef {
+ kpiKey: string;
+ target: number;
+ timeframe: KpiTimeframe;
+}
+
+export interface ActionDetail {
+ tasks: ActionTask[];
+ signals: Signal[];
+ events: ActionEvent[];
+ kpis: ActionKpiRef[];
+}
+
+/** Everything the drawer's tabs need beyond the list row, in one round trip
+ * per source. `kpis` are the brand's configured definitions among the
+ * action's kpi_keys — evidence of which goals this work serves. */
+export async function getActionDetail(brandId: string, actionId: string): Promise<ActionDetail> {
+ const supabase = await createClient();
+ const [tasksRes, signalsRes, eventsRes, kpisRes] = await Promise.all([
+ supabase
+ .from('action_tasks')
+ .select('id, position, task_key, status')
+ .eq('action_id', actionId)
+ .order('position'),
+ supabase
+ .from('signals')
+ .select(SIGNAL_ROW_COLUMNS)
+ .eq('brand_id', brandId)
+ .eq('action_id', actionId)
+ .order('detected_at', { ascending: false }),
+ supabase
+ .from('action_events')
+ .select('id, event, data, actor_id, created_at')
+ .eq('action_id', actionId)
+ .order('created_at'),
+ supabase
+ .from('kpi_definitions')
+ .select('kpi_key, target, timeframe')
+ .eq('brand_id', brandId)
+ .eq('is_active', true),
+ ]);
+ if (tasksRes.error) throw new Error(tasksRes.error.message);
+ if (signalsRes.error) throw new Error(signalsRes.error.message);
+ if (eventsRes.error) throw new Error(eventsRes.error.message);
+ if (kpisRes.error) throw new Error(kpisRes.error.message);
+
+ return {
+ tasks: (tasksRes.data ?? []).map((task) => ({
+ id: task.id,
+ position: task.position,
+ taskKey: task.task_key,
+ status: task.status as TaskStatus,
+ })),
+ signals: mapSignalRows((signalsRes.data ?? []) as SignalRow[]),
+ events: (eventsRes.data ?? []).map((event) => ({
+ id: event.id,
+ event: event.event,
+ data: (event.data ?? {}) as Record<string, unknown>,
+ actorId: event.actor_id,
+ createdAt: event.created_at,
+ })),
+ kpis: (kpisRes.data ?? []).map((kpi) => ({
+ kpiKey: kpi.kpi_key,
+ target: Number(kpi.target),
+ timeframe: kpi.timeframe as KpiTimeframe,
+ })),
+ };
+}
+
+async function logEvent(
+ supabase: Awaited<ReturnType<typeof createClient>>,
+ actionId: string,
+ event: string,
+ data: Record<string, string | number | null>,
+) {
+ const { data: auth } = await supabase.auth.getUser();
+ // Best-effort: a missing trail entry must not fail the change it records.
+ await supabase
+ .from('action_events')
+ .insert({ action_id: actionId, event, data, actor_id: auth.user?.id ?? null });
+}
+
+export async function updateActionStatus(
+ brandId: string,
+ actionId: string,
+ status: ActionStatus,
+): Promise<void> {
+ const supabase = await createClient();
+ const { error } = await supabase
+ .from('actions')
+ .update({
+ status,
+ completed_at: status === 'completed' ? new Date().toISOString() : null,
+ updated_at: new Date().toISOString(),
+ })
+ .eq('brand_id', brandId)
+ .eq('id', actionId);
+ if (error) throw new Error(error.message);
+ await logEvent(supabase, actionId, 'status_changed', { to: status });
+}
+
+export async function assignAction(
+ brandId: string,
+ actionId: string,
+ assigneeId: string | null,
+): Promise<void> {
+ const supabase = await createClient();
+ const { error } = await supabase
+ .from('actions')
+ .update({ assignee_id: assigneeId, updated_at: new Date().toISOString() })
+ .eq('brand_id', brandId)
+ .eq('id', actionId);
+ if (error) throw new Error(error.message);
+ await logEvent(supabase, actionId, 'assigned', { assigneeId });
+}
+
+export async function setActionDueDate(
+ brandId: string,
+ actionId: string,
+ dueDate: string | null,
+): Promise<void> {
+ const supabase = await createClient();
+ const { error } = await supabase
+ .from('actions')
+ .update({ due_date: dueDate, updated_at: new Date().toISOString() })
+ .eq('brand_id', brandId)
+ .eq('id', actionId);
+ if (error) throw new Error(error.message);
+ await logEvent(supabase, actionId, 'due_date_set', { dueDate });
+}
+
+export async function updateTaskStatus(
+ brandId: string,
+ actionId: string,
+ taskId: string,
+ status: TaskStatus,
+): Promise<void> {
+ const supabase = await createClient();
+ const { error } = await supabase
+ .from('action_tasks')
+ .update({ status, updated_at: new Date().toISOString() })
+ .eq('action_id', actionId)
+ .eq('id', taskId);
+ if (error) throw new Error(error.message);
+ await logEvent(supabase, actionId, 'task_status', { taskId, to: status });
+ // Bump the action's updated stamp so the table's Updated column tracks
+ // real work, not just nightly refreshes.
+ await supabase
+ .from('actions')
+ .update({ updated_at: new Date().toISOString() })
+ .eq('brand_id', brandId)
+ .eq('id', actionId);
+}
diff --git a/web/src/lib/actions/kpis.ts b/web/src/lib/actions/kpis.ts
new file mode 100644
index 000000000..3aa1ebd06
--- /dev/null
+++ b/web/src/lib/actions/kpis.ts
@@ -0,0 +1,424 @@
+'use server';
+
+/**
+ * Action Center KPI snapshots.
+ *
+ * `kpi_definitions` stores what the user decided (target, timeframe, active);
+ * this module computes everything a reader sees next to it — value, change,
+ * 7-day trend, progress, status — at read time, from the same actions and
+ * RPCs the analytics surfaces already use. Reusing those paths is the point:
+ * a KPI row and the dashboard it summarizes cannot show different numbers,
+ * because they are the same query.
+ *
+ * Nothing computed is ever written back. Status in particular is derived on
+ * every read (lib/kpis/status.ts) so a badge can never go stale against the
+ * value standing next to it.
+ */
+
+import { createClient } from '@/lib/supabase/server';
+import {
+ DEFAULT_KPI_SET,
+ KPI_REGISTRY,
+ TIMEFRAME_DAYS,
+ isKpiKey,
+ isValidKpiTarget,
+ type KpiCategory,
+ type KpiDirection,
+ type KpiKey,
+ type KpiTimeframe,
+ type KpiUnit,
+} from '@/lib/kpis/registry';
+import {
+ deriveKpiStatus,
+ kpiProgress,
+ scaleTargetToWindow,
+ type KpiStatus,
+} from '@/lib/kpis/status';
+import { getInsightsSummary, getShareOfVoiceData, getVisibilityRateTrend } from './tracking';
+import { getTrafficSummary, getTrafficTrend } from './traffic';
+
+const TREND_DAYS = 7;
+
+export interface KpiTrendPoint {
+ date: string;
+ value: number;
+}
+
+export interface KpiSnapshot {
+ key: KpiKey;
+ category: KpiCategory;
+ unit: KpiUnit;
+ direction: KpiDirection;
+ timeframe: KpiTimeframe;
+ /** Current value over the timeframe window, in the KPI's own unit. */
+ value: number;
+ /**
+ * Movement vs the previous equal-length window. Points for percent-unit
+ * KPIs, percent for counts — `changeKind` says which, and the UI must not
+ * render "+2.4 pts" as "+2.4%".
+ */
+ change: number | null;
+ changeKind: 'points' | 'percent';
+ /** Last 7 days, oldest first. Empty when the source has no daily series. */
+ trend: KpiTrendPoint[];
+ target: number;
+ /** value vs target as a percentage; may exceed 100. */
+ progress: number;
+ status: KpiStatus;
+}
+
+export interface KpiSnapshotsResult {
+ /** False only when the brand has no definitions at all → empty state. */
+ configured: boolean;
+ kpis: KpiSnapshot[];
+}
+
+interface KpiDefinitionRow {
+ kpi_key: string;
+ target: number;
+ timeframe: KpiTimeframe;
+ is_active: boolean;
+}
+
+const DAY_MS = 86_400_000;
+
+function utcToday(): string {
+ return new Date().toISOString().slice(0, 10);
+}
+
+function daysAgo(n: number): string {
+ return new Date(Date.now() - n * DAY_MS).toISOString().slice(0, 10);
+}
+
+function percentChange(current: number, previous: number | null): number | null {
+ if (previous === null || previous <= 0) return null;
+ return Math.round(((current - previous) / previous) * 1000) / 10;
+}
+
+function sumTrafficPoint(point: Record<string, unknown>): number {
+ let sum = 0;
+ for (const [key, val] of Object.entries(point)) {
+ if (key !== 'date' && typeof val === 'number') sum += val;
+ }
+ return sum;
+}
+
+/**
+ * Everything the tracking-backed KPIs in one timeframe window need, fetched
+ * once and shared: five KPIs must not mean five times the round trips when
+ * they share a window.
+ */
+async function fetchWindowMetrics(
+ brandId: string,
+ timeframe: KpiTimeframe,
+ keys: Set<KpiKey>,
+ windowOverride?: KpiWindow,
+) {
+ const windowDays = TIMEFRAME_DAYS[timeframe];
+ const days = windowOverride ?? { dayFrom: daysAgo(windowDays - 1), dayTo: utcToday() };
+ const trendFrom = daysAgo(TREND_DAYS - 1);
+
+ const wantsInsights = keys.has('citations') || keys.has('mentions');
+
+ const [visibility, insights, sov, traffic, trafficTrend, dailyTotals] = await Promise.all([
+ keys.has('ai_visibility') ? getVisibilityRateTrend(brandId, { days }) : null,
+ wantsInsights ? getInsightsSummary(brandId, { days }) : null,
+ keys.has('share_of_voice') ? getShareOfVoiceData(brandId, { days }) : null,
+ keys.has('ai_referral_traffic')
+ ? getTrafficSummary(brandId, {
+ dateFrom: `${days.dayFrom}T00:00:00.000Z`,
+ dateTo: `${days.dayTo}T23:59:59.999Z`,
+ })
+ : null,
+ keys.has('ai_referral_traffic')
+ ? getTrafficTrend(brandId, {
+ dateFrom: `${trendFrom}T00:00:00.000Z`,
+ dateTo: new Date().toISOString(),
+ })
+ : null,
+ // Mentions/citations have window aggregates but no daily-series RPC, so
+ // the 7-point sparkline is seven one-day aggregates in parallel. Each is
+ // a rollup read returning one JSON row; both KPIs share the same seven.
+ wantsInsights ? fetchDailyInsightTotals(brandId) : null,
+ ]);
+
+ return { visibility, insights, sov, traffic, trafficTrend, dailyTotals };
+}
+
+async function fetchDailyInsightTotals(brandId: string) {
+ const supabase = await createClient();
+ const days = Array.from({ length: TREND_DAYS }, (_, i) => daysAgo(TREND_DAYS - 1 - i));
+ const rows = await Promise.all(
+ days.map(async (day) => {
+ const { data, error } = await supabase.rpc('insights_aggregates_daily', {
+ p_brand_id: brandId,
+ p_platform: undefined,
+ p_models: undefined,
+ p_region: undefined,
+ p_day_from: day,
+ p_day_to: day,
+ });
+ if (error) throw new Error(error.message);
+ const agg = (data ?? {}) as { total_mentions?: number; total_citations?: number };
+ return {
+ date: day,
+ mentions: Number(agg.total_mentions ?? 0),
+ citations: Number(agg.total_citations ?? 0),
+ };
+ }),
+ );
+ return rows;
+}
+
+type WindowMetrics = Awaited<ReturnType<typeof fetchWindowMetrics>>;
+
+function buildSnapshot(
+ def: { kpiKey: KpiKey; target: number; timeframe: KpiTimeframe },
+ metrics: WindowMetrics,
+ windowDays?: number,
+): KpiSnapshot | null {
+ const meta = KPI_REGISTRY[def.kpiKey];
+
+ let value: number;
+ let change: number | null;
+ let changeKind: 'points' | 'percent';
+ let trend: KpiTrendPoint[];
+
+ switch (def.kpiKey) {
+ case 'ai_visibility': {
+ if (!metrics.visibility) return null;
+ const { summary, points } = metrics.visibility;
+ value = summary.rate;
+ change = summary.change;
+ changeKind = 'points';
+ trend = points.slice(-TREND_DAYS).map((p) => ({ date: p.date, value: p.values['you'] ?? 0 }));
+ break;
+ }
+ case 'citations': {
+ if (!metrics.insights || !metrics.dailyTotals) return null;
+ value = metrics.insights.totalCitations;
+ change = metrics.insights.citationsChange;
+ changeKind = 'percent';
+ trend = metrics.dailyTotals.map((d) => ({ date: d.date, value: d.citations }));
+ break;
+ }
+ case 'mentions': {
+ if (!metrics.insights || !metrics.dailyTotals) return null;
+ value = metrics.insights.totalMentions;
+ change = metrics.insights.mentionsChange;
+ changeKind = 'percent';
+ trend = metrics.dailyTotals.map((d) => ({ date: d.date, value: d.mentions }));
+ break;
+ }
+ case 'share_of_voice': {
+ if (!metrics.sov) return null;
+ value = metrics.sov.overallSov;
+ change = metrics.sov.overallSovChange;
+ changeKind = 'points';
+ trend = metrics.sov.trend
+ .slice(-TREND_DAYS)
+ .map((p) => ({ date: p.date, value: p.brandSov }));
+ break;
+ }
+ case 'ai_referral_traffic': {
+ if (!metrics.traffic || !metrics.trafficTrend) return null;
+ value = metrics.traffic.totalVisits;
+ change = percentChange(
+ metrics.traffic.totalVisits,
+ metrics.traffic.totalVisitsPrev > 0 ? metrics.traffic.totalVisitsPrev : null,
+ );
+ changeKind = 'percent';
+ trend = metrics.trafficTrend
+ .slice(-TREND_DAYS)
+ .map((p) => ({ date: p.date, value: sumTrafficPoint(p) }));
+ break;
+ }
+ }
+
+ // With an explicit window, the goal is held against that window's slice
+ // (flow metrics scale, percent levels don't) — otherwise a monthly target
+ // next to a 7-day value would report false alarm on every row.
+ const target = windowDays
+ ? scaleTargetToWindow(def.target, meta.unit, windowDays, TIMEFRAME_DAYS[def.timeframe])
+ : def.target;
+ const progress = kpiProgress(value, target, meta.direction);
+ return {
+ key: def.kpiKey,
+ category: meta.category,
+ unit: meta.unit,
+ direction: meta.direction,
+ timeframe: def.timeframe,
+ value,
+ change,
+ changeKind,
+ trend,
+ target,
+ progress,
+ status: deriveKpiStatus({ progress, change, direction: meta.direction }),
+ };
+}
+
+/**
+ * Whole-day UTC measurement window, inclusive on both ends. When given, it
+ * overrides every KPI's own timeframe window — the toolbar's date range is
+ * one control over one table, so all rows must answer for the same days.
+ * The 7-day trend sparkline is deliberately not affected: its column is
+ * labeled "Trend (7D)" whatever the window.
+ */
+export interface KpiWindow {
+ dayFrom: string;
+ dayTo: string;
+}
+
+export async function getKpiSnapshots(
+ brandId: string,
+ window?: KpiWindow,
+): Promise<KpiSnapshotsResult> {
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('kpi_definitions')
+ .select('kpi_key, target, timeframe, is_active')
+ .eq('brand_id', brandId);
+ if (error) throw new Error(error.message);
+
+ const rows = (data ?? []) as KpiDefinitionRow[];
+ if (rows.length === 0) return { configured: false, kpis: [] };
+
+ // Only registry-known keys are computable. An unknown key (a KPI removed
+ // from the registry, or a future source not shipped yet) is skipped, not
+ // an error — old definitions must not take down the page.
+ const active = rows
+ .filter((r) => r.is_active && isKpiKey(r.kpi_key))
+ .map((r) => ({
+ kpiKey: r.kpi_key as KpiKey,
+ target: Number(r.target),
+ timeframe: r.timeframe,
+ }));
+ if (active.length === 0) return { configured: true, kpis: [] };
+
+ // Definitions can carry different timeframes; each distinct one is a
+ // distinct comparison window, fetched once and shared by its KPIs.
+ const byTimeframe = new Map<KpiTimeframe, typeof active>();
+ for (const def of active) {
+ const group = byTimeframe.get(def.timeframe) ?? [];
+ group.push(def);
+ byTimeframe.set(def.timeframe, group);
+ }
+
+ const windowDays = window
+ ? Math.round((Date.parse(window.dayTo) - Date.parse(window.dayFrom)) / DAY_MS) + 1
+ : undefined;
+
+ const snapshots: KpiSnapshot[] = [];
+ await Promise.all(
+ [...byTimeframe.entries()].map(async ([timeframe, defs]) => {
+ const metrics = await fetchWindowMetrics(
+ brandId,
+ timeframe,
+ new Set(defs.map((d) => d.kpiKey)),
+ window,
+ );
+ for (const def of defs) {
+ const snapshot = buildSnapshot(def, metrics, windowDays);
+ if (snapshot) snapshots.push(snapshot);
+ }
+ }),
+ );
+
+ // Registry order, so the table reads the same on every load regardless of
+ // which timeframe group resolved first.
+ const order = new Map(DEFAULT_KPI_SET.map((k, i) => [k, i]));
+ snapshots.sort((a, b) => (order.get(a.key) ?? 99) - (order.get(b.key) ?? 99));
+ return { configured: true, kpis: snapshots };
+}
+
+export interface KpiDefinition {
+ kpiKey: KpiKey;
+ target: number;
+ timeframe: KpiTimeframe;
+ isActive: boolean;
+}
+
+/** Raw definitions for the framework drawer's prefill — registry-known keys
+ * only, same skip rule as the snapshot read. */
+export async function getKpiDefinitions(brandId: string): Promise<KpiDefinition[]> {
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('kpi_definitions')
+ .select('kpi_key, target, timeframe, is_active')
+ .eq('brand_id', brandId);
+ if (error) throw new Error(error.message);
+ return ((data ?? []) as KpiDefinitionRow[])
+ .filter((r) => isKpiKey(r.kpi_key))
+ .map((r) => ({
+ kpiKey: r.kpi_key as KpiKey,
+ target: Number(r.target),
+ timeframe: r.timeframe,
+ isActive: r.is_active,
+ }));
+}
+
+export interface KpiFrameworkEntry {
+ key: KpiKey;
+ target: number;
+}
+
+/**
+ * Save & Apply from the framework drawer: the entries ARE the framework.
+ * Listed KPIs are upserted active with their targets; every other definition
+ * the brand has is deactivated, not deleted, so its target survives being
+ * re-enabled later. One timeframe for the whole framework, per the drawer's
+ * single Time Period control. RLS restricts the write to admins and managers.
+ */
+export async function saveKpiFramework(
+ brandId: string,
+ timeframe: KpiTimeframe,
+ entries: KpiFrameworkEntry[],
+): Promise<void> {
+ if (entries.length === 0) throw new Error('empty framework');
+ if (!(timeframe in TIMEFRAME_DAYS)) throw new Error('unknown timeframe');
+ for (const entry of entries) {
+ if (!isKpiKey(entry.key) || !isValidKpiTarget(entry.key, entry.target)) {
+ throw new Error(`invalid target for ${entry.key}`);
+ }
+ }
+
+ const supabase = await createClient();
+ const now = new Date().toISOString();
+ const { error } = await supabase.from('kpi_definitions').upsert(
+ entries.map((entry) => ({
+ brand_id: brandId,
+ kpi_key: entry.key,
+ target: entry.target,
+ timeframe,
+ is_active: true,
+ updated_at: now,
+ })),
+ { onConflict: 'brand_id,kpi_key' },
+ );
+ if (error) throw new Error(error.message);
+
+ // Safe as a not-in filter: kpi_key values come from the registry, which
+ // has no commas or quotes to break PostgREST's list syntax.
+ const { error: deactivateErr } = await supabase
+ .from('kpi_definitions')
+ .update({ is_active: false, updated_at: now })
+ .eq('brand_id', brandId)
+ .not('kpi_key', 'in', `(${entries.map((e) => e.key).join(',')})`);
+ if (deactivateErr) throw new Error(deactivateErr.message);
+}
+
+/**
+ * Remove deletes the definition outright. Pause/resume (is_active) waits for
+ * the framework drawer: without a surface that lists paused KPIs, pausing
+ * would make a row vanish with no way back.
+ */
+export async function removeKpi(brandId: string, kpiKey: KpiKey): Promise<void> {
+ const supabase = await createClient();
+ const { error } = await supabase
+ .from('kpi_definitions')
+ .delete()
+ .eq('brand_id', brandId)
+ .eq('kpi_key', kpiKey);
+ if (error) throw new Error(error.message);
+}
diff --git a/web/src/lib/actions/signals.ts b/web/src/lib/actions/signals.ts
new file mode 100644
index 000000000..d24f41c54
--- /dev/null
+++ b/web/src/lib/actions/signals.ts
@@ -0,0 +1,169 @@
+'use server';
+
+/**
+ * Action Center signals — reads and triage writes.
+ *
+ * The rows are produced nightly by the server's detectors; this module only
+ * reads them and moves their status. Titles and descriptions do not exist in
+ * the database (they are i18n templates composed in the UI from `kind` +
+ * `payload`), which is also why the free-text search box filters
+ * client-side: there is no stored text to search.
+ */
+
+import { createClient } from '@/lib/supabase/server';
+import type {
+ SignalCategory,
+ SignalImpact,
+ SignalSource,
+ SignalStatus,
+} from '@/lib/signals/registry';
+import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';
+
+export type { Signal } from '@/lib/signals/map';
+
+export interface SignalFilters {
+ category?: SignalCategory;
+ impact?: SignalImpact;
+ status?: SignalStatus;
+ source?: SignalSource;
+ /** ISO day bounds, inclusive. A signal is in the window when its lifetime
+ * overlaps it — same semantics as the summary's "total". */
+ dayFrom: string;
+ dayTo: string;
+}
+
+/**
+ * A brand's signals for the window, newest first. Fetched whole (up to the
+ * PostgREST 1000-row cap) rather than paged: per-brand signal counts are
+ * tens — the detectors' own thresholds and dedup bound them — and search
+ * plus pagination happen client-side over composed titles anyway.
+ */
+export async function getSignals(brandId: string, filters: SignalFilters): Promise<Signal[]> {
+ const supabase = await createClient();
+ let query = supabase
+ .from('signals')
+ .select(SIGNAL_ROW_COLUMNS)
+ .eq('brand_id', brandId)
+ .lt('detected_at', nextDay(filters.dayTo))
+ .or(`resolved_at.is.null,resolved_at.gte.${filters.dayFrom}T00:00:00.000Z`)
+ .order('detected_at', { ascending: false })
+ .limit(1000);
+
+ if (filters.category) query = query.eq('category', filters.category);
+ if (filters.impact) query = query.eq('impact', filters.impact);
+ if (filters.status) query = query.eq('status', filters.status);
+ if (filters.source) query = query.contains('source', [filters.source]);
+
+ const { data, error } = await query;
+ if (error) throw new Error(error.message);
+
+ return mapSignalRows((data ?? []) as SignalRow[]);
+}
+
+export interface SignalsSummary {
+ /** Conditions active in the window (lifetime overlaps it). */
+ total: number;
+ prevTotal: number;
+ /** High-impact subset of `total`. */
+ important: number;
+ prevImportant: number;
+ /** Conditions first detected inside the window. */
+ newCount: number;
+ prevNew: number;
+ /** Conditions resolved inside the window. */
+ resolved: number;
+ prevResolved: number;
+ /** ISO day → count series for the card sparklines. */
+ byDayActive: Record<string, number>;
+ byDayImportant: Record<string, number>;
+ byDayNew: Record<string, number>;
+ byDayResolved: Record<string, number>;
+ byCategory: Record<string, number>;
+ bySource: Record<string, number>;
+}
+
+export async function getSignalsSummary(
+ brandId: string,
+ dayFrom: string,
+ dayTo: string,
+): Promise<SignalsSummary> {
+ const supabase = await createClient();
+ const { data, error } = await supabase.rpc('signals_summary', {
+ p_brand_id: brandId,
+ p_from: `${dayFrom}T00:00:00.000Z`,
+ p_to: nextDay(dayTo),
+ });
+ if (error) throw new Error(error.message);
+ const raw = (data ?? {}) as {
+ total?: number;
+ prev_total?: number;
+ important?: number;
+ prev_important?: number;
+ new?: number;
+ prev_new?: number;
+ resolved?: number;
+ prev_resolved?: number;
+ by_day_active?: Record<string, number>;
+ by_day_important?: Record<string, number>;
+ by_day_new?: Record<string, number>;
+ by_day_resolved?: Record<string, number>;
+ by_category?: Record<string, number>;
+ by_source?: Record<string, number>;
+ };
+ return {
+ total: Number(raw.total ?? 0),
+ prevTotal: Number(raw.prev_total ?? 0),
+ important: Number(raw.important ?? 0),
+ prevImportant: Number(raw.prev_important ?? 0),
+ newCount: Number(raw.new ?? 0),
+ prevNew: Number(raw.prev_new ?? 0),
+ resolved: Number(raw.resolved ?? 0),
+ prevResolved: Number(raw.prev_resolved ?? 0),
+ byDayActive: raw.by_day_active ?? {},
+ byDayImportant: raw.by_day_important ?? {},
+ byDayNew: raw.by_day_new ?? {},
+ byDayResolved: raw.by_day_resolved ?? {},
+ byCategory: raw.by_category ?? {},
+ bySource: raw.by_source ?? {},
+ };
+}
+
+/** Count of untriaged signals, for the Action Center tab badge. A head
+ * count query — no rows transferred, immune to the row cap. */
+export async function getNewSignalCount(brandId: string): Promise<number> {
+ const supabase = await createClient();
+ const { count, error } = await supabase
+ .from('signals')
+ .select('id', { count: 'exact', head: true })
+ .eq('brand_id', brandId)
+ .eq('status', 'new');
+ if (error) throw new Error(error.message);
+ return count ?? 0;
+}
+
+/**
+ * Triage: any org member can move a signal through its lifecycle (RLS
+ * enforces membership). Resolving stamps resolved_at; leaving the resolved
+ * state clears it so the summary's "Resolved" count stays truthful.
+ */
+export async function updateSignalStatus(
+ brandId: string,
+ signalId: string,
+ status: SignalStatus,
+): Promise<void> {
+ const supabase = await createClient();
+ const { error } = await supabase
+ .from('signals')
+ .update({
+ status,
+ resolved_at: status === 'resolved' ? new Date().toISOString() : null,
+ updated_at: new Date().toISOString(),
+ })
+ .eq('brand_id', brandId)
+ .eq('id', signalId);
+ if (error) throw new Error(error.message);
+}
+
+function nextDay(day: string): string {
+ return new Date(Date.parse(`${day}T00:00:00Z`) + 86_400_000).toISOString();
+}
diff --git a/web/src/lib/dashboard-navigation.ts b/web/src/lib/dashboard-navigation.ts
index b2faeea78..7252eecec 100644
--- a/web/src/lib/dashboard-navigation.ts
+++ b/web/src/lib/dashboard-navigation.ts
@@ -10,6 +10,7 @@ type NavLabelKey = { namespace: 'nav'; key: string } | { namespace: 'brands'; ke
export const dashboardNavLabelKeys: Record<string, NavLabelKey> = {
Brands: { namespace: 'brands', key: 'title' },
Agent: { namespace: 'nav', key: 'agent' },
+ 'Action Center': { namespace: 'nav', key: 'actionCenter' },
'Answer Engine Insights': { namespace: 'nav', key: 'insights' },
'AI Traffic Analytics': { namespace: 'nav', key: 'traffic' },
Prompts: { namespace: 'nav', key: 'prompts' },
diff --git a/web/src/lib/kpis/registry.ts b/web/src/lib/kpis/registry.ts
new file mode 100644
index 000000000..8e69f33a2
--- /dev/null
+++ b/web/src/lib/kpis/registry.ts
@@ -0,0 +1,146 @@
+/**
+ * The KPI registry — static product knowledge about every KPI the Action
+ * Center can track. The database (`kpi_definitions`) stores only what the
+ * user decided: target, timeframe, active. Everything intrinsic to a KPI —
+ * what it measures, its unit, which way is up, where the number comes from —
+ * lives here, keyed by `kpi_key`, so a metric's meaning cannot drift per
+ * brand and adding a KPI never takes a migration.
+ *
+ * Display names and descriptions are next-intl keys under
+ * `actionCenter.registry.<key>`, not strings: the registry is imported by
+ * server actions where no translator is in scope.
+ */
+
+export type KpiKey =
+ | 'ai_visibility'
+ | 'citations'
+ | 'mentions'
+ | 'share_of_voice'
+ | 'ai_referral_traffic';
+
+export type KpiCategory = 'visibility' | 'citations' | 'mentions' | 'traffic' | 'content';
+
+export type KpiUnit = 'percent' | 'count' | 'sessions';
+
+/**
+ * Which way improvement points. Every v1 KPI grows upward, but the field is
+ * in the model from the start because retrofitting it later would mean
+ * revisiting every place that colors a change arrow (negative-sentiment or
+ * issue-count KPIs will invert it).
+ */
+export type KpiDirection = 'higher_is_better' | 'lower_is_better';
+
+/** Where the snapshot value is computed from. GA-backed KPIs are skipped for
+ * brands without the connection instead of rendering as zero. */
+export type KpiSource = 'tracking' | 'ga';
+
+export type KpiTimeframe = 'weekly' | 'monthly' | 'quarterly';
+
+export interface KpiMeta {
+ key: KpiKey;
+ category: KpiCategory;
+ unit: KpiUnit;
+ direction: KpiDirection;
+ source: KpiSource;
+ /** Seed target for the default framework, in the KPI's own unit. */
+ defaultTarget: number;
+}
+
+export const KPI_REGISTRY: Record<KpiKey, KpiMeta> = {
+ ai_visibility: {
+ key: 'ai_visibility',
+ category: 'visibility',
+ unit: 'percent',
+ direction: 'higher_is_better',
+ source: 'tracking',
+ defaultTarget: 50,
+ },
+ citations: {
+ key: 'citations',
+ category: 'citations',
+ unit: 'count',
+ direction: 'higher_is_better',
+ source: 'tracking',
+ defaultTarget: 100,
+ },
+ mentions: {
+ key: 'mentions',
+ category: 'mentions',
+ unit: 'count',
+ direction: 'higher_is_better',
+ source: 'tracking',
+ defaultTarget: 100,
+ },
+ share_of_voice: {
+ key: 'share_of_voice',
+ category: 'visibility',
+ unit: 'percent',
+ direction: 'higher_is_better',
+ source: 'tracking',
+ defaultTarget: 35,
+ },
+ ai_referral_traffic: {
+ key: 'ai_referral_traffic',
+ category: 'traffic',
+ unit: 'sessions',
+ direction: 'higher_is_better',
+ source: 'tracking',
+ defaultTarget: 100,
+ },
+};
+
+export const KPI_KEYS = Object.keys(KPI_REGISTRY) as KpiKey[];
+
+export function isKpiKey(value: string): value is KpiKey {
+ return value in KPI_REGISTRY;
+}
+
+/**
+ * The default framework: the core AI-search set. Doubles as the canonical
+ * display order for KPI rows.
+ */
+export const DEFAULT_KPI_SET: KpiKey[] = [
+ 'ai_visibility',
+ 'citations',
+ 'mentions',
+ 'share_of_voice',
+ 'ai_referral_traffic',
+];
+
+export type KpiTemplateKey =
+ | 'ai_search_visibility'
+ | 'content_performance'
+ | 'brand_monitoring'
+ | 'custom';
+
+/**
+ * Templates are presets over the registry, nothing more — picking one checks
+ * a set of KPIs and seeds their default targets. A template with no
+ * computable KPIs yet (content, brand monitoring) renders disabled in the
+ * drawer rather than being hidden: the roadmap is allowed to show.
+ *
+ * AI Search Visibility is deliberately the four answer-engine KPIs, not the
+ * whole registry: referral traffic measures what arrives at the site, not
+ * presence in answers, and a template identical to "everything" would make
+ * picking it indistinguishable from not picking it.
+ */
+export const KPI_TEMPLATES: Record<KpiTemplateKey, KpiKey[]> = {
+ ai_search_visibility: ['ai_visibility', 'citations', 'mentions', 'share_of_voice'],
+ content_performance: [],
+ brand_monitoring: [],
+ custom: [],
+};
+
+/** A target must be positive, and a percent target cannot exceed 100. Used
+ * by both the drawer (to gate Save) and the server action (to reject). */
+export function isValidKpiTarget(key: KpiKey, target: number): boolean {
+ if (!Number.isFinite(target) || target <= 0) return false;
+ return KPI_REGISTRY[key].unit !== 'percent' || target <= 100;
+}
+
+/** Days in a timeframe's comparison window. */
+export const TIMEFRAME_DAYS: Record<KpiTimeframe, number> = {
+ weekly: 7,
+ monthly: 30,
+ quarterly: 90,
+};
diff --git a/web/src/lib/kpis/status.test.ts b/web/src/lib/kpis/status.test.ts
new file mode 100644
index 000000000..97b00b03e
--- /dev/null
+++ b/web/src/lib/kpis/status.test.ts
@@ -0,0 +1,71 @@
+import { expect, test } from 'vitest';
+import { deriveKpiStatus, isImprovement, kpiProgress, scaleTargetToWindow } from './status';
+
+test('progress is a plain ratio for higher_is_better', () => {
+ expect(kpiProgress(42.6, 50, 'higher_is_better')).toBe(85);
+ expect(kpiProgress(56, 50, 'higher_is_better')).toBe(112);
+ expect(kpiProgress(0, 50, 'higher_is_better')).toBe(0);
+});
+
+test('progress inverts for lower_is_better', () => {
+ expect(kpiProgress(20, 10, 'lower_is_better')).toBe(50);
+ expect(kpiProgress(10, 10, 'lower_is_better')).toBe(100);
+ // At-or-below-zero value against a lower-is-better target is fully met.
+ expect(kpiProgress(0, 10, 'lower_is_better')).toBe(100);
+});
+
+test('a non-positive target yields zero progress, not Infinity', () => {
+ expect(kpiProgress(42, 0, 'higher_is_better')).toBe(0);
+});
+
+test('goal_reached wins over a bad trend', () => {
+ expect(deriveKpiStatus({ progress: 104, change: -8, direction: 'higher_is_better' })).toBe(
+ 'goal_reached',
+ );
+});
+
+test('status follows the documented progress bands', () => {
+ expect(deriveKpiStatus({ progress: 39, change: 5, direction: 'higher_is_better' })).toBe(
+ 'off_track',
+ );
+ expect(deriveKpiStatus({ progress: 69, change: 5, direction: 'higher_is_better' })).toBe(
+ 'at_risk',
+ );
+ expect(deriveKpiStatus({ progress: 85, change: 5, direction: 'higher_is_better' })).toBe(
+ 'on_track',
+ );
+});
+
+test('moving the wrong way demotes on_track to at_risk', () => {
+ expect(deriveKpiStatus({ progress: 85, change: -3, direction: 'higher_is_better' })).toBe(
+ 'at_risk',
+ );
+ expect(deriveKpiStatus({ progress: 85, change: 3, direction: 'lower_is_better' })).toBe(
+ 'at_risk',
+ );
+});
+
+test('no previous window means progress alone decides', () => {
+ expect(deriveKpiStatus({ progress: 85, change: null, direction: 'higher_is_better' })).toBe(
+ 'on_track',
+ );
+});
+
+test('improvement respects direction', () => {
+ expect(isImprovement(5, 'higher_is_better')).toBe(true);
+ expect(isImprovement(-5, 'higher_is_better')).toBe(false);
+ expect(isImprovement(-5, 'lower_is_better')).toBe(true);
+});
+
+test('flow targets scale to the viewed window, percent levels never do', () => {
+ // Monthly 100 citations viewed over a week: the week's slice.
+ expect(scaleTargetToWindow(100, 'count', 7, 30)).toBe(23);
+ // Longer window than the timeframe scales up.
+ expect(scaleTargetToWindow(100, 'count', 90, 30)).toBe(300);
+ // A rate goal is a level: 50% is 50% over any window.
+ expect(scaleTargetToWindow(50, 'percent', 7, 30)).toBe(50);
+ // Window equal to the timeframe is a no-op.
+ expect(scaleTargetToWindow(100, 'sessions', 30, 30)).toBe(100);
+ // A tiny slice never rounds to zero — progress against 0 is undefined.
+ expect(scaleTargetToWindow(2, 'count', 1, 90)).toBe(1);
+});
diff --git a/web/src/lib/kpis/status.ts b/web/src/lib/kpis/status.ts
new file mode 100644
index 000000000..38c39d5f8
--- /dev/null
+++ b/web/src/lib/kpis/status.ts
@@ -0,0 +1,77 @@
+import type { KpiDirection, KpiUnit } from './registry';
+
+/**
+ * Status is derived, never stored. A stored badge can go stale against the
+ * numbers standing next to it; a derived one cannot. The thresholds are the
+ * whole definition — if a status ever looks wrong, this file is the only
+ * place to argue with.
+ */
+export type KpiStatus = 'on_track' | 'at_risk' | 'off_track' | 'goal_reached';
+
+/**
+ * Progress toward the target as a percentage. May exceed 100 — the caller
+ * caps the *bar*, not the number.
+ *
+ * For lower_is_better KPIs the ratio inverts: being at or under the target
+ * is 100%+. A zero value against a lower-is-better target is fully met, not
+ * a division by zero.
+ */
+export function kpiProgress(value: number, target: number, direction: KpiDirection): number {
+ if (target <= 0) return 0;
+ if (direction === 'lower_is_better') {
+ if (value <= 0) return 100;
+ return Math.round((target / value) * 100);
+ }
+ return Math.round((value / target) * 100);
+}
+
+/**
+ * @param change movement vs the previous window in the KPI's own terms
+ * (points for percents, percent for counts); sign is raw, not
+ * direction-adjusted. Null when there is no previous window to compare.
+ *
+ * Rules, in order:
+ * - `goal_reached` at 100%+ progress, whatever the trend.
+ * - `off_track` under 40% — too far out for trend to change the verdict.
+ * - `at_risk` under 70%, or when the value is moving the wrong way
+ * (per `direction`) while the goal is still unmet.
+ * - `on_track` otherwise.
+ */
+export function deriveKpiStatus({
+ progress,
+ change,
+ direction,
+}: {
+ progress: number;
+ change: number | null;
+ direction: KpiDirection;
+}): KpiStatus {
+ if (progress >= 100) return 'goal_reached';
+ if (progress < 40) return 'off_track';
+ const movingWrongWay =
+ change !== null && (direction === 'higher_is_better' ? change < 0 : change > 0);
+ if (progress < 70 || movingWrongWay) return 'at_risk';
+ return 'on_track';
+}
+
+/** Whether a raw change is an improvement for this KPI — drives arrow color. */
+export function isImprovement(change: number, direction: KpiDirection): boolean {
+ return direction === 'higher_is_better' ? change > 0 : change < 0;
+}
+
+/**
+ * The target to hold a KPI against when the viewed window differs from the
+ * goal's own timeframe. Flow metrics (counts, sessions) accumulate, so a
+ * monthly 100 viewed over a week is ~23 — the week's slice of the goal.
+ * Percent metrics are levels, not flows: a 50% visibility goal is 50% over
+ * any window, so it never scales.
+ */
+export function scaleTargetToWindow(
+ target: number,
+ unit: KpiUnit,
+ windowDays: number,
+ timeframeDays: number,
+): number {
+ if (unit === 'percent' || windowDays <= 0 || timeframeDays <= 0) return target;
+ return Math.max(1, Math.round(target * (windowDays / timeframeDays)));
+}
diff --git a/web/src/lib/signals/display.ts b/web/src/lib/signals/display.ts
new file mode 100644
index 000000000..96ac079a6
--- /dev/null
+++ b/web/src/lib/signals/display.ts
@@ -0,0 +1,97 @@
+import type { Signal } from '@/lib/actions/signals';
+
+/**
+ * Composes the display strings a signal row shows from `kind` + `payload`.
+ * Titles live in i18n templates (actionCenter.signalTexts.<kind>), not the
+ * database — this module only prepares the interpolation values, so the
+ * page's search box can match what the user actually reads.
+ */
+
+type Translator = (key: string, values?: Record<string, string | number>) => string;
+
+function str(payload: Record<string, unknown>, key: string): string {
+ const value = payload[key];
+ return typeof value === 'string' ? value : String(value ?? '');
+}
+
+export function signalTexts(signal: Signal, t: Translator): { title: string; description: string } {
+ const p = signal.payload;
+ const values = ((): Record<string, string | number> => {
+ switch (signal.kind) {
+ case 'sharp_drop':
+ return { from: signal.previousValue ?? 0, to: signal.currentValue ?? 0 };
+ case 'prompt_gain':
+ return { prompt: str(p, 'promptText'), gain: signal.changeValue ?? 0 };
+ case 'new_engine':
+ return { platform: str(p, 'platform') };
+ case 'lost_citations':
+ return { prompt: str(p, 'promptText') };
+ case 'first_citation':
+ return { url: str(p, 'label') || str(p, 'url'), prompt: str(p, 'promptText') };
+ case 'competitor_surge':
+ return {
+ name: str(p, 'competitorName'),
+ from: signal.previousValue ?? 0,
+ to: signal.currentValue ?? 0,
+ };
+ case 'competitor_crossed':
+ case 'competitor_overtaken':
+ return {
+ name: str(p, 'competitorName'),
+ competitorRate: Number(p.competitorRate ?? 0),
+ brandRate: Number(p.brandRate ?? 0),
+ };
+ case 'page_opportunity':
+ return {
+ page: str(p, 'landingPage'),
+ rank: Number(p.valueRank ?? 0),
+ signal: str(p, 'valueSignal').replace('_', ' '),
+ };
+ case 'uncited_mentions':
+ return { count: signal.currentValue ?? 0 };
+ case 'audit_low_score':
+ return { count: signal.currentValue ?? 0 };
+ }
+ })();
+
+ return {
+ title: t(`${signal.kind}.title`, values),
+ description: t(`${signal.kind}.description`, values),
+ };
+}
+
+/** What the Affected column shows: a compact count label + optional detail. */
+export function signalAffected(
+ signal: Signal,
+ t: Translator,
+): { label: string; detail: string | null } {
+ const p = signal.payload;
+ switch (signal.kind) {
+ case 'sharp_drop':
+ return { label: t('affected.allPrompts'), detail: null };
+ case 'prompt_gain':
+ case 'lost_citations':
+ return { label: t('affected.prompts', { count: 1 }), detail: str(p, 'promptText') };
+ case 'new_engine':
+ return { label: t('affected.platform'), detail: str(p, 'platform') };
+ case 'first_citation':
+ return { label: t('affected.urls', { count: 1 }), detail: str(p, 'label') || str(p, 'url') };
+ case 'competitor_surge':
+ case 'competitor_crossed':
+ case 'competitor_overtaken':
+ return { label: t('affected.competitor'), detail: str(p, 'competitorName') };
+ case 'page_opportunity':
+ return { label: t('affected.urls', { count: 1 }), detail: str(p, 'landingPage') };
+ case 'uncited_mentions': {
+ const count = Array.isArray(p.promptIds) ? p.promptIds.length : (signal.currentValue ?? 0);
+ return { label: t('affected.prompts', { count: Number(count) }), detail: null };
+ }
+ case 'audit_low_score': {
+ const urls = Array.isArray(p.urls) ? (p.urls as { url?: string }[]) : [];
+ return {
+ label: t('affected.urls', { count: Number(signal.currentValue ?? urls.length) }),
+ detail: urls[0]?.url ?? null,
+ };
+ }
+ }
+}
diff --git a/web/src/lib/signals/map.ts b/web/src/lib/signals/map.ts
new file mode 100644
index 000000000..f43f5703d
--- /dev/null
+++ b/web/src/lib/signals/map.ts
@@ -0,0 +1,78 @@
+import {
+ isSignalKind,
+ type SignalCategory,
+ type SignalImpact,
+ type SignalKind,
+ type SignalSource,
+ type SignalStatus,
+} from './registry';
+
+/**
+ * Row → domain mapping for signals, shared by every server action that
+ * returns them (the Signals page's own reads and the Action drawer's
+ * linked-signals read). Kept out of the 'use server' modules because those
+ * may only export async functions.
+ */
+
+export interface Signal {
+ id: string;
+ category: SignalCategory;
+ kind: SignalKind;
+ impact: SignalImpact;
+ status: SignalStatus;
+ source: SignalSource[];
+ detectedAt: string;
+ lastDetectedAt: string;
+ resolvedAt: string | null;
+ previousValue: number | null;
+ currentValue: number | null;
+ changeValue: number | null;
+ payload: Record<string, unknown>;
+ kpiKeys: string[];
+ actionId: string | null;
+}
+
+export interface SignalRow {
+ id: string;
+ category: string;
+ kind: string;
+ impact: string;
+ status: string;
+ source: string[];
+ detected_at: string;
+ last_detected_at: string;
+ resolved_at: string | null;
+ previous_value: number | null;
+ current_value: number | null;
+ change_value: number | null;
+ payload: Record<string, unknown>;
+ kpi_keys: string[];
+ action_id: string | null;
+}
+
+export const SIGNAL_ROW_COLUMNS =
+ 'id, category, kind, impact, status, source, detected_at, last_detected_at, resolved_at, previous_value, current_value, change_value, payload, kpi_keys, action_id';
+
+/** Maps rows, silently skipping unknown kinds (a detector removed from the
+ * registry must not take down a page). */
+export function mapSignalRows(rows: SignalRow[]): Signal[] {
+ return rows
+ .filter((row) => isSignalKind(row.kind))
+ .map((row) => ({
+ id: row.id,
+ category: row.category as SignalCategory,
+ kind: row.kind as SignalKind,
+ impact: row.impact as SignalImpact,
+ status: row.status as SignalStatus,
+ source: (row.source ?? []) as SignalSource[],
+ detectedAt: row.detected_at,
+ lastDetectedAt: row.last_detected_at,
+ resolvedAt: row.resolved_at,
+ previousValue: row.previous_value === null ? null : Number(row.previous_value),
+ currentValue: row.current_value === null ? null : Number(row.current_value),
+ changeValue: row.change_value === null ? null : Number(row.change_value),
+ payload: row.payload ?? {},
+ kpiKeys: row.kpi_keys ?? [],
+ actionId: row.action_id,
+ }));
+}
diff --git a/web/src/lib/signals/registry.ts b/web/src/lib/signals/registry.ts
new file mode 100644
index 000000000..9f2057cae
--- /dev/null
+++ b/web/src/lib/signals/registry.ts
@@ -0,0 +1,95 @@
+/**
+ * The signal registry — static product knowledge about every detector kind
+ * the Signals page can render. The database stores what gets filtered and
+ * aggregated (category, impact, status, source, values, payload); this file
+ * owns how a kind is DISPLAYED: which i18n templates compose its title and
+ * description, and the short state word the Type column shows under the
+ * category.
+ *
+ * The server-side twin (server/src/lib/signals/record.js KIND_META) owns
+ * what gets stored. Adding a detector means touching both, and neither
+ * takes a migration.
+ */
+
+export type SignalCategory =
+ | 'visibility'
+ | 'citation'
+ | 'mention'
+ | 'traffic'
+ | 'technical'
+ | 'competitor';
+
+export type SignalImpact = 'high' | 'medium' | 'low';
+
+export type SignalStatus = 'new' | 'acknowledged' | 'resolved' | 'dismissed';
+
+export type SignalKind =
+ | 'sharp_drop'
+ | 'prompt_gain'
+ | 'new_engine'
+ | 'lost_citations'
+ | 'first_citation'
+ | 'competitor_surge'
+ | 'competitor_crossed'
+ | 'competitor_overtaken'
+ | 'page_opportunity'
+ | 'uncited_mentions'
+ | 'audit_low_score';
+
+export const SIGNAL_CATEGORIES: readonly SignalCategory[] = [
+ 'visibility',
+ 'citation',
+ 'mention',
+ 'traffic',
+ 'technical',
+ 'competitor',
+];
+
+export const SIGNAL_STATUSES: readonly SignalStatus[] = [
+ 'new',
+ 'acknowledged',
+ 'resolved',
+ 'dismissed',
+];
+
+export const SIGNAL_IMPACTS: readonly SignalImpact[] = ['high', 'medium', 'low'];
+
+/** Data sources a signal row can carry (the `source` array's vocabulary). */
+export const SIGNAL_SOURCES = ['ai_results', 'ga4', 'gsc', 'site_audit'] as const;
+export type SignalSource = (typeof SIGNAL_SOURCES)[number];
+
+export interface SignalKindMeta {
+ kind: SignalKind;
+ /** i18n key under actionCenter.signalKinds.<key> for the Type column's
+ * state word (Dropped, Lost, Gained, Opportunity…). */
+ stateKey:
+ | 'dropped'
+ | 'gained'
+ | 'lost'
+ | 'opportunity'
+ | 'gain'
+ | 'overtaken'
+ | 'crossed'
+ | 'uncited'
+ | 'issue';
+ /** Whether the change arrow, when change_value is present, is good news. */
+ positive: boolean;
+}
+
+export const SIGNAL_KINDS: Record<SignalKind, SignalKindMeta> = {
+ sharp_drop: { kind: 'sharp_drop', stateKey: 'dropped', positive: false },
+ prompt_gain: { kind: 'prompt_gain', stateKey: 'gained', positive: true },
+ new_engine: { kind: 'new_engine', stateKey: 'gained', positive: true },
+ lost_citations: { kind: 'lost_citations', stateKey: 'lost', positive: false },
+ first_citation: { kind: 'first_citation', stateKey: 'gained', positive: true },
+ competitor_surge: { kind: 'competitor_surge', stateKey: 'gain', positive: false },
+ competitor_crossed: { kind: 'competitor_crossed', stateKey: 'crossed', positive: false },
+ competitor_overtaken: { kind: 'competitor_overtaken', stateKey: 'overtaken', positive: true },
+ page_opportunity: { kind: 'page_opportunity', stateKey: 'opportunity', positive: true },
+ uncited_mentions: { kind: 'uncited_mentions', stateKey: 'uncited', positive: false },
+ audit_low_score: { kind: 'audit_low_score', stateKey: 'issue', positive: false },
+};
+
+export function isSignalKind(value: string): value is SignalKind {
+ return value in SIGNAL_KINDS;
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 36b7df8ee..25c2ec4c3 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -10,10 +10,162 @@ export type Database = {
// Allows to automatically instantiate createClient with right options
// instead of createClient<Database, { PostgrestVersion: 'XX' }>(URL, KEY)
__InternalSupabase: {
- PostgrestVersion: "14.1"
+ PostgrestVersion: "14.5"
}
public: {
Tables: {
+ action_events: {
+ Row: {
+ action_id: string
+ actor_id: string | null
+ created_at: string
+ data: Json
+ event: string
+ id: string
+ }
+ Insert: {
+ action_id: string
+ actor_id?: string | null
+ created_at?: string
+ data?: Json
+ event: string
+ id?: string
+ }
+ Update: {
+ action_id?: string
+ actor_id?: string | null
+ created_at?: string
+ data?: Json
+ event?: string
+ id?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "action_events_action_id_fkey"
+ columns: ["action_id"]
+ isOneToOne: false
+ referencedRelation: "actions"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "action_events_actor_id_fkey"
+ columns: ["actor_id"]
+ isOneToOne: false
+ referencedRelation: "profiles"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ action_tasks: {
+ Row: {
+ action_id: string
+ created_at: string
+ id: string
+ position: number
+ status: string
+ task_key: string
+ updated_at: string
+ }
+ Insert: {
+ action_id: string
+ created_at?: string
+ id?: string
+ position: number
+ status?: string
+ task_key: string
+ updated_at?: string
+ }
+ Update: {
+ action_id?: string
+ created_at?: string
+ id?: string
+ position?: number
+ status?: string
+ task_key?: string
+ updated_at?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "action_tasks_action_id_fkey"
+ columns: ["action_id"]
+ isOneToOne: false
+ referencedRelation: "actions"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ actions: {
+ Row: {
+ action_no: number
+ assignee_id: string | null
+ baseline: Json
+ brand_id: string
+ category: string
+ completed_at: string | null
+ created_at: string
+ dedup_key: string
+ due_date: string | null
+ id: string
+ impact: string
+ kind: string
+ kpi_keys: string[]
+ payload: Json
+ status: string
+ updated_at: string
+ }
+ Insert: {
+ action_no?: never
+ assignee_id?: string | null
+ baseline?: Json
+ brand_id: string
+ category: string
+ completed_at?: string | null
+ created_at?: string
+ dedup_key: string
+ due_date?: string | null
+ id?: string
+ impact: string
+ kind: string
+ kpi_keys?: string[]
+ payload?: Json
+ status?: string
+ updated_at?: string
+ }
+ Update: {
+ action_no?: never
+ assignee_id?: string | null
+ baseline?: Json
+ brand_id?: string
+ category?: string
+ completed_at?: string | null
+ created_at?: string
+ dedup_key?: string
+ due_date?: string | null
+ id?: string
+ impact?: string
+ kind?: string
+ kpi_keys?: string[]
+ payload?: Json
+ status?: string
+ updated_at?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "actions_assignee_id_fkey"
+ columns: ["assignee_id"]
+ isOneToOne: false
+ referencedRelation: "profiles"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "actions_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
agent_conversations: {
Row: {
brand_id: string | null
@@ -1247,6 +1399,47 @@ export type Database = {
},
]
}
+ kpi_definitions: {
+ Row: {
+ brand_id: string
+ created_at: string
+ id: string
+ is_active: boolean
+ kpi_key: string
+ target: number
+ timeframe: string
+ updated_at: string
+ }
+ Insert: {
+ brand_id: string
+ created_at?: string
+ id?: string
+ is_active?: boolean
+ kpi_key: string
+ target: number
+ timeframe?: string
+ updated_at?: string
+ }
+ Update: {
+ brand_id?: string
+ created_at?: string
+ id?: string
+ is_active?: boolean
+ kpi_key?: string
+ target?: number
+ timeframe?: string
+ updated_at?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "kpi_definitions_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
organizations: {
Row: {
anthropic_api_key_encrypted: string | null
@@ -2088,6 +2281,87 @@ export type Database = {
},
]
}
+ signals: {
+ Row: {
+ action_id: string | null
+ brand_id: string
+ category: string
+ change_value: number | null
+ created_at: string
+ current_value: number | null
+ dedup_key: string
+ detected_at: string
+ id: string
+ impact: string
+ kind: string
+ kpi_keys: string[]
+ last_detected_at: string
+ payload: Json
+ previous_value: number | null
+ resolved_at: string | null
+ source: string[]
+ status: string
+ updated_at: string
+ }
+ Insert: {
+ action_id?: string | null
+ brand_id: string
+ category: string
+ change_value?: number | null
+ created_at?: string
+ current_value?: number | null
+ dedup_key: string
+ detected_at?: string
+ id?: string
+ impact: string
+ kind: string
+ kpi_keys?: string[]
+ last_detected_at?: string
+ payload?: Json
+ previous_value?: number | null
+ resolved_at?: string | null
+ source?: string[]
+ status?: string
+ updated_at?: string
+ }
+ Update: {
+ action_id?: string | null
+ brand_id?: string
+ category?: string
+ change_value?: number | null
+ created_at?: string
+ current_value?: number | null
+ dedup_key?: string
+ detected_at?: string
+ id?: string
+ impact?: string
+ kind?: string
+ kpi_keys?: string[]
+ last_detected_at?: string
+ payload?: Json
+ previous_value?: number | null
+ resolved_at?: string | null
+ source?: string[]
+ status?: string
+ updated_at?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "signals_action_id_fkey"
+ columns: ["action_id"]
+ isOneToOne: false
+ referencedRelation: "actions"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "signals_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
site_audit_usage: {
Row: {
audit_id: string | null
@@ -2418,10 +2692,7 @@ export type Database = {
}
Returns: Json
}
- apply_prompt_locations: {
- Args: { p_updates: Json }
- Returns: number
- }
+ apply_prompt_locations: { Args: { p_updates: Json }; Returns: number }
citation_competitor_sources: {
Args: {
p_brand_domains: string[]
@@ -2597,6 +2868,23 @@ export type Database = {
sent_count: number
}[]
}
+ ga_page_ai_visibility: {
+ Args: { p_brand_id: string; p_since: string }
+ Returns: {
+ ai_platforms: string[]
+ ai_sessions: number
+ citations: number
+ citing_prompts: number
+ engaged_sessions: number
+ engagement_seconds: number
+ key_events: number
+ landing_page: string
+ revenue: number
+ sessions: number
+ targeting_prompts: number
+ transactions: number
+ }[]
+ }
get_latest_prompt_results:
| {
Args: { p_brand_id: string; p_platform?: string }
@@ -2665,23 +2953,6 @@ export type Database = {
isSetofReturn: true
}
}
- ga_page_ai_visibility: {
- Args: { p_brand_id: string; p_since: string }
- Returns: {
- ai_platforms: string[]
- ai_sessions: number
- citations: number
- citing_prompts: number
- engaged_sessions: number
- engagement_seconds: number
- key_events: number
- landing_page: string
- revenue: number
- sessions: number
- targeting_prompts: number
- transactions: number
- }[]
- }
gsc_candidate_queries: {
Args: { p_brand_id: string; p_min_impressions: number; p_since: string }
Returns: {
@@ -2722,10 +2993,7 @@ export type Database = {
regions: string[]
}[]
}
- normalize_page_path: {
- Args: { p_url: string }
- Returns: string
- }
+ normalize_page_path: { Args: { p_url: string }; Returns: string }
org_prompt_location_usage: {
Args: { p_organization_id: string }
Returns: {
@@ -2870,6 +3138,10 @@ export type Database = {
}
Returns: Json
}
+ signals_summary: {
+ Args: { p_brand_id: string; p_from: string; p_to: string }
+ Returns: Json
+ }
topics_overview_aggregates: {
Args: { p_brand_id: string }
Returns: {
@@ -2922,10 +3194,7 @@ export type Database = {
}
Returns: number
}
- url_decode_safe: {
- Args: { p_value: string }
- Returns: string
- }
+ url_decode_safe: { Args: { p_value: string }; Returns: string }
visibility_rate_trend: {
Args: {
p_brand_id: string
@@ -3003,12 +3272,12 @@ export type Tables<
DefaultSchemaTableNameOrOptions extends
| keyof (DefaultSchema["Tables"] & DefaultSchema["Views"])
| { schema: keyof DatabaseWithoutInternals },
- TableName extends DefaultSchemaTableNameOrOptions extends {
+ TableName extends (DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof (DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"] &
DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Views"])
- : never = never,
+ : never) = never,
> = DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
@@ -3032,11 +3301,11 @@ export type TablesInsert<
DefaultSchemaTableNameOrOptions extends
| keyof DefaultSchema["Tables"]
| { schema: keyof DatabaseWithoutInternals },
- TableName extends DefaultSchemaTableNameOrOptions extends {
+ TableName extends (DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"]
- : never = never,
+ : never) = never,
> = DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
@@ -3057,11 +3326,11 @@ export type TablesUpdate<
DefaultSchemaTableNameOrOptions extends
| keyof DefaultSchema["Tables"]
| { schema: keyof DatabaseWithoutInternals },
- TableName extends DefaultSchemaTableNameOrOptions extends {
+ TableName extends (DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"]
- : never = never,
+ : never) = never,
> = DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
@@ -3082,11 +3351,11 @@ export type Enums<
DefaultSchemaEnumNameOrOptions extends
| keyof DefaultSchema["Enums"]
| { schema: keyof DatabaseWithoutInternals },
- EnumName extends DefaultSchemaEnumNameOrOptions extends {
+ EnumName extends (DefaultSchemaEnumNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[DefaultSchemaEnumNameOrOptions["schema"]]["Enums"]
- : never = never,
+ : never) = never,
> = DefaultSchemaEnumNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
@@ -3099,11 +3368,11 @@ export type CompositeTypes<
PublicCompositeTypeNameOrOptions extends
| keyof DefaultSchema["CompositeTypes"]
| { schema: keyof DatabaseWithoutInternals },
- CompositeTypeName extends PublicCompositeTypeNameOrOptions extends {
+ CompositeTypeName extends (PublicCompositeTypeNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[PublicCompositeTypeNameOrOptions["schema"]]["CompositeTypes"]
- : never = never,
+ : never) = never,
> = PublicCompositeTypeNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}