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): give a finding somewhere to wait (#831)

Gökhan Geyik1855e36711f2
diff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.js
index 640b34be0..470857e78 100644
--- a/server/src/config/action-engine.js
+++ b/server/src/config/action-engine.js
@@ -163,6 +163,46 @@ export const ENGINE_THRESHOLDS = Object.freeze({
outageMinBaseline: 20,
}),
+ /**
+ * How the queue of waiting findings is ordered (#818 phase 6).
+ *
+ * Everything the engine finds becomes a candidate; only some become actions
+ * tonight, because a definition's slot may be busy, resting, or the brand
+ * may already have had its day's worth. These weights decide which of the
+ * ones that can be promoted goes first.
+ *
+ * They reproduce the ordering the Action Center has always sorted by —
+ * impact, then weight of evidence — and add the one thing a queue needs
+ * that a sort does not: age. Without it a low-impact finding sitting behind
+ * a brand with a steady stream of urgent ones would never be worked on at
+ * all.
+ *
+ * The numbers are chosen so two rules hold, and the arithmetic is the only
+ * thing enforcing them:
+ *
+ * * **Nothing starves.** A full two-week wait is worth 42, and the gap
+ * between low and medium is 35 — so a low-impact finding that has
+ * waited out the cap outranks a medium one detected tonight with
+ * comparable evidence. Patience is worth one grade.
+ * * **A high-impact finding is never outranked.** It sits at 200, out of
+ * reach of any wait and any amount of evidence (65 + 15 + 42 = 122 at
+ * most). A brand losing ground right now is worked on before a queue of
+ * older, milder findings, however patient — a queue that lets forty
+ * pages of low-impact opportunity outrank a visibility collapse is not
+ * a priority order, it is a vote.
+ */
+ priority: Object.freeze({
+ impactHigh: 200,
+ impactMedium: 65,
+ impactLow: 30,
+ /** Per linked signal, up to `evidenceCap` signals: at most 15. */
+ evidencePerSignal: 1.5,
+ evidenceCap: 10,
+ /** Per day waited, up to `ageCapDays` days: at most 42. */
+ agePerDay: 3,
+ ageCapDays: 14,
+ }),
+
/** How an action's effect is measured once it closes. */
validation: Object.freeze({
/** Length of the before and after windows. Equal, so the comparison is
diff --git a/server/src/lib/action-center/candidates.js b/server/src/lib/action-center/candidates.js
new file mode 100644
index 000000000..a062528f8
--- /dev/null
+++ b/server/src/lib/action-center/candidates.js
@@ -0,0 +1,84 @@
+/**
+ * The candidate queue (#818, phase 6).
+ *
+ * One active action per definition is the right rule — nobody should be
+ * handed the same piece of work twice — but until now it left a second
+ * finding nowhere to go. Phase 1 stopped such a finding corrupting the open
+ * action's scope; it did not stop it being lost. A condition detected while
+ * the slot was busy was linked as evidence and then forgotten, because the
+ * next cycle is built from whatever happens to be open on the night the slot
+ * frees up. Anything that had resolved in between was never worked on at all.
+ *
+ * So the engine now answers two questions separately. *What did we find?*
+ * produces candidates, every night, whether or not anything can be done about
+ * them. *What should we act on?* promotes from that queue, subject to the
+ * slot, the rest window, eligibility and the daily cap.
+ *
+ * A candidate's lifecycle mirrors a signal's, deliberately: it waits while
+ * its evidence is live, goes stale when the evidence is gone, and comes back
+ * if the condition returns. What it must never do is disappear quietly, which
+ * is the behaviour this phase exists to end.
+ */
+
+import { resolve } from '../../config/action-engine.js';
+
+const DAY_MS = 86_400_000;
+
+const { priority } = resolve();
+
+const IMPACT_SCORE = {
+ high: priority.impactHigh,
+ medium: priority.impactMedium,
+ low: priority.impactLow,
+};
+
+/**
+ * What a candidate is worth acting on, tonight.
+ *
+ * Three terms, in the order they matter: how bad it is, how much evidence
+ * stands behind it, and how long it has been waiting. The first two reproduce
+ * the ordering the Action Center has always used; the third is what a queue
+ * needs and a sort does not — without it, a low-impact finding behind a brand
+ * with a steady stream of high-impact ones would never come up at all.
+ *
+ * Both of the lower terms are capped, so evidence and patience can move a
+ * candidate up the queue but cannot make it outrank a whole grade of impact
+ * on their own. Deliberate: a queue that lets forty pages of low-impact
+ * opportunity outrank a visibility collapse is not a priority order, it is a
+ * vote.
+ *
+ * @param {{ impact: string, signalCount: number, firstSeenAt?: string|Date }} candidate
+ * @param {Date} now
+ */
+export function scoreCandidate({ impact, signalCount, firstSeenAt }, now = new Date()) {
+ const base = IMPACT_SCORE[impact] ?? IMPACT_SCORE.low;
+
+ // Defensive rather than trusting: a caller that forgets to pass the count
+ // used to produce NaN, which sorts as "no opinion" and silently degraded
+ // the whole queue to alphabetical order. A scoring bug that still promotes
+ // something every night, just the wrong thing, is not one anybody notices.
+ const count = Number.isFinite(signalCount) ? Math.max(signalCount, 0) : 0;
+ const evidence = Math.min(count, priority.evidenceCap) * priority.evidencePerSignal;
+
+ const seen = firstSeenAt ? new Date(firstSeenAt).getTime() : now.getTime();
+ const waitedDays = Math.max(0, Math.floor((now.getTime() - seen) / DAY_MS));
+ const age = Math.min(waitedDays, priority.ageCapDays) * priority.agePerDay;
+
+ return base + evidence + age;
+}
+
+/**
+ * The queue in the order it should be worked, highest first.
+ *
+ * Ties break on how long the candidate has waited and then on definition id,
+ * so two runs over the same data promote the same thing. An engine whose
+ * output depends on map iteration order is one nobody can reason about.
+ */
+export function orderByPriority(candidates, now = new Date()) {
+ return [...candidates].sort(
+ (a, b) =>
+ scoreCandidate(b, now) - scoreCandidate(a, now) ||
+ Date.parse(a.firstSeenAt ?? 0) - Date.parse(b.firstSeenAt ?? 0) ||
+ String(a.definitionId).localeCompare(String(b.definitionId)),
+ );
+}
diff --git a/server/src/lib/action-center/candidates.test.js b/server/src/lib/action-center/candidates.test.js
new file mode 100644
index 000000000..213b9f17d
--- /dev/null
+++ b/server/src/lib/action-center/candidates.test.js
@@ -0,0 +1,151 @@
+import { describe, expect, it } from 'vitest';
+import { orderByPriority, scoreCandidate } from './candidates.js';
+import { ENGINE_THRESHOLDS } from '../../config/action-engine.js';
+
+const { priority } = ENGINE_THRESHOLDS;
+const NOW = new Date('2026-09-25T02:00:00Z');
+const daysAgo = (n) => new Date(NOW.getTime() - n * 86_400_000).toISOString();
+
+const candidate = (over = {}) => ({
+ definitionId: 'recover_visibility',
+ impact: 'medium',
+ signalCount: 1,
+ firstSeenAt: NOW.toISOString(),
+ ...over,
+});
+
+describe('scoreCandidate', () => {
+ it('ranks by impact before anything else', () => {
+ const high = scoreCandidate(candidate({ impact: 'high' }), NOW);
+ const medium = scoreCandidate(candidate({ impact: 'medium' }), NOW);
+ const low = scoreCandidate(candidate({ impact: 'low' }), NOW);
+
+ expect(high).toBeGreaterThan(medium);
+ expect(medium).toBeGreaterThan(low);
+ });
+
+ it('counts evidence, so two findings outrank one of the same grade', () => {
+ expect(scoreCandidate(candidate({ signalCount: 4 }), NOW)).toBeGreaterThan(
+ scoreCandidate(candidate({ signalCount: 1 }), NOW),
+ );
+ });
+
+ /**
+ * The term a queue needs and a sort does not. Without it a low-impact
+ * finding behind a brand with a steady stream of urgent ones is never
+ * worked on at all.
+ */
+ it('lifts a candidate that has been waiting', () => {
+ expect(scoreCandidate(candidate({ firstSeenAt: daysAgo(10) }), NOW)).toBeGreaterThan(
+ scoreCandidate(candidate({ firstSeenAt: daysAgo(0) }), NOW),
+ );
+ });
+
+ it('stops paying for patience past the cap', () => {
+ const capped = scoreCandidate(candidate({ firstSeenAt: daysAgo(priority.ageCapDays) }), NOW);
+ expect(scoreCandidate(candidate({ firstSeenAt: daysAgo(400) }), NOW)).toBe(capped);
+ });
+
+ it('stops paying for evidence past the cap', () => {
+ const capped = scoreCandidate(candidate({ signalCount: priority.evidenceCap }), NOW);
+ expect(scoreCandidate(candidate({ signalCount: 500 }), NOW)).toBe(capped);
+ });
+
+ /**
+ * The caps exist for this: a queue where forty low-impact pages outrank a
+ * visibility collapse is not a priority order, it is a vote. A brand losing
+ * ground right now is worked on first, however patient the rest of the
+ * queue is.
+ */
+ it('never lets evidence and patience outrank a high-impact finding', () => {
+ const loudest = scoreCandidate(
+ candidate({ impact: 'medium', signalCount: 1000, firstSeenAt: daysAgo(400) }),
+ NOW,
+ );
+ expect(scoreCandidate(candidate({ impact: 'high' }), NOW)).toBeGreaterThan(loudest);
+ });
+
+ /**
+ * The other half of the same rule: patience must be worth *something*, or
+ * the low-impact end of the queue is never reached at all. Compared at
+ * equal evidence, so it is the wait doing the work and not the count.
+ */
+ it('lets a candidate that waited out the cap cross the grade above it', () => {
+ const patient = scoreCandidate(
+ candidate({ impact: 'low', signalCount: 2, firstSeenAt: daysAgo(30) }),
+ NOW,
+ );
+ const fresh = scoreCandidate(candidate({ impact: 'medium', signalCount: 2 }), NOW);
+
+ expect(patient).toBeGreaterThan(fresh);
+ });
+
+ it('does not let it cross two grades, however long it waits', () => {
+ const patient = scoreCandidate(
+ candidate({ impact: 'low', signalCount: 1000, firstSeenAt: daysAgo(400) }),
+ NOW,
+ );
+ expect(patient).toBeLessThan(scoreCandidate(candidate({ impact: 'high' }), NOW));
+ });
+
+ it('treats an unknown impact as the lowest grade rather than as nothing', () => {
+ expect(scoreCandidate(candidate({ impact: 'catastrophic' }), NOW)).toBe(
+ scoreCandidate(candidate({ impact: 'low' }), NOW),
+ );
+ });
+
+ it('scores a candidate first seen tonight without reading the clock wrong', () => {
+ expect(scoreCandidate(candidate({ firstSeenAt: undefined }), NOW)).toBe(
+ scoreCandidate(candidate({ firstSeenAt: NOW.toISOString() }), NOW),
+ );
+ });
+});
+
+describe('orderByPriority', () => {
+ it('puts the worst problem first', () => {
+ const ordered = orderByPriority(
+ [
+ candidate({ definitionId: 'a', impact: 'low' }),
+ candidate({ definitionId: 'b', impact: 'high' }),
+ candidate({ definitionId: 'c', impact: 'medium' }),
+ ],
+ NOW,
+ );
+
+ expect(ordered.map((c) => c.definitionId)).toEqual(['b', 'c', 'a']);
+ });
+
+ it('breaks a tie on how long it has waited, oldest first', () => {
+ const ordered = orderByPriority(
+ [
+ candidate({ definitionId: 'new', firstSeenAt: daysAgo(priority.ageCapDays + 1) }),
+ candidate({ definitionId: 'older', firstSeenAt: daysAgo(priority.ageCapDays + 9) }),
+ ],
+ NOW,
+ );
+
+ // Both are past the age cap, so they score the same — the tie-break is
+ // what decides, and it has to be the one that has waited longer.
+ expect(ordered.map((c) => c.definitionId)).toEqual(['older', 'new']);
+ });
+
+ /**
+ * A scoring bug that degrades to "alphabetical order" is invisible: the
+ * engine still promotes something every night, just the wrong thing. This
+ * is the shape that bug took once already.
+ */
+ it('produces a real number for every candidate, never NaN', () => {
+ for (const c of [candidate(), candidate({ signalCount: undefined })]) {
+ expect(Number.isFinite(scoreCandidate(c, NOW))).toBe(true);
+ }
+ });
+
+ it('does not modify the list it was given', () => {
+ const list = [
+ candidate({ definitionId: 'a', impact: 'low' }),
+ candidate({ definitionId: 'b', impact: 'high' }),
+ ];
+ orderByPriority(list, NOW);
+ expect(list.map((c) => c.definitionId)).toEqual(['a', 'b']);
+ });
+});
diff --git a/server/src/lib/action-center/generate.js b/server/src/lib/action-center/generate.js
index 6c551488e..71119ae3a 100644
--- a/server/src/lib/action-center/generate.js
+++ b/server/src/lib/action-center/generate.js
@@ -26,10 +26,20 @@
* still firing condition opens a NEW action beside the old one, with its
* own baseline, tasks and outcome.
*
- * Three things stop an action being raised, and they are counted separately
- * so a quiet night is legible: the brand lacks the data the definition needs
- * (`ineligible`), the last cycle closed too recently (`resting`), or the
- * brand has already had its day's worth (`capped`).
+ * Two questions, answered in that order (#818 phase 6). *What did we find?*
+ * writes a candidate for every definition that matched, every night, whether
+ * or not anything can be done about it. *What should we act on?* promotes
+ * from that queue. Keeping them apart is what stopped findings disappearing:
+ * a condition detected while the slot was busy used to be linked as evidence
+ * and then forgotten, because the next cycle was built from whatever happened
+ * to be open on the night the slot freed up.
+ *
+ * Three things stop a candidate being promoted, and they are counted
+ * separately so a quiet night is legible: the brand lacks the data the
+ * definition needs (`ineligible`), the last cycle closed too recently
+ * (`resting`), or the brand has already had its day's worth (`capped`). None
+ * of them loses the finding — it stays in the queue, and its wait is what
+ * lifts it up the order.
*
* `baseline` snapshots the linked signals' measured values at creation —
* the "before" half of the validation comparison (#818, phase 2).
@@ -41,6 +51,7 @@ import { resolve } from '../../config/action-engine.js';
import { isEligible, loadDefinitions } from './definitions/index.js';
import { resolveBrandSources } from './sources.js';
import { planTasks } from './tasks/plan.js';
+import { orderByPriority, scoreCandidate } from './candidates.js';
const DAY_MS = 86_400_000;
@@ -91,29 +102,11 @@ async function linkSignals(actionId, signals) {
return unlinked.length;
}
-/**
- * Which candidate gets the day's remaining room.
- *
- * The same order the Action Center sorts by: impact, then weight of
- * evidence, then something stable. Phase 6 replaces this with scoring across
- * candidates; until definitions compete for the room there is nothing for a
- * score to say that this does not.
- */
-function comparePriority(a, b) {
- return (
- IMPACT_RANK[b.impact] - IMPACT_RANK[a.impact] ||
- b.signals.length - a.signals.length ||
- a.definition.id.localeCompare(b.definition.id)
- );
-}
-
function startOfUtcDay(now) {
return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
}
-async function openCycle({ brandId, definition, signals, impact, available }) {
- const payload = { signalCount: signals.length, ...definition.payload(groupByKind(signals)) };
-
+async function openCycle({ brandId, definition, signals, impact, available, payload }) {
const { data: inserted, error } = await supabaseAdmin
.from('actions')
.insert({
@@ -156,6 +149,7 @@ async function openCycle({ brandId, definition, signals, impact, available }) {
taskCount: plan.length,
});
await linkSignals(inserted.id, signals);
+ return inserted.id;
}
export async function generateActionsForBrand(brandId, { now = new Date(), sources } = {}) {
@@ -211,10 +205,26 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc
).length;
const nowIso = now.toISOString();
- const candidates = [];
+
+ // What the queue already holds. `first_seen_at` is the only thing here that
+ // cannot be recomputed — it is how long a finding has been waiting, which
+ // is the term that stops a low-impact one starving behind a brand with a
+ // steady stream of urgent ones.
+ const { data: waitingRows, error: waitingErr } = await supabaseAdmin
+ .from('action_candidates')
+ .select('id, definition_id, first_seen_at, signal_ids')
+ .eq('brand_id', brandId)
+ .eq('status', 'waiting')
+ .limit(1000);
+ if (waitingErr) throw new Error(waitingErr.message);
+ const waiting = new Map((waitingRows ?? []).map((row) => [row.definition_id, row]));
+
+ const ready = [];
+ const seen = new Set();
let refreshed = 0;
let resting = 0;
let ineligible = 0;
+ let queued = 0;
for (const definition of definitions) {
const matched = (openSignals ?? []).filter((signal) =>
@@ -224,53 +234,136 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc
const current = active.get(definition.id);
if (current) {
- // An active action (new / in_progress / on_hold) keeps the scope it was
- // created with. Signals that arrived since are linked as evidence —
- // they are why this action exists — but `payload` is the work package
- // someone may already be executing against, and rewriting it nightly
- // turned a recovery for six prompts into a recovery for a different
- // nine without telling anyone. New targets wait for the next cycle.
+ // An active action 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.
+ //
+ // 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);
if (linked > 0) {
await supabaseAdmin.from('actions').update({ updated_at: nowIso }).eq('id', current.id);
await logEvent(current.id, 'signals_linked', { count: linked });
}
refreshed += 1;
- continue;
}
- // Eligibility gates opening a cycle, not maintaining one: a brand that
- // disconnects an integration mid-cycle keeps the action it was given.
+ // 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
+ // 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);
+ if (unclaimed.length === 0) continue;
+
+ const impact = unclaimed
+ .map((signal) => signal.impact)
+ .sort((a, b) => IMPACT_RANK[b] - IMPACT_RANK[a])[0];
+ const payload = {
+ signalCount: unclaimed.length,
+ ...definition.payload(groupByKind(unclaimed)),
+ };
+
+ const existing = waiting.get(definition.id);
+ const firstSeenAt = existing?.first_seen_at ?? nowIso;
+ const score = scoreCandidate({ impact, signalCount: unclaimed.length, firstSeenAt }, now);
+ const row = {
+ brand_id: brandId,
+ definition_id: definition.id,
+ status: 'waiting',
+ signal_ids: unclaimed.map((signal) => signal.id),
+ impact,
+ payload,
+ priority: score,
+ first_seen_at: firstSeenAt,
+ last_seen_at: nowIso,
+ updated_at: nowIso,
+ };
+
+ let candidateId = existing?.id;
+ if (candidateId) {
+ const { error } = await supabaseAdmin
+ .from('action_candidates')
+ .update(row)
+ .eq('id', candidateId);
+ if (error) throw new Error(error.message);
+ } else {
+ const { data: inserted, error } = await supabaseAdmin
+ .from('action_candidates')
+ .insert(row)
+ .select('id')
+ .single();
+ if (error) throw new Error(error.message);
+ candidateId = inserted.id;
+ queued += 1;
+ }
+ seen.add(definition.id);
+
+ // Whether it can be promoted tonight is a separate question from whether
+ // it is real, and it is asked after the queue is written — so a finding
+ // that cannot be acted on now is still recorded as found.
+ if (current) continue;
+
if (!isEligible(definition, available)) {
ineligible += 1;
continue;
}
- // The slot is open. Leave it open a while after a cycle closed, so a
- // condition that is still firing does not produce a fresh action every
- // night — the same restraint the old reopen window provided, minus the
- // resurrection.
const closedAt = lastClosedAt.get(definition.id) ?? 0;
if (closedAt && now.getTime() - closedAt < noise.restAfterCloseDays * DAY_MS) {
resting += 1;
continue;
}
- candidates.push({
+ ready.push({
+ candidateId,
+ definitionId: definition.id,
definition,
- signals: matched,
- impact: matched
- .map((signal) => signal.impact)
- .sort((a, b) => IMPACT_RANK[b] - IMPACT_RANK[a])[0],
+ signals: unclaimed,
+ impact,
+ // What the score reads. Named rather than derived from `signals` inside
+ // the scorer so the same shape can be scored straight out of the
+ // database, where the signals themselves are just ids.
+ signalCount: unclaimed.length,
+ payload,
+ firstSeenAt,
});
}
+ // A candidate nothing detected tonight no longer describes anything true.
+ // Stale rather than deleted: it is the record of something the engine once
+ // found, and re-detection brings it back as a new waiting row with a fresh
+ // clock — the same lifecycle a signal has.
+ const gone = (waitingRows ?? []).filter((row) => !seen.has(row.definition_id));
+ if (gone.length > 0) {
+ const { error } = await supabaseAdmin
+ .from('action_candidates')
+ .update({ status: 'stale', updated_at: nowIso })
+ .in(
+ 'id',
+ gone.map((row) => row.id),
+ );
+ if (error) throw new Error(error.message);
+ }
+
const room = Math.max(0, noise.maxNewActionsPerDay - createdToday);
- candidates.sort(comparePriority);
- const opening = candidates.slice(0, room);
+ const ordered = orderByPriority(ready, now);
+ const opening = ordered.slice(0, room);
for (const candidate of opening) {
- await openCycle({ brandId, available, ...candidate });
+ const actionId = await openCycle({ brandId, available, ...candidate });
+ const { error } = await supabaseAdmin
+ .from('action_candidates')
+ .update({
+ status: 'promoted',
+ promoted_at: nowIso,
+ promoted_action_id: actionId,
+ updated_at: nowIso,
+ })
+ .eq('id', candidate.candidateId);
+ if (error) throw new Error(error.message);
}
const summary = {
@@ -278,7 +371,10 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourc
refreshed,
resting,
ineligible,
- capped: candidates.length - opening.length,
+ capped: ordered.length - opening.length,
+ queued,
+ waiting: (waitingRows ?? []).length - gone.length + queued - opening.length,
+ stale: gone.length,
};
logger.info({ brandId, ...summary }, '[actions] generated');
return summary;
diff --git a/server/src/lib/action-center/generate.test.js b/server/src/lib/action-center/generate.test.js
index ff5bc6a2b..06e3a4203 100644
--- a/server/src/lib/action-center/generate.test.js
+++ b/server/src/lib/action-center/generate.test.js
@@ -27,7 +27,7 @@ const NOW = new Date('2026-09-16T04:00:00Z');
* lets `await supabase.from(x).select(y).eq(...)` resolve without a terminal
* call.
*/
-function mockDb({ signals = [], activeActions = [], closedActions = [] } = {}) {
+function mockDb({ signals = [], activeActions = [], closedActions = [], candidates = [] } = {}) {
const writes = { inserted: [], updated: [] };
from.mockImplementation((table) => {
@@ -69,6 +69,7 @@ function mockDb({ signals = [], activeActions = [], closedActions = [] } = {}) {
if (table === 'actions') {
return { data: state.negated ? activeActions : closedActions, error: null };
}
+ if (table === 'action_candidates') return { data: candidates, error: null };
return { data: [], error: null };
}
@@ -231,6 +232,9 @@ describe('generateActionsForBrand', () => {
resting: 0,
ineligible: 0,
capped: 0,
+ queued: 0,
+ waiting: 0,
+ stale: 0,
});
expect(writes.inserted).toHaveLength(0);
});
@@ -451,3 +455,163 @@ describe('the task plan the action is created with', () => {
});
});
});
+
+/**
+ * Phase 6's exit condition (#818): a finding the engine cannot act on yet is
+ * not lost. One active action per definition is the right rule, but until now
+ * it left a second finding nowhere to go — linked as evidence and then
+ * forgotten, because the next cycle was built from whatever happened to be
+ * open on the night the slot freed up.
+ */
+describe('the candidate queue', () => {
+ const queueWrites = (writes) => [
+ ...writes.inserted.filter((w) => w.table === 'action_candidates'),
+ ...writes.updated.filter((w) => w.table === 'action_candidates'),
+ ];
+
+ it('queues a finding it cannot act on, instead of only logging it as evidence', async () => {
+ const writes = mockDb({
+ signals: [signal({ id: 'newcomer' })],
+ activeActions: [{ id: 'a1', dedup_key: 'recover_visibility', status: 'in_progress' }],
+ });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(summary.created).toBe(0);
+ expect(summary.refreshed).toBe(1);
+ expect(summary.queued).toBe(1);
+
+ const queued = writes.inserted.find((w) => w.table === 'action_candidates');
+ expect(queued.rows[0]).toMatchObject({
+ brand_id: BRAND,
+ definition_id: 'recover_visibility',
+ status: 'waiting',
+ signal_ids: ['newcomer'],
+ });
+ });
+
+ it('promotes what it queued once the slot is free', async () => {
+ const writes = mockDb({ signals: [signal()] });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(summary.created).toBe(1);
+ expect(writes.inserted.find((w) => w.table === 'actions')).toBeDefined();
+ const promoted = writes.updated.filter(
+ (w) => w.table === 'action_candidates' && w.patch.status === 'promoted',
+ );
+ expect(promoted).toHaveLength(1);
+ expect(promoted[0].patch.promoted_action_id).toBe('new-actions');
+ });
+
+ /**
+ * The clock that decides priority. A candidate that has been waiting since
+ * last week must not look like one found tonight, or the age term — the
+ * only thing stopping a quiet finding starving — never fires.
+ */
+ it('keeps the date a waiting candidate was first found', async () => {
+ const writes = mockDb({
+ signals: [signal()],
+ candidates: [
+ {
+ id: 'c1',
+ definition_id: 'recover_visibility',
+ first_seen_at: daysAgo(9),
+ signal_ids: [],
+ },
+ ],
+ });
+
+ await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ const refresh = writes.updated.find(
+ (w) => w.table === 'action_candidates' && w.patch.status === 'waiting',
+ );
+ expect(refresh.patch.first_seen_at).toBe(daysAgo(9));
+ expect(refresh.patch.last_seen_at).toBe(NOW.toISOString());
+ });
+
+ it('does not queue a signal an action has already claimed', async () => {
+ const writes = mockDb({
+ signals: [signal({ action_id: 'a1' })],
+ activeActions: [{ id: 'a1', dedup_key: 'recover_visibility', status: 'new' }],
+ });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(summary.queued).toBe(0);
+ expect(queueWrites(writes).filter((w) => w.rows || w.patch.status === 'waiting')).toHaveLength(
+ 0,
+ );
+ });
+
+ /**
+ * 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 rather
+ * than inherit the patience of a finding that ended.
+ */
+ it('stales a candidate whose signals are gone', async () => {
+ const writes = mockDb({
+ signals: [],
+ candidates: [
+ {
+ id: 'c1',
+ definition_id: 'recover_visibility',
+ first_seen_at: daysAgo(3),
+ signal_ids: [],
+ },
+ ],
+ });
+
+ const summary = await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ expect(summary.stale).toBe(1);
+ expect(
+ writes.updated.some((w) => w.table === 'action_candidates' && w.patch.status === 'stale'),
+ ).toBe(true);
+ });
+
+ /** A finding that cannot be acted on for any reason is still recorded as
+ * found — the queue is written before promotion is even considered. */
+ it('queues a resting definition rather than dropping the night', 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, sources: ALL_SOURCES });
+
+ expect(summary.created).toBe(0);
+ expect(summary.resting).toBe(1);
+ expect(summary.queued).toBe(1);
+ expect(writes.inserted.find((w) => w.table === 'action_candidates')).toBeDefined();
+ });
+
+ it('queues an ineligible definition too', async () => {
+ const writes = mockDb({ signals: [signal({ kind: 'page_opportunity', impact: 'medium' })] });
+
+ const summary = await generateActionsForBrand(BRAND, {
+ now: NOW,
+ sources: new Set(['tracking']),
+ });
+
+ expect(summary.created).toBe(0);
+ expect(summary.ineligible).toBe(1);
+ expect(writes.inserted.find((w) => w.table === 'action_candidates').rows[0]).toMatchObject({
+ definition_id: 'capture_ai_traffic',
+ status: 'waiting',
+ });
+ });
+
+ it('scores every candidate it writes', async () => {
+ const writes = mockDb({ signals: [signal()] });
+
+ await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });
+
+ const row = writes.inserted.find((w) => w.table === 'action_candidates').rows[0];
+ expect(Number.isFinite(row.priority)).toBe(true);
+ expect(row.priority).toBeGreaterThan(0);
+ });
+});
diff --git a/supabase/migrations/00089_action_candidates.sql b/supabase/migrations/00089_action_candidates.sql
new file mode 100644
index 000000000..3b0284ed7
--- /dev/null
+++ b/supabase/migrations/00089_action_candidates.sql
@@ -0,0 +1,77 @@
+-- Action Engine, phase 6 (#818): what the engine found but could not act on.
+--
+-- One active action per definition is the right rule — a brand should not be
+-- handed the same piece of work twice — but it left nowhere for a second
+-- finding to go. Phase 1 stopped it corrupting the open action's scope, which
+-- fixed the damage without fixing the loss: a condition detected while the
+-- slot was busy was linked as evidence and then forgotten, because the next
+-- cycle is built from whatever happens to be open on the night the slot frees
+-- up. Anything that resolved in between was simply never worked on.
+--
+-- A candidate is the waiting room. Every definition that matches signals
+-- accumulates one; promotion is what turns it into an action, subject to the
+-- slot being free, the rest window having passed, and the day's budget. The
+-- generator therefore no longer decides what becomes an action while it is
+-- still deciding what was found — those are two questions and they now have
+-- two answers.
+
+create table if not exists public.action_candidates (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+
+ -- The definition this is waiting to become. Matches actions.kind and
+ -- actions.dedup_key; a candidate is a pending action of that definition.
+ definition_id text not null,
+
+ -- 'waiting' — has live signals behind it, has not been promoted
+ -- 'promoted' — became the action named in promoted_action_id
+ -- 'stale' — the signals behind it are gone; it no longer describes
+ -- anything true. Re-detection moves it back to waiting, the
+ -- same lifecycle signals themselves have.
+ status text not null default 'waiting'
+ check (status in ('waiting', 'promoted', 'stale')),
+
+ -- The signals this candidate would cover. Not a foreign key array by
+ -- design: a signal that is deleted takes nothing with it, and the payload
+ -- below is what the action would be built from either way.
+ signal_ids uuid[] not null default '{}',
+
+ impact text not null check (impact in ('high', 'medium', 'low')),
+
+ -- What the action's payload would be, shaped by the definition at the time
+ -- the candidate was last refreshed.
+ payload jsonb not null default '{}'::jsonb,
+
+ -- Score at the last scoring pass, kept so an ordering can be explained
+ -- after the fact rather than recomputed and hoped to match.
+ priority numeric not null default 0,
+
+ first_seen_at timestamptz not null default now(),
+ last_seen_at timestamptz not null default now(),
+ promoted_at timestamptz,
+ promoted_action_id uuid references public.actions(id) on delete set null,
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+-- One waiting candidate per definition per brand. Promoted and stale rows
+-- pile up behind it as the record of what the queue held — the same partial
+-- unique shape actions use for their active cycle (00084).
+create unique index if not exists action_candidates_waiting_idx
+ on public.action_candidates (brand_id, definition_id)
+ where status = 'waiting';
+
+create index if not exists action_candidates_brand_status_idx
+ on public.action_candidates (brand_id, status);
+
+-- Service-role only. No policy rather than a policy named for the service
+-- role: such a policy applies to anon and authenticated, which is the
+-- opposite of its name (the lesson of 00082). Nothing in the web reads this
+-- table yet.
+alter table public.action_candidates enable row level security;
+
+comment on table public.action_candidates is
+ 'The queue of findings waiting to become actions. One waiting row per (brand, definition); promotion turns the highest-priority into an action when the slot, the rest window and the daily cap allow.';
+comment on column public.action_candidates.priority is
+ 'Score at the last pass. Impact, weight of evidence, and how long it has waited — see config/action-engine.js.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 8a26e94f3..a74695839 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -10569,3 +10569,84 @@ comment on column public.action_tasks.depends_on is
comment on column public.action_tasks.title_params is
'Values the task text names, as i18n parameters. Empty when the task names nothing specific.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00089_action_candidates.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Action Engine, phase 6 (#818): what the engine found but could not act on.
+--
+-- One active action per definition is the right rule — a brand should not be
+-- handed the same piece of work twice — but it left nowhere for a second
+-- finding to go. Phase 1 stopped it corrupting the open action's scope, which
+-- fixed the damage without fixing the loss: a condition detected while the
+-- slot was busy was linked as evidence and then forgotten, because the next
+-- cycle is built from whatever happens to be open on the night the slot frees
+-- up. Anything that resolved in between was simply never worked on.
+--
+-- A candidate is the waiting room. Every definition that matches signals
+-- accumulates one; promotion is what turns it into an action, subject to the
+-- slot being free, the rest window having passed, and the day's budget. The
+-- generator therefore no longer decides what becomes an action while it is
+-- still deciding what was found — those are two questions and they now have
+-- two answers.
+
+create table if not exists public.action_candidates (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+
+ -- The definition this is waiting to become. Matches actions.kind and
+ -- actions.dedup_key; a candidate is a pending action of that definition.
+ definition_id text not null,
+
+ -- 'waiting' — has live signals behind it, has not been promoted
+ -- 'promoted' — became the action named in promoted_action_id
+ -- 'stale' — the signals behind it are gone; it no longer describes
+ -- anything true. Re-detection moves it back to waiting, the
+ -- same lifecycle signals themselves have.
+ status text not null default 'waiting'
+ check (status in ('waiting', 'promoted', 'stale')),
+
+ -- The signals this candidate would cover. Not a foreign key array by
+ -- design: a signal that is deleted takes nothing with it, and the payload
+ -- below is what the action would be built from either way.
+ signal_ids uuid[] not null default '{}',
+
+ impact text not null check (impact in ('high', 'medium', 'low')),
+
+ -- What the action's payload would be, shaped by the definition at the time
+ -- the candidate was last refreshed.
+ payload jsonb not null default '{}'::jsonb,
+
+ -- Score at the last scoring pass, kept so an ordering can be explained
+ -- after the fact rather than recomputed and hoped to match.
+ priority numeric not null default 0,
+
+ first_seen_at timestamptz not null default now(),
+ last_seen_at timestamptz not null default now(),
+ promoted_at timestamptz,
+ promoted_action_id uuid references public.actions(id) on delete set null,
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+-- One waiting candidate per definition per brand. Promoted and stale rows
+-- pile up behind it as the record of what the queue held — the same partial
+-- unique shape actions use for their active cycle (00084).
+create unique index if not exists action_candidates_waiting_idx
+ on public.action_candidates (brand_id, definition_id)
+ where status = 'waiting';
+
+create index if not exists action_candidates_brand_status_idx
+ on public.action_candidates (brand_id, status);
+
+-- Service-role only. No policy rather than a policy named for the service
+-- role: such a policy applies to anon and authenticated, which is the
+-- opposite of its name (the lesson of 00082). Nothing in the web reads this
+-- table yet.
+alter table public.action_candidates enable row level security;
+
+comment on table public.action_candidates is
+ 'The queue of findings waiting to become actions. One waiting row per (brand, definition); promotion turns the highest-priority into an action when the slot, the rest window and the daily cap allow.';
+comment on column public.action_candidates.priority is
+ 'Score at the last pass. Impact, weight of evidence, and how long it has waited — see config/action-engine.js.';
+