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): judge a Site Audit fix by its pages audited again since it closed (learning A2) (#1689)
Cihana1db5200f1c7
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdxindex f6d44027f..9ae5891fb 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**, **No meaningful change** or **Declined**. 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. 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**, **No meaningful change** or **Declined**. 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. 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.- A dismissed action is **Not measurable**, and so is one with no metric to read.- 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/lib/action-center/audit-recheck.js b/server/src/lib/action-center/audit-recheck.jsnew file mode 100644index 000000000..6f2a05470--- /dev/null+++ b/server/src/lib/action-center/audit-recheck.js@@ -0,0 +1,97 @@+import supabaseAdmin from '../../config/supabase.js';+import { resolve } from '../../config/action-engine.js';+import { pageScope } from './basket-metrics.js';++/**+ * Did a Site Audit fix take? (learning A2.) F01, F03 and F10 had no metric+ * to measure (their signals name none), so their result always read "could+ * not be measured", and the audit's own answer was never asked: does the+ * page pass now? This reads it from the audits run on the action's pages+ * since it closed.+ */++const { detection } = resolve();++/** A check's status that says the issue it raised is gone: as the Action Center's page check reads it. */+const passes = (key, status) =>+ status === 'pass' || status === 'na' || (status === 'warn' && key !== 'json-ld-validity');++const keyOf = (url) => pageScope([url]).keys[0] ?? null;++/**+ * Whether a Site Audit fix's pages pass in the latest audit of each run+ * since the action closed: a page whose target names the checks that raised+ * it (F03 structured data, F10 internal links…) when every one of them+ * passes; a low-scored page (F01) when its score is past the low-score line+ * the signal is raised under. `{ pages, audited, passed }`: the pages it can+ * tell about, those audited again, those passing. Null for an action with no+ * such page.+ */+export async function auditRecheck(action) {+ if (!action.completed_at) return null;+ const lowScore = action.kind === 'fix_low_scores';+ const targets = (Array.isArray(action.payload?.targets) ? action.payload.targets : []).filter(+ (t) =>+ typeof t?.id === 'string' &&+ /^https?:\/\//i.test(t.id) &&+ (lowScore || (Array.isArray(t.checks) && t.checks.length > 0)),+ );+ if (!targets.length) return null;++ const { data: audits, error } = await supabaseAdmin+ .from('site_audits')+ .select('id, url, final_url, total_score')+ .eq('brand_id', action.brand_id)+ .eq('status', 'completed')+ .gt('completed_at', action.completed_at)+ .order('completed_at', { ascending: false })+ .limit(500);+ if (error) throw new Error(`site_audits: ${error.message}`);+ // Each page's latest audit, by the address it was asked for or ended at.+ const latest = new Map();+ for (const audit of audits ?? []) {+ for (const url of [audit.url, audit.final_url]) {+ const key = url ? keyOf(url) : null;+ if (key && !latest.has(key)) latest.set(key, audit);+ }+ }+ const found = targets+ .map((target) => ({ target, audit: latest.get(keyOf(target.id)) }))+ .filter((f) => f.audit);+ if (!found.length) return { pages: targets.length, audited: 0, passed: 0 };++ if (lowScore) {+ const passed = found.filter(+ ({ audit }) =>+ audit.total_score != null && Number(audit.total_score) * 100 >= detection.auditLowScore,+ ).length;+ return { pages: targets.length, audited: found.length, passed };+ }++ const checks = [...new Set(found.flatMap(({ target }) => target.checks))];+ const { data: results, error: resultsError } = await supabaseAdmin+ .from('audit_signal_results')+ .select('audit_id, signal_key, status')+ .in(+ 'audit_id',+ found.map(({ audit }) => audit.id),+ )+ .in('signal_key', checks);+ if (resultsError) throw new Error(`audit_signal_results: ${resultsError.message}`);+ const statusOf = new Map((results ?? []).map((r) => [`${r.audit_id}|${r.signal_key}`, r.status]));+ const passed = found.filter(({ target, audit }) =>+ target.checks.every((key) => passes(key, statusOf.get(`${audit.id}|${key}`))),+ ).length;+ return { pages: targets.length, audited: found.length, passed };+}++/**+ * A fix's verdict from its pages audited again: its aim is the check+ * passing, more than any metric over a week. All passing reads improved;+ * none, no meaningful change; some, improved (part of the work took).+ */+export function auditOutcome({ audited, passed }) {+ if (!audited) return null;+ if (passed === 0) return 'no_meaningful_change';+ return 'improved';+}diff --git a/server/src/lib/action-center/audit-recheck.test.js b/server/src/lib/action-center/audit-recheck.test.jsnew file mode 100644index 000000000..ec8332f3d--- /dev/null+++ b/server/src/lib/action-center/audit-recheck.test.js@@ -0,0 +1,120 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** Did a Site Audit fix take? Its pages audited again since it closed (learning A2). */++let tables;+const reads = [];+vi.mock('../../config/supabase.js', () => ({+ default: {+ from: (table) => {+ const q = { table, filters: [] };+ const chain = {+ select: () => chain,+ eq: (...a) => (q.filters.push(['eq', ...a]), chain),+ gt: (...a) => (q.filters.push(['gt', ...a]), chain),+ in: (...a) => (q.filters.push(['in', ...a]), chain),+ order: () => chain,+ limit: () => chain,+ then: (resolve) => {+ reads.push(q);+ return resolve({ data: tables[table] ?? [], error: null });+ },+ };+ return chain;+ },+ },+}));++const { auditOutcome, auditRecheck } = await import('./audit-recheck.js');+const { resolve } = await import('../../config/action-engine.js');+const LOW = resolve().detection.auditLowScore;++const action = (over = {}) => ({+ id: 'a1',+ brand_id: 'b1',+ kind: 'fix_structured_data',+ completed_at: '2026-10-01T00:00:00Z',+ payload: {+ targetEntity: 'pages',+ targets: [+ { id: 'https://acme.example/pricing', checks: ['json-ld-validity'] },+ { id: 'https://acme.example/faq', checks: ['faq-schema', 'json-ld-relevance'] },+ { id: 'https://acme.example/about', checks: ['json-ld-presence'] },+ ],+ },+ ...over,+});++beforeEach(() => {+ reads.length = 0;+ tables = {+ site_audits: [+ // The latest first, as read: /pricing's newer audit counts, not the older one.+ { id: 'au3', url: 'https://www.acme.example/pricing/', final_url: null, total_score: 0.8 },+ { id: 'au1', url: 'https://acme.example/pricing', final_url: null, total_score: 0.4 },+ {+ id: 'au2',+ url: 'http://acme.example/go',+ final_url: 'https://acme.example/faq',+ total_score: 0.5,+ },+ ],+ audit_signal_results: [+ { audit_id: 'au3', signal_key: 'json-ld-validity', status: 'pass' },+ { audit_id: 'au1', signal_key: 'json-ld-validity', status: 'fail' },+ { audit_id: 'au2', signal_key: 'faq-schema', status: 'pass' },+ // Relevance's warn: types, none from the high-value list — the issue it raised is gone.+ { audit_id: 'au2', signal_key: 'json-ld-relevance', status: 'warn' },+ ],+ };+});++describe('auditRecheck', () => {+ it('counts the pages audited again since it closed whose named checks pass', async () => {+ expect(await auditRecheck(action())).toEqual({ pages: 3, audited: 2, passed: 2 });+ const audits = reads.find((r) => r.table === 'site_audits').filters;+ expect(audits).toContainEqual(['gt', 'completed_at', '2026-10-01T00:00:00Z']);+ expect(audits).toContainEqual(['eq', 'status', 'completed']);+ });++ it('reads validity’s warn as still failing, and a check with no result as not passing', async () => {+ tables.audit_signal_results = [+ { audit_id: 'au3', signal_key: 'json-ld-validity', status: 'warn' },+ { audit_id: 'au2', signal_key: 'faq-schema', status: 'pass' },+ ];+ expect(await auditRecheck(action())).toEqual({ pages: 3, audited: 2, passed: 0 });+ });++ it('passes a low-scored page (F01) once its score is past the line the signal is raised under', async () => {+ tables.site_audits = [+ { id: 'au3', url: 'https://acme.example/pricing', total_score: LOW / 100 },+ { id: 'au2', url: 'https://acme.example/faq', total_score: LOW / 100 - 0.01 },+ ];+ const low = action({+ kind: 'fix_low_scores',+ payload: {+ targets: [{ id: 'https://acme.example/pricing' }, { id: 'https://acme.example/faq' }],+ },+ });+ expect(await auditRecheck(low)).toEqual({ pages: 2, audited: 2, passed: 1 });+ expect(reads.some((r) => r.table === 'audit_signal_results')).toBe(false);+ });++ it('is null with no page it can tell about, and says when none was audited again', async () => {+ expect(+ await auditRecheck(action({ payload: { targets: [{ id: 'https://acme.example/x' }] } })),+ ).toBeNull();+ expect(await auditRecheck(action({ completed_at: null }))).toBeNull();+ tables.site_audits = [];+ expect(await auditRecheck(action())).toEqual({ pages: 3, audited: 0, passed: 0 });+ });+});++describe('auditOutcome', () => {+ it('judges a fix by its pages audited again, and leaves it to the metrics with none', () => {+ expect(auditOutcome({ audited: 2, passed: 2 })).toBe('improved');+ expect(auditOutcome({ audited: 2, passed: 1 })).toBe('improved');+ expect(auditOutcome({ audited: 2, passed: 0 })).toBe('no_meaningful_change');+ expect(auditOutcome({ audited: 0, passed: 0 })).toBeNull();+ });+});diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.jsindex a3826087c..13b5e93e9 100644--- a/server/src/lib/action-center/validate.js+++ b/server/src/lib/action-center/validate.js@@ -28,6 +28,7 @@ import { computeAiVisibilityScore } from '../../config/visibility-score.js';import { logger } from '../logger.js';import { resolve } from '../../config/action-engine.js';import { BASKET_KPIS, basketScope, measureBasket } from './basket-metrics.js';+import { auditOutcome, auditRecheck } from './audit-recheck.js';const DAY_MS = 86_400_000;@@ -308,9 +309,21 @@ export async function validateAction(action, { now = new Date() } = {}) {// action, and would file most recent work as a decline.if (afterWindow.to >= utcDay(now)) return null;- // What became of the signals that raised it, kept beside the metrics.- const signals = await signalOutcome(action.id);- const withSignals = (validation) => (signals ? { ...validation, signals } : validation);+ // What became of the signals that raised it (A3), and for a Site Audit+ // fix whether its pages pass when audited again (A2), kept beside the+ // metrics. A fix whose pages were audited again is judged by that: the+ // check passing is its aim.+ const [signals, audit] = await Promise.all([signalOutcome(action.id), auditRecheck(action)]);+ const finish = async (validation, outcome) => {+ const beside = { ...(signals ? { signals } : {}), ...(audit ? { audit } : {}) };+ const kept =+ validation || Object.keys(beside).length+ ? { measuredAt: now.toISOString(), ...(validation ?? {}), ...beside }+ : null;+ const verdict = (audit && auditOutcome(audit)) ?? outcome;+ await write(action.id, kept, verdict, now);+ return verdict;+ };// An action sent from a content opportunity is measured on its own prompts// and pages; the brand-wide numbers would bury a single piece of content.@@ -339,20 +352,16 @@ export async function validateAction(action, { now = new Date() } = {}) {before: before[metric],after: after[metric],}));- const outcome = deriveOutcome(metrics);- await write(- action.id,- withSignals({+ return finish(+ {measuredAt: now.toISOString(),beforeWindow,afterWindow,metrics,scope: { kind: 'basket', prompts: scope.promptIds.length, pages: scope.pages.length },- }),- outcome,- now,+ },+ deriveOutcome(metrics),);- return outcome;}const kpiKeys = (action.kpi_keys ?? []).filter((key) => key in MEASURABLE_KPIS);@@ -387,10 +396,8 @@ export async function validateAction(action, { now = new Date() } = {}) {before: brandBefore[metric] ?? null,after: brandAfter[metric] ?? null,}));- const outcome = deriveOutcome(metrics);- await write(- action.id,- withSignals({+ return finish(+ {measuredAt: now.toISOString(),beforeWindow,afterWindow,@@ -402,26 +409,16 @@ export async function validateAction(action, { now = new Date() } = {}) {pages: targets.pages.length,},...(brandWide.length ? { brandWide } : {}),- }),- outcome,- now,+ },+ deriveOutcome(metrics),);- return outcome;}}// An action with no success metrics has nothing to measure. That is a gap// in the rule that produced it, not a failure here — say so plainly rather// than inventing a metric it never claimed.- if (kpiKeys.length === 0) {- await write(- action.id,- signals ? { measuredAt: now.toISOString(), signals } : null,- 'not_measurable',- now,- );- return 'not_measurable';- }+ if (kpiKeys.length === 0) return finish(null, 'not_measurable');const [before, after] = await Promise.all([measureKpis(action.brand_id, kpiKeys, beforeWindow.from, beforeWindow.to),@@ -435,14 +432,10 @@ export async function validateAction(action, { now = new Date() } = {}) {after: after[metric] ?? null,}));- const outcome = deriveOutcome(metrics);- await write(- action.id,- withSignals({ measuredAt: now.toISOString(), beforeWindow, afterWindow, metrics }),- outcome,- now,+ return finish(+ { measuredAt: now.toISOString(), beforeWindow, afterWindow, metrics },+ deriveOutcome(metrics),);- return outcome;}async function write(actionId, validation, outcome, now) {diff --git a/server/src/lib/action-center/validate.test.js b/server/src/lib/action-center/validate.test.jsindex b02bb379f..32ddebea9 100644--- a/server/src/lib/action-center/validate.test.js+++ b/server/src/lib/action-center/validate.test.js@@ -33,6 +33,8 @@ function mockWrites(rows = {}) {not: () => builder,limit: () => builder,order: () => builder,+ gt: () => builder,+ in: () => builder,maybeSingle: async () => ({ data: (rows[table] ?? [])[0] ?? null, error: null }),update: (patch) => {writes.updated.push({ table, patch });@@ -465,6 +467,36 @@ describe('validateAction', () => {});});+ it('judges a Site Audit fix by its pages audited again since it closed (learning A2)', async () => {+ const writes = mockWrites({+ site_audits: [{ id: 'au1', url: 'https://acme.example/pricing', total_score: 0.7 }],+ audit_signal_results: [{ audit_id: 'au1', signal_key: 'json-ld-validity', status: 'pass' }],+ });+ // The page's citations didn't move over the week.+ rpc.mockResolvedValue({ data: { page_citations: 3 }, error: null });++ const outcome = await validateAction(+ action({+ kind: 'fix_structured_data',+ kpi_keys: [],+ payload: {+ targetEntity: 'pages',+ targets: [{ id: 'https://acme.example/pricing', checks: ['json-ld-validity'] }],+ },+ }),+ { now: NOW },+ );++ expect(outcome).toBe('improved');+ const patch = writes.updated.find((w) => w.table === 'actions').patch;+ expect(patch.outcome).toBe('improved');+ expect(patch.validation.audit).toEqual({ pages: 1, audited: 1, passed: 1 });+ expect(patch.validation.metrics.find((m) => m.metric === 'citations')).toMatchObject({+ before: 3,+ after: 3,+ });+ });+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 ea8c01df7..bf0ce197b 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2592,6 +2592,8 @@"triggeredBy": "Consolidated from {count, plural, one {# signal} other {# signals}}","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}",+ "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}}.","result": "Result","visibilityChange": "Visibility Change",diff --git a/web/src/components/action-center/history-drawer.test.tsx b/web/src/components/action-center/history-drawer.test.tsxindex 7254e83a8..2dcdc9fc3 100644--- a/web/src/components/action-center/history-drawer.test.tsx+++ b/web/src/components/action-center/history-drawer.test.tsx@@ -183,6 +183,31 @@ describe('HistoryDrawer', () => {expect(result).toMatch(/Brand-wide over the same days: \S.* 100 → 104/);});+ it('says how a Site Audit fix’s pages read when audited again, or that none was yet (learning A2)', async () => {+ getActionSignals.mockResolvedValue([]);+ render(+ <HistoryDrawer+ brandId="b1"+ item={{ ...item, auditAfter: { pages: 3, audited: 2, passed: 1 } }}+ onOpenChange={() => {}}+ />,+ );+ await act(async () => {});+ expect(under('Result')).toContain('Audited again since it closed: 1 of 2 pages pass.');++ render(+ <HistoryDrawer+ brandId="b1"+ item={{ ...item, auditAfter: { pages: 3, audited: 0, passed: 0 } }}+ onOpenChange={() => {}}+ />,+ );+ await act(async () => {});+ expect(under('Result')).toContain(+ 'None of its 3 pages was audited again since it closed: the result is from the metrics.',+ );+ });+it('keeps the general sentences when the signals cannot be read', async () => {getActionSignals.mockRejectedValue(new Error('offline'));render(<HistoryDrawer brandId="b1" item={item} onOpenChange={() => {}} />);diff --git a/web/src/components/action-center/history-drawer.tsx b/web/src/components/action-center/history-drawer.tsxindex 0bc4adea3..601de6853 100644--- a/web/src/components/action-center/history-drawer.tsx+++ b/web/src/components/action-center/history-drawer.tsx@@ -213,6 +213,14 @@ export function HistoryDrawer({{t('drawer.measuredOn', { ...item.measuredOn })}</p>)}+ {item.auditAfter && (+ // A fix's own aim: does the page pass when audited again?+ <p className="mt-1 text-xs">+ {item.auditAfter.audited+ ? t('drawer.auditAfter', { ...item.auditAfter })+ : t('drawer.auditNotYet', { pages: item.auditAfter.pages })}+ </p>+ )}{item.signalsAfter && (// The closest measure to the action's own aim: did what raised it end?<p className="mt-1 text-xs">{t('drawer.signalsAfter', { ...item.signalsAfter })}</p>diff --git a/web/src/lib/action-center/history.ts b/web/src/lib/action-center/history.tsindex dcf1960b6..c44074924 100644--- a/web/src/lib/action-center/history.ts+++ b/web/src/lib/action-center/history.ts@@ -122,6 +122,8 @@ export interface ActionHistoryItem {* A1), with the brand-wide figures kept as a second line.*/measuredOn?: { entity: 'prompts' | 'pages'; count: number } | null;+ /** A Site Audit fix's pages audited again since it closed, and how many pass (learning A2). */+ auditAfter?: { pages: number; audited: number; passed: number } | null;brandWideResults?: ActionResultMetric[];/** Improve actions only: positions per platform against the baseline (PROMPT-008). */positionOutcome: ImproveOutcome | null;diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.tsindex 92e0503d6..f231fed4d 100644--- a/web/src/lib/actions/action-history.ts+++ b/web/src/lib/actions/action-history.ts@@ -73,6 +73,18 @@ interface ValidationSnapshot {scope?: { kind?: string; entity?: string; prompts?: number; pages?: number };/** The brand-wide figures, beside a measure on its targets. */brandWide?: ValidationSnapshot['metrics'];+ /** A Site Audit fix's pages audited again (learning A2). */+ audit?: { pages?: number; audited?: number; passed?: number };+}++/** A Site Audit fix's pages audited again, when the sweep read them. */+function auditFrom(+ validation: ValidationSnapshot | null,+): { pages: number; audited: number; passed: number } | null {+ const a = validation?.audit;+ const pages = Number(a?.pages) || 0;+ if (!pages) return null;+ return { pages, audited: Number(a?.audited) || 0, passed: Number(a?.passed) || 0 };}/** The prompts or pages it was measured on, when it was measured on its own targets. */@@ -298,6 +310,7 @@ export async function getActionHistory(results,signalsAfter: signalsFrom(row.validation),measuredOn: measuredOnFrom(row.validation),+ auditAfter: auditFrom(row.validation),brandWideResults: resultsFrom(row.validation?.brandWide ? { ...row.validation, metrics: row.validation.brandWide } : null,),