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
fix(action-center): give a new brand its first actions after its first run (#844)
Gökhan Geyik55862cc2952c
diff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.jsindex d7f1e7ce9..98ceccba4 100644--- a/server/src/config/action-engine.js+++ b/server/src/config/action-engine.js@@ -153,8 +153,14 @@ export const ENGINE_THRESHOLDS = Object.freeze({maxSignalsPerKind: 5,// Prompts- /** Tracked on at least this many days of the window before absence counts. */+ /** Tracked on at least this many days of the window before absence counts… */promptMinDays: 3,+ /**+ * …or answered at least this many times, whichever days. A new brand's+ * first run answers each prompt once per platform on a single day; this+ * is what lets that run open actions instead of waiting three days.+ */+ promptMinAnswers: 5,/** Mentioned on at least this many days before, and not at all now, is a* lost mention rather than noise. */lostMentionMinDays: 3,diff --git a/server/src/lib/job-runner.js b/server/src/lib/job-runner.jsindex 013ffe06c..06f9bb325 100644--- a/server/src/lib/job-runner.js+++ b/server/src/lib/job-runner.js@@ -16,7 +16,7 @@ import {import { processTrackingJob } from '../workers/tracking-worker.js';import { processContentJob } from '../workers/content-worker.js';import { generatePulseForBrand } from './pulse/engine.js';-import { runSignalPass } from './signals/pass.js';+import { runFirstSignalPass, runSignalPass } from './signals/pass.js';import logger from './logger.js';// Concurrency counters (the default of 2 per queue is inherited from the Bull@@ -112,6 +112,16 @@ export async function runTrackingJob(jobId, io) {'skipping daily pulse — tracking run was not stamped, window would be stale',);}+ } else if (immediate && !promptId && !promptIds?.length && result?.stamped) {+ // A new brand's first run is a manual one, and passes otherwise wait for+ // the night. It gets one now so the Action Center is not empty until+ // tomorrow; the function is a no-op for a brand that already had one.+ runFirstSignalPass(brandId).catch((err) => {+ logger.error(+ { err, brandId },+ '[signals] first pass failed — the nightly pass will cover it',+ );+ });}} catch (err) {if (abortController.signal.aborted) {diff --git a/server/src/lib/signals/library/classify.js b/server/src/lib/signals/library/classify.jsindex 2e224a624..ea0d33e71 100644--- a/server/src/lib/signals/library/classify.js+++ b/server/src/lib/signals/library/classify.js@@ -38,8 +38,18 @@ export function strongest(items, score, max) {* visible. Among the never-visible, demand and an existing page decide the* work: create content, optimise the page that exists, or map one.*/+/**+ * Whether a prompt has been observed enough this window to judge: on enough+ * days, or in enough answers. Answers only accumulate inside the window, so a+ * prompt that qualifies on its first day still qualifies on its second — the+ * signal it raises does not flap closed while the days catch up.+ */+export function isTracked(p, t) {+ return p.cur_days >= t.promptMinDays || (p.cur_answers ?? 0) >= t.promptMinAnswers;+}+export function classifyPrompt(p, t) {- const tracked = p.cur_days >= t.promptMinDays;+ const tracked = isTracked(p, t);const highValue = (p.volume ?? 0) >= t.highDemandVolume;if (tracked && p.cur_mention_days === 0 && p.prev_mention_days >= t.lostMentionMinDays) {@@ -133,7 +143,7 @@ export function topicCoverage(prompts, t) {prompts: [],mapped: 0,};- if (p.cur_days >= t.promptMinDays) {+ if (isTracked(p, t)) {e.tracked += 1;if (p.cur_mention_days > 0) e.visible += 1;}@@ -207,7 +217,7 @@ export function classifyCompetitor(c, brandMentions, t) {* it is creating — and the specification gives those different definitions.*/export function classifyCompetitorTopic(topic, competitorPresent, t) {- const contested = topic.prompts.filter((p) => p.cur_days >= t.promptMinDays);+ const contested = topic.prompts.filter((p) => isTracked(p, t));if (contested.length < t.topicMinPrompts) return null;const lost = contested.filter((p) => p.cur_mention_days === 0 && competitorPresent.has(p.prompt_id),diff --git a/server/src/lib/signals/library/classify.test.js b/server/src/lib/signals/library/classify.test.jsindex 769dbcd43..fdd1513bc 100644--- a/server/src/lib/signals/library/classify.test.js+++ b/server/src/lib/signals/library/classify.test.js@@ -66,6 +66,39 @@ describe('classifyPrompt', () => {it('says nothing about a prompt tracked too few days to judge', () => {expect(c.classifyPrompt(prompt({ cur_days: t.promptMinDays - 1 }), t)).toBeNull();});++ /**+ * A new brand's first run: one day, every platform. Invisible on all of+ * them is a finding, and waiting three days to say so left new brands with+ * an empty Action Center.+ */+ it('judges a prompt answered enough times on a single day', () => {+ expect(+ c.classifyPrompt(prompt({ cur_days: 1, cur_answers: t.promptMinAnswers, volume: 500 }), t),+ ).toBe('uncovered_demand');+ });++ it('still waits on a single day with too few answers', () => {+ expect(+ c.classifyPrompt(prompt({ cur_days: 1, cur_answers: t.promptMinAnswers - 1 }), t),+ ).toBeNull();+ });+});++describe('isTracked', () => {+ it('accepts enough days, whatever the answers', () => {+ expect(c.isTracked(prompt({ cur_days: t.promptMinDays, cur_answers: 0 }), t)).toBe(true);+ });++ it('accepts enough answers, whatever the days', () => {+ expect(c.isTracked(prompt({ cur_days: 1, cur_answers: t.promptMinAnswers }), t)).toBe(true);+ });++ /** Rows from before the field existed read as no answers, not as an error. */+ it('treats a missing answer count as none', () => {+ const { cur_answers: _, ...row } = prompt({ cur_days: 1 });+ expect(c.isTracked(row, t)).toBe(false);+ });});describe('groupPrompts', () => {diff --git a/server/src/lib/signals/library/detect.js b/server/src/lib/signals/library/detect.jsindex 44218f5f0..3613a0329 100644--- a/server/src/lib/signals/library/detect.js+++ b/server/src/lib/signals/library/detect.js@@ -353,9 +353,20 @@ const FAMILIES = [const names = new Map((dims.competitors ?? []).map((x) => [x.key, x.name]));const leader = new Map();for (const row of compRows) {- if (row.cur_days < t.competitorPromptMinDays) continue;+ if (+ row.cur_days < t.competitorPromptMinDays &&+ (row.cur_answers ?? 0) < t.promptMinAnswers+ ) {+ continue;+ }const current = leader.get(row.prompt_id);- if (!current || row.cur_days > current.cur_days) leader.set(row.prompt_id, row);+ // Most days, then most answers — a new brand's rows are all one day.+ const ahead =+ !current ||+ row.cur_days > current.cur_days ||+ (row.cur_days === current.cur_days &&+ (row.cur_answers ?? 0) > (current.cur_answers ?? 0));+ if (ahead) leader.set(row.prompt_id, row);}const present = new Set(leader.keys());const found = [];@@ -364,7 +375,7 @@ const FAMILIES = [const contested = prompts.filter((p) =>(p.volume ?? 0) >= t.highDemandVolume &&- p.cur_days >= t.promptMinDays &&+ c.isTracked(p, t) &&p.cur_mention_days === 0 &&present.has(p.prompt_id),);diff --git a/server/src/lib/signals/pass.js b/server/src/lib/signals/pass.jsindex 44cf1fbe0..490c53771 100644--- a/server/src/lib/signals/pass.js+++ b/server/src/lib/signals/pass.js@@ -30,16 +30,18 @@ import { generateActionsForBrand } from '../action-center/generate.js';*/const CATCH_UP_WINDOW_MS = 36 * 60 * 60 * 1000;-/** The brand's most recent stamped nightly run, or null. */-async function latestStampedRun(brandId) {- const { data, error } = await supabaseAdmin+/**+ * The brand's most recent stamped run, or null. Nightly runs only unless+ * `anySource` — a manual run is what a brand's first pass has to go on.+ */+async function latestStampedRun(brandId, { anySource = false } = {}) {+ let query = supabaseAdmin.from('tracking_runs').select('completed_at').eq('brand_id', brandId)- .eq('source', 'cron')- .not('completed_at', 'is', null)- .order('completed_at', { ascending: false })- .limit(1);+ .not('completed_at', 'is', null);+ if (!anySource) query = query.eq('source', 'cron');+ const { data, error } = await query.order('completed_at', { ascending: false }).limit(1);if (error) throw new Error(error.message);return data?.[0]?.completed_at ?? null;}@@ -82,6 +84,34 @@ export async function runSignalPass(brandId, { runAt, now = new Date() } = {}) {return { trackingRunAt, signals: recorded, actions: generated };}+/**+ * A brand's first pass, straight after its first run.+ *+ * Passes ride the nightly run, and a brand's first run is not one: onboarding+ * starts it by hand, so a new brand used to open an empty Action Center and+ * wait for the next night — up to a day — before anything appeared. Its first+ * complete run now gets a pass of its own.+ *+ * Only the first. Every later manual run would otherwise re-run detection on+ * a refresh, and the nightly pass is what the rest of the engine is paced+ * around.+ *+ * @param {string} brandId+ */+export async function runFirstSignalPass(brandId, { now = new Date() } = {}) {+ const { data: passes, error } = await supabaseAdmin+ .from('signal_runs')+ .select('brand_id')+ .eq('brand_id', brandId)+ .limit(1);+ if (error) throw new Error(error.message);+ if ((passes ?? []).length > 0) return { skipped: 'not_first' };++ const runAt = await latestStampedRun(brandId, { anySource: true });+ if (!runAt) return { skipped: 'no_stamped_run' };+ return runSignalPass(brandId, { runAt, now });+}+/*** Re-run the passes that never finished.*diff --git a/server/src/lib/signals/pass.test.js b/server/src/lib/signals/pass.test.jsindex dbcf29aae..88af4e74d 100644--- a/server/src/lib/signals/pass.test.js+++ b/server/src/lib/signals/pass.test.js@@ -13,7 +13,7 @@ vi.mock('../action-center/generate.js', () => ({generateActionsForBrand: (...a) => generateActionsForBrand(...a),}));-import { runSignalCatchUp, runSignalPass } from './pass.js';+import { runFirstSignalPass, runSignalCatchUp, runSignalPass } from './pass.js';const BRAND = 'brand-1';const NOW = new Date('2026-09-25T06:00:00Z');@@ -25,10 +25,14 @@ const RUN_AT = '2026-09-25T02:13:00.000Z';*/function mockDb({ runs = [], passes = [] } = {}) {const writes = [];+ writes.filters = [];from.mockImplementation((table) => {const builder = {select: () => builder,- eq: () => builder,+ eq: (column, value) => {+ writes.filters.push({ table, column, value });+ return builder;+ },not: () => builder,gte: () => builder,order: () => builder,@@ -180,3 +184,55 @@ describe('runSignalCatchUp', () => {expect(await runSignalCatchUp({ now: NOW })).toEqual({ error: true });});});++/**+ * A new brand's first run is a manual one. Passes otherwise wait for the+ * nightly run, which left a new brand's Action Center empty for up to a day.+ */+describe('runFirstSignalPass', () => {+ it('runs a pass against the manual run a brand with no passes just finished', async () => {+ const writes = mockDb({ runs: [{ completed_at: RUN_AT }], passes: [] });++ const result = await runFirstSignalPass(BRAND, { now: NOW });++ expect(result.trackingRunAt).toBe(RUN_AT);+ expect(generateActionsForBrand).toHaveBeenCalledOnce();+ // Any source: the run it covers is not a nightly one.+ expect(writes.filters).not.toContainEqual({+ table: 'tracking_runs',+ column: 'source',+ value: 'cron',+ });+ });++ /** Otherwise every manual refresh would re-run detection. */+ it('does nothing for a brand that has had a pass', async () => {+ const writes = mockDb({+ runs: [{ completed_at: RUN_AT }],+ passes: [{ brand_id: BRAND }],+ });++ expect(await runFirstSignalPass(BRAND, { now: NOW })).toEqual({ skipped: 'not_first' });+ expect(recordSignalsForBrand).not.toHaveBeenCalled();+ expect(writes).toHaveLength(0);+ });++ it('does nothing when no run has stamped', async () => {+ mockDb({ runs: [], passes: [] });++ expect(await runFirstSignalPass(BRAND, { now: NOW })).toEqual({ skipped: 'no_stamped_run' });+ expect(recordSignalsForBrand).not.toHaveBeenCalled();+ });++ it('leaves the nightly pass reading nightly runs only', async () => {+ const writes = mockDb({ runs: [{ completed_at: RUN_AT }] });++ await runSignalPass(BRAND, { now: NOW });++ expect(writes.filters).toContainEqual({+ table: 'tracking_runs',+ column: 'source',+ value: 'cron',+ });+ });+});diff --git a/supabase/migrations/00097_action_engine_prompt_answer_counts.sql b/supabase/migrations/00097_action_engine_prompt_answer_counts.sqlnew file mode 100644index 000000000..a683a8616--- /dev/null+++ b/supabase/migrations/00097_action_engine_prompt_answer_counts.sql@@ -0,0 +1,76 @@+-- Prompt and competitor stats count answers as well as days.+--+-- The library's detectors judged a prompt only once it had three days of+-- results. That kept one odd day from raising an action, and it also meant a+-- new brand saw nothing in the Action Center for three days: its first run+-- answers every prompt on every platform, but it is one day. `cur_answers`+-- lets a detector accept a prompt answered enough times, whichever days those+-- answers came from.+--+-- Additive: both functions return jsonb, and a caller that does not read the+-- new field is unaffected.++create or replace function public.ae_prompt_stats(+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date+) returns jsonb+language sql stable+as $$+ with days as (+ select prompt_id, day, bool_or(has_mention) as m, bool_or(has_citation) as c,+ sum(answer_count) as answers+ from public.insights_prompt_daily+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to+ group by prompt_id, day+ ),+ active as (+ select p.id, p.topic_id+ from public.prompts p+ join public.prompt_sets s on s.id = p.prompt_set_id+ where s.brand_id = p_brand_id and p.is_active+ )+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (+ select a.id as prompt_id, a.topic_id,+ count(d.day) filter (where d.day between p_cur_from and p_cur_to) as cur_days,+ coalesce(sum(d.answers) filter (where d.day between p_cur_from and p_cur_to), 0) as cur_answers,+ count(d.day) filter (where d.day between p_cur_from and p_cur_to and d.m) as cur_mention_days,+ count(d.day) filter (where d.day between p_cur_from and p_cur_to and d.c) as cur_citation_days,+ count(d.day) filter (where d.day between p_prev_from and p_prev_to) as prev_days,+ count(d.day) filter (where d.day between p_prev_from and p_prev_to and d.m) as prev_mention_days,+ count(d.day) filter (where d.day between p_prev_from and p_prev_to and d.c) as prev_citation_days,+ max(d.day) filter (where d.m) as last_mention_day,+ max(d.day) filter (where d.c) as last_citation_day,+ (select coalesce(max(v.est_ai_volume), 0) from public.prompt_volumes v where v.prompt_id = a.id) as volume,+ exists (select 1 from public.prompt_target_urls t where t.prompt_id = a.id) as has_target_url+ from active a+ left join days d on d.prompt_id = a.id+ group by a.id, a.topic_id+ ) x+$$;++-- One row per (day, platform, model, region) the competitor appeared in, so+-- the count of rows is the count of answers naming it.+create or replace function public.ae_competitor_prompt_stats(+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date+) returns jsonb+language sql stable+as $$+ with days as (+ select prompt_id, competitor_id, day, count(*) as answers+ from public.insights_competitor_prompt_daily+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to+ group by prompt_id, competitor_id, day+ )+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (+ select prompt_id, competitor_id,+ count(*) filter (where day between p_cur_from and p_cur_to) as cur_days,+ coalesce(sum(answers) filter (where day between p_cur_from and p_cur_to), 0) as cur_answers,+ count(*) filter (where day between p_prev_from and p_prev_to) as prev_days+ from days+ group by prompt_id, competitor_id+ ) x+$$;++revoke all on function public.ae_prompt_stats(uuid, date, date, date, date) from public, anon, authenticated;+revoke all on function public.ae_competitor_prompt_stats(uuid, date, date, date, date) from public, anon, authenticated;+grant execute on function public.ae_prompt_stats(uuid, date, date, date, date) to service_role;+grant execute on function public.ae_competitor_prompt_stats(uuid, date, date, date, date) to service_role;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 4a16e346c..7f7afd1e7 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -11218,3 +11218,83 @@ alter table public.action_tasksadd constraint action_tasks_permission_checkcheck (permission in ('read', 'write', 'execute'));+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00097_action_engine_prompt_answer_counts.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Prompt and competitor stats count answers as well as days.+--+-- The library's detectors judged a prompt only once it had three days of+-- results. That kept one odd day from raising an action, and it also meant a+-- new brand saw nothing in the Action Center for three days: its first run+-- answers every prompt on every platform, but it is one day. `cur_answers`+-- lets a detector accept a prompt answered enough times, whichever days those+-- answers came from.+--+-- Additive: both functions return jsonb, and a caller that does not read the+-- new field is unaffected.++create or replace function public.ae_prompt_stats(+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date+) returns jsonb+language sql stable+as $$+ with days as (+ select prompt_id, day, bool_or(has_mention) as m, bool_or(has_citation) as c,+ sum(answer_count) as answers+ from public.insights_prompt_daily+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to+ group by prompt_id, day+ ),+ active as (+ select p.id, p.topic_id+ from public.prompts p+ join public.prompt_sets s on s.id = p.prompt_set_id+ where s.brand_id = p_brand_id and p.is_active+ )+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (+ select a.id as prompt_id, a.topic_id,+ count(d.day) filter (where d.day between p_cur_from and p_cur_to) as cur_days,+ coalesce(sum(d.answers) filter (where d.day between p_cur_from and p_cur_to), 0) as cur_answers,+ count(d.day) filter (where d.day between p_cur_from and p_cur_to and d.m) as cur_mention_days,+ count(d.day) filter (where d.day between p_cur_from and p_cur_to and d.c) as cur_citation_days,+ count(d.day) filter (where d.day between p_prev_from and p_prev_to) as prev_days,+ count(d.day) filter (where d.day between p_prev_from and p_prev_to and d.m) as prev_mention_days,+ count(d.day) filter (where d.day between p_prev_from and p_prev_to and d.c) as prev_citation_days,+ max(d.day) filter (where d.m) as last_mention_day,+ max(d.day) filter (where d.c) as last_citation_day,+ (select coalesce(max(v.est_ai_volume), 0) from public.prompt_volumes v where v.prompt_id = a.id) as volume,+ exists (select 1 from public.prompt_target_urls t where t.prompt_id = a.id) as has_target_url+ from active a+ left join days d on d.prompt_id = a.id+ group by a.id, a.topic_id+ ) x+$$;++-- One row per (day, platform, model, region) the competitor appeared in, so+-- the count of rows is the count of answers naming it.+create or replace function public.ae_competitor_prompt_stats(+ p_brand_id uuid, p_cur_from date, p_cur_to date, p_prev_from date, p_prev_to date+) returns jsonb+language sql stable+as $$+ with days as (+ select prompt_id, competitor_id, day, count(*) as answers+ from public.insights_competitor_prompt_daily+ where brand_id = p_brand_id and day between p_prev_from and p_cur_to+ group by prompt_id, competitor_id, day+ )+ select coalesce(jsonb_agg(row_to_json(x)), '[]'::jsonb) from (+ select prompt_id, competitor_id,+ count(*) filter (where day between p_cur_from and p_cur_to) as cur_days,+ coalesce(sum(answers) filter (where day between p_cur_from and p_cur_to), 0) as cur_answers,+ count(*) filter (where day between p_prev_from and p_prev_to) as prev_days+ from days+ group by prompt_id, competitor_id+ ) x+$$;++revoke all on function public.ae_prompt_stats(uuid, date, date, date, date) from public, anon, authenticated;+revoke all on function public.ae_competitor_prompt_stats(uuid, date, date, date, date) from public, anon, authenticated;+grant execute on function public.ae_prompt_stats(uuid, date, date, date, date) to service_role;+grant execute on function public.ae_competitor_prompt_stats(uuid, date, date, date, date) to service_role;+