Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(action-center): link signals and actions both ways and keep priority current (#1074)
Cihanb526bded5675
diff --git a/server/src/lib/action-center/generate.js b/server/src/lib/action-center/generate.jsindex 6a6cee9c8..11c8c4888 100644--- a/server/src/lib/action-center/generate.js+++ b/server/src/lib/action-center/generate.js@@ -90,18 +90,32 @@ async function logEvent(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;+/**+ * Takes signals as an action's evidence (AC-007). Each becomes the action's+ * (`signals.action_id`, the signal's current action), and the link is kept+ * in `action_signals` for good: the action still lists the signal after it+ * moves on to a later cycle, and the signal lists every action it was used+ * by. The rows in hand are updated too, so the rest of the night sees them+ * as taken.+ */+async function linkSignals(actionId, signals, linkedAt) {+ if (signals.length === 0) return 0;+ const ids = signals.map((signal) => signal.id);+ // The link first: if pointing the signals at the action then fails, they+ // are not taken yet and the next night links them again. The other way+ // round, a signal could be taken with no link, and missing from the action.+ const { error: linkErr } = await supabaseAdmin.from('action_signals').upsert(+ ids.map((signalId) => ({ action_id: actionId, signal_id: signalId, linked_at: linkedAt })),+ { onConflict: 'action_id,signal_id', ignoreDuplicates: true },+ );+ if (linkErr) throw new Error(linkErr.message);const { error } = await supabaseAdmin.from('signals').update({ action_id: actionId })- .in(- 'id',- unlinked.map((signal) => signal.id),- );+ .in('id', ids);if (error) throw new Error(error.message);- return unlinked.length;+ for (const signal of signals) signal.action_id = actionId;+ return signals.length;}function startOfUtcDay(now) {@@ -160,7 +174,7 @@ async function openCycle({definitionVersion: definition.version,taskCount: plan.length,});- await linkSignals(inserted.id, signals);+ await linkSignals(inserted.id, signals, now.toISOString());return inserted.id;}@@ -183,12 +197,24 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc// 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, created_at, kind, category, impact, payload')+ .select('id, dedup_key, status, created_at, kind, category, impact, payload, baseline').eq('brand_id', brandId).not('status', 'in', '("completed","dismissed")').limit(1000);if (actionsErr) throw new Error(actionsErr.message);const active = new Map((activeRows ?? []).map((row) => [row.dedup_key, row]));+ // A signal is taken while an active action holds it. One whose action has+ // closed is free again: if it is still open, the condition is still firing,+ // and it is evidence for the definition's next cycle (AC-007). Before,+ // `action_id` was written once and such a signal could never start one.+ const activeIds = new Set((activeRows ?? []).map((row) => row.id));+ const taken = (signal) => Boolean(signal.action_id) && activeIds.has(signal.action_id);+ // What active actions cover: the signals each was created from. A signal+ // linked to one later is its evidence, not its scope, so it is still what+ // the next cycle is for (#818 phase 6).+ const inScope = new Set(+ (activeRows ?? []).flatMap((row) => (row.baseline?.signals ?? []).map((s) => s.id)),+ );// How recently each definition was closed, so a condition that is still// firing does not reopen as a fresh action the very next night.@@ -245,10 +271,6 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc} catch (err) {logger.warn({ brandId, err: err.message }, '[actions] prompt demand unavailable');}- // Signals linked to an active action tonight, which the rows in hand do- // not show yet: they are its evidence when its priority is refreshed.- const linkedTonight = new Map();-const ready = [];const seen = new Set();let refreshed = 0;@@ -273,12 +295,13 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc// executing against, and rewriting it nightly turned a recovery for six// prompts into a recovery for a different nine without telling anyone.//- // Those newcomers are not dropped any more, which is this phase: they- // stay in the queue below and are what the next cycle covers.- const linked = await linkSignals(current.id, matched);- for (const signal of matched) {- if (!signal.action_id) linkedTonight.set(signal.id, current.id);- }+ // Those newcomers are not dropped either: outside its scope, they stay+ // in the queue below and are what the next cycle covers.+ const linked = await linkSignals(+ current.id,+ matched.filter((signal) => !taken(signal)),+ nowIso,+ );if (linked > 0) {await supabaseAdmin.from('actions').update({ updated_at: nowIso }).eq('id', current.id);await logEvent(current.id, 'signals_linked', { count: linked });@@ -286,12 +309,13 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourcrefreshed += 1;}- // A candidate covers exactly the matched signals no action has claimed.- // Recomputed rather than accumulated: a signal that resolved leaves the- // queue by itself, and one the active action has taken as evidence is+ // A candidate covers exactly the matched signals no active action was+ // created from. Recomputed rather than accumulated: a signal that resolved+ // leaves the queue by itself, and one in an active action's scope is// already accounted for. The queue therefore cannot drift out of step- // with what is actually true tonight.- const unclaimed = matched.filter((signal) => !signal.action_id);+ // with what is actually true tonight — and a newcomer stays in it on the+ // nights after it was linked, not only the first.+ const unclaimed = matched.filter((signal) => !inScope.has(signal.id));if (unclaimed.length === 0) continue;const impact = unclaimed@@ -417,9 +441,8 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc// that cannot be written is logged, never a reason to fail the night.let rescored = 0;for (const row of activeRows ?? []) {- const evidence = (openSignals ?? []).filter(- (signal) => signal.action_id === row.id || linkedTonight.get(signal.id) === row.id,- );+ // Including the signals linked to it tonight: the rows in hand say so.+ const evidence = (openSignals ?? []).filter((signal) => signal.action_id === row.id);const priority = scorePriority({ action: row, signals: evidence, prompts: demand }, now);const { error } = await supabaseAdmin.from('actions')diff --git a/server/src/lib/action-center/generate.test.js b/server/src/lib/action-center/generate.test.jsindex 08219bdcd..040855cab 100644--- a/server/src/lib/action-center/generate.test.js+++ b/server/src/lib/action-center/generate.test.js@@ -35,7 +35,8 @@ function mockDb({promptVolumes = [],failActionUpdates = false,} = {}) {- const writes = { inserted: [], updated: [] };+ // `log` keeps the order of the writes across tables.+ const writes = { inserted: [], updated: [], upserted: [], log: [] };from.mockImplementation((table) => {const state = { op: 'select', payload: null, negated: false };@@ -66,6 +67,13 @@ function mockDb({state.op = 'update';state.payload = payload;writes.updated.push({ table, patch: payload });+ writes.log.push(`update ${table}`);+ return builder;+ },+ upsert: (payload) => {+ state.op = 'upsert';+ writes.upserted.push({ table, rows: Array.isArray(payload) ? payload : [payload] });+ writes.log.push(`upsert ${table}`);return builder;},then: (resolve, reject) => Promise.resolve(result()).then(resolve, reject),@@ -73,6 +81,7 @@ function mockDb({function result() {if (state.op === 'insert') return { data: { id: `new-${table}` }, error: null };+ if (state.op === 'upsert') return { data: null, error: null };if (state.op === 'update') {const failed =failActionUpdates && table === 'actions' && 'priority_score' in state.payload;@@ -189,6 +198,83 @@ describe('generateActionsForBrand', () => {).toBe(true);});+ it('keeps every link in action_signals, the signals and the action both ways', async () => {+ const writes = mockDb({ signals: [signal({ id: 's1' }), signal({ id: 's2' })] });++ await generateActionsForBrand(BRAND, { now: NOW });++ const links = writes.upserted.filter((w) => w.table === 'action_signals');+ expect(links.flatMap((w) => w.rows)).toEqual([+ { action_id: 'new-actions', signal_id: 's1', linked_at: NOW.toISOString() },+ { action_id: 'new-actions', signal_id: 's2', linked_at: NOW.toISOString() },+ ]);+ });++ it('writes the link before pointing the signal at the action', async () => {+ const writes = mockDb({ signals: [signal()] });++ await generateActionsForBrand(BRAND, { now: NOW });++ // If the second write fails, the signal is not taken and is linked again+ // the next night, rather than taken with no link to show it by.+ const link = writes.log.indexOf('upsert action_signals');+ const point = writes.log.indexOf('update signals');+ expect(link).toBeGreaterThanOrEqual(0);+ expect(link).toBeLessThan(point);+ });++ /**+ * AC-007: signals stay granular, actions don't multiply. Two prompts that+ * say much the same thing are two signals of one kind, and one kind is one+ * response — so they are one action covering both.+ */+ it('makes one action of two similar prompts with the same root cause', async () => {+ const writes = mockDb({+ signals: [+ signal({ id: 'best', payload: { promptText: 'What is the best AI rank tracker?' } }),+ signal({+ id: 'accurate',+ payload: { promptText: 'What are the most accurate AI rank tracker tools?' },+ }),+ ],+ });++ const summary = await generateActionsForBrand(BRAND, { now: NOW });++ expect(summary.created).toBe(1);+ expect(writes.inserted.filter((w) => w.table === 'actions')).toHaveLength(1);+ const linked = writes.updated.find((w) => w.table === 'signals');+ expect(linked.patch).toEqual({ action_id: 'new-actions' });+ expect(writes.upserted.flatMap((w) => w.rows).map((row) => row.signal_id)).toEqual([+ 'best',+ 'accurate',+ ]);+ });++ /**+ * A signal still open after its action closed is a condition still firing.+ * It used to keep pointing at the closed action and never start another.+ */+ it('lets a signal whose action closed start the next cycle', async () => {+ const writes = mockDb({+ signals: [signal({ action_id: 'closed-1' })],+ 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(writes.updated.find((w) => w.table === 'signals').patch).toEqual({+ action_id: 'new-actions',+ });+ // The closed action keeps its link: it still lists the signal.+ expect(writes.upserted.flatMap((w) => w.rows)).toEqual([+ { action_id: 'new-actions', signal_id: 's1', linked_at: NOW.toISOString() },+ ]);+ });+/*** 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@@ -607,10 +693,17 @@ describe('the candidate queue', () => {expect(refresh.patch.last_seen_at).toBe(NOW.toISOString());});- it('does not queue a signal an action has already claimed', async () => {+ it('does not queue a signal an active action was created from', async () => {const writes = mockDb({signals: [signal({ action_id: 'a1' })],- activeActions: [{ id: 'a1', dedup_key: 'recover_visibility', status: 'new' }],+ activeActions: [+ {+ id: 'a1',+ dedup_key: 'recover_visibility',+ status: 'new',+ baseline: { signals: [{ id: 's1' }] },+ },+ ],});const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });@@ -621,6 +714,34 @@ describe('the candidate queue', () => {);});+ /**+ * A signal linked to an active action after it was created is its evidence,+ * not its scope. It used to leave the queue the night after it was linked+ * and the candidate went stale, so the next cycle never covered it.+ */+ it('keeps a newcomer queued on the nights after it was linked', async () => {+ const writes = mockDb({+ signals: [signal({ id: 'newcomer', action_id: 'a1' })],+ activeActions: [+ {+ id: 'a1',+ dedup_key: 'recover_visibility',+ status: 'in_progress',+ baseline: { signals: [{ id: 'original' }] },+ },+ ],+ });++ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });++ expect(summary.queued).toBe(1);+ expect(summary.stale).toBe(0);+ const queued = writes.inserted.find((w) => w.table === 'action_candidates');+ expect(queued.rows[0].signal_ids).toEqual(['newcomer']);+ // Already its evidence: not linked again.+ expect(writes.updated.some((w) => w.table === 'signals')).toBe(false);+ });+/*** Stale rather than deleted: the queue is a record of what the engine found,* and a condition that returns should come back with a fresh clock ratherdiff --git a/server/src/lib/action-center/priority-data.js b/server/src/lib/action-center/priority-data.jsindex bfc761fca..31a3c089e 100644--- a/server/src/lib/action-center/priority-data.js+++ b/server/src/lib/action-center/priority-data.js@@ -74,3 +74,77 @@ export async function priorityOnCreate(action, now = new Date()) {);return priorityColumns(priority, now);}++/** An action still being worked on: its priority is kept current. */+const ACTIVE_STATUSES = ['new', 'in_progress', 'on_hold'];+/** A signal that still supports its action. */+const OPEN_SIGNAL_STATUSES = ['new', 'acknowledged'];++/**+ * An active action's priority, worked out again from its open signals as+ * they stand now, as the nightly pass would. Best effort: a score that can't+ * be read or saved is logged and left for the night.+ *+ * @param {{ id: string, kind: string, category: string, impact: string, payload?: object, created_at?: string }} action+ * @returns {Promise<boolean>} whether the score was saved+ */+export async function rescoreAction(action, now = new Date()) {+ const { data: signals, error } = await supabaseAdmin+ .from('signals')+ .select('id, kind, impact, payload, current_value, source, detected_at')+ .eq('action_id', action.id)+ .in('status', OPEN_SIGNAL_STATUSES)+ .limit(1000);+ if (error) {+ logger.warn({ actionId: action.id, err: error.message }, '[actions] rescore read failed');+ return false;+ }+ let prompts = new Map();+ try {+ prompts = await loadPromptDemand(+ promptIdsOf([action.payload, ...(signals ?? []).map((signal) => signal.payload)]),+ );+ } catch (err) {+ logger.warn({ actionId: action.id, err: err.message }, '[actions] prompt demand unavailable');+ }+ const priority = scorePriority({ action, signals: signals ?? [], prompts }, now);+ const { error: saveErr } = await supabaseAdmin+ .from('actions')+ .update(priorityColumns(priority, now))+ .eq('id', action.id);+ if (saveErr) {+ logger.warn({ actionId: action.id, err: saveErr.message }, '[actions] priority not saved');+ return false;+ }+ return true;+}++/**+ * Every active action a signal supports, scored again (AC-007): resolving,+ * dismissing or reopening a signal changes its actions' support and+ * confidence at once, not the next night.+ *+ * @returns {Promise<number>} how many actions were rescored+ */+export async function rescoreActionsForSignal(signalId, now = new Date()) {+ const { data: links, error } = await supabaseAdmin+ .from('action_signals')+ .select('action_id')+ .eq('signal_id', signalId);+ if (error) throw new Error(error.message);+ const ids = [...new Set((links ?? []).map((link) => link.action_id))];+ if (ids.length === 0) return 0;++ const { data: actions, error: actionsErr } = await supabaseAdmin+ .from('actions')+ .select('id, kind, category, impact, payload, created_at')+ .in('id', ids)+ .in('status', ACTIVE_STATUSES);+ if (actionsErr) throw new Error(actionsErr.message);++ let rescored = 0;+ for (const action of actions ?? []) {+ if (await rescoreAction(action, now)) rescored += 1;+ }+ return rescored;+}diff --git a/server/src/lib/action-center/rescore.test.js b/server/src/lib/action-center/rescore.test.jsnew file mode 100644index 000000000..c84a70aa6--- /dev/null+++ b/server/src/lib/action-center/rescore.test.js@@ -0,0 +1,152 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * AC-007: moving a signal scores its actions again at once. Only active+ * actions the signal supports are touched, from their open signals as they+ * stand now, and a score that can't be saved never fails the request.+ */++let db;+let saves;+let failSave;++/** Enough of PostgREST: eq/in filters over in-memory rows, and updates recorded. */+function from(table) {+ const filters = [];+ let patch = null;+ const rows = () => (db[table] ?? []).filter((row) => filters.every((test) => test(row)));+ const chain = {+ select: () => chain,+ eq: (column, value) => {+ filters.push((row) => row[column] === value);+ return chain;+ },+ in: (column, values) => {+ filters.push((row) => values.includes(row[column]));+ return chain;+ },+ order: () => chain,+ limit: () => chain,+ range: async (start, end) => ({ data: rows().slice(start, end + 1), error: null }),+ maybeSingle: async () => ({ data: rows()[0] ?? null, error: null }),+ update: (values) => {+ patch = values;+ return chain;+ },+ then: (resolve, reject) => {+ if (patch) {+ if (failSave) return Promise.resolve({ error: { message: 'down' } }).then(resolve, reject);+ for (const row of rows()) saves.push({ table, id: row.id, patch });+ return Promise.resolve({ error: null }).then(resolve, reject);+ }+ return Promise.resolve({ data: rows(), error: null }).then(resolve, reject);+ },+ };+ return chain;+}++vi.mock('../../config/supabase.js', () => ({ default: { from: (table) => from(table) } }));+vi.mock('../logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));+const assertBrandAccess = vi.fn();+vi.mock('../access.js', () => ({ assertBrandAccess: (...args) => assertBrandAccess(...args) }));++const { rescoreActionsForSignal } = await import('./priority-data.js');+const { rescoreForSignal } = await import('../../routes/action-center.js');++const NOW = new Date('2026-10-15T06:00:00Z');++const action = (over = {}) => ({+ id: 'a1',+ brand_id: 'b1',+ kind: 'recover_lost_citations',+ category: 'recover',+ impact: 'high',+ status: 'in_progress',+ payload: {},+ created_at: '2026-10-10T00:00:00Z',+ ...over,+});++const signal = (over = {}) => ({+ id: 's1',+ brand_id: 'b1',+ kind: 'lost_citations',+ impact: 'high',+ status: 'new',+ action_id: 'a1',+ source: ['ai_results'],+ payload: {},+ detected_at: '2026-10-14T00:00:00Z',+ ...over,+});++beforeEach(() => {+ saves = [];+ failSave = false;+ assertBrandAccess.mockReset();+ db = {+ actions: [action(), action({ id: 'closed', status: 'completed' })],+ signals: [+ signal(),+ // A second source confirming it: more confidence while it is open.+ signal({ id: 's2', kind: 'lost_citations', source: ['gsc'] }),+ ],+ action_signals: [+ { action_id: 'a1', signal_id: 's1' },+ { action_id: 'a1', signal_id: 's2' },+ { action_id: 'closed', signal_id: 's1' },+ ],+ prompt_volumes: [],+ };+});++describe('rescoreActionsForSignal', () => {+ it('scores again the active actions the signal supports, and no closed one', async () => {+ await expect(rescoreActionsForSignal('s1', NOW)).resolves.toBe(1);+ expect(saves.map((s) => s.id)).toEqual(['a1']);+ expect(saves[0].patch).toMatchObject({+ priority_updated_at: NOW.toISOString(),+ priority_score: expect.any(Number),+ });+ });++ it('loses confidence when a confirming signal is resolved', async () => {+ await rescoreActionsForSignal('s1', NOW);+ const before = saves[0].patch.priority_reason.factors.confidence;++ db.signals[1].status = 'resolved';+ saves = [];+ await rescoreActionsForSignal('s2', NOW);+ const after = saves[0].patch.priority_reason.factors.confidence;++ expect(after).toBeLessThan(before);+ });++ it('touches nothing for a signal no action uses', async () => {+ await expect(rescoreActionsForSignal('lonely', NOW)).resolves.toBe(0);+ expect(saves).toEqual([]);+ });++ it('leaves a score it cannot save to the night, without failing', async () => {+ failSave = true;+ await expect(rescoreActionsForSignal('s1', NOW)).resolves.toBe(0);+ });+});++describe('rescoreForSignal', () => {+ it("checks the signal's brand belongs to the caller before scoring", async () => {+ await expect(rescoreForSignal('s1', 'user-1')).resolves.toEqual({ rescored: 1 });+ expect(assertBrandAccess).toHaveBeenCalledWith('b1', 'user-1');+ });++ it('refuses a signal it cannot find', async () => {+ await expect(rescoreForSignal('missing', 'user-1')).rejects.toMatchObject({ status: 404 });+ expect(assertBrandAccess).not.toHaveBeenCalled();+ });++ it('scores nothing when the caller is outside the organization', async () => {+ assertBrandAccess.mockRejectedValue(Object.assign(new Error('Unauthorized'), { status: 403 }));+ await expect(rescoreForSignal('s1', 'stranger')).rejects.toMatchObject({ status: 403 });+ expect(saves).toEqual([]);+ });+});diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.jsnew file mode 100644index 000000000..f648e5a4a--- /dev/null+++ b/server/src/routes/action-center.js@@ -0,0 +1,49 @@+import { Router } from 'express';+import { z } from 'zod';+import supabaseAdmin from '../config/supabase.js';+import { assertBrandAccess } from '../lib/access.js';+import { rescoreActionsForSignal } from '../lib/action-center/priority-data.js';++const router = Router();++/**+ * Scores again the active actions a signal supports, after a member moved+ * the signal (AC-007). The dashboard writes the status itself; this keeps the+ * priority in step without waiting for the night. Checked against the+ * caller's organization first, like every route on the admin client.+ *+ * @returns {Promise<{ rescored: number }>}+ */+export async function rescoreForSignal(signalId, userId) {+ const { data: signal } = await supabaseAdmin+ .from('signals')+ .select('id, brand_id')+ .eq('id', signalId)+ .maybeSingle();+ if (!signal) {+ const err = new Error('Signal not found');+ err.status = 404;+ throw err;+ }+ await assertBrandAccess(signal.brand_id, userId);+ return { rescored: await rescoreActionsForSignal(signal.id) };+}++/** Seeded ids (the demo's) aren't RFC 4122 versions, so a plain GUID shape. */+const signalIdSchema = z.guid();++/** POST /api/action-center/signals/:id/rescore */+router.post('/signals/:id/rescore', async (req, res) => {+ const id = signalIdSchema.safeParse(req.params.id);+ if (!id.success) return res.status(400).json({ error: 'Invalid signal id' });+ try {+ return res.json(await rescoreForSignal(id.data, req.user.id));+ } catch (error) {+ req.log.error({ err: error }, 'rescore actions for a signal error');+ return res.status(error.status || 500).json({+ error: error.status ? error.message : 'Failed to update the actions.',+ });+ }+});++export default router;diff --git a/server/src/routes/index.js b/server/src/routes/index.jsindex e20475fc2..4f07286e6 100644--- a/server/src/routes/index.js+++ b/server/src/routes/index.js@@ -9,6 +9,7 @@ import auditRoutes from './audits.js';import reportRoutes from './reports.js';import integrationRoutes from './integrations.js';import brandRoutes from './brands.js';+import actionCenterRoutes from './action-center.js';const router = Router();@@ -22,6 +23,7 @@ router.use('/audits', auditRoutes);router.use('/reports', reportRoutes);router.use('/integrations', integrationRoutes);router.use('/brands', brandRoutes);+router.use('/action-center', actionCenterRoutes);router.get('/health', (req, res) => {res.json({ status: 'ok', user: req.user?.id });diff --git a/supabase/migrations/00145_action_signals.sql b/supabase/migrations/00145_action_signals.sqlnew file mode 100644index 000000000..70163ef28--- /dev/null+++ b/supabase/migrations/00145_action_signals.sql@@ -0,0 +1,49 @@+-- Which signals each action rests on, kept for good (AC-007).+--+-- signals.action_id holds one action per signal and was written once: a+-- signal that stayed open after its action closed kept pointing at the+-- closed action, so it could never start the next one, and no signal could be+-- shown as used by more than one action. This table keeps every link, both+-- ways: an action's supporting signals, and every action a signal has been+-- used by, including closed ones.+--+-- signals.action_id stays as the signal's current action (the latest one+-- that took it as evidence), which the signals list, its filters and the API+-- already read. The nightly generator (server/src/lib/action-center/+-- generate.js) writes both.++create table if not exists public.action_signals (+ action_id uuid not null references public.actions(id) on delete cascade,+ signal_id uuid not null references public.signals(id) on delete cascade,+ linked_at timestamptz not null default now(),+ primary key (action_id, signal_id)+);++-- "Used by actions" reads a signal's links.+create index if not exists action_signals_signal_idx+ on public.action_signals (signal_id);++-- Every link made so far. When a signal joined its action isn't recorded;+-- the later of the two dates is the closest honest answer.+insert into public.action_signals (action_id, signal_id, linked_at)+select s.action_id, s.id, greatest(a.created_at, s.detected_at)+from public.signals s+join public.actions a on a.id = s.action_id+on conflict do nothing;++-- Members read their brands' links; only the server (service role, which+-- bypasses RLS) writes them.+alter table public.action_signals enable row level security;++create policy "action_signals: member select" on public.action_signals+ 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()+ )+ );++comment on table public.action_signals is+ 'Every signal an action has taken as evidence, kept after either closes (AC-007). signals.action_id is the signal''s current action.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex c992d3e40..c86f7f33b 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -17927,6 +17927,59 @@ comment on column public.actions.priority_level iscomment on column public.actions.priority_reason is'The facts the score rests on, for "Why this priority?" (server/src/lib/action-center/priority.js).';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00145_action_signals.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Which signals each action rests on, kept for good (AC-007).+--+-- signals.action_id holds one action per signal and was written once: a+-- signal that stayed open after its action closed kept pointing at the+-- closed action, so it could never start the next one, and no signal could be+-- shown as used by more than one action. This table keeps every link, both+-- ways: an action's supporting signals, and every action a signal has been+-- used by, including closed ones.+--+-- signals.action_id stays as the signal's current action (the latest one+-- that took it as evidence), which the signals list, its filters and the API+-- already read. The nightly generator (server/src/lib/action-center/+-- generate.js) writes both.++create table if not exists public.action_signals (+ action_id uuid not null references public.actions(id) on delete cascade,+ signal_id uuid not null references public.signals(id) on delete cascade,+ linked_at timestamptz not null default now(),+ primary key (action_id, signal_id)+);++-- "Used by actions" reads a signal's links.+create index if not exists action_signals_signal_idx+ on public.action_signals (signal_id);++-- Every link made so far. When a signal joined its action isn't recorded;+-- the later of the two dates is the closest honest answer.+insert into public.action_signals (action_id, signal_id, linked_at)+select s.action_id, s.id, greatest(a.created_at, s.detected_at)+from public.signals s+join public.actions a on a.id = s.action_id+on conflict do nothing;++-- Members read their brands' links; only the server (service role, which+-- bypasses RLS) writes them.+alter table public.action_signals enable row level security;++create policy "action_signals: member select" on public.action_signals+ 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()+ )+ );++comment on table public.action_signals is+ 'Every signal an action has taken as evidence, kept after either closes (AC-007). signals.action_id is the signal''s current action.';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00147_insights_same_prompts_definer.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex ff29cf380..d81a7220d 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -985,7 +985,8 @@"kpis": "KPIs","kpiTarget": "target {target}","noKpis": "No configured KPIs are linked to this action.",- "primarySignals": "Primary signals",+ "support": "{count, plural, =0 {No open signal supports this action any more.} one {# signal supports this action} other {# signals support this action}}",+ "supportAll": "All signals ({count})","tasksProgress": "{completed} / {total} tasks completed","noSignals": "No linked signals.","assignee": "Assignee",diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex 2743214cf..43ae6f434 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -56,11 +56,12 @@ import {} from '@/lib/action-center/display';import { signalTexts } from '@/lib/signals/display';import { isKpiKey } from '@/lib/kpis/registry';-import { ImpactDots, isSuperseded, SignalStatusBadge } from './signal-table';+import { isSuperseded, SignalStatusBadge } from './signal-table';import { ActionIcon, PriorityBadge } from './action-table';import { priorityReasonText } from '@/lib/action-center/priority';import { OpportunityContext } from './opportunity-context';import { ActionExportButtons } from './action-export-buttons';+import { SupportingSignals } from './supporting-signals';import { ImproveContext } from './improve-context';import { TopicGapContext } from './topic-gap-context';import { TopicOpportunityContext } from './topic-opportunity-context';@@ -317,6 +318,14 @@ export function ActionDrawer({<section><p className="text-xs font-medium text-muted-foreground">{t('drawer.why')}</p><p className="mt-1">{texts.description}</p>+ {detail.signals.length > 0 && (+ <SupportingSignals+ actionId={action.id}+ signals={detail.signals}+ onOpenSignal={openSignal}+ onShowAll={() => setTab('signals')}+ />+ )}</section><Separator /><section>@@ -343,9 +352,11 @@ export function ActionDrawer({<p className="mt-1 text-xs text-muted-foreground">{t('drawer.noKpis')}</p>)}</section>- <Separator />+ {/* What a person sent the action from; a detected action's+ evidence is its supporting signals, above. */}{action.kind === 'prompt_improve' ? (<>+ <Separator />{detail.positionOutcome && (<><ImproveOutcomeCard@@ -358,40 +369,24 @@ export function ActionDrawer({<ImproveContext payload={action.payload ?? {}} /></>) : action.kind === 'topic_competitor_gap' ? (- <TopicGapContext payload={action.payload ?? {}} />+ <>+ <Separator />+ <TopicGapContext payload={action.payload ?? {}} />+ </>) : action.kind === 'topic_opportunity' ? (- <TopicOpportunityContext payload={action.payload ?? {}} />+ <>+ <Separator />+ <TopicOpportunityContext payload={action.payload ?? {}} />+ </>) : opportunityId ? (- <OpportunityContext- opportunityId={opportunityId}- pageUrls={action.payload?.assetKey ? opportunityPages : undefined}- />- ) : (- <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>- )}+ <>+ <Separator />+ <OpportunityContext+ opportunityId={opportunityId}+ pageUrls={action.payload?.assetKey ? opportunityPages : undefined}+ />+ </>+ ) : null}</>) : tab === 'tasks' ? (<section>diff --git a/web/src/components/action-center/action-export-buttons.tsx b/web/src/components/action-center/action-export-buttons.tsxindex a6a8cb275..301c63e4f 100644--- a/web/src/components/action-center/action-export-buttons.tsx+++ b/web/src/components/action-center/action-export-buttons.tsx@@ -27,8 +27,7 @@ import {import { opportunityLists } from '@/lib/content/opportunity-lists';import { priorityReasonText } from '@/lib/action-center/priority';import { isKpiKey } from '@/lib/kpis/registry';-import { signalAffected, signalTexts } from '@/lib/signals/display';-import { SIGNAL_KINDS } from '@/lib/signals/registry';+import { signalAffected, signalTexts, signalTypeLabel } from '@/lib/signals/display';import { viewerTimeZone } from '@/lib/time-zone';import { isSuperseded } from './signal-table';@@ -209,7 +208,7 @@ export function ActionExportButtons({const affected = signalAffected(signal, tSignals);return {...signalTexts(signal, tSignalTexts),- type: `${tSignalCategories(signal.category)} · ${tSignals(`states.${SIGNAL_KINDS[signal.kind].stateKey}`)}`,+ type: signalTypeLabel(signal, tSignalCategories, tSignals),entity: affected.detail ?? affected.label,category: tSignalCategories(signal.category),status: isSuperseded(signal)diff --git a/web/src/components/action-center/supporting-signals.test.tsx b/web/src/components/action-center/supporting-signals.test.tsxnew file mode 100644index 000000000..32a6548a2--- /dev/null+++ b/web/src/components/action-center/supporting-signals.test.tsx@@ -0,0 +1,142 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';+import type { Signal } from '@/lib/signals/map';+import { SupportingSignals } from './supporting-signals';++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++function render(node: React.ReactNode) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ {node}+ </NextIntlClientProvider>,+ );+ });+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++const signal = (over: Partial<Signal> = {}): Signal => ({+ id: 's1',+ category: 'citation',+ kind: 'lost_citations',+ impact: 'high',+ status: 'new',+ source: ['ai_results'],+ detectedAt: '2026-10-14T00:00:00Z',+ lastDetectedAt: '2026-10-14T00:00:00Z',+ resolvedAt: null,+ previousValue: null,+ currentValue: null,+ changeValue: null,+ payload: { promptText: 'What is the best AI rank tracker?' },+ kpiKeys: [],+ actionId: 'a1',+ where: { platforms: ['chatgpt-web', 'gemini-web'], regions: ['US'], topics: [] },+ ...over,+});++const lines = () => [...container.querySelectorAll('li')].map((li) => li.textContent);++describe('SupportingSignals', () => {+ it('counts the open signals and names each by type, platform and prompt', () => {+ render(+ <SupportingSignals+ actionId="a1"+ signals={[+ signal(),+ signal({+ id: 's2',+ status: 'acknowledged',+ where: { platforms: [], regions: [], topics: [] },+ }),+ // No longer supports it.+ signal({ id: 's3', status: 'resolved' }),+ ]}+ onOpenSignal={vi.fn()}+ onShowAll={vi.fn()}+ />,+ );+ expect(container.textContent).toContain('2 signals support this action');+ expect(lines()).toEqual([+ 'Citation · LostChatGPT, Gemini · What is the best AI rank tracker?',+ 'Citation · LostWhat is the best AI rank tracker?',+ ]);+ // The resolved one is still on the Signals tab.+ expect(container.textContent).toContain('All signals (3)');+ });++ it('opens a signal, and the Signals tab for the rest', () => {+ const onOpenSignal = vi.fn();+ const onShowAll = vi.fn();+ const many = Array.from({ length: 7 }, (_, i) => signal({ id: `s${i}` }));+ render(+ <SupportingSignals+ actionId="a1"+ signals={many}+ onOpenSignal={onOpenSignal}+ onShowAll={onShowAll}+ />,+ );++ expect(lines()).toHaveLength(5);+ act(() =>+ container+ .querySelector('li button')!+ .dispatchEvent(new MouseEvent('click', { bubbles: true })),+ );+ expect(onOpenSignal).toHaveBeenCalledWith('s0');++ const all = [...container.querySelectorAll('button')].find((b) =>+ b.textContent?.startsWith('All signals'),+ )!;+ act(() => all.dispatchEvent(new MouseEvent('click', { bubbles: true })));+ expect(onShowAll).toHaveBeenCalled();+ });++ it('does not count a signal that has moved on to a later action', () => {+ render(+ <SupportingSignals+ actionId="a1"+ signals={[signal(), signal({ id: 's2', actionId: 'a2' })]}+ onOpenSignal={vi.fn()}+ onShowAll={vi.fn()}+ />,+ );+ expect(container.textContent).toContain('1 signal supports this action');+ expect(container.textContent).toContain('All signals (2)');+ });++ it('says so when nothing open supports the action any more', () => {+ render(+ <SupportingSignals+ actionId="a1"+ signals={[signal({ status: 'dismissed' })]}+ onOpenSignal={vi.fn()}+ onShowAll={vi.fn()}+ />,+ );+ expect(container.textContent).toContain('No open signal supports this action any more.');+ expect(lines()).toEqual([]);+ });+});diff --git a/web/src/components/action-center/supporting-signals.tsx b/web/src/components/action-center/supporting-signals.tsxnew file mode 100644index 000000000..1f198d8cd--- /dev/null+++ b/web/src/components/action-center/supporting-signals.tsx@@ -0,0 +1,81 @@+'use client';++import { useTranslations } from 'next-intl';+import type { Signal } from '@/lib/actions/signals';+import { signalAffected, signalTypeLabel } from '@/lib/signals/display';+import { platformName } from '@/lib/signals/names';+import { OPEN_SIGNAL_STATUSES } from '@/lib/signals/registry';++/** How many supporting signals "Why this action?" lists before "All signals". */+export const SUPPORT_SHOWN = 5;++/**+ * "n signals support this action" (AC-007): the open signals an action rests+ * on, each by type, platform and what it is about, so why it exists can be+ * checked. Resolved and dismissed signals no longer support it, nor do ones+ * that have moved on to a later cycle's action; the Signals tab, which+ * "All signals" opens, still lists them all.+ */+export function SupportingSignals({+ actionId,+ signals,+ onOpenSignal,+ onShowAll,+}: {+ actionId: string;+ /** Every signal the action has taken as evidence, newest first. */+ signals: Signal[];+ onOpenSignal: (id: string) => void;+ onShowAll: () => void;+}) {+ const t = useTranslations('actionCenter.actionsPage.drawer');+ const tSignals = useTranslations('actionCenter.signalsPage');+ const tCategories = useTranslations('actionCenter.signalCategories');++ // As the list counts them: open, and this action's now.+ const supporting = signals.filter(+ (signal) => OPEN_SIGNAL_STATUSES.includes(signal.status) && signal.actionId === actionId,+ );++ return (+ <div className="mt-3">+ <p className="text-sm font-medium">{t('support', { count: supporting.length })}</p>+ {supporting.length > 0 && (+ <ul className="mt-2 space-y-1.5">+ {supporting.slice(0, SUPPORT_SHOWN).map((signal) => {+ const affected = signalAffected(signal, tSignals);+ const where = [+ signal.where.platforms.map(platformName).join(', '),+ affected.detail ?? affected.label,+ ].filter(Boolean);+ return (+ <li key={signal.id}>+ <button+ type="button"+ onClick={() => onOpenSignal(signal.id)}+ className="flex w-full items-baseline gap-2 rounded-md border px-3 py-1.5 text-left text-xs transition-colors hover:bg-muted/40"+ >+ <span className="shrink-0 font-medium">+ {signalTypeLabel(signal, tCategories, tSignals)}+ </span>+ <span className="min-w-0 truncate text-muted-foreground">+ {where.join(' · ')}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ {signals.length > Math.min(supporting.length, SUPPORT_SHOWN) && (+ <button+ type="button"+ onClick={onShowAll}+ className="mt-2 text-xs font-medium underline-offset-2 hover:underline"+ >+ {t('supportAll', { count: signals.length })}+ </button>+ )}+ </div>+ );+}diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex e5ec3b1c2..e6542f73a 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -19,6 +19,7 @@ import {type TaskStatus,} from '@/lib/action-center/registry';import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';+import { OPEN_SIGNAL_STATUSES, type SignalStatus } from '@/lib/signals/registry';import type { KpiTimeframe } from '@/lib/kpis/registry';import { parseImproveOutcome, type ImproveOutcome } from '@/lib/improve-outcome';import {@@ -99,10 +100,12 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {const [tasksRes, signalsRes, profilesRes] = await Promise.all([supabase.from('action_tasks').select('action_id, status').in('action_id', actionIds),+ // The signals that support each action now (AC-007): its open ones.supabase.from('signals').select('action_id').eq('brand_id', brandId)+ .in('status', OPEN_SIGNAL_STATUSES as SignalStatus[]).not('action_id', 'is', null),assigneeIds.length > 0? supabase.from('profiles').select('id, full_name, avatar_url').in('id', assigneeIds)@@ -233,11 +236,13 @@ export async function getActionDetail(brandId: string, actionId: string): Promis).eq('action_id', actionId).order('position'),+ // Every signal the action has taken as evidence (AC-007), kept after a+ // signal moves on to a later cycle: a closed action still shows its own.supabase.from('signals')- .select(SIGNAL_ROW_COLUMNS)+ .select(`${SIGNAL_ROW_COLUMNS}, action_signals!inner(action_id)`).eq('brand_id', brandId)- .eq('action_id', actionId)+ .eq('action_signals.action_id', actionId).order('detected_at', { ascending: false }),supabase.from('action_events')diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.tsindex 8c1d1d10d..c78649262 100644--- a/web/src/lib/actions/action-history.ts+++ b/web/src/lib/actions/action-history.ts@@ -184,10 +184,11 @@ export async function getActionHistory(.select('id, action_id, position, task_key, title, status').in('action_id', actionIds).order('position'),+ // Every signal each action took as evidence (AC-007): a closed action+ // keeps the ones that have since moved on to a later cycle.supabase- .from('signals')- .select('id, action_id, kind, source, detected_at')- .eq('brand_id', brandId)+ .from('action_signals')+ .select('action_id, signals!inner(id, kind, source, detected_at)').in('action_id', actionIds),assigneeIds.length > 0? supabase.from('profiles').select('id, full_name, avatar_url').in('id', assigneeIds)@@ -212,18 +213,18 @@ export async function getActionHistory(const signalsByAction = new Map<string, TriggerSignal[]>();const sourcesByAction = new Map<string, Set<SignalSource>>();- for (const signal of signalsRes.data ?? []) {- if (!signal.action_id) continue;- const list = signalsByAction.get(signal.action_id) ?? [];+ for (const { action_id: actionId, signals: signal } of signalsRes.data ?? []) {+ if (!signal) continue;+ const list = signalsByAction.get(actionId) ?? [];list.push({ signalId: signal.id, kind: signal.kind, detectedAt: signal.detected_at });- signalsByAction.set(signal.action_id, list);+ signalsByAction.set(actionId, list);// `source` is an array — one signal can be corroborated by several feeds.- const set = sourcesByAction.get(signal.action_id) ?? new Set<SignalSource>();+ const set = sourcesByAction.get(actionId) ?? new Set<SignalSource>();for (const source of (signal.source ?? []) as string[]) {if ((SIGNAL_SOURCES as readonly string[]).includes(source)) set.add(source as SignalSource);}- if (set.size > 0) sourcesByAction.set(signal.action_id, set);+ if (set.size > 0) sourcesByAction.set(actionId, set);}const profiles = new Map(diff --git a/web/src/lib/actions/action-signals.test.ts b/web/src/lib/actions/action-signals.test.tsnew file mode 100644index 000000000..29a201edb--- /dev/null+++ b/web/src/lib/actions/action-signals.test.ts@@ -0,0 +1,84 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * AC-007 reads. The list counts the signals that support an action now (open+ * ones it holds); the drawer lists every signal the action took as evidence,+ * through action_signals, so a closed action keeps the ones that moved on.+ */++type Call = [string, ...unknown[]];+let queries: { table: string; calls: Call[] }[];+let rows: Record<string, unknown[]>;++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ from: (table: string) => {+ const query = { table, calls: [] as Call[] };+ queries.push(query);+ const chain: Record<string, unknown> = {};+ for (const method of ['select', 'eq', 'in', 'not', 'order', 'limit']) {+ chain[method] = (...args: unknown[]) => {+ query.calls.push([method, ...args]);+ return chain;+ };+ }+ chain.then = (resolve: (value: unknown) => unknown) =>+ resolve({ data: rows[table] ?? [], error: null });+ chain.maybeSingle = async () => ({ data: rows[table]?.[0] ?? null, error: null });+ return chain;+ },+ })),+}));++const { getActionDetail, getActions } = await import('./action-center');++const signalsQuery = () => queries.find((q) => q.table === 'signals')!;++beforeEach(() => {+ queries = [];+ rows = {+ actions: [+ {+ id: 'a1',+ action_no: 9,+ category: 'recover',+ kind: 'recover_lost_citations',+ impact: 'high',+ status: 'new',+ payload: {},+ kpi_keys: [],+ assignee_id: null,+ due_date: null,+ created_at: '2026-10-15T00:00:00Z',+ updated_at: '2026-10-15T00:00:00Z',+ priority_score: 87,+ priority_level: 'high',+ priority_reason: null,+ priority_updated_at: null,+ },+ ],+ signals: [{ action_id: 'a1' }, { action_id: 'a1' }],+ };+});++describe('getActions', () => {+ it('counts only the open signals an action holds', async () => {+ const [action] = await getActions('b1');++ expect(action.signalCount).toBe(2);+ expect(signalsQuery().calls).toContainEqual(['in', 'status', ['new', 'acknowledged']]);+ });+});++describe('getActionDetail', () => {+ it('lists every signal the action took, through action_signals', async () => {+ rows.signals = [];+ await getActionDetail('b1', 'a1');++ const calls = signalsQuery().calls;+ expect(calls[0][1]).toContain('action_signals!inner(action_id)');+ expect(calls).toContainEqual(['eq', 'action_signals.action_id', 'a1']);+ // Not by the signal's current action, which moves to a later cycle.+ expect(calls).not.toContainEqual(['eq', 'action_id', 'a1']);+ });+});diff --git a/web/src/lib/actions/signal-status-rescore.test.ts b/web/src/lib/actions/signal-status-rescore.test.tsnew file mode 100644index 000000000..8549b88e4--- /dev/null+++ b/web/src/lib/actions/signal-status-rescore.test.ts@@ -0,0 +1,96 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * AC-007: when a signal starts or stops supporting its action, the server is+ * asked to score the action again, after the response has gone. Moves that+ * leave the signal open, and signals no action holds, ask for nothing.+ */++let previousStatus: string | null;+let actionId: string | null;+let writes: Record<string, unknown>[];+const fetchMock = vi.fn();++vi.mock('next/server', () => ({ after: (task: () => unknown) => task() }));++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ auth: { getSession: async () => ({ data: { session: { access_token: 'token-1' } } }) },+ from: () => {+ let patch: Record<string, unknown> | null = null;+ const chain = {+ select: () => chain,+ eq: () => chain,+ in: () => chain,+ update: (values: Record<string, unknown>) => {+ patch = values;+ writes.push(values);+ return chain;+ },+ // The read before the change, then the updated rows.+ then: (resolve: (value: unknown) => unknown) =>+ resolve(+ patch+ ? { data: [{ id: 's1', action_id: actionId }], error: null }+ : {+ data: previousStatus ? [{ id: 's1', status: previousStatus }] : [],+ error: null,+ },+ ),+ };+ return chain;+ },+ })),+}));++const { updateSignalStatus } = await import('./signals');++beforeEach(() => {+ previousStatus = 'new';+ actionId = 'a1';+ writes = [];+ fetchMock.mockReset();+ fetchMock.mockResolvedValue({ ok: true, status: 200 });+ vi.stubGlobal('fetch', fetchMock);+});++describe('updateSignalStatus', () => {+ it("asks the server to rescore the signal's actions when it is resolved", async () => {+ await updateSignalStatus('b1', ['s1'], 'resolved');++ expect(writes[0]).toMatchObject({ status: 'resolved' });+ expect(fetchMock).toHaveBeenCalledWith(+ expect.stringMatching(/\/api\/action-center\/signals\/s1\/rescore$/),+ expect.objectContaining({+ method: 'POST',+ headers: { Authorization: 'Bearer token-1' },+ }),+ );+ });++ it('asks again when a dismissed signal is reopened', async () => {+ previousStatus = 'dismissed';+ await updateSignalStatus('b1', ['s1'], 'new');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('asks nothing when the signal stays open', async () => {+ await updateSignalStatus('b1', ['s1'], 'acknowledged');+ expect(writes).toHaveLength(1);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('asks nothing for a signal no action holds', async () => {+ actionId = null;+ await updateSignalStatus('b1', ['s1'], 'resolved');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('keeps the status change when the server cannot be reached', async () => {+ fetchMock.mockRejectedValue(new Error('offline'));+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);+ await expect(updateSignalStatus('b1', ['s1'], 'dismissed')).resolves.toBeUndefined();+ expect(writes[0]).toMatchObject({ status: 'dismissed' });+ warn.mockRestore();+ });+});diff --git a/web/src/lib/actions/signals.ts b/web/src/lib/actions/signals.tsindex e8780f27c..d0c672057 100644--- a/web/src/lib/actions/signals.ts+++ b/web/src/lib/actions/signals.ts@@ -11,11 +11,14 @@*/import { createClient } from '@/lib/supabase/server';-import type {- SignalCategory,- SignalImpact,- SignalSource,- SignalStatus,+import { after } from 'next/server';+import { API_BASE_URL } from '@/config/api';+import {+ OPEN_SIGNAL_STATUSES,+ type SignalCategory,+ type SignalImpact,+ type SignalSource,+ type SignalStatus,} from '@/lib/signals/registry';import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';import { readPromptPlaces } from '@/lib/signals/prompt-places';@@ -195,7 +198,12 @@ export async function updateSignalStatus(): Promise<void> {if (signalIds.length === 0) return;const supabase = await createClient();- const { error } = await supabase+ const { data: before } = await supabase+ .from('signals')+ .select('id, status')+ .eq('brand_id', brandId)+ .in('id', signalIds);+ const { data, error } = await supabase.from('signals').update({status,@@ -203,8 +211,43 @@ export async function updateSignalStatus(updated_at: new Date().toISOString(),}).eq('brand_id', brandId)- .in('id', signalIds);+ .in('id', signalIds)+ .select('id, action_id');if (error) throw new Error(error.message);++ // When one starts or stops supporting its action, the action's support and+ // confidence follow at once, not the next night (AC-007). Acknowledging+ // leaves it open, so nothing changes for the action.+ const isOpen = (value: unknown) => OPEN_SIGNAL_STATUSES.includes(value as SignalStatus);+ const wasOpen = new Map((before ?? []).map((row) => [row.id as string, isOpen(row.status)]));+ const moved = (data ?? []).filter(+ (row) => row.action_id && wasOpen.get(row.id as string) !== isOpen(status),+ );+ if (moved.length === 0) return;+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (session) for (const row of moved) scheduleRescore(row.id as string, session.access_token);+}++/**+ * Asks the server to score again the active actions a signal supports, once+ * the response has gone: the click doesn't wait for it. Best effort, as the+ * status change is saved either way and the nightly pass scores every action+ * again.+ */+function scheduleRescore(signalId: string, accessToken: string) {+ after(async () => {+ try {+ const res = await fetch(`${API_BASE_URL}/api/action-center/signals/${signalId}/rescore`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${accessToken}` },+ });+ if (!res.ok) console.warn(`[signals] action rescore failed: ${res.status}`);+ } catch (err) {+ console.warn('[signals] action rescore failed:', err);+ }+ });}function nextDay(day: string): string {diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex fe89811fd..ff1a1ac65 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -2691,11 +2691,13 @@ export async function getActionFor().eq('action_id', actionId).order('position'),+ // Every signal the action has taken as evidence (AC-007), kept after a+ // signal moves on to a later cycle.supabaseAdmin.from('signals')- .select(MCP_SIGNAL_COLUMNS)+ .select(`${MCP_SIGNAL_COLUMNS}, action_signals!inner(action_id)`).eq('brand_id', action.brand_id)- .eq('action_id', actionId)+ .eq('action_signals.action_id', actionId).order('detected_at', { ascending: false }),supabaseAdmin.from('action_events')@@ -2739,7 +2741,10 @@ export async function getActionFor(permission: t.permission ?? null,depends_on: (t.depends_on ?? []) as string[],})),- signals: (signalsRes.data ?? []) as Record<string, unknown>[],+ // The join that found them is not part of a signal.+ signals: ((signalsRes.data ?? []) as Record<string, unknown>[]).map((row) =>+ Object.fromEntries(Object.entries(row).filter(([key]) => key !== 'action_signals')),+ ),events: (eventsRes.data ?? []).map((e) => ({event: e.event,data: (e.data ?? {}) as Record<string, unknown>,diff --git a/web/src/lib/signals/display.ts b/web/src/lib/signals/display.tsindex a03071ee0..b30cbb634 100644--- a/web/src/lib/signals/display.ts+++ b/web/src/lib/signals/display.ts@@ -1,5 +1,5 @@import type { Signal } from '@/lib/actions/signals';-import { isLibrarySignalKind } from '@/lib/signals/registry';+import { SIGNAL_KINDS, isLibrarySignalKind } from '@/lib/signals/registry';import { locationName, platformName, targetName } from '@/lib/signals/names';/**@@ -147,6 +147,15 @@ export function signalTexts(signal: Signal, t: Translator): { title: string; des};}+/**+ * "Citation · Lost": the signal's category and what happened, as the signals+ * list's Type column reads. `tCategories` is actionCenter.signalCategories,+ * `t` actionCenter.signalsPage.+ */+export function signalTypeLabel(signal: Signal, tCategories: Translator, t: Translator): string {+ return `${tCategories(signal.category)} · ${t(`states.${SIGNAL_KINDS[signal.kind].stateKey}`)}`;+}+/** What the Affected column shows: a compact count label + optional detail. */export function signalAffected(signal: Signal,diff --git a/web/src/lib/signals/registry.ts b/web/src/lib/signals/registry.tsindex 9b95cf8ae..184a942de 100644--- a/web/src/lib/signals/registry.ts+++ b/web/src/lib/signals/registry.ts@@ -61,6 +61,9 @@ export const SIGNAL_STATUSES: readonly SignalStatus[] = ['dismissed',];+/** A signal that still supports its action: resolved and dismissed ones don't (AC-007). */+export const OPEN_SIGNAL_STATUSES: readonly SignalStatus[] = ['new', 'acknowledged'];+export const SIGNAL_IMPACTS: readonly SignalImpact[] = ['high', 'medium', 'low'];/** Data sources a signal row can carry (the `source` array's vocabulary). */diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex aea4ac64f..61d915d84 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -56,6 +56,39 @@ export type Database = {},]}+ action_signals: {+ Row: {+ action_id: string+ linked_at: string+ signal_id: string+ }+ Insert: {+ action_id: string+ linked_at?: string+ signal_id: string+ }+ Update: {+ action_id?: string+ linked_at?: string+ signal_id?: string+ }+ Relationships: [+ {+ foreignKeyName: "action_signals_action_id_fkey"+ columns: ["action_id"]+ isOneToOne: false+ referencedRelation: "actions"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "action_signals_signal_id_fkey"+ columns: ["signal_id"]+ isOneToOne: false+ referencedRelation: "signals"+ referencedColumns: ["id"]+ },+ ]+ }action_tasks: {Row: {action_id: string