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): read the weeks tracking missed nights of at a full week's worth, and leave counts out past two (learning A6) (#1691)
Cihanc1139b55b535
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdxindex 9991cc758..1f35e2eb8 100644--- a/docs/guides/action-center.mdx+++ b/docs/guides/action-center.mdx@@ -191,7 +191,7 @@ The **History** tab lists actions once they are In Progress, On Hold, CompletedClick an action to see **What was the goal?**, **What happened?** (the signals it was built from), its affected items and tasks, and the **Result**:-- When a completed action's week after closing is over, Ansvisor compares its metrics over the 7 days before it was raised with the 7 days after it closed. The result reads **Improved**, **Mixed**, **No meaningful change** or **Declined**, judged by the action's main metric (the first one it names): **Mixed** when another metric it names moved the other way, or, without the main one measured, when the ones it names moved both ways. Other metrics show beside but don't count. It is measured after the action, not proven to be caused by it. An action that names its prompts or pages is measured on them, with the brand-wide figures over the same days beside; when they can't show its main metric (citations, for prompts), it is measured brand-wide. A Site Audit fix is judged by its pages audited again since it closed: the check that raised it passing, or a low score past the line; with none audited again yet, by the metrics. The History drawer also says what became of the signals that raised it by then: how many ended, turned into another, were dismissed, or are still open.+- When a completed action's week after closing is over, Ansvisor compares its metrics over the 7 days before it was raised with the 7 days after it closed. The result reads **Improved**, **Mixed**, **No meaningful change** or **Declined**, judged by the action's main metric (the first one it names): **Mixed** when another metric it names moved the other way, or, without the main one measured, when the ones it names moved both ways. Other metrics show beside but don't count. It is measured after the action, not proven to be caused by it. An action that names its prompts or pages is measured on them, with the brand-wide figures over the same days beside; when they can't show its main metric (citations, for prompts), it is measured brand-wide. A Site Audit fix is judged by its pages audited again since it closed: the check that raised it passing, or a low score past the line; with none audited again yet, by the metrics. When tracking missed nights in either week, the drawer says so, and mentions and citations are read at a full week's worth from the nights that ran. More than two in one week are too few to read them from: they're left out of the result, and an action whose main metric is one of them reads **Not measurable**. The History drawer also says what became of the signals that raised it by then: how many ended, turned into another, were dismissed, or are still open.- Only a completed action is measured: a dismissed one reads **Not measured**, dismissed. One with no metric to read is **Not measurable**.- An action sent from a prompt's Improve tab reports on how many platforms its position improved. It is read again daily while the action is open and for 30 days after it is completed.diff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.jsindex c56fac1c2..da8ba25f1 100644--- a/server/src/config/action-engine.js+++ b/server/src/config/action-engine.js@@ -368,6 +368,16 @@ export const ENGINE_THRESHOLDS = Object.freeze({* floor every outcome would be a verdict and none would mean anything.*/meaningfulChangeRatio: 0.05,++ /**+ * Days of a window with no stamped tracking run beyond which its counts+ * can't be compared (learning A6): a missed night reads as fewer+ * mentions and citations, a decline nobody caused. Up to this many, the+ * counts are read at a full window's worth from the nights that ran, and+ * flagged; more, and they're left out of the verdict (not measurable when+ * the main metric is one).+ */+ maxGapDays: 2,}),});diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.jsindex 73ff3e41f..899c875a7 100644--- a/server/src/lib/action-center/validate.js+++ b/server/src/lib/action-center/validate.js@@ -59,6 +59,16 @@ export const VALIDATION_WAIT_DAYS = MEASUREMENT_WINDOW_DAYS + 1;*/export const MEANINGFUL_CHANGE_RATIO = validation.meaningfulChangeRatio;+/** Days a window may lack a tracking run and still be compared (learning A6). */+export const MAX_GAP_DAYS = validation.maxGapDays;++/**+ * Metrics tracking's answers add up night by night: a night without a run+ * reads low in them. The rates (visibility, share of voice, the lead over a+ * competitor) are shares of the answers there were, and don't drift from one.+ */+const COUNT_METRICS = new Set(['mentions', 'citations']);+/** Every metric here reads higher-is-better; a drop is a decline. */const MEASURABLE_KPIS = {ai_visibility: 'percent',@@ -240,6 +250,52 @@ export function deriveOutcome(metrics, primary = null, aims = null) {return 'no_meaningful_change';}+/**+ * The days of a window (inclusive, UTC) with no stamped tracking run for the+ * brand (learning A6): a night whose collection failed, or fell short and+ * was discarded, leaves no stamped row.+ */+export async function missingDays(brandId, window) {+ const end = new Date(Date.parse(`${window.to}T00:00:00Z`) + DAY_MS).toISOString();+ const { data, error } = await supabaseAdmin+ .from('tracking_runs')+ .select('completed_at')+ .eq('brand_id', brandId)+ .not('completed_at', 'is', null)+ .gte('completed_at', `${window.from}T00:00:00Z`)+ .lt('completed_at', end)+ .limit(1000);+ if (error) throw new Error(`tracking_runs: ${error.message}`);+ const ran = new Set((data ?? []).map((r) => new Date(r.completed_at).toISOString().slice(0, 10)));+ let missing = 0;+ for (let t = Date.parse(`${window.from}T00:00:00Z`); t < Date.parse(end); t += DAY_MS) {+ if (!ran.has(new Date(t).toISOString().slice(0, 10))) missing += 1;+ }+ return missing;+}++/**+ * The counts read over windows tracking missed nights of, each at a full+ * window's worth (learning A6): what the nights that ran read, per night,+ * times the window's nights. Both windows on the same scale, a missed night+ * no longer reads as a decline nobody caused. What was read stays as `raw`.+ */+export function fullWindowCounts(metrics, gaps) {+ if (!metrics || !(gaps.before || gaps.after)) return metrics;+ const full = (value, missing) => {+ if (value == null || !missing) return value;+ const ran = MEASUREMENT_WINDOW_DAYS - missing;+ return ran > 0 ? Math.round(((value * MEASUREMENT_WINDOW_DAYS) / ran) * 10) / 10 : null;+ };+ return metrics.map((m) => {+ if (!COUNT_METRICS.has(m.metric)) return m;+ const before = full(m.before, gaps.before);+ const after = full(m.after, gaps.after);+ if (before === m.before && after === m.after) return m;+ return { ...m, before, after, raw: { before: m.before, after: m.after } };+ });+}+/** A target the night engine names that a basket can be measured on (learning A1). */const TARGET_BASKETS = new Set(['prompts', 'pages']);const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -339,14 +395,48 @@ export async function validateAction(action, { now = new Date() } = {}) {// The verdict from the metrics kept, by its main metric; given `aims`,// only the metrics the action names count (see deriveOutcome).const finish = async (validation, aims = null) => {- const beside = { ...(signals ? { signals } : {}), ...(audit ? { audit } : {}) };+ // Nights tracking missed in either window (A6), when a count was read.+ // Up to MAX_GAP_DAYS, its counts are read at a full window's worth; past+ // it, too few nights ran to scale from: the counts stay as read and+ // don't count toward the verdict, and an action whose main metric is a+ // count can't be compared. The rates can.+ const counted = [...(validation?.metrics ?? []), ...(validation?.brandWide ?? [])].some(+ (m) => COUNT_METRICS.has(m.metric) && m.before != null && m.after != null,+ );+ const [gapBefore, gapAfter] = counted+ ? await Promise.all([+ missingDays(action.brand_id, beforeWindow),+ missingDays(action.brand_id, afterWindow),+ ])+ : [0, 0];+ const tooMany = Math.max(gapBefore, gapAfter) > MAX_GAP_DAYS;+ const gaps =+ gapBefore || gapAfter+ ? { gaps: { before: gapBefore, after: gapAfter, ...(tooMany ? { tooMany: true } : {}) } }+ : {};+ const nights = { before: gapBefore, after: gapAfter };+ const read =+ validation && !tooMany+ ? {+ ...validation,+ metrics: fullWindowCounts(validation.metrics, nights),+ ...(validation.brandWide+ ? { brandWide: fullWindowCounts(validation.brandWide, nights) }+ : {}),+ }+ : validation;+ const beside = { ...(signals ? { signals } : {}), ...(audit ? { audit } : {}), ...gaps };const kept =- validation || Object.keys(beside).length- ? { measuredAt: now.toISOString(), ...(validation ?? {}), ...beside }+ read || Object.keys(beside).length+ ? { measuredAt: now.toISOString(), ...(read ?? {}), ...beside }: null;- const outcome = validation- ? deriveOutcome(validation.metrics, validation.primary, aims)- : 'not_measurable';+ const comparable = tooMany+ ? read?.metrics.filter((m) => !COUNT_METRICS.has(m.metric))+ : read?.metrics;+ const outcome =+ !read || (tooMany && COUNT_METRICS.has(read.primary))+ ? 'not_measurable'+ : deriveOutcome(comparable, read.primary, aims);const verdict = (audit && auditOutcome(audit)) ?? outcome;await write(action.id, kept, verdict, now);return verdict;diff --git a/server/src/lib/action-center/validate.test.js b/server/src/lib/action-center/validate.test.jsindex 905636e9b..3a0b2eb1b 100644--- a/server/src/lib/action-center/validate.test.js+++ b/server/src/lib/action-center/validate.test.js@@ -10,6 +10,7 @@ vi.mock('../logger.js', () => ({}));import {+ MAX_GAP_DAYS,MEANINGFUL_CHANGE_RATIO,VALIDATION_WAIT_DAYS,deriveOutcome,@@ -20,8 +21,12 @@ import {const NOW = new Date('2026-09-20T04:00:00Z');const daysAgo = (n) => new Date(NOW.getTime() - n * 86_400_000).toISOString();+/** A stamped tracking run every night of the last 60 days: no window misses one. */+const EVERY_NIGHT = Array.from({ length: 60 }, (_, i) => ({ completed_at: daysAgo(i) }));+/** Records every write so a test can assert what was stored; `rows` answers a table's reads. */function mockWrites(rows = {}) {+ rows = { tracking_runs: EVERY_NIGHT, ...rows };const writes = { updated: [], inserted: [] };from.mockImplementation((table) => {const builder = {@@ -34,6 +39,7 @@ function mockWrites(rows = {}) {limit: () => builder,order: () => builder,gt: () => builder,+ lt: () => builder,in: () => builder,maybeSingle: async () => ({ data: (rows[table] ?? [])[0] ?? null, error: null }),update: (patch) => {@@ -594,6 +600,150 @@ describe('validateAction', () => {});});+ describe('with nights tracking missed (learning A6)', () => {+ const missing = (nights) => EVERY_NIGHT.filter((_, i) => !nights.includes(i));+ // The after window is the 7 days from 9 days ago; the before, from 37 days ago.++ it('flags a window with a missed night or two, and still reads it', async () => {+ const writes = mockWrites({ tracking_runs: missing([5, 6]) });+ rpc+ .mockResolvedValueOnce({ data: { total_citations: 100 }, error: null })+ .mockResolvedValueOnce({ data: { total_citations: 140 }, error: null });++ expect(await validateAction(action(), { now: NOW })).toBe('improved');+ const { validation } = writes.updated.find((w) => w.table === 'actions').patch;+ expect(validation.gaps).toEqual({ before: 0, after: 2 });+ });++ /** Each source answers `before` over the week before, `after` over the week after. */+ const weeks = (byName) =>+ rpc.mockImplementation(async (name, args) => {+ const from = args.p_day_from ?? args.p_from;+ const [before, after] = byName[name] ?? [{}, {}];+ return { data: from < daysAgo(20).slice(0, 10) ? before : after, error: null };+ });++ it('reads a count at a full week’s worth from the nights that ran: 7 nights of 100 vs 6', async () => {+ const writes = mockWrites({ tracking_runs: missing([5]) });+ weeks({ insights_aggregates_daily: [{ total_citations: 700 }, { total_citations: 600 }] });++ // Read as it came, the missed night is a 14% decline nobody caused.+ expect(await validateAction(action(), { now: NOW })).toBe('no_meaningful_change');+ const { validation } = writes.updated.find((w) => w.table === 'actions').patch;+ expect(validation.metrics).toEqual([+ {+ metric: 'citations',+ unit: 'count',+ before: 700,+ after: 700,+ raw: { before: 700, after: 600 },+ },+ ]);+ expect(validation.gaps).toEqual({ before: 0, after: 1 });+ });++ it('reads the counts of the prompts it names, and the brand-wide ones, the same way', async () => {+ const P1 = '11111111-1111-4111-8111-111111111111';+ const writes = mockWrites({ tracking_runs: missing([5]) });+ weeks({+ opportunity_basket_metrics: [+ { cells: 70, visible: 14, mention_answers: 70 },+ { cells: 60, visible: 12, mention_answers: 60 },+ ],+ insights_aggregates_daily: [{ total_mentions: 700 }, { total_mentions: 600 }],+ });++ const outcome = await validateAction(+ action({+ kind: 'recover_lost_visibility',+ kpi_keys: ['mentions'],+ payload: { targetEntity: 'prompts', targets: [{ id: P1 }] },+ }),+ { now: NOW },+ );++ expect(outcome).toBe('no_meaningful_change');+ const { validation } = writes.updated.find((w) => w.table === 'actions').patch;+ expect(validation.metrics[0]).toMatchObject({ metric: 'mentions', before: 70, after: 70 });+ expect(validation.brandWide[0]).toMatchObject({+ metric: 'mentions',+ before: 700,+ after: 700,+ raw: { before: 700, after: 600 },+ });+ });++ it('past MAX_GAP_DAYS leaves the counts out, and a rate still judges', async () => {+ // Share of voice 20% → 30%; citations read over 3 nights of the week after.+ const sources = {+ share_of_voice_aggregates_daily: [+ { total_brand_mentions: 20, total_competitor_mentions: 80 },+ { total_brand_mentions: 30, total_competitor_mentions: 70 },+ ],+ insights_aggregates_daily: [{ total_citations: 700 }, { total_citations: 300 }],+ };+ let writes = mockWrites({ tracking_runs: missing([3, 4, 5, 6]) });+ weeks(sources);++ expect(+ await validateAction(action({ kpi_keys: ['share_of_voice', 'citations'] }), { now: NOW }),+ ).toBe('improved');+ const { validation } = writes.updated.find((w) => w.table === 'actions').patch;+ expect(validation.gaps).toEqual({ before: 0, after: 4, tooMany: true });+ // Too few nights to scale from: the counts stay as read.+ expect(validation.metrics[1]).toEqual({+ metric: 'citations',+ unit: 'count',+ before: 700,+ after: 300,+ });++ // Its main metric a count: the weeks can't be compared.+ writes = mockWrites({ tracking_runs: missing([3, 4, 5, 6]) });+ expect(+ await validateAction(action({ kpi_keys: ['citations', 'share_of_voice'] }), { now: NOW }),+ ).toBe('not_measurable');+ });++ it('reads it not measurable past MAX_GAP_DAYS when its main metric is a count', async () => {+ const writes = mockWrites({ tracking_runs: missing([3, 4, 5, 6]) });+ rpc+ .mockResolvedValueOnce({ data: { total_citations: 100 }, error: null })+ .mockResolvedValueOnce({ data: { total_citations: 60 }, error: null });++ expect(await validateAction(action(), { now: NOW })).toBe('not_measurable');+ const patch = writes.updated.find((w) => w.table === 'actions').patch;+ expect(patch.validation.gaps).toEqual({ before: 0, after: 4, tooMany: true });+ // The figures stay, to see.+ expect(patch.validation.metrics[0]).toMatchObject({ before: 100, after: 60 });+ expect(MAX_GAP_DAYS).toBe(2);+ });++ it('doesn’t count nights for metrics tracking doesn’t read (AI sessions)', async () => {+ const writes = mockWrites({ tracking_runs: [] });+ rpc.mockResolvedValue({ data: {}, error: null });+ await validateAction(action({ kpi_keys: ['ai_referral_traffic'] }), { now: NOW });+ const { validation } = writes.updated.find((w) => w.table === 'actions').patch;+ expect(validation?.gaps).toBeUndefined();+ });++ it('doesn’t count nights for a rate alone: it doesn’t drift from a missed one', async () => {+ const writes = mockWrites({ tracking_runs: [] });+ weeks({+ share_of_voice_aggregates_daily: [+ { total_brand_mentions: 20, total_competitor_mentions: 80 },+ { total_brand_mentions: 30, total_competitor_mentions: 70 },+ ],+ });++ expect(await validateAction(action({ kpi_keys: ['share_of_voice'] }), { now: NOW })).toBe(+ 'improved',+ );+ const { validation } = writes.updated.find((w) => w.table === 'actions').patch;+ expect(validation.gaps).toBeUndefined();+ });+ });+it('does nothing for an action that never closed', async () => {const writes = mockWrites();diff --git a/web/messages/en.json b/web/messages/en.jsonindex 0b1debffe..240f43c74 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2597,6 +2597,8 @@"measuredOn": "Measured on the {entity, select, pages {{count, plural, one {page} other {# pages}}} other {{count, plural, one {prompt} other {# prompts}}}} it named.","brandWide": "Brand-wide over the same days: {list}","primary": "Judged by {metric}, its main metric.",+ "gaps": "Tracking missed {before, plural, =0 {} one {# night of the week before it} other {# nights of the week before it}}{before, plural, =0 {} other {{after, plural, =0 {} other { and }}}}{after, plural, =0 {} one {# night of the week after it} other {# nights of the week after it}}: mentions and citations are counted as for a full week.",+ "gapsTooMany": "Tracking missed {before, plural, =0 {} one {# night of the week before it} other {# nights of the week before it}}{before, plural, =0 {} other {{after, plural, =0 {} other { and }}}}{after, plural, =0 {} one {# night of the week after it} other {# nights of the week after it}}: too many to compare mentions and citations fairly, so they are left out of the result.","auditAfter": "Audited again since it closed: {passed} of {audited} {audited, plural, one {page passes} other {pages pass}}.","auditNotYet": "None of its {pages, plural, one {page} other {# pages}} was audited again since it closed: the result is from the metrics.","signalsAfter": "Of the {total, plural, one {signal} other {# signals}} that raised it, when measured: {ended} ended{replaced, plural, =0 {} other {, # turned into another}}{dismissed, plural, =0 {} other {, # dismissed}}{open, plural, =0 {} other {, # still open}}.",diff --git a/web/src/components/action-center/history-drawer.test.tsx b/web/src/components/action-center/history-drawer.test.tsxindex 796668ca0..80d830ba8 100644--- a/web/src/components/action-center/history-drawer.test.tsx+++ b/web/src/components/action-center/history-drawer.test.tsx@@ -225,6 +225,33 @@ describe('HistoryDrawer', () => {);});+ it('says which nights tracking missed, and when too many to compare (learning A6)', async () => {+ getActionSignals.mockResolvedValue([]);+ render(+ <HistoryDrawer+ brandId="b1"+ item={{ ...item, dataGaps: { before: 1, after: 2, tooMany: false } }}+ onOpenChange={() => {}}+ />,+ );+ await act(async () => {});+ expect(under('Result')).toContain(+ 'Tracking missed 1 night of the week before it and 2 nights of the week after it: mentions and citations are counted as for a full week.',+ );++ render(+ <HistoryDrawer+ brandId="b1"+ item={{ ...item, dataGaps: { before: 0, after: 4, tooMany: true } }}+ onOpenChange={() => {}}+ />,+ );+ await act(async () => {});+ expect(under('Result')).toContain(+ 'Tracking missed 4 nights of the week after it: too many to compare mentions and citations fairly, so they are left out of the result.',+ );+ });+it('says a dismissed action was not measured, not that nothing could be read', async () => {getActionSignals.mockResolvedValue([]);for (const outcome of ['not_measurable', 'pending_measurement'] as const) {diff --git a/web/src/components/action-center/history-drawer.tsx b/web/src/components/action-center/history-drawer.tsxindex 2da44506d..9ead85245 100644--- a/web/src/components/action-center/history-drawer.tsx+++ b/web/src/components/action-center/history-drawer.tsx@@ -218,6 +218,14 @@ export function HistoryDrawer({{t('drawer.measuredOn', { ...item.measuredOn })}</p>)}+ {item.dataGaps && (+ <p className="mt-1 text-xs text-amber-700 dark:text-amber-400">+ {t(item.dataGaps.tooMany ? 'drawer.gapsTooMany' : 'drawer.gaps', {+ before: item.dataGaps.before,+ after: item.dataGaps.after,+ })}+ </p>+ )}{item.auditAfter && (// A fix's own aim: does the page pass when audited again?<p className="mt-1 text-xs">diff --git a/web/src/lib/action-center/history.ts b/web/src/lib/action-center/history.tsindex 686782b1b..d6178c647 100644--- a/web/src/lib/action-center/history.ts+++ b/web/src/lib/action-center/history.ts@@ -122,6 +122,11 @@ export interface ActionHistoryItem {* A1), with the brand-wide figures kept as a second line.*/measuredOn?: { entity: 'prompts' | 'pages'; count: number } | null;+ /**+ * Nights tracking missed in its before and after windows (learning A6);+ * `tooMany` when past the limit, the result then not measurable.+ */+ dataGaps?: { before: number; after: number; tooMany: boolean } | null;/** The metric its result is judged by (learning A4); absent before it was measured. */primaryMetric?: string | null;/** A Site Audit fix's pages audited again since it closed, and how many pass (learning A2). */diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.tsindex c2496c1dd..54c888d2f 100644--- a/web/src/lib/actions/action-history.ts+++ b/web/src/lib/actions/action-history.ts@@ -77,6 +77,18 @@ interface ValidationSnapshot {audit?: { pages?: number; audited?: number; passed?: number };/** The metric its result is judged by (learning A4). */primary?: string;+ /** Nights tracking missed in each window (learning A6). */+ gaps?: { before?: number; after?: number; tooMany?: boolean };+}++/** Nights tracking missed in its windows, when there were any. */+function gapsFrom(+ validation: ValidationSnapshot | null,+): { before: number; after: number; tooMany: boolean } | null {+ const g = validation?.gaps;+ const before = Number(g?.before) || 0;+ const after = Number(g?.after) || 0;+ return before || after ? { before, after, tooMany: g?.tooMany === true } : null;}/** A Site Audit fix's pages audited again, when the sweep read them. */@@ -313,6 +325,7 @@ export async function getActionHistory(signalsAfter: signalsFrom(row.validation),measuredOn: measuredOnFrom(row.validation),auditAfter: auditFrom(row.validation),+ dataGaps: gapsFrom(row.validation),// Shown only when it was measured: a main metric with no pair says nothing.primaryMetric: resultsFrom(row.validation).some((m) => m.metric === row.validation?.primary)? (row.validation?.primary ?? null)