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): an action becomes a cycle, not a row (#819)

Gökhan Geyik13ced7622672
diff --git a/server/src/lib/action-center/generate.js b/server/src/lib/action-center/generate.js
index a21930dd9..32f799489 100644
--- a/server/src/lib/action-center/generate.js
+++ b/server/src/lib/action-center/generate.js
@@ -11,21 +11,34 @@
* 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.
+ * - an ACTIVE action keeps its scope. Newly detected signals are linked to
+ * it as evidence, but its payload is not rewritten: it is a work package
+ * someone may already be executing against, and silently changing what it
+ * covers is worse than leaving a new problem for the next cycle;
+ * - a CLOSED action — completed or dismissed — is finished. It is never
+ * written to again and never resurrected; it is the historical record of
+ * one execution cycle;
+ * - closing frees the kind's slot. Once the rest window has passed, a still
+ * firing condition opens a NEW action beside the old one, with its own
+ * baseline, tasks and outcome.
*
* `baseline` snapshots the linked signals' measured values at creation —
- * the "before" half of the future validation comparison.
+ * the "before" half of the future validation comparison (#818, phase 2).
*/
import supabaseAdmin from '../../config/supabase.js';
import { logger } from '../logger.js';
-const REOPEN_AFTER_DAYS = 14;
+/**
+ * How long a kind rests after a cycle closes before a new one may open.
+ *
+ * Without it, a condition that is still firing would produce a fresh action
+ * the night after someone closed the last one — a treadmill. The old code
+ * used this window to decide whether to resurrect the completed row; now it
+ * decides when the next cycle may begin, and the completed row is never
+ * touched again.
+ */
+const REST_AFTER_CLOSE_DAYS = 14;
const DAY_MS = 86_400_000;
const IMPACT_RANK = { high: 3, medium: 2, low: 1 };
@@ -152,18 +165,40 @@ export async function generateActionsForBrand(brandId, { now = new Date() } = {}
.limit(1000);
if (signalsErr) throw new Error(signalsErr.message);
- const { data: existingRows, error: actionsErr } = await supabaseAdmin
+ // Only the active ones. A completed or dismissed action is a finished
+ // cycle: it neither blocks a new one nor is ever written to again, so it
+ // has no bearing on what happens tonight beyond the rest window below.
+ const { data: activeRows, error: actionsErr } = await supabaseAdmin
.from('actions')
- .select('id, dedup_key, status, completed_at')
+ .select('id, dedup_key, status')
.eq('brand_id', brandId)
+ .not('status', 'in', '("completed","dismissed")')
.limit(1000);
if (actionsErr) throw new Error(actionsErr.message);
- const existing = new Map((existingRows ?? []).map((row) => [row.dedup_key, row]));
+ const active = new Map((activeRows ?? []).map((row) => [row.dedup_key, row]));
+
+ // How recently each kind was closed, so a condition that is still firing
+ // does not reopen as a fresh action the very next night.
+ const { data: closedRows, error: closedErr } = await supabaseAdmin
+ .from('actions')
+ .select('dedup_key, completed_at, updated_at')
+ .eq('brand_id', brandId)
+ .in('status', ['completed', 'dismissed'])
+ .order('created_at', { ascending: false })
+ .limit(1000);
+ if (closedErr) throw new Error(closedErr.message);
+ const lastClosedAt = new Map();
+ for (const row of closedRows ?? []) {
+ const closed = Date.parse(row.completed_at ?? row.updated_at ?? '') || 0;
+ if (closed > (lastClosedAt.get(row.dedup_key) ?? 0)) {
+ lastClosedAt.set(row.dedup_key, closed);
+ }
+ }
const nowIso = now.toISOString();
let created = 0;
let refreshed = 0;
- let reopened = 0;
+ let resting = 0;
for (const rule of ACTION_RULES) {
const matched = (openSignals ?? []).filter((signal) => rule.signalKinds.includes(signal.kind));
@@ -174,9 +209,19 @@ export async function generateActionsForBrand(brandId, { now = new Date() } = {}
.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);
+ const current = active.get(rule.kind);
if (!current) {
+ // The slot is open. Leave it open a while after a cycle closed, so a
+ // condition that is still firing does not produce a fresh action every
+ // night — the same restraint the old reopen window provided, minus the
+ // resurrection.
+ const closedAt = lastClosedAt.get(rule.kind) ?? 0;
+ if (closedAt && now.getTime() - closedAt < REST_AFTER_CLOSE_DAYS * DAY_MS) {
+ resting += 1;
+ continue;
+ }
+
const { data: inserted, error } = await supabaseAdmin
.from('actions')
.insert({
@@ -208,43 +253,21 @@ export async function generateActionsForBrand(brandId, { now = new Date() } = {}
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);
+ // An active action (new / in_progress / on_hold) keeps the scope it was
+ // created with. Signals that arrived since are linked as evidence — they
+ // are why this action exists — but `payload` is the work package someone
+ // may already be executing against, and rewriting it nightly turned a
+ // recovery for six prompts into a recovery for a different nine without
+ // telling anyone. New targets wait for the next cycle.
const linked = await linkSignals(current.id, matched);
- if (linked > 0) await logEvent(current.id, 'signals_linked', { count: linked });
+ if (linked > 0) {
+ await supabaseAdmin.from('actions').update({ updated_at: nowIso }).eq('id', current.id);
+ await logEvent(current.id, 'signals_linked', { count: linked });
+ }
refreshed += 1;
}
- const summary = { created, refreshed, reopened };
+ const summary = { created, refreshed, resting };
logger.info({ brandId, ...summary }, '[actions] generated');
return summary;
}
diff --git a/server/src/lib/action-center/generate.test.js b/server/src/lib/action-center/generate.test.js
new file mode 100644
index 000000000..d590c62f0
--- /dev/null
+++ b/server/src/lib/action-center/generate.test.js
@@ -0,0 +1,225 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// The module reaches the supabase admin client at import time, whose config
+// hard-exits when SUPABASE_* env is absent (as in CI).
+const from = vi.fn();
+vi.mock('../../config/supabase.js', () => ({ default: { from: (...a) => from(...a) } }));
+vi.mock('../logger.js', () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+import { generateActionsForBrand } from './generate.js';
+
+const BRAND = 'brand-1';
+const NOW = new Date('2026-09-16T04:00:00Z');
+
+/**
+ * Enough of the PostgREST builder to drive the generator.
+ *
+ * Each table answers from `tables`, and every write is recorded so a test can
+ * assert what the night actually did. The builder is thenable, which is what
+ * lets `await supabase.from(x).select(y).eq(...)` resolve without a terminal
+ * call.
+ */
+function mockDb({ signals = [], activeActions = [], closedActions = [] } = {}) {
+ const writes = { inserted: [], updated: [] };
+
+ from.mockImplementation((table) => {
+ const state = { op: 'select', payload: null, negated: false };
+
+ const builder = {
+ select: () => builder,
+ eq: () => builder,
+ // The generator asks for actions twice: `.not('status', 'in', ...)` for
+ // the active ones, `.in('status', [...])` for the closed ones. The mock
+ // has to tell them apart or every test sees one list.
+ not: () => {
+ state.negated = true;
+ return builder;
+ },
+ in: () => builder,
+ order: () => builder,
+ limit: () => builder,
+ single: () => Promise.resolve(result()),
+ insert: (payload) => {
+ state.op = 'insert';
+ state.payload = payload;
+ writes.inserted.push({ table, rows: Array.isArray(payload) ? payload : [payload] });
+ return builder;
+ },
+ update: (payload) => {
+ state.op = 'update';
+ state.payload = payload;
+ writes.updated.push({ table, patch: payload });
+ return builder;
+ },
+ then: (resolve, reject) => Promise.resolve(result()).then(resolve, reject),
+ };
+
+ function result() {
+ if (state.op === 'insert') return { data: { id: `new-${table}` }, error: null };
+ if (state.op === 'update') return { data: null, error: null };
+ if (table === 'signals') return { data: signals, error: null };
+ if (table === 'actions') {
+ return { data: state.negated ? activeActions : closedActions, error: null };
+ }
+ return { data: [], error: null };
+ }
+
+ return builder;
+ });
+
+ return writes;
+}
+
+const signal = (over = {}) => ({
+ id: 's1',
+ kind: 'sharp_drop',
+ impact: 'high',
+ kpi_keys: ['ai_visibility'],
+ payload: {},
+ previous_value: 40,
+ current_value: 20,
+ change_value: -20,
+ action_id: null,
+ ...over,
+});
+
+const daysAgo = (n) => new Date(NOW.getTime() - n * 86_400_000).toISOString();
+
+beforeEach(() => {
+ from.mockReset();
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('generateActionsForBrand', () => {
+ it('opens an action when the kind has no active one', async () => {
+ const writes = mockDb({ signals: [signal()] });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW });
+
+ expect(summary.created).toBe(1);
+ const action = writes.inserted.find((w) => w.table === 'actions');
+ expect(action.rows[0]).toMatchObject({
+ brand_id: BRAND,
+ kind: 'recover_visibility',
+ dedup_key: 'recover_visibility',
+ });
+ // Its own baseline — the "before" half of a future measurement.
+ expect(action.rows[0].baseline.signals).toHaveLength(1);
+ expect(writes.inserted.find((w) => w.table === 'action_tasks').rows).toHaveLength(5);
+ });
+
+ /**
+ * The bug this phase exists for. The nightly pass used to rewrite an active
+ * action's payload, so a recovery someone had already started silently
+ * became a recovery for a different set of prompts.
+ */
+ it('never rewrites an active action’s scope', async () => {
+ const writes = mockDb({
+ signals: [signal({ id: 's2' })],
+ activeActions: [{ id: 'a1', dedup_key: 'recover_visibility', status: 'in_progress' }],
+ });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW });
+
+ expect(summary.created).toBe(0);
+ expect(summary.refreshed).toBe(1);
+ expect(writes.inserted.find((w) => w.table === 'actions')).toBeUndefined();
+
+ const actionPatches = writes.updated.filter((w) => w.table === 'actions');
+ for (const patch of actionPatches) {
+ expect(patch.patch).not.toHaveProperty('payload');
+ expect(patch.patch).not.toHaveProperty('impact');
+ expect(patch.patch).not.toHaveProperty('kpi_keys');
+ }
+ });
+
+ it('links new signals to the active action as evidence', async () => {
+ const writes = mockDb({
+ signals: [signal({ id: 's3' })],
+ activeActions: [{ id: 'a1', dedup_key: 'recover_visibility', status: 'new' }],
+ });
+
+ await generateActionsForBrand(BRAND, { now: NOW });
+
+ expect(writes.updated.some((w) => w.table === 'signals')).toBe(true);
+ expect(
+ writes.inserted.some(
+ (w) => w.table === 'action_events' && w.rows[0].event === 'signals_linked',
+ ),
+ ).toBe(true);
+ });
+
+ /**
+ * A closed action is the record of one execution cycle. The old code set a
+ * completed row's status back to 'new' and cleared completed_at, which
+ * destroyed that record instead of adding to it.
+ */
+ it('never resurrects a closed action', async () => {
+ const writes = mockDb({
+ signals: [signal()],
+ closedActions: [
+ { dedup_key: 'recover_visibility', completed_at: daysAgo(40), updated_at: daysAgo(40) },
+ ],
+ });
+
+ await generateActionsForBrand(BRAND, { now: NOW });
+
+ const patches = writes.updated.filter((w) => w.table === 'actions');
+ for (const patch of patches) {
+ expect(patch.patch).not.toHaveProperty('status');
+ expect(patch.patch).not.toHaveProperty('completed_at');
+ }
+ expect(
+ writes.inserted.some((w) => w.table === 'action_events' && w.rows[0].event === 'reopened'),
+ ).toBe(false);
+ });
+
+ it('opens a new cycle once the rest window has passed', async () => {
+ const writes = mockDb({
+ signals: [signal()],
+ // No active action; the last cycle closed well outside the rest window.
+ closedActions: [
+ { dedup_key: 'recover_visibility', completed_at: daysAgo(40), updated_at: daysAgo(40) },
+ ],
+ });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW });
+
+ expect(summary.created).toBe(1);
+ expect(summary.resting).toBe(0);
+ // A second row beside the old one, not a rewrite of it.
+ expect(writes.inserted.find((w) => w.table === 'actions')).toBeDefined();
+ expect(writes.updated.filter((w) => w.table === 'actions')).toHaveLength(0);
+ });
+
+ it('rests instead of reopening the night after a cycle closed', async () => {
+ const writes = mockDb({
+ signals: [signal()],
+ closedActions: [
+ { dedup_key: 'recover_visibility', completed_at: daysAgo(1), updated_at: daysAgo(1) },
+ ],
+ });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW });
+
+ expect(summary.created).toBe(0);
+ expect(summary.resting).toBe(1);
+ expect(writes.inserted.find((w) => w.table === 'actions')).toBeUndefined();
+ });
+
+ it('does nothing for a kind with no matching open signals', async () => {
+ const writes = mockDb({ signals: [] });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW });
+
+ expect(summary).toEqual({ created: 0, refreshed: 0, resting: 0 });
+ expect(writes.inserted).toHaveLength(0);
+ });
+});
diff --git a/supabase/migrations/00084_action_lifecycle.sql b/supabase/migrations/00084_action_lifecycle.sql
new file mode 100644
index 000000000..1c140b595
--- /dev/null
+++ b/supabase/migrations/00084_action_lifecycle.sql
@@ -0,0 +1,110 @@
+-- Action Engine, phase 1 (#818): an action becomes a cycle rather than a row.
+--
+-- 00081 gave every action `dedup_key = kind` under `unique (brand_id,
+-- dedup_key)`, so a brand held at most one action per kind for its entire
+-- lifetime. Three consequences, all wrong:
+--
+-- * the nightly pass overwrote an open action's payload, so a new problem
+-- silently became the old one's description — including for an action
+-- someone was already working on;
+-- * a completed action was resurrected by setting status back to 'new' and
+-- clearing completed_at, which erased the historical record rather than
+-- adding to it;
+-- * a definition could therefore never produce a second execution cycle,
+-- so History had nothing to accumulate.
+--
+-- The rule the engine actually wants is one *active* action per kind, not one
+-- ever. A partial unique index says exactly that: open actions still collide,
+-- closed ones are free to pile up behind them.
+--
+-- Separately, `no_improvement` has been sitting in the status column since
+-- 00081. It is not an execution status — an action reaches it by being
+-- completed and then measured. Execution status answers "was the work done";
+-- outcome answers "did the work help". Conflating them makes the second
+-- question unanswerable for an action that was completed but never measured,
+-- which today is all of them.
+
+-- ─── One active action per kind, unlimited closed ones ──────────────────────
+
+alter table public.actions
+ drop constraint if exists actions_brand_id_dedup_key_key;
+
+-- 'dismissed' joins 'completed' as terminal: both mean the cycle is over and
+-- the slot is free. A dismissed action is not reopened — the user said no.
+create unique index if not exists actions_active_dedup_idx
+ on public.actions (brand_id, dedup_key)
+ where status not in ('completed', 'dismissed');
+
+-- ─── Outcome, separate from execution status ────────────────────────────────
+
+alter table public.actions
+ add column if not exists outcome text not null default 'pending_measurement';
+
+alter table public.actions
+ drop constraint if exists actions_outcome_check;
+
+alter table public.actions
+ add constraint actions_outcome_check
+ check (outcome in (
+ 'pending_measurement',
+ 'improved',
+ 'no_meaningful_change',
+ 'declined',
+ 'not_measurable'
+ ));
+
+comment on column public.actions.outcome is
+ 'Did the work help? Measured after completion, independent of status. Phase 2 (#818) fills this; until then every row reads pending_measurement.';
+
+comment on column public.actions.status is
+ 'Was the work done? Execution only — never an outcome.';
+
+-- Rows that reached 'no_improvement' were completed and then judged. Split
+-- that into the two facts it always was.
+alter table public.actions
+ drop constraint if exists actions_status_check;
+
+update public.actions
+set status = 'completed',
+ outcome = 'no_meaningful_change',
+ completed_at = coalesce(completed_at, updated_at)
+where status = 'no_improvement';
+
+-- A dismissed action was never executed, so there is nothing to measure.
+update public.actions
+set outcome = 'not_measurable'
+where status = 'dismissed';
+
+alter table public.actions
+ add constraint actions_status_check
+ check (status in ('new', 'in_progress', 'on_hold', 'completed', 'dismissed'));
+
+-- ─── Task statuses: skipped, failed, waiting approval ───────────────────────
+--
+-- 00083 renamed 'blocked' to 'canceled'. The execution vocabulary the task
+-- specification settles on is Skipped — with a stored reason, because "we
+-- decided not to" is only useful if it says why — alongside Failed for a run
+-- that was attempted and did not work, and Waiting Approval for an external
+-- write that needs a person.
+
+alter table public.action_tasks
+ add column if not exists skip_reason text;
+
+comment on column public.action_tasks.skip_reason is
+ 'Why this task was skipped. Required in the UI when moving to skipped; a skip without a reason is indistinguishable from an abandoned task.';
+
+alter table public.action_tasks
+ drop constraint if exists action_tasks_status_check;
+
+update public.action_tasks set status = 'skipped' where status = 'canceled';
+
+alter table public.action_tasks
+ add constraint action_tasks_status_check
+ check (status in (
+ 'todo',
+ 'in_progress',
+ 'waiting_approval',
+ 'completed',
+ 'skipped',
+ 'failed'
+ ));
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 64f7f0e7c..c384f6d18 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -10260,3 +10260,117 @@ create policy "action_tasks: member delete" on public.action_tasks
)
);
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00084_action_lifecycle.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Action Engine, phase 1 (#818): an action becomes a cycle rather than a row.
+--
+-- 00081 gave every action `dedup_key = kind` under `unique (brand_id,
+-- dedup_key)`, so a brand held at most one action per kind for its entire
+-- lifetime. Three consequences, all wrong:
+--
+-- * the nightly pass overwrote an open action's payload, so a new problem
+-- silently became the old one's description — including for an action
+-- someone was already working on;
+-- * a completed action was resurrected by setting status back to 'new' and
+-- clearing completed_at, which erased the historical record rather than
+-- adding to it;
+-- * a definition could therefore never produce a second execution cycle,
+-- so History had nothing to accumulate.
+--
+-- The rule the engine actually wants is one *active* action per kind, not one
+-- ever. A partial unique index says exactly that: open actions still collide,
+-- closed ones are free to pile up behind them.
+--
+-- Separately, `no_improvement` has been sitting in the status column since
+-- 00081. It is not an execution status — an action reaches it by being
+-- completed and then measured. Execution status answers "was the work done";
+-- outcome answers "did the work help". Conflating them makes the second
+-- question unanswerable for an action that was completed but never measured,
+-- which today is all of them.
+
+-- ─── One active action per kind, unlimited closed ones ──────────────────────
+
+alter table public.actions
+ drop constraint if exists actions_brand_id_dedup_key_key;
+
+-- 'dismissed' joins 'completed' as terminal: both mean the cycle is over and
+-- the slot is free. A dismissed action is not reopened — the user said no.
+create unique index if not exists actions_active_dedup_idx
+ on public.actions (brand_id, dedup_key)
+ where status not in ('completed', 'dismissed');
+
+-- ─── Outcome, separate from execution status ────────────────────────────────
+
+alter table public.actions
+ add column if not exists outcome text not null default 'pending_measurement';
+
+alter table public.actions
+ drop constraint if exists actions_outcome_check;
+
+alter table public.actions
+ add constraint actions_outcome_check
+ check (outcome in (
+ 'pending_measurement',
+ 'improved',
+ 'no_meaningful_change',
+ 'declined',
+ 'not_measurable'
+ ));
+
+comment on column public.actions.outcome is
+ 'Did the work help? Measured after completion, independent of status. Phase 2 (#818) fills this; until then every row reads pending_measurement.';
+
+comment on column public.actions.status is
+ 'Was the work done? Execution only — never an outcome.';
+
+-- Rows that reached 'no_improvement' were completed and then judged. Split
+-- that into the two facts it always was.
+alter table public.actions
+ drop constraint if exists actions_status_check;
+
+update public.actions
+set status = 'completed',
+ outcome = 'no_meaningful_change',
+ completed_at = coalesce(completed_at, updated_at)
+where status = 'no_improvement';
+
+-- A dismissed action was never executed, so there is nothing to measure.
+update public.actions
+set outcome = 'not_measurable'
+where status = 'dismissed';
+
+alter table public.actions
+ add constraint actions_status_check
+ check (status in ('new', 'in_progress', 'on_hold', 'completed', 'dismissed'));
+
+-- ─── Task statuses: skipped, failed, waiting approval ───────────────────────
+--
+-- 00083 renamed 'blocked' to 'canceled'. The execution vocabulary the task
+-- specification settles on is Skipped — with a stored reason, because "we
+-- decided not to" is only useful if it says why — alongside Failed for a run
+-- that was attempted and did not work, and Waiting Approval for an external
+-- write that needs a person.
+
+alter table public.action_tasks
+ add column if not exists skip_reason text;
+
+comment on column public.action_tasks.skip_reason is
+ 'Why this task was skipped. Required in the UI when moving to skipped; a skip without a reason is indistinguishable from an abandoned task.';
+
+alter table public.action_tasks
+ drop constraint if exists action_tasks_status_check;
+
+update public.action_tasks set status = 'skipped' where status = 'canceled';
+
+alter table public.action_tasks
+ add constraint action_tasks_status_check
+ check (status in (
+ 'todo',
+ 'in_progress',
+ 'waiting_approval',
+ 'completed',
+ 'skipped',
+ 'failed'
+ ));
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 1edf62dff..c8c8c86f5 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -411,9 +411,8 @@
"status": {
"new": "New",
"in_progress": "In Progress",
- "completed": "Completed",
"on_hold": "On Hold",
- "no_improvement": "No Improvement",
+ "completed": "Completed",
"dismissed": "Dismissed"
},
"impact": {
@@ -479,7 +478,11 @@
"addTask": "Add task",
"addTaskPlaceholder": "What needs doing?",
"addTaskConfirm": "Add",
- "addTaskCancel": "Cancel"
+ "addTaskCancel": "Cancel",
+ "skipReason": "Why was this skipped?",
+ "skipReasonPlaceholder": "e.g. handled elsewhere, no longer relevant",
+ "skipConfirm": "Skip task",
+ "skipCancel": "Cancel"
}
},
"actionTexts": {
@@ -531,8 +534,10 @@
"taskStatus": {
"todo": "To Do",
"in_progress": "In Progress",
+ "waiting_approval": "Waiting Approval",
"completed": "Completed",
- "canceled": "Canceled"
+ "skipped": "Skipped",
+ "failed": "Failed"
},
"historyPage": {
"title": "History",
@@ -549,9 +554,8 @@
"status": {
"new": "New",
"in_progress": "In Progress",
- "completed": "Completed",
"on_hold": "On Hold",
- "no_improvement": "No Improvement",
+ "completed": "Completed",
"dismissed": "Dismissed"
},
"affected": {
@@ -563,30 +567,6 @@
"competitor": "Competitor",
"platform": "{count} platforms"
},
- "validation": {
- "pending": "Not measured",
- "running": "Measuring",
- "improved": "Improved",
- "no_improvement": "No improvement",
- "declined": "Declined",
- "not_required": "Not applicable"
- },
- "validationHint": {
- "pending": "no result recorded",
- "running": "in progress",
- "improved": "vs before",
- "no_improvement": "vs before",
- "declined": "vs before",
- "not_required": "action was dismissed"
- },
- "validationExplain": {
- "pending": "This action's effect has not been measured. The metrics below fill in once validation runs.",
- "running": "Validation is running. Results appear when it finishes.",
- "improved": "Measured after this action closed.",
- "no_improvement": "Measured after this action closed; the metrics did not move.",
- "declined": "Measured after this action closed; the metrics moved the wrong way.",
- "not_required": "This action was dismissed, so nothing was measured."
- },
"range": {
"7d": "7d",
"30d": "30d",
@@ -658,7 +638,28 @@
"noBrand": {
"title": "No brand selected",
"description": "Select a brand to view its action history."
+ },
+ "outcomeHint": {
+ "pending_measurement": "no result recorded",
+ "improved": "vs before",
+ "no_meaningful_change": "vs before",
+ "declined": "vs before",
+ "not_measurable": "action was dismissed"
+ },
+ "outcomeExplain": {
+ "pending_measurement": "This action's effect has not been measured. The metrics below fill in once validation runs.",
+ "improved": "Measured after this action closed.",
+ "no_meaningful_change": "Measured after this action closed; the metrics did not move.",
+ "declined": "Measured after this action closed; the metrics moved the wrong way.",
+ "not_measurable": "This action was dismissed, so nothing was measured."
}
+ },
+ "actionOutcome": {
+ "pending_measurement": "Not measured",
+ "improved": "Improved",
+ "no_meaningful_change": "No meaningful change",
+ "declined": "Declined",
+ "not_measurable": "Not measurable"
}
},
"agent": {
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
index b27f67f79..f13c6341e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx
@@ -49,7 +49,7 @@ import {
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';
-const OPEN_STATUSES: ActionStatus[] = ['new', 'in_progress', 'on_hold', 'no_improvement'];
+const OPEN_STATUSES: ActionStatus[] = ['new', 'in_progress', 'on_hold'];
const isOpen = (action: ActionItem) => OPEN_STATUSES.includes(action.status);
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index cdc44a049..ab860da46 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -42,6 +42,7 @@ import type { TeamMember } from '@/lib/actions/team';
import {
ACTION_STATUSES,
TASK_STATUSES,
+ UNCOUNTED_TASK_STATUSES,
type ActionStatus,
type TaskStatus,
} from '@/lib/action-center/registry';
@@ -262,7 +263,9 @@ export function ActionDrawer({
<p className="text-xs text-muted-foreground">
{t('drawer.tasksProgress', {
completed: detail.tasks.filter((task) => task.status === 'completed').length,
- total: detail.tasks.filter((task) => task.status !== 'canceled').length,
+ total: detail.tasks.filter(
+ (task) => !UNCOUNTED_TASK_STATUSES.includes(task.status),
+ ).length,
})}
</p>
<div className="mt-3 space-y-2">
@@ -274,8 +277,10 @@ export function ActionDrawer({
text={taskText(task, tTasks)}
statusLabel={tTaskStatus}
t={t}
- onStatusChange={(status) =>
- void mutate(() => updateTaskStatus(brandId, action.id, task.id, status))
+ onStatusChange={(status, skipReason) =>
+ void mutate(() =>
+ updateTaskStatus(brandId, action.id, task.id, status, skipReason),
+ )
}
onRename={(title) =>
void mutate(() => updateTaskTitle(brandId, action.id, task.id, title))
@@ -442,12 +447,15 @@ function TaskRow({
disabled: boolean;
statusLabel: TaskTranslator;
t: TaskTranslator;
- onStatusChange: (status: TaskStatus) => void;
+ onStatusChange: (status: TaskStatus, skipReason?: string) => void;
onRename: (title: string) => void;
onDelete: () => void;
}) {
const [draft, setDraft] = useState<string | null>(null);
const isEditing = draft !== null;
+ // Choosing Skipped opens a reason field rather than committing: a skip
+ // without a reason cannot be told apart from an abandoned task later.
+ const [skipDraft, setSkipDraft] = useState<string | null>(null);
const commit = () => {
const next = (draft ?? '').trim();
@@ -456,70 +464,128 @@ function TaskRow({
};
return (
- <div className="flex items-center justify-between gap-2 rounded-md border px-3 py-2">
- {isEditing ? (
- <Input
- autoFocus
- value={draft}
- maxLength={200}
- disabled={disabled}
- aria-label={t('drawer.taskText')}
- className="h-7 min-w-0 flex-1 text-sm"
- onChange={(e) => setDraft(e.target.value)}
- onBlur={commit}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- commit();
- } else if (e.key === 'Escape') {
- e.preventDefault();
- setDraft(null);
- }
+ <div className="rounded-md border">
+ <div className="flex items-center justify-between gap-2 px-3 py-2">
+ {isEditing ? (
+ <Input
+ autoFocus
+ value={draft}
+ maxLength={200}
+ disabled={disabled}
+ aria-label={t('drawer.taskText')}
+ className="h-7 min-w-0 flex-1 text-sm"
+ onChange={(e) => setDraft(e.target.value)}
+ onBlur={commit}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ commit();
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ setDraft(null);
+ }
+ }}
+ />
+ ) : (
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => setDraft(text)}
+ title={t('drawer.renameTask')}
+ className={cn(
+ 'min-w-0 flex-1 truncate rounded px-1 py-0.5 text-left text-sm hover:bg-muted/60',
+ (task.status === 'completed' || UNCOUNTED_TASK_STATUSES.includes(task.status)) &&
+ 'text-muted-foreground line-through',
+ )}
+ >
+ {task.position}. {text}
+ </button>
+ )}
+ <Select
+ value={task.status}
+ onValueChange={(value) => {
+ const next = value as TaskStatus;
+ if (next === 'skipped') setSkipDraft('');
+ else onStatusChange(next);
}}
- />
- ) : (
- <button
+ disabled={disabled || isEditing || skipDraft !== null}
+ items={TASK_STATUSES.map((status) => ({ value: status, label: statusLabel(status) }))}
+ >
+ <SelectTrigger className="h-7 w-32 shrink-0 text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {TASK_STATUSES.map((status) => (
+ <SelectItem key={status} value={status}>
+ {statusLabel(status)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Button
type="button"
- disabled={disabled}
- onClick={() => setDraft(text)}
- title={t('drawer.renameTask')}
- className={cn(
- 'min-w-0 flex-1 truncate rounded px-1 py-0.5 text-left text-sm hover:bg-muted/60',
- (task.status === 'completed' || task.status === 'canceled') &&
- 'text-muted-foreground line-through',
- )}
+ variant="ghost"
+ size="icon"
+ disabled={disabled || isEditing || skipDraft !== null}
+ onClick={onDelete}
+ aria-label={t('drawer.deleteTask')}
+ className="h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive"
>
- {task.position}. {text}
- </button>
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+
+ {skipDraft !== null && (
+ <div className="flex items-center gap-2 border-t bg-muted/30 px-3 py-2">
+ <Input
+ autoFocus
+ value={skipDraft}
+ maxLength={200}
+ disabled={disabled}
+ placeholder={t('drawer.skipReasonPlaceholder')}
+ aria-label={t('drawer.skipReason')}
+ className="h-7 min-w-0 flex-1 text-xs"
+ onChange={(e) => setSkipDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && skipDraft.trim()) {
+ e.preventDefault();
+ onStatusChange('skipped', skipDraft.trim());
+ setSkipDraft(null);
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ setSkipDraft(null);
+ }
+ }}
+ />
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={disabled || skipDraft.trim() === ''}
+ className="h-7 shrink-0 text-xs"
+ onClick={() => {
+ onStatusChange('skipped', skipDraft.trim());
+ setSkipDraft(null);
+ }}
+ >
+ {t('drawer.skipConfirm')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ disabled={disabled}
+ className="h-7 shrink-0 text-xs"
+ onClick={() => setSkipDraft(null)}
+ >
+ {t('drawer.skipCancel')}
+ </Button>
+ </div>
+ )}
+
+ {task.status === 'skipped' && task.skipReason && skipDraft === null && (
+ <p className="border-t px-3 py-1.5 text-[11px] text-muted-foreground">{task.skipReason}</p>
)}
- <Select
- value={task.status}
- onValueChange={(value) => onStatusChange(value as TaskStatus)}
- disabled={disabled || isEditing}
- items={TASK_STATUSES.map((status) => ({ value: status, label: statusLabel(status) }))}
- >
- <SelectTrigger className="h-7 w-32 shrink-0 text-xs">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {TASK_STATUSES.map((status) => (
- <SelectItem key={status} value={status}>
- {statusLabel(status)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <Button
- type="button"
- variant="ghost"
- size="icon"
- disabled={disabled || isEditing}
- onClick={onDelete}
- aria-label={t('drawer.deleteTask')}
- className="h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive"
- >
- <Trash2 className="h-3.5 w-3.5" />
- </Button>
</div>
);
}
diff --git a/web/src/components/action-center/action-table.tsx b/web/src/components/action-center/action-table.tsx
index 888949543..716c21cb0 100644
--- a/web/src/components/action-center/action-table.tsx
+++ b/web/src/components/action-center/action-table.tsx
@@ -32,7 +32,6 @@ export const ACTION_STATUS_BADGE: Record<ActionStatus, string> = {
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',
};
diff --git a/web/src/components/action-center/history-drawer.tsx b/web/src/components/action-center/history-drawer.tsx
index 750608aed..1ad1a34e2 100644
--- a/web/src/components/action-center/history-drawer.tsx
+++ b/web/src/components/action-center/history-drawer.tsx
@@ -14,6 +14,7 @@ import {
} from '@/components/ui/sheet';
import { actionTexts } from '@/lib/action-center/display';
import type { ActionHistoryItem } from '@/lib/action-center/history';
+import { UNCOUNTED_TASK_STATUSES } from '@/lib/action-center/registry';
import { ImpactDots } from './signal-table';
import { KIND_ICONS } from './action-table';
import { HistoryStatusBadge } from './history-table';
@@ -68,7 +69,9 @@ export function HistoryDrawer({
const date = item.completedAt ?? item.createdAt;
const measured = item.results.length > 0;
const completedTasks = item.tasks.filter((task) => task.status === 'completed').length;
- const countedTasks = item.tasks.filter((task) => task.status !== 'canceled').length;
+ const countedTasks = item.tasks.filter(
+ (task) => !UNCOUNTED_TASK_STATUSES.includes(task.status),
+ ).length;
const metricValue = (metric: string) => {
const found = item.results.find((r) => r.metric === metric);
@@ -139,7 +142,7 @@ export function HistoryDrawer({
// line is recorded; the effect is not, because nothing re-reads
// these metrics after an action closes.
<p className="mt-1 text-xs text-muted-foreground">
- {t(`validationExplain.${item.validationStatus}`)}
+ {t(`outcomeExplain.${item.outcome}`)}
</p>
)}
<div className="mt-2 grid grid-cols-2 gap-2">
@@ -206,7 +209,8 @@ export function HistoryDrawer({
<span
className={cn(
'min-w-0 flex-1',
- (task.status === 'completed' || task.status === 'canceled') &&
+ (task.status === 'completed' ||
+ UNCOUNTED_TASK_STATUSES.includes(task.status)) &&
'text-muted-foreground line-through',
)}
>
diff --git a/web/src/components/action-center/history-table.tsx b/web/src/components/action-center/history-table.tsx
index c3032cd66..f68e7ef83 100644
--- a/web/src/components/action-center/history-table.tsx
+++ b/web/src/components/action-center/history-table.tsx
@@ -31,7 +31,6 @@ const STATUS_TONES: Record<string, string> = {
completed: 'text-emerald-600 dark:text-emerald-400',
in_progress: 'text-blue-600 dark:text-blue-400',
on_hold: 'text-muted-foreground',
- no_improvement: 'text-amber-600 dark:text-amber-400',
dismissed: 'text-muted-foreground',
};
@@ -55,6 +54,7 @@ export function HistoryStatusBadge({ status }: { status: ActionStatus }) {
*/
function ResultCell({ item }: { item: ActionHistoryItem }) {
const t = useTranslations('actionCenter.historyPage');
+ const tOutcome = useTranslations('actionCenter.actionOutcome');
if (item.results.length > 0) {
return (
@@ -70,10 +70,8 @@ function ResultCell({ item }: { item: ActionHistoryItem }) {
return (
<div className="space-y-0.5">
- <p className="text-xs text-muted-foreground">{t(`validation.${item.validationStatus}`)}</p>
- <p className="text-[11px] text-muted-foreground/70">
- {t(`validationHint.${item.validationStatus}`)}
- </p>
+ <p className="text-xs text-muted-foreground">{tOutcome(item.outcome)}</p>
+ <p className="text-[11px] text-muted-foreground/70">{t(`outcomeHint.${item.outcome}`)}</p>
</div>
);
}
diff --git a/web/src/lib/action-center/history.ts b/web/src/lib/action-center/history.ts
index 2b324e41a..46d55f71d 100644
--- a/web/src/lib/action-center/history.ts
+++ b/web/src/lib/action-center/history.ts
@@ -16,32 +16,22 @@
* is no "after" to compare it to. Visibility change, citations change, prompts
* improved: none of them have a source.
*
- * So `results` comes back empty and `validationStatus` says `pending` rather
- * than a number, and the UI says so plainly instead of implying a measurement
- * that did not happen. The types below are the full shape a validation pass
- * would fill in; adding it is a matter of populating these, not reshaping
- * them.
+ * So `results` comes back empty and `outcome` reads `pending_measurement`
+ * rather than a number, and the UI says so plainly instead of implying a
+ * measurement that did not happen. The types below are the full shape the
+ * validation pass (#818, phase 2) will fill in; adding it is a matter of
+ * populating these, not reshaping them.
*/
-import type { ActionCategory, ActionImpact, ActionStatus } from './registry';
+import type {
+ ActionCategory,
+ ActionImpact,
+ ActionOutcome,
+ ActionStatus,
+ TaskStatus,
+} from './registry';
import type { SignalSource } from '@/lib/signals/registry';
-/**
- * Whether an action's effect has been measured.
- *
- * Distinct from ActionStatus on purpose: an action can be `completed` while
- * its validation is still `pending`, which is exactly the state every closed
- * action is in today. `not_required` is for actions that were dismissed —
- * nothing ran, so there is nothing to measure.
- */
-export type ValidationStatus =
- | 'pending'
- | 'running'
- | 'improved'
- | 'no_improvement'
- | 'declined'
- | 'not_required';
-
/** A metric an action moved, read before and after it ran. */
export interface ActionResultMetric {
id: string;
@@ -82,7 +72,7 @@ export interface ActionHistoryTask {
id: string;
/** Resolved text: the user's title when they wrote one, else the template. */
title: string;
- status: 'completed' | 'skipped' | 'failed' | 'todo' | 'in_progress' | 'canceled';
+ status: TaskStatus;
completedAt?: string;
}
@@ -102,7 +92,8 @@ export interface ActionHistoryItem {
type: ActionCategory;
impact: ActionImpact;
status: ActionStatus;
- validationStatus: ValidationStatus;
+ /** Did it help? Read from the action's own column, not inferred here. */
+ outcome: ActionOutcome;
payload: Record<string, unknown>;
kpiKeys: string[];
sources: SignalSource[];
@@ -137,10 +128,9 @@ export interface HistorySummary {
* still running so the tab shows the whole arc rather than only its end. */
export const HISTORY_STATUSES: readonly ActionStatus[] = [
'in_progress',
+ 'on_hold',
'completed',
- 'no_improvement',
'dismissed',
- 'on_hold',
];
export const HISTORY_SORTS = ['newest', 'oldest', 'impact'] as const;
@@ -155,7 +145,9 @@ export function summarize(items: ActionHistoryItem[]): HistorySummary {
const count = (status: ActionStatus) => items.filter((i) => i.status === status).length;
const completed = count('completed');
const inProgress = count('in_progress');
- const noImprovement = count('no_improvement');
+ // An outcome, not a status: an action reaches it by being completed and
+ // then measured, so it is counted from the outcome column.
+ const noImprovement = items.filter((i) => i.outcome === 'no_meaningful_change').length;
const dismissed = count('dismissed');
const impacts = items.map((i) => i.impact);
@@ -181,27 +173,6 @@ export function summarize(items: ActionHistoryItem[]): HistorySummary {
};
}
-/**
- * Whether an action's effect has been measured.
- *
- * Every closed action answers `pending` today, and a dismissed one answers
- * `not_required` — nothing ran, so there is nothing to measure. The other
- * values exist for the validation pass to return; nothing produces them yet,
- * and inferring one from the action's own status would be inventing the
- * measurement rather than reporting it.
- */
-export function validationStatusFor(
- status: ActionStatus,
- results: ActionResultMetric[],
-): ValidationStatus {
- if (status === 'dismissed') return 'not_required';
- if (results.length === 0) return 'pending';
- const improved = results.some((r) =>
- r.direction === 'higher_is_better' ? (r.delta ?? 0) > 0 : (r.delta ?? 0) < 0,
- );
- return improved ? 'improved' : 'no_improvement';
-}
-
/** Whole days between two stamps, floored — "4 days" means four elapsed. */
export function daysBetween(fromIso: string, toIso: string): number {
const ms = new Date(toIso).getTime() - new Date(fromIso).getTime();
diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.ts
index 27d16c81a..c34475792 100644
--- a/web/src/lib/action-center/registry.ts
+++ b/web/src/lib/action-center/registry.ts
@@ -10,13 +10,24 @@ 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';
+/** Was the work done? Execution only — see ActionOutcome for whether it helped. */
+export type ActionStatus = 'new' | 'in_progress' | 'on_hold' | 'completed' | 'dismissed';
+
+/**
+ * Did the work help?
+ *
+ * Kept apart from ActionStatus on purpose: an action is completed by someone
+ * finishing it, and measured afterwards by something re-reading its metrics.
+ * `no_improvement` used to live in the status column, which made the two
+ * questions unanswerable for an action that was completed but never measured
+ * — today, every one of them.
+ */
+export type ActionOutcome =
+ | 'pending_measurement'
+ | 'improved'
+ | 'no_meaningful_change'
+ | 'declined'
+ | 'not_measurable';
export type ActionKind =
| 'recover_visibility'
@@ -25,7 +36,13 @@ export type ActionKind =
| 'fix_low_scores'
| 'close_competitor_gap';
-export type TaskStatus = 'todo' | 'in_progress' | 'completed' | 'canceled';
+export type TaskStatus =
+ | 'todo'
+ | 'in_progress'
+ | 'waiting_approval'
+ | 'completed'
+ | 'skipped'
+ | 'failed';
export const ACTION_CATEGORIES: readonly ActionCategory[] = [
'growth',
@@ -38,21 +55,36 @@ export const ACTION_CATEGORIES: readonly ActionCategory[] = [
export const ACTION_STATUSES: readonly ActionStatus[] = [
'new',
'in_progress',
- 'completed',
'on_hold',
- 'no_improvement',
+ 'completed',
'dismissed',
];
+export const ACTION_OUTCOMES: readonly ActionOutcome[] = [
+ 'pending_measurement',
+ 'improved',
+ 'no_meaningful_change',
+ 'declined',
+ 'not_measurable',
+];
+
+/** An action whose cycle is over: it is history, and its kind's slot is free. */
+export const CLOSED_ACTION_STATUSES: readonly ActionStatus[] = ['completed', 'dismissed'];
+
export const ACTION_IMPACTS: readonly ActionImpact[] = ['high', 'medium', 'low'];
export const TASK_STATUSES: readonly TaskStatus[] = [
'todo',
'in_progress',
+ 'waiting_approval',
'completed',
- 'canceled',
+ 'skipped',
+ 'failed',
];
+/** Statuses that leave the progress denominator — the work is not outstanding. */
+export const UNCOUNTED_TASK_STATUSES: readonly TaskStatus[] = ['skipped', 'failed'];
+
export interface ActionKindMeta {
kind: ActionKind;
/** Ordered task template keys — the DB rows carry the same keys. */
diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.ts
index 538d196d9..c402e64ee 100644
--- a/web/src/lib/actions/action-center.ts
+++ b/web/src/lib/actions/action-center.ts
@@ -16,6 +16,7 @@ import {
type ActionCategory,
type ActionImpact,
type ActionKind,
+ UNCOUNTED_TASK_STATUSES,
type ActionStatus,
type TaskStatus,
} from '@/lib/action-center/registry';
@@ -93,11 +94,11 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {
if (signalsRes.error) throw new Error(signalsRes.error.message);
if (profilesRes.error) throw new Error(profilesRes.error.message);
- // Canceled tasks leave the denominator: the work was called off, so it must
- // not hold the action below 100% forever the way a blocked one used to.
+ // Skipped and failed tasks leave the denominator: neither is outstanding
+ // work, so neither should hold an action below 100% for good.
const taskTotals = new Map<string, { total: number; completed: number }>();
for (const task of tasksRes.data ?? []) {
- if (task.status === 'canceled') continue;
+ if ((UNCOUNTED_TASK_STATUSES as readonly string[]).includes(task.status)) continue;
const acc = taskTotals.get(task.action_id) ?? { total: 0, completed: 0 };
acc.total += 1;
if (task.status === 'completed') acc.completed += 1;
@@ -146,6 +147,8 @@ export interface ActionTask {
/** User-supplied text. Takes precedence over the template when present. */
title: string | null;
status: TaskStatus;
+ /** Why the task was skipped; null for every other status. */
+ skipReason: string | null;
}
export interface ActionEvent {
@@ -177,7 +180,7 @@ export async function getActionDetail(brandId: string, actionId: string): Promis
const [tasksRes, signalsRes, eventsRes, kpisRes] = await Promise.all([
supabase
.from('action_tasks')
- .select('id, position, task_key, title, status')
+ .select('id, position, task_key, title, status, skip_reason')
.eq('action_id', actionId)
.order('position'),
supabase
@@ -209,6 +212,7 @@ export async function getActionDetail(brandId: string, actionId: string): Promis
taskKey: task.task_key,
title: task.title,
status: task.status as TaskStatus,
+ skipReason: task.skip_reason,
})),
signals: mapSignalRows((signalsRes.data ?? []) as SignalRow[]),
events: (eventsRes.data ?? []).map((event) => ({
@@ -307,15 +311,27 @@ export async function updateTaskStatus(
actionId: string,
taskId: string,
status: TaskStatus,
+ skipReason?: string,
): Promise<void> {
const supabase = await createClient();
+
+ // A skip records why. "We decided not to" is only useful to the next reader
+ // if it says what the decision was; without it a skipped task is
+ // indistinguishable from an abandoned one.
+ const reason = status === 'skipped' ? (skipReason ?? '').trim().slice(0, 200) : null;
+ if (status === 'skipped' && !reason) throw new Error('A skipped task needs a reason');
+
const { error } = await supabase
.from('action_tasks')
- .update({ status, updated_at: new Date().toISOString() })
+ .update({ status, skip_reason: reason, 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 });
+ await logEvent(supabase, actionId, 'task_status', {
+ taskId,
+ to: status,
+ ...(reason ? { reason } : {}),
+ });
await touchAction(supabase, brandId, actionId);
}
diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.ts
index 17ee8489b..6a3a456d3 100644
--- a/web/src/lib/actions/action-history.ts
+++ b/web/src/lib/actions/action-history.ts
@@ -14,12 +14,11 @@
import { createClient } from '@/lib/supabase/server';
import { isActionKind, type ActionCategory, type ActionImpact } from '@/lib/action-center/registry';
-import type { ActionStatus, TaskStatus } from '@/lib/action-center/registry';
+import type { ActionOutcome, ActionStatus, TaskStatus } from '@/lib/action-center/registry';
import { SIGNAL_SOURCES, type SignalSource } from '@/lib/signals/registry';
import {
HISTORY_STATUSES,
daysBetween,
- validationStatusFor,
type ActionHistoryItem,
type ActionHistoryTask,
type ActionResultMetric,
@@ -34,6 +33,7 @@ interface HistoryRow {
kind: string;
impact: string;
status: string;
+ outcome: string;
payload: Record<string, unknown>;
kpi_keys: string[];
assignee_id: string | null;
@@ -43,7 +43,7 @@ interface HistoryRow {
}
const HISTORY_COLUMNS =
- 'id, action_no, category, kind, impact, status, payload, kpi_keys, assignee_id, created_at, completed_at, updated_at';
+ 'id, action_no, category, kind, impact, status, outcome, payload, kpi_keys, assignee_id, created_at, completed_at, updated_at';
function num(payload: Record<string, unknown>, key: string): number {
const value = payload[key];
@@ -196,7 +196,7 @@ export async function getActionHistory(
type: row.category as ActionCategory,
impact: row.impact as ActionImpact,
status: row.status as ActionStatus,
- validationStatus: validationStatusFor(row.status as ActionStatus, results),
+ outcome: row.outcome as ActionOutcome,
payload: row.payload ?? {},
kpiKeys: row.kpi_keys ?? [],
sources: [...(sourcesByAction.get(row.id) ?? [])],
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index e9c46f51f..b08fb0fe5 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -62,6 +62,7 @@ export type Database = {
created_at: string
id: string
position: number
+ skip_reason: string | null
status: string
task_key: string | null
title: string | null
@@ -72,6 +73,7 @@ export type Database = {
created_at?: string
id?: string
position: number
+ skip_reason?: string | null
status?: string
task_key?: string | null
title?: string | null
@@ -82,6 +84,7 @@ export type Database = {
created_at?: string
id?: string
position?: number
+ skip_reason?: string | null
status?: string
task_key?: string | null
title?: string | null
@@ -112,6 +115,7 @@ export type Database = {
impact: string
kind: string
kpi_keys: string[]
+ outcome: string
payload: Json
status: string
updated_at: string
@@ -130,6 +134,7 @@ export type Database = {
impact: string
kind: string
kpi_keys?: string[]
+ outcome?: string
payload?: Json
status?: string
updated_at?: string
@@ -148,6 +153,7 @@ export type Database = {
impact?: string
kind?: string
kpi_keys?: string[]
+ outcome?: string
payload?: Json
status?: string
updated_at?: string