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): send a page from its Site Audit report to the Action Center (learning D2) (#1709)

Cihanfe7ace369d04
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdx
index 558933816..b661a086c 100644
--- a/docs/guides/action-center.mdx
+++ b/docs/guides/action-center.mdx
@@ -213,7 +213,7 @@ Most actions are generated from signals each night. You can also send work to th
|---|---|
| **Mentions** | Select answers on the Mentions tab, or open one, and click **Send to Action Center**. |
| **Content** | **Send to Actions** on a content opportunity; **Assign to…** on a Content Plan row; or **Who does it → Team** when you start new content. See [Content Editor](/guides/content-editor). |
-| **Site Audit** | Audit results become signals with the Site Audit source, such as low AEO scores or missing structured data, and turn into Fix actions overnight. |
+| **Site Audit** | Audit results become signals with the Site Audit source, such as low AEO scores or missing structured data, and turn into Fix actions overnight. To send one page now, click **Send to Action Center** on its audit report: the page and the checks it fails go as one Fix action. |
| **AI Traffic** | On the [AI Traffic Analytics](/guides/ai-traffic-analytics) pages list, select pages under *Cited, not clicked* or *No AI traffic* and click **Send to Action Center**. Traffic drops and strong or weak landing pages also arrive as signals. |
| **Insights** | **Send action** on a topic in Insights' Opportunities opens a Growth action for it. |
| **Prompts** | **Send Actions** on a prompt's Improve tab sends the selected suggestions as one action. |
diff --git a/docs/guides/site-audit.mdx b/docs/guides/site-audit.mdx
index 542f97e39..0d2c09ed4 100644
--- a/docs/guides/site-audit.mdx
+++ b/docs/guides/site-audit.mdx
@@ -87,7 +87,7 @@ Click a row to open its latest report. The arrow beside a page lists its earlier
## The audit report
-Each audit has its own report at `/dashboard/audit/[id]`. The icons at the top re-run the audit on the same URL or delete it (**Delete audit** can't be undone).
+Each audit has its own report at `/dashboard/audit/[id]`. The icons at the top re-run the audit on the same URL or delete it (**Delete audit** can't be undone). On a page that fails checks, **Send to Action Center** sends the page and the checks it fails as one Fix action, without waiting for the nightly pass (see below). Sent again while that action is open, it doesn't add another: a notice names the open action (AC-…) with **Open**. Only a page's latest report can be sent; an older one's notice offers **Open the latest report**.
### Total score
@@ -172,6 +172,8 @@ Each night the Action Center reads the latest audit of each page from the last 9
An action lists the pages it covers and the failed checks on each, with a link to **Open Site Audit**. Re-audit the pages after you fix them: only each page's latest audit counts, so once the new audit no longer fails the check, the Action Center stops reporting that page. An audit older than 90 days no longer counts either.
+You can also send one page yourself from its report with **Send to Action Center** (see [The audit report](#the-audit-report)). The action names the page and the checks it fails, takes the Fix low-scoring pages plan, and is measured on the page's citations and AI visits. Like a nightly Site Audit fix, once you complete it, it is judged by the page audited again since it closed: the checks it failed passing. Until the page is audited again, the metrics judge it.
+
The **Audit Score** section of [Reports](/guides/reports) brings your audit scores into a report.
<Card title="Continue: Reports" icon="arrow-right" href="/guides/reports">
diff --git a/server/src/lib/action-center/from-audit.js b/server/src/lib/action-center/from-audit.js
new file mode 100644
index 000000000..fe242ea66
--- /dev/null
+++ b/server/src/lib/action-center/from-audit.js
@@ -0,0 +1,224 @@
+/**
+ * "Send to Action Center" from a Site Audit report (learning D2): the page
+ * and the checks it fails, sent as one Fix action.
+ *
+ * The audit is read again here, by its id, within the brand: the page, its
+ * score and its failing checks as the database has them, not as a client
+ * says they are. The action names its page and those checks as its target,
+ * so the Action Center can tell whether the fix took once the page is
+ * audited again, as it does for a nightly Site Audit fix. Measured
+ * afterwards on its page like any person-sent action (basket-metrics.js):
+ * its citations and AI-referred sessions.
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+import { resolve } from '../../config/action-engine.js';
+import { describeSignal } from '../audit/rubric.js';
+import { opportunityKey } from '../audit/opportunities.js';
+import { readAllRpcRows } from '../rpc-pages.js';
+import fixLowScores from './definitions/f01-fix-low-scores.js';
+import { priorityOnCreate } from './priority-data.js';
+import { resolveBrandSources } from './sources.js';
+import { planTasks } from './tasks/plan.js';
+
+export const AUDIT_PAGE_ACTION_KIND = 'audit_page';
+
+const ACTIVE = ['new', 'in_progress', 'on_hold'];
+const KPI_KEYS = ['citations', 'ai_referral_traffic'];
+
+const { detection } = resolve();
+
+function httpError(message, status, code, extra) {
+ const err = new Error(message);
+ err.status = status;
+ if (code) err.code = code;
+ if (extra) err.extra = extra;
+ return err;
+}
+
+/** A check's status that says the page fails it: as the Action Center's page check reads it. */
+export function failing(key, status) {
+ return status === 'fail' || (status === 'warn' && key === 'json-ld-validity');
+}
+
+/** One open action per page: the same page sent again finds it. */
+export function auditDedupKey(url) {
+ return `${AUDIT_PAGE_ACTION_KIND}:${opportunityKey(url) ?? url}`;
+}
+
+/**
+ * The page's latest completed audit after this one, if any: the one its row
+ * on the Pages list opens (one page per opportunityKey of final_url, else
+ * url). Read newest first, so the first of the page's is the latest.
+ */
+async function newerAuditOf(audit) {
+ const key = opportunityKey(audit.final_url || audit.url);
+ if (!key || !audit.created_at) return null;
+ const { data, error } = await readAllRpcRows('site_audits', (from, to) =>
+ supabaseAdmin
+ .from('site_audits')
+ .select('id, url, final_url')
+ .eq('brand_id', audit.brand_id)
+ .eq('status', 'completed')
+ .not('total_score', 'is', null)
+ .gt('created_at', audit.created_at)
+ .order('created_at', { ascending: false })
+ .order('id', { ascending: false })
+ .range(from, to),
+ );
+ if (error) throw new Error(error.message);
+ return (
+ (data ?? []).find(
+ (row) => row.id !== audit.id && opportunityKey(row.final_url || row.url) === key,
+ ) ?? null
+ );
+}
+
+/** High below the low-score line the nightly F01 is raised under; more failures, more urgent. */
+export function auditImpact(score, failures) {
+ if (score != null && Number(score) * 100 < detection.auditLowScore) return 'high';
+ return failures >= 3 ? 'medium' : 'low';
+}
+
+/**
+ * Creates the action, or returns the one open for the page. Refused (409)
+ * for an audit not finished, one the page has a newer completed audit than
+ * (`newer_audit`, with `extra.latestAuditId`), and one with nothing to fix.
+ *
+ * @param {string} brandId - checked against the caller's org by the route
+ * @param {{ auditId: string, userId: string }} opts
+ * @returns {Promise<{ actionId: string, actionNo: number, created: boolean }>}
+ */
+export async function sendAuditToActionCenter(brandId, { auditId, userId }) {
+ const { data: audit, error: auditErr } = await supabaseAdmin
+ .from('site_audits')
+ .select('id, brand_id, url, final_url, status, total_score, created_at')
+ .eq('id', auditId)
+ .eq('brand_id', brandId)
+ .maybeSingle();
+ if (auditErr) throw new Error(auditErr.message);
+ if (!audit) throw httpError('Audit not found', 404, 'not_found');
+ if (audit.status !== 'completed') {
+ throw httpError('The audit hasn’t finished', 409, 'not_completed');
+ }
+ // An older report of the page: what it failed then may be fixed by now.
+ const newer = await newerAuditOf(audit);
+ if (newer) {
+ throw httpError('The page has a newer audit', 409, 'newer_audit', {
+ latestAuditId: newer.id,
+ });
+ }
+
+ const { data: results, error: resultsErr } = await supabaseAdmin
+ .from('audit_signal_results')
+ .select('signal_key, status')
+ .eq('audit_id', audit.id);
+ if (resultsErr) throw new Error(resultsErr.message);
+ const checks = (results ?? [])
+ .filter((r) => failing(r.signal_key, r.status))
+ .map((r) => ({
+ key: r.signal_key,
+ label: describeSignal(r.signal_key)?.label ?? r.signal_key,
+ }));
+ if (!checks.length) throw httpError('The page passes its checks', 409, 'nothing_to_fix');
+
+ const url = audit.final_url || audit.url;
+ const dedupKey = auditDedupKey(url);
+ const openAction = async () => {
+ const { data } = await supabaseAdmin
+ .from('actions')
+ .select('id, action_no')
+ .eq('brand_id', brandId)
+ .eq('dedup_key', dedupKey)
+ .in('status', ACTIVE)
+ .maybeSingle();
+ return data;
+ };
+ const open = await openAction();
+ if (open) return { actionId: open.id, actionNo: Number(open.action_no), created: false };
+
+ const score = audit.total_score == null ? null : Number(audit.total_score);
+ const impact = auditImpact(score, checks.length);
+ let path = url;
+ try {
+ path = new URL(url).pathname || '/';
+ } catch {
+ // Kept as given.
+ }
+ const payload = {
+ source: AUDIT_PAGE_ACTION_KIND,
+ auditId: audit.id,
+ url,
+ score,
+ checks,
+ // Measured on this page once done (basket-metrics.js).
+ pages: [url],
+ targetEntity: 'pages',
+ targetCount: 1,
+ targetIds: [url],
+ // The page and the checks it fails: what an audit run on it again reads.
+ targets: [{ id: url, label: path, checks: checks.map((c) => c.key) }],
+ };
+
+ const { data: action, error } = await supabaseAdmin
+ .from('actions')
+ .insert({
+ brand_id: brandId,
+ category: 'fix',
+ kind: AUDIT_PAGE_ACTION_KIND,
+ definition_version: 1,
+ impact,
+ payload,
+ kpi_keys: KPI_KEYS,
+ baseline: { score, failing: checks.length },
+ dedup_key: dedupKey,
+ ...(await priorityOnCreate({
+ kind: AUDIT_PAGE_ACTION_KIND,
+ category: 'fix',
+ impact,
+ payload,
+ })),
+ })
+ .select('id, action_no')
+ .single();
+ if (error) {
+ // Two sends at once: the other one opened it (the open-action dedup index, 00084).
+ if (error.code === '23505') {
+ const winner = await openAction();
+ if (winner) {
+ return { actionId: winner.id, actionNo: Number(winner.action_no), created: false };
+ }
+ }
+ throw new Error(error.message);
+ }
+
+ const sources = await resolveBrandSources(brandId);
+ const plan = planTasks(
+ { id: AUDIT_PAGE_ACTION_KIND, tasks: fixLowScores.tasks },
+ { sources, payload },
+ );
+ const { error: tasksErr } = await supabaseAdmin.from('action_tasks').insert(
+ plan.map((item) => ({
+ action_id: action.id,
+ position: item.position,
+ task_key: item.taskKey,
+ task_version: item.version,
+ mode: item.mode,
+ permission: item.permission,
+ depends_on: item.dependsOn,
+ title_params: item.titleParams,
+ details: item.details,
+ status: 'todo',
+ })),
+ );
+ if (tasksErr) throw new Error(tasksErr.message);
+
+ await supabaseAdmin.from('action_events').insert({
+ action_id: action.id,
+ event: 'created',
+ actor_id: userId,
+ data: { source: AUDIT_PAGE_ACTION_KIND, checks: checks.length, taskCount: plan.length },
+ });
+
+ return { actionId: action.id, actionNo: Number(action.action_no), created: true };
+}
diff --git a/server/src/lib/action-center/from-audit.test.js b/server/src/lib/action-center/from-audit.test.js
new file mode 100644
index 000000000..2d08a29f0
--- /dev/null
+++ b/server/src/lib/action-center/from-audit.test.js
@@ -0,0 +1,291 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * sendAuditToActionCenter (learning D2): a Site Audit report's page and the
+ * checks it fails as one Fix action. These pin that the audit is read again
+ * on the server within the brand, that only failing checks go (not one that
+ * isn't applicable), that an older report of a page audited since is
+ * refused, that the same page sent again (or twice at once) returns the open
+ * action, and that the action names its page and checks as its target and
+ * takes F01's plan, its audit tasks included.
+ */
+
+let db;
+
+function table(name) {
+ const state = { name, filters: {}, op: 'select', row: null };
+ const result = () => {
+ if (state.op === 'insert') {
+ db.inserts.push({ table: name, row: state.row });
+ if (name === 'actions') {
+ return db.insertError
+ ? { data: null, error: db.insertError }
+ : { data: { id: 'act-1', action_no: 71 }, error: null };
+ }
+ return { data: null, error: null };
+ }
+ return { data: db.rows[name]?.(state.filters) ?? null, error: null };
+ };
+ const chain = {
+ select: () => chain,
+ insert: (row) => {
+ state.op = 'insert';
+ state.row = row;
+ return chain;
+ },
+ eq: (col, val) => {
+ state.filters[col] = val;
+ return chain;
+ },
+ in: (col, val) => {
+ state.filters[col] = val;
+ return chain;
+ },
+ gt: (col, val) => {
+ state.filters[`${col}>`] = val;
+ return chain;
+ },
+ not: (col, op, val) => {
+ state.filters[`${col} not ${op}`] = val;
+ return chain;
+ },
+ order: () => chain,
+ limit: () => chain,
+ range: () => chain,
+ maybeSingle: async () => result(),
+ single: async () => result(),
+ then: (resolve, reject) => Promise.resolve(result()).then(resolve, reject),
+ };
+ return chain;
+}
+
+const rpc = vi.fn();
+vi.mock('../../config/supabase.js', () => ({
+ default: { from: (name) => table(name), rpc: (...args) => rpc(...args) },
+}));
+// A brand sending from a Site Audit report has its audits: F01's audit tasks plan.
+vi.mock('./sources.js', () => ({
+ resolveBrandSources: async () => new Set(['tracking', 'analytics', 'ai_traffic', 'site_audits']),
+}));
+vi.mock('./priority-data.js', () => ({
+ priorityOnCreate: async () => ({ priority_score: 61, priority_level: 'medium' }),
+}));
+
+const { AUDIT_PAGE_ACTION_KIND, auditDedupKey, auditImpact, failing, sendAuditToActionCenter } =
+ await import('./from-audit.js');
+
+const AUDIT = '11111111-2222-4333-8444-555555555555';
+const URL_ = 'https://acme.example/blog/espresso';
+
+beforeEach(() => {
+ db = {
+ inserts: [],
+ insertError: null,
+ newer: [],
+ newerRead: null,
+ rows: {
+ site_audits: (f) => {
+ // The brand's completed audits after the sent one (newer_audit).
+ if (f.id === undefined) {
+ db.newerRead = f;
+ return db.newer;
+ }
+ return f.id === AUDIT && f.brand_id === 'b1'
+ ? {
+ id: AUDIT,
+ brand_id: 'b1',
+ url: 'https://acme.example/blog/espresso?utm=x',
+ final_url: URL_,
+ status: 'completed',
+ total_score: 0.42,
+ created_at: '2026-10-20T10:00:00Z',
+ }
+ : null;
+ },
+ audit_signal_results: () => [
+ { signal_key: 'faq-schema', status: 'fail' },
+ { signal_key: 'tables', status: 'warn' },
+ { signal_key: 'json-ld-validity', status: 'warn' },
+ { signal_key: 'h1-quality', status: 'pass' },
+ ],
+ actions: () => null,
+ },
+ };
+});
+
+describe('failing', () => {
+ it('reads a fail, and a warn only for JSON-LD validity, as the page check does', () => {
+ expect(failing('faq-schema', 'fail')).toBe(true);
+ expect(failing('tables', 'warn')).toBe(false);
+ expect(failing('json-ld-validity', 'warn')).toBe(true);
+ expect(failing('h1-quality', 'pass')).toBe(false);
+ // Not applicable to the page: nothing to fix.
+ expect(failing('faq-schema', 'na')).toBe(false);
+ expect(failing('json-ld-validity', 'na')).toBe(false);
+ });
+});
+
+describe('auditImpact', () => {
+ it('is high below the low-score line, medium with three failures or more', () => {
+ expect(auditImpact(0.42, 1)).toBe('high');
+ expect(auditImpact(0.9, 3)).toBe('medium');
+ expect(auditImpact(0.9, 1)).toBe('low');
+ });
+});
+
+describe('sendAuditToActionCenter', () => {
+ it("sends the page and its failing checks as a Fix action, with F01's plan", async () => {
+ expect(await sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' })).toEqual({
+ actionId: 'act-1',
+ actionNo: 71,
+ created: true,
+ });
+ const action = db.inserts.find((i) => i.table === 'actions').row;
+ expect(action).toMatchObject({
+ brand_id: 'b1',
+ category: 'fix',
+ kind: AUDIT_PAGE_ACTION_KIND,
+ impact: 'high',
+ kpi_keys: ['citations', 'ai_referral_traffic'],
+ baseline: { score: 0.42, failing: 2 },
+ dedup_key: auditDedupKey(URL_),
+ });
+ expect(action.payload).toMatchObject({
+ auditId: AUDIT,
+ url: URL_,
+ pages: [URL_],
+ targetEntity: 'pages',
+ targetCount: 1,
+ // What an audit run on the page again reads.
+ targets: [{ id: URL_, label: '/blog/espresso', checks: ['faq-schema', 'json-ld-validity'] }],
+ });
+ expect(action.payload.checks.map((c) => c.key)).toEqual(['faq-schema', 'json-ld-validity']);
+ expect(action.payload.checks[0].label).toEqual(expect.any(String));
+ // F01's plan, its audit tasks included: the page's audit read first, the fix checked by the next.
+ const tasks = db.inserts.find((i) => i.table === 'action_tasks').row;
+ expect(tasks.map((task) => task.task_key)).toEqual([
+ 'analyze_site_audit',
+ 'prioritize_targets',
+ 'fix_technical_issue',
+ 'validate_technical_fix',
+ 'measure_action_outcome',
+ ]);
+ expect(tasks.map((task) => task.position)).toEqual([1, 2, 3, 4, 5]);
+ expect(tasks.every((task) => task.action_id === 'act-1' && task.status === 'todo')).toBe(true);
+ expect(db.inserts.find((i) => i.table === 'action_events').row).toMatchObject({
+ event: 'created',
+ actor_id: 'u1',
+ data: { source: AUDIT_PAGE_ACTION_KIND, checks: 2, taskCount: 5 },
+ });
+ });
+
+ it('leaves out a check that is not applicable to the page', async () => {
+ db.rows.audit_signal_results = () => [
+ { signal_key: 'faq-schema', status: 'na' },
+ { signal_key: 'json-ld-validity', status: 'na' },
+ { signal_key: 'tables', status: 'fail' },
+ ];
+ await sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' });
+ const action = db.inserts.find((i) => i.table === 'actions').row;
+ expect(action.payload.checks.map((c) => c.key)).toEqual(['tables']);
+ expect(action.baseline).toEqual({ score: 0.42, failing: 1 });
+
+ db.inserts = [];
+ db.rows.audit_signal_results = () => [
+ { signal_key: 'faq-schema', status: 'na' },
+ { signal_key: 'h1-quality', status: 'pass' },
+ ];
+ await expect(
+ sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' }),
+ ).rejects.toMatchObject({ status: 409, code: 'nothing_to_fix' });
+ expect(db.inserts).toEqual([]);
+ });
+
+ it('returns the action the other of two sends at once opened', async () => {
+ // Not open when read, open once the insert hits the open-action dedup index.
+ let reads = 0;
+ db.rows.actions = () => (reads++ === 0 ? null : { id: 'act-0', action_no: 70 });
+ db.insertError = { code: '23505', message: 'duplicate key value' };
+ expect(await sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' })).toEqual({
+ actionId: 'act-0',
+ actionNo: 70,
+ created: false,
+ });
+ expect(reads).toBe(2);
+ // Its plan and trail are the other send's.
+ expect(db.inserts.map((i) => i.table)).toEqual(['actions']);
+ });
+
+ it('fails when the insert is refused for another reason, or no action is open after all', async () => {
+ db.insertError = { code: '23505', message: 'duplicate key value' };
+ await expect(sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' })).rejects.toThrow(
+ 'duplicate key value',
+ );
+ // Another refusal isn't a send racing this one: no second read.
+ db.insertError = { code: '23502', message: 'null value' };
+ let reads = 0;
+ db.rows.actions = () => (reads++ === 0 ? null : { id: 'act-0', action_no: 70 });
+ await expect(sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' })).rejects.toThrow(
+ 'null value',
+ );
+ expect(reads).toBe(1);
+ });
+
+ it('returns the action open for the page', async () => {
+ db.rows.actions = () => ({ id: 'act-0', action_no: 70 });
+ expect(await sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' })).toEqual({
+ actionId: 'act-0',
+ actionNo: 70,
+ created: false,
+ });
+ expect(db.inserts).toEqual([]);
+ });
+
+ it('refuses an older report of a page audited since, naming its latest audit', async () => {
+ db.newer = [
+ // Another page, audited later still: not this page's.
+ { id: 'a-other', url: 'https://acme.example/blog/latte', final_url: null },
+ // The same page, read with www. and a trailing slash, as the Pages list groups it.
+ { id: 'a-new', url: 'http://www.acme.example/blog/espresso/', final_url: null },
+ { id: 'a-mid', url: URL_, final_url: URL_ },
+ ];
+ await expect(
+ sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' }),
+ ).rejects.toMatchObject({
+ status: 409,
+ code: 'newer_audit',
+ extra: { latestAuditId: 'a-new' },
+ });
+ // Read within the brand: completed, scored, and after the sent one.
+ expect(db.newerRead).toMatchObject({
+ brand_id: 'b1',
+ status: 'completed',
+ 'total_score not is': null,
+ 'created_at>': '2026-10-20T10:00:00Z',
+ });
+ expect(db.inserts).toEqual([]);
+ });
+
+ it('sends a report when only other pages were audited since', async () => {
+ db.newer = [{ id: 'a-other', url: 'https://acme.example/blog/latte', final_url: null }];
+ expect(await sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' })).toMatchObject({
+ created: true,
+ });
+ });
+
+ it("refuses another brand's audit, one not finished, and a page with nothing to fix", async () => {
+ await expect(
+ sendAuditToActionCenter('b2', { auditId: AUDIT, userId: 'u1' }),
+ ).rejects.toMatchObject({ status: 404 });
+ const completed = db.rows.site_audits;
+ db.rows.site_audits = (f) => ({ ...completed(f), status: 'running' });
+ await expect(
+ sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' }),
+ ).rejects.toMatchObject({ status: 409, code: 'not_completed' });
+ db.rows.site_audits = completed;
+ db.rows.audit_signal_results = () => [{ signal_key: 'faq-schema', status: 'pass' }];
+ await expect(
+ sendAuditToActionCenter('b1', { auditId: AUDIT, userId: 'u1' }),
+ ).rejects.toMatchObject({ status: 409, code: 'nothing_to_fix' });
+ });
+});
diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.js
index a78adbd3e..cebdd01f0 100644
--- a/server/src/lib/action-center/priority.js
+++ b/server/src/lib/action-center/priority.js
@@ -425,6 +425,18 @@ function sentByHand(action) {
subject: { entity: 'pages', count: p.targetCount ?? null },
};
}
+ // A page sent from a Site Audit report (learning D2): a fix on the site,
+ // as urgent as the checks it fails are many, near to hand.
+ if (action.kind === 'audit_page') {
+ const failing = Array.isArray(p.checks) ? p.checks.length : 0;
+ return {
+ change: 'issue',
+ severity: failing >= 5 ? 0.6 : 0.5,
+ confidence: 0.6,
+ recoverability: 0.9,
+ subject: { entity: 'pages', count: 1 },
+ };
+ }
return null;
}
diff --git a/server/src/lib/action-center/priority.test.js b/server/src/lib/action-center/priority.test.js
index 60cac3d57..b5aa8cebd 100644
--- a/server/src/lib/action-center/priority.test.js
+++ b/server/src/lib/action-center/priority.test.js
@@ -369,6 +369,28 @@ describe('scorePriority', () => {
expect(sent('no_ai_traffic', { valueSignal: 'revenue' }).reason.commercial).toBe(true);
});
+ /** A page sent from a Site Audit report (learning D2): a fix on the site, near to hand. */
+ it('scores a page sent from a Site Audit report as a site fix', () => {
+ const sent = (checks) =>
+ scorePriority(
+ {
+ action: action({
+ kind: 'audit_page',
+ category: 'fix',
+ impact: 'medium',
+ payload: { checks: Array.from({ length: checks }, (_, i) => ({ key: `c${i}` })) },
+ }),
+ signals: [],
+ },
+ NOW,
+ );
+ expect(sent(2).reason).toMatchObject({
+ change: 'issue',
+ subject: { entity: 'pages', count: 1 },
+ });
+ expect(sent(6).score).toBeGreaterThan(sent(2).score);
+ });
+
it('scores a live page linking products that no longer sell as a sure, quick fix (shopping path, part 7)', () => {
const linked = scorePriority(
{
diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.js
index ecd43505b..1d9ee688e 100644
--- a/server/src/lib/action-center/validate.js
+++ b/server/src/lib/action-center/validate.js
@@ -574,7 +574,8 @@ async function measureReading(
// sent from AI Traffic (AT-006) on those pages. A draft sent from the
// Content Editor (CE-015) on its prompts and its page, and a product or
// category sent from Product Visibility (ECOM-013) on its shopping
- // questions and the product's page.
+ // questions and the product's page. A page sent from a Site Audit report
+ // (learning D2) on that page.
if (
action.kind === 'content_opportunity' ||
action.kind === 'content_draft' ||
@@ -584,7 +585,8 @@ async function measureReading(
action.kind === 'mention_review' ||
action.kind === 'traffic_pages' ||
action.kind === 'shopping_product' ||
- action.kind === 'shopping_category'
+ action.kind === 'shopping_category' ||
+ action.kind === 'audit_page'
) {
const scope = await basketScope(action);
const [before, after] = await Promise.all([
diff --git a/server/src/routes/action-center-audits.test.js b/server/src/routes/action-center-audits.test.js
new file mode 100644
index 000000000..850356cdb
--- /dev/null
+++ b/server/src/routes/action-center-audits.test.js
@@ -0,0 +1,168 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * Route-level tests for "Send to Action Center" on a Site Audit report
+ * (learning D2): POST /api/action-center/audits. The action itself is tested
+ * in from-audit.test.js; here, what the route lets through (ids in the
+ * format seeded data uses, a caller from the brand's organization) and how
+ * it answers: 201 created, 200 already open, and the action's refusals with
+ * their code, an older report's with the page's latest audit.
+ */
+
+const assertBrandAccess = vi.fn();
+const sendAuditToActionCenter = vi.fn();
+
+let server;
+let baseUrl;
+
+async function startApp() {
+ vi.resetModules();
+ vi.doMock('../config/supabase.js', () => ({ default: {} }));
+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess }));
+ vi.doMock('../lib/action-center/priority-data.js', () => ({ rescoreActionsForSignal: vi.fn() }));
+ vi.doMock('../lib/plan-guard.js', () => ({
+ PlanLimitError: class extends Error {},
+ requireFeature: () => (_req, _res, next) => next(),
+ }));
+ vi.doMock('../lib/action-center/task-writer/index.js', () => ({
+ TaskWriterError: class extends Error {},
+ isTaskWriterEnabled: () => false,
+ writeTasksForAction: vi.fn(),
+ }));
+ vi.doMock('../lib/action-center/task-send.js', () => ({
+ TaskSendError: class extends Error {},
+ loadTask: vi.fn(),
+ sendTaskToContent: vi.fn(),
+ sendTaskToWebhook: vi.fn(),
+ }));
+ vi.doMock('../lib/action-center/from-traffic-pages.js', () => ({
+ MAX_TRAFFIC_PAGES: 50,
+ TRAFFIC_PAGE_REASONS: ['cited_not_clicked', 'no_ai_traffic'],
+ sendTrafficPagesToActionCenter: vi.fn(),
+ }));
+ vi.doMock('../lib/action-center/from-content-draft.js', () => ({
+ sendContentDraftToActionCenter: vi.fn(),
+ }));
+ vi.doMock('../lib/action-center/from-audit.js', () => ({ sendAuditToActionCenter }));
+
+ const { default: router } = await import('./action-center.js');
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.user = { id: 'u1' };
+ req.log = { error: vi.fn(), info: vi.fn() };
+ next();
+ });
+ app.use('/api/action-center', router);
+
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/api/action-center`;
+}
+
+// Seeded ids aren't RFC 4122 versions; the route must still take them.
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const AUDIT = '44444444-4444-4444-4444-444444444444';
+
+const post = (body) =>
+ fetch(`${baseUrl}/audits`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+/** The action's refusal, as from-audit.js throws it. */
+const refusal = (message, status, code, extra) =>
+ Object.assign(new Error(message), { status, code, ...(extra ? { extra } : {}) });
+
+beforeEach(async () => {
+ assertBrandAccess.mockReset().mockResolvedValue({});
+ sendAuditToActionCenter.mockReset();
+ await startApp();
+});
+
+afterEach(async () => {
+ await new Promise((resolve) => server.close(resolve));
+});
+
+describe('POST /api/action-center/audits', () => {
+ it('sends the audit for a member: 201 when created, 200 when already open', async () => {
+ sendAuditToActionCenter.mockResolvedValue({ actionId: 'a1', actionNo: 71, created: true });
+ const res = await post({ brandId: BRAND, auditId: AUDIT });
+ expect(res.status).toBe(201);
+ expect(await res.json()).toEqual({ actionId: 'a1', actionNo: 71, created: true });
+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');
+ expect(sendAuditToActionCenter).toHaveBeenCalledWith(BRAND, { auditId: AUDIT, userId: 'u1' });
+
+ sendAuditToActionCenter.mockResolvedValue({ actionId: 'a1', actionNo: 71, created: false });
+ const again = await post({ brandId: BRAND, auditId: AUDIT });
+ expect(again.status).toBe(200);
+ expect(await again.json()).toEqual({ actionId: 'a1', actionNo: 71, created: false });
+ });
+
+ it('rejects a body without valid ids', async () => {
+ expect((await post({ brandId: BRAND })).status).toBe(400);
+ expect((await post({ brandId: BRAND, auditId: 'nope' })).status).toBe(400);
+ expect((await post({ brandId: 'nope', auditId: AUDIT })).status).toBe(400);
+ expect(assertBrandAccess).not.toHaveBeenCalled();
+ expect(sendAuditToActionCenter).not.toHaveBeenCalled();
+ });
+
+ it('rejects a caller outside the brand’s workspace', async () => {
+ assertBrandAccess.mockRejectedValue(refusal('nope', 403, 'not_in_workspace'));
+ const res = await post({ brandId: BRAND, auditId: AUDIT });
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: 'not_in_workspace' });
+ expect(sendAuditToActionCenter).not.toHaveBeenCalled();
+ });
+
+ it('passes on an audit the brand doesn’t have', async () => {
+ sendAuditToActionCenter.mockRejectedValue(refusal('Audit not found', 404, 'not_found'));
+ const res = await post({ brandId: BRAND, auditId: AUDIT });
+ expect(res.status).toBe(404);
+ expect(await res.json()).toMatchObject({ code: 'not_found' });
+ });
+
+ it('passes on the action’s refusals with their code', async () => {
+ sendAuditToActionCenter.mockRejectedValue(
+ refusal('The page passes its checks', 409, 'nothing_to_fix'),
+ );
+ let res = await post({ brandId: BRAND, auditId: AUDIT });
+ expect(res.status).toBe(409);
+ expect(await res.json()).toEqual({
+ error: 'Failed to send to the Action Center',
+ details: 'The page passes its checks',
+ code: 'nothing_to_fix',
+ });
+
+ sendAuditToActionCenter.mockRejectedValue(
+ refusal('The audit hasn’t finished', 409, 'not_completed'),
+ );
+ res = await post({ brandId: BRAND, auditId: AUDIT });
+ expect(res.status).toBe(409);
+ expect(await res.json()).toMatchObject({ code: 'not_completed' });
+ });
+
+ it("answers an older report with the page's latest audit", async () => {
+ sendAuditToActionCenter.mockRejectedValue(
+ refusal('The page has a newer audit', 409, 'newer_audit', { latestAuditId: 'a-new' }),
+ );
+ const res = await post({ brandId: BRAND, auditId: AUDIT });
+ expect(res.status).toBe(409);
+ expect(await res.json()).toEqual({
+ error: 'Failed to send to the Action Center',
+ details: 'The page has a newer audit',
+ code: 'newer_audit',
+ latestAuditId: 'a-new',
+ });
+ });
+
+ it('answers 500 for an unexpected failure', async () => {
+ sendAuditToActionCenter.mockRejectedValue(new Error('db down'));
+ const res = await post({ brandId: BRAND, auditId: AUDIT });
+ expect(res.status).toBe(500);
+ expect(await res.json()).not.toHaveProperty('code');
+ });
+});
diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.js
index 7f1e201bb..0942b5a2e 100644
--- a/server/src/routes/action-center.js
+++ b/server/src/routes/action-center.js
@@ -26,6 +26,7 @@ import {
PRODUCT_WORK_TYPES,
sendProductActions,
} from '../lib/action-center/from-products.js';
+import { sendAuditToActionCenter } from '../lib/action-center/from-audit.js';
import { runTaskCheck } from '../lib/action-center/task-checks.js';
import { taskCheckLimiter } from '../middleware/rate-limiter.js';
@@ -315,6 +316,45 @@ router.post('/pages', async (req, res) => {
}
});
+const auditPageSchema = z.object({
+ // guid, not uuid: seeded ids aren't RFC 4122 versions.
+ brandId: z.guid(),
+ auditId: z.guid(),
+});
+
+/**
+ * POST /api/action-center/audits
+ * Body: { brandId, auditId }
+ *
+ * "Send to Action Center" on a Site Audit report (learning D2): the page and
+ * the checks it fails as one Fix action. Sending the page again returns the
+ * action already open for it; sending an older report of a page audited since
+ * is refused (409 newer_audit, with latestAuditId).
+ */
+router.post('/audits', async (req, res) => {
+ try {
+ const parsed = auditPageSchema.safeParse(req.body ?? {});
+ if (!parsed.success) {
+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });
+ }
+ const { brandId, auditId } = parsed.data;
+ await assertBrandAccess(brandId, req.user.id);
+
+ const result = await sendAuditToActionCenter(brandId, { auditId, userId: req.user.id });
+ return res.status(result.created ? 201 : 200).json(result);
+ } catch (error) {
+ const status = error.status || 500;
+ if (status >= 500) req.log.error({ err: error }, 'audit page action error');
+ return res.status(status).json({
+ error: 'Failed to send to the Action Center',
+ details: error.message,
+ ...(error.code ? { code: error.code } : {}),
+ // newer_audit: the page's latest audit, to open instead.
+ ...(error.extra ?? {}),
+ });
+ }
+});
+
const contentDraftSchema = z.object({
// guid, not uuid: seeded ids aren't RFC 4122 versions.
brandId: z.guid(),
diff --git a/web/messages/en.json b/web/messages/en.json
index 42261d2f5..373d3de86 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1693,6 +1693,7 @@
"noSignalsTopicOpportunity": "This action was sent from Insights' Opportunities, so it has no detection signals. Its evidence is the topic and suggested prompts on the Overview tab.",
"noSignalsMentionReview": "This action was sent from Mentions, so it has no detection signals. Its evidence is the answers quoted on the Overview tab.",
"noSignalsTrafficPages": "This action was sent from AI Traffic Analytics, so it has no detection signals. Its evidence is the pages and figures on the Overview tab.",
+ "noSignalsAuditPage": "This action was sent from a Site Audit report, so it has no detection signals. Its evidence is the page and the checks it fails on the Overview tab.",
"noSignalsShoppingLinks": "This action comes from the catalog check after each sync, so it has no detection signals. Its evidence is the page and the products on the Overview tab.",
"topicOpportunity": {
"source": "Source",
@@ -1729,6 +1730,13 @@
"swaps": "In stock, from its shopping path",
"check": "Checked again after each catalog sync, or now with Check now on its task: the action closes once the page links none of them."
},
+ "auditPage": {
+ "source": "Source",
+ "sourceValue": "Site Audit report",
+ "openReport": "Open the report",
+ "page": "Page",
+ "checks": "{count, plural, one {The check it failed when sent} other {The # checks it failed when sent}}"
+ },
"mentionReview": {
"source": "Source",
"sourceValue": "Mentions & Sentiment › Mentions",
@@ -2476,6 +2484,14 @@
"noAiDescription": "Sent from AI Traffic Analytics: {count, plural, one {a page} other {# pages}} with visitors or in your sitemap that got no AI visit in the range.",
"goal": "Earn AI-referred visits to these pages."
},
+ "audit_page": {
+ "title": "Fix the issues Site Audit found on {targets}",
+ "titleGeneric": "Fix the issues Site Audit found on a page",
+ "pageTitle": "Fix the issues Site Audit found on {page}",
+ "description": "Sent from Site Audit: a page and the checks it fails.",
+ "checksDescription": "Sent from Site Audit: the page fails {count, plural, one {# check} other {# checks}}. Audit it again once fixed to see them pass.",
+ "goal": "Get the page to pass the checks it fails, so AI engines read and cite it."
+ },
"content_draft": {
"title": "Write a page for {targets}",
"titleGeneric": "Write a page",
@@ -3174,6 +3190,20 @@
"deleteAudit": "Delete audit",
"loadFailed": "Couldn't load this audit",
"reaudit": "Re-run audit",
+ "sendToAction": {
+ "button": "Send to Action Center",
+ "sending": "Sending to the Action Center…",
+ "sent": "Sent to the Action Center",
+ "sentDescription": "AC-{number}: fix the {count, plural, one {# check} other {# checks}} this page fails.",
+ "alreadySent": "Already in the Action Center",
+ "alreadySentDescription": "AC-{number} is open for this page.",
+ "failed": "Couldn't send to the Action Center",
+ "nothingToFix": "This page passes its checks: nothing to send.",
+ "newerAudit": "This page has a newer audit",
+ "newerAuditDescription": "Send it from its latest report, so the action names the checks it fails now.",
+ "openLatest": "Open the latest report",
+ "open": "Open"
+ },
"deleteConfirm": "This permanently deletes this audit and its results. This can't be undone.",
"cancel": "Cancel",
"auditsLeft": "audits left this month",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/[id]/page.tsx
index c3b6b05b7..e00a1eec5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/[id]/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/[id]/page.tsx
@@ -4,7 +4,7 @@ import { useState, useEffect, useCallback, useRef } from 'react';
import { useParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
-import { Loader2, ArrowLeft, Trash2, RefreshCw, AlertCircle } from 'lucide-react';
+import { Loader2, ArrowLeft, Trash2, RefreshCw, AlertCircle, ListChecks } from 'lucide-react';
import { Link, useRouter } from '@/i18n/navigation';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
@@ -18,8 +18,15 @@ import {
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
-import { getAudit, runAudit, deleteAudit, type AuditResult } from '@/lib/actions/audits';
+import {
+ getAudit,
+ runAudit,
+ deleteAudit,
+ sendAuditToActionCenter,
+ type AuditResult,
+} from '@/lib/actions/audits';
import { AuditReport } from '@/components/audit/audit-report';
+import { failingChecks } from '@/lib/audit/failing-checks';
import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';
import { useUpgradeGate } from '@/components/providers/upgrade-gate';
@@ -126,6 +133,69 @@ export default function AuditDetailPage() {
}
};
+ // The page and the checks it fails, sent to the Action Center as one Fix action (learning D2).
+ const [sendingToAction, setSendingToAction] = useState(false);
+ const failing = failingChecks(audit?.signals ?? []);
+ const handleSendToAction = async () => {
+ if (!audit) return;
+ setSendingToAction(true);
+ const toastId = toast.loading(t('sendToAction.sending'));
+ try {
+ const result = await sendAuditToActionCenter(audit.brandId, audit.id);
+ if ('error' in result) {
+ // An older report of a page audited since: send from its latest report instead.
+ const latestAuditId = result.code === 'newer_audit' ? result.latestAuditId : undefined;
+ if (latestAuditId) {
+ toast.error(t('sendToAction.newerAudit'), {
+ id: toastId,
+ description: t('sendToAction.newerAuditDescription'),
+ duration: 10_000,
+ action: {
+ label: t('sendToAction.openLatest'),
+ onClick: () => router.push(`/dashboard/audit/${latestAuditId}`),
+ },
+ });
+ return;
+ }
+ toast.error(t('sendToAction.failed'), {
+ id: toastId,
+ description:
+ result.code === 'nothing_to_fix' ? t('sendToAction.nothingToFix') : result.error,
+ });
+ return;
+ }
+ const open = {
+ label: t('sendToAction.open'),
+ onClick: () => router.push(`/dashboard/action-center/actions?action=${result.actionId}`),
+ };
+ if (result.created) {
+ toast.success(t('sendToAction.sent'), {
+ id: toastId,
+ description: t('sendToAction.sentDescription', {
+ number: result.actionNo,
+ count: failing,
+ }),
+ duration: 10_000,
+ action: open,
+ });
+ } else {
+ toast.info(t('sendToAction.alreadySent'), {
+ id: toastId,
+ description: t('sendToAction.alreadySentDescription', { number: result.actionNo }),
+ duration: 10_000,
+ action: open,
+ });
+ }
+ } catch (err) {
+ toast.error(t('sendToAction.failed'), {
+ id: toastId,
+ description: err instanceof Error ? err.message : undefined,
+ });
+ } finally {
+ setSendingToAction(false);
+ }
+ };
+
// Re-run the audit on the same URL → navigate to the new audit's detail page.
const handleRefresh = async () => {
if (!audit) return;
@@ -153,6 +223,22 @@ export default function AuditDetailPage() {
</Link>
{audit && (audit.status !== 'running' || timedOut) && (
<div className="flex items-center gap-1">
+ {audit.status === 'completed' && failing > 0 && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="mr-1 gap-1.5"
+ disabled={sendingToAction}
+ onClick={() => void handleSendToAction()}
+ >
+ {sendingToAction ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <ListChecks className="h-3.5 w-3.5" />
+ )}
+ {t('sendToAction.button')}
+ </Button>
+ )}
<Button
variant="ghost"
size="icon"
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index 20a0f9443..c6cc94905 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -77,6 +77,7 @@ import { MentionReviewContext } from './mention-review-context';
import { TrafficPagesContext } from './traffic-pages-context';
import { ContentDraftContext } from './content-draft-context';
import { ShoppingLinksContext } from './shopping-links-context';
+import { AuditPageContext } from './audit-page-context';
import {
TaskDetailForm,
TaskDetailView,
@@ -712,6 +713,11 @@ export function ActionDrawer({
<Separator />
<ShoppingLinksContext payload={action.payload ?? {}} />
</>
+ ) : action.kind === 'audit_page' ? (
+ <>
+ <Separator />
+ <AuditPageContext payload={action.payload ?? {}} />
+ </>
) : opportunityId ? (
<>
<Separator />
@@ -828,11 +834,13 @@ export function ActionDrawer({
? t('drawer.noSignalsMentionReview')
: action.kind === 'traffic_pages'
? t('drawer.noSignalsTrafficPages')
- : action.kind === 'shopping_links'
- ? t('drawer.noSignalsShoppingLinks')
- : opportunityId
- ? t('drawer.noSignalsOpportunity')
- : t('drawer.noSignals')}
+ : action.kind === 'audit_page'
+ ? t('drawer.noSignalsAuditPage')
+ : action.kind === 'shopping_links'
+ ? t('drawer.noSignalsShoppingLinks')
+ : opportunityId
+ ? t('drawer.noSignalsOpportunity')
+ : t('drawer.noSignals')}
</p>
)}
{detail.signals.map((signal) => {
diff --git a/web/src/components/action-center/audit-page-context.test.tsx b/web/src/components/action-center/audit-page-context.test.tsx
new file mode 100644
index 000000000..431028e62
--- /dev/null
+++ b/web/src/components/action-center/audit-page-context.test.tsx
@@ -0,0 +1,79 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+import { AuditPageContext } from './audit-page-context';
+
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render(payload: Record<string, unknown>) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <AuditPageContext payload={payload} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('AuditPageContext', () => {
+ it('links the report it was sent from, and names the page and the checks it failed', async () => {
+ await render({
+ source: 'audit_page',
+ auditId: 'a1',
+ url: 'https://acme.example/blog/espresso',
+ checks: [
+ { key: 'faq-schema', label: 'FAQ schema' },
+ { key: 'json-ld-validity', label: 'JSON-LD validity' },
+ ],
+ });
+ const link = container.querySelector('a')!;
+ expect(link.getAttribute('href')).toBe('/dashboard/audit/a1');
+ expect(link.textContent).toContain('Open the report');
+ expect(container.textContent).toContain('Site Audit report');
+ expect(container.textContent).toContain('/blog/espresso');
+ expect(container.textContent).toContain('The 2 checks it failed when sent');
+ const items = [...container.querySelectorAll('li')].map((li) => li.textContent);
+ expect(items).toEqual(['FAQ schema', 'JSON-LD validity']);
+ });
+
+ it('names a check without a label by its key', async () => {
+ await render({ auditId: 'a1', checks: [{ key: 'faq-schema' }] });
+ expect(container.textContent).toContain('The check it failed when sent');
+ expect(container.querySelector('li')?.textContent).toBe('faq-schema');
+ });
+
+ it('reads a payload of the wrong shape without breaking', async () => {
+ await render({ auditId: 5, url: null, checks: 'none' });
+ expect(container.querySelector('a')).toBeNull();
+ expect(container.textContent).not.toContain('Page');
+ expect(container.textContent).not.toContain('failed when sent');
+ });
+});
diff --git a/web/src/components/action-center/audit-page-context.tsx b/web/src/components/action-center/audit-page-context.tsx
new file mode 100644
index 000000000..42f934202
--- /dev/null
+++ b/web/src/components/action-center/audit-page-context.tsx
@@ -0,0 +1,75 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { ExternalLink } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { pagePath } from '@/lib/content/overlap';
+
+/**
+ * The payload's failing checks, read defensively: each named by the label
+ * Site Audit gave it when sent (server rubric), else by its key.
+ */
+function checksOf(raw: unknown): { key: string; label: string }[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.flatMap((item) => {
+ const c = (item ?? {}) as Record<string, unknown>;
+ const key = typeof c.key === 'string' ? c.key : '';
+ const label = typeof c.label === 'string' && c.label.trim() ? c.label.trim() : key;
+ return label ? [{ key: key || label, label }] : [];
+ });
+}
+
+/**
+ * What a page sent from its Site Audit report carries (learning D2): the
+ * report it came from, the page, and the checks it failed when sent. Copied
+ * onto the action at send time, so it still reads after the page is audited
+ * again.
+ */
+export function AuditPageContext({ payload }: { payload: Record<string, unknown> }) {
+ const t = useTranslations('actionCenter.actionsPage.drawer.auditPage');
+ const auditId = typeof payload.auditId === 'string' && payload.auditId ? payload.auditId : null;
+ const page = typeof payload.url === 'string' && payload.url ? payload.url : null;
+ const checks = checksOf(payload.checks);
+
+ return (
+ <section className="space-y-3">
+ <div>
+ <p className="text-xs font-medium text-muted-foreground">{t('source')}</p>
+ <div className="mt-1 flex flex-wrap items-center gap-2">
+ <span>{t('sourceValue')}</span>
+ {auditId && (
+ <Link
+ href={`/dashboard/audit/${auditId}`}
+ className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
+ >
+ {t('openReport')}
+ <ExternalLink className="h-3 w-3" />
+ </Link>
+ )}
+ </div>
+ </div>
+ {page && (
+ <div>
+ <p className="text-xs font-medium text-muted-foreground">{t('page')}</p>
+ <p className="mt-1 truncate" title={page}>
+ {pagePath(page)}
+ </p>
+ </div>
+ )}
+ {checks.length > 0 && (
+ <div>
+ <p className="text-xs font-medium text-muted-foreground">
+ {t('checks', { count: checks.length })}
+ </p>
+ <ul className="mt-1 list-disc space-y-1 pl-4">
+ {checks.map((check) => (
+ <li key={check.key} className="break-words">
+ {check.label}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.ts
index cae7f3b93..fe6eb2a29 100644
--- a/web/src/lib/action-center/display.test.ts
+++ b/web/src/lib/action-center/display.test.ts
@@ -54,8 +54,8 @@ describe('actionTexts', () => {
expect(() => actionGoal(kind, t)).not.toThrow();
});
- it("holds copy for all sixty-two definitions, the nine person-sent kinds and the catalog check's", () => {
- expect(ACTION_KINDS).toHaveLength(72);
+ it("holds copy for all sixty-two definitions, the ten person-sent kinds and the catalog check's", () => {
+ expect(ACTION_KINDS).toHaveLength(73);
});
it('names a product or category sent from Product Visibility after it (ECOM-013)', () => {
@@ -289,6 +289,33 @@ describe('actionTexts', () => {
});
});
+/** A page sent from a Site Audit report (learning D2). */
+describe('actionTexts for a page sent from Site Audit', () => {
+ const tTexts = createTranslator({
+ locale: 'en',
+ messages,
+ namespace: 'actionCenter.actionTexts',
+ });
+ it('names the page and how many checks it fails', () => {
+ expect(
+ actionTexts(
+ {
+ kind: 'audit_page',
+ payload: {
+ targets: [{ id: 'https://acme.example/blog/espresso', label: '/blog/espresso' }],
+ checks: [{ key: 'faq-schema' }, { key: 'json-ld-validity' }],
+ },
+ },
+ tTexts as unknown as (key: string, values?: Record<string, string | number>) => string,
+ ),
+ ).toEqual({
+ title: 'Fix the issues Site Audit found on /blog/espresso',
+ description:
+ 'Sent from Site Audit: the page fails 2 checks. Audit it again once fixed to see them pass.',
+ });
+ });
+});
+
describe('humanizeKind', () => {
it('reads a definition id as the phrase it was written to be', () => {
expect(humanizeKind('expand_platform_visibility')).toBe('Expand platform visibility');
diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.ts
index e8895bd8d..74183e058 100644
--- a/web/src/lib/action-center/display.ts
+++ b/web/src/lib/action-center/display.ts
@@ -206,6 +206,17 @@ export function actionTexts(
}),
};
}
+ // A page sent from a Site Audit report (learning D2) names the page and how many checks it fails.
+ if (action.kind === 'audit_page' && Array.isArray(p.targets) && Array.isArray(p.checks)) {
+ const page = (p.targets[0] as { label?: unknown } | undefined)?.label;
+ return {
+ title:
+ typeof page === 'string' && page
+ ? t(`${action.kind}.pageTitle`, { page })
+ : t(`${action.kind}.titleGeneric`),
+ description: t(`${action.kind}.checksDescription`, { count: p.checks.length }),
+ };
+ }
const targets = targetLabel(p, t);
return {
title: targets ? t(`${action.kind}.title`, { targets }) : t(`${action.kind}.titleGeneric`),
@@ -296,6 +307,7 @@ const PERSON_SENT_KINDS: string[] = [
'topic_opportunity',
'mention_review',
'traffic_pages',
+ 'audit_page',
'content_draft',
'shopping_product',
'shopping_category',
diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.ts
index 8fbca3415..c569967df 100644
--- a/web/src/lib/action-center/registry.ts
+++ b/web/src/lib/action-center/registry.ts
@@ -115,6 +115,8 @@ export type ActionKind =
| 'mention_review'
// Sent by a person from AI Traffic's Pages section (AT-006).
| 'traffic_pages'
+ // Sent by a person from a Site Audit report (learning D2).
+ | 'audit_page'
// Sent by a person from the Content Editor's Start, as Team (CE-015).
| 'content_draft'
// Sent by a person from Product Visibility: a product, or a catalog category (ECOM-013).
@@ -272,6 +274,7 @@ export const ACTION_KINDS: readonly ActionKind[] = [
'topic_opportunity',
'mention_review',
'traffic_pages',
+ 'audit_page',
'content_draft',
'shopping_product',
'shopping_category',
diff --git a/web/src/lib/actions/audits-send-to-action.test.ts b/web/src/lib/actions/audits-send-to-action.test.ts
new file mode 100644
index 000000000..52b315a47
--- /dev/null
+++ b/web/src/lib/actions/audits-send-to-action.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * "Send to Action Center" on a Site Audit report (learning D2): the server's
+ * answer returned as it is, and its refusals with their code, so the report
+ * can say why; an older report names the page's latest audit to open.
+ */
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ auth: { getSession: async () => ({ data: { session: { access_token: 'token' } } }) },
+ })),
+}));
+
+const { sendAuditToActionCenter } = await import('./audits');
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const AUDIT = '44444444-4444-4444-4444-444444444444';
+
+const respond = (status: number, body: unknown) =>
+ vi.fn(async () => new Response(JSON.stringify(body), { status }));
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('sendAuditToActionCenter', () => {
+ it('posts the brand and audit as the user and returns the action', async () => {
+ const fetch = respond(201, { actionId: 'act-1', actionNo: 71, created: true });
+ vi.stubGlobal('fetch', fetch);
+ expect(await sendAuditToActionCenter(BRAND, AUDIT)).toEqual({
+ actionId: 'act-1',
+ actionNo: 71,
+ created: true,
+ });
+ const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit];
+ expect(new URL(url).pathname).toBe('/api/action-center/audits');
+ expect(JSON.parse(String(init.body))).toEqual({ brandId: BRAND, auditId: AUDIT });
+ });
+
+ it("returns an older report's refusal with the page's latest audit", async () => {
+ vi.stubGlobal(
+ 'fetch',
+ respond(409, {
+ error: 'Failed to send to the Action Center',
+ details: 'The page has a newer audit',
+ code: 'newer_audit',
+ latestAuditId: 'a-new',
+ }),
+ );
+ expect(await sendAuditToActionCenter(BRAND, AUDIT)).toEqual({
+ error: 'The page has a newer audit',
+ code: 'newer_audit',
+ latestAuditId: 'a-new',
+ });
+ });
+
+ it('returns other refusals with their code only', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ respond(409, {
+ error: 'Failed to send to the Action Center',
+ details: 'The page passes its checks',
+ code: 'nothing_to_fix',
+ }),
+ );
+ expect(await sendAuditToActionCenter(BRAND, AUDIT)).toEqual({
+ error: 'The page passes its checks',
+ code: 'nothing_to_fix',
+ });
+ });
+});
diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.ts
index 0c59d2f23..e0ccb9925 100644
--- a/web/src/lib/actions/audits.ts
+++ b/web/src/lib/actions/audits.ts
@@ -649,3 +649,43 @@ export async function getAuditHubExtras(brandId: string): Promise<AuditHubExtras
]);
return { opportunities, latestRun };
}
+
+/**
+ * "Send to Action Center" on a Site Audit report (learning D2): the page and
+ * the checks it fails as one Fix action. The server reads the audit again;
+ * the same page sent again returns the action open for it, and an older
+ * report of a page audited since is refused with its latest audit's id.
+ * Returned, not thrown: a thrown error's message is masked in production.
+ */
+export async function sendAuditToActionCenter(
+ brandId: string,
+ auditId: string,
+): Promise<
+ | { actionId: string; actionNo: number; created: boolean }
+ // newer_audit names the page's latest audit, to send from instead.
+ | { error: string; code?: string; latestAuditId?: string }
+> {
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) return { error: 'Not authenticated' };
+
+ const res = await fetch(`${AEO_SERVER_URL}/api/action-center/audits`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${session.access_token}`,
+ },
+ body: JSON.stringify({ brandId, auditId }),
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ return {
+ error: body.details || body.error || `Server error: ${res.status}`,
+ ...(typeof body.code === 'string' ? { code: body.code } : {}),
+ ...(typeof body.latestAuditId === 'string' ? { latestAuditId: body.latestAuditId } : {}),
+ };
+ }
+ return res.json();
+}
diff --git a/web/src/lib/audit/failing-checks.test.ts b/web/src/lib/audit/failing-checks.test.ts
new file mode 100644
index 000000000..5d0f61843
--- /dev/null
+++ b/web/src/lib/audit/failing-checks.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+import { failingChecks } from './failing-checks';
+
+/** What a Site Audit report sends to the Action Center (learning D2). */
+describe('failingChecks', () => {
+ it('counts the fails, and a warning only for JSON-LD validity', () => {
+ expect(
+ failingChecks([
+ { key: 'faq-schema', status: 'fail' },
+ { key: 'tables', status: 'warn' },
+ { key: 'json-ld-validity', status: 'warn' },
+ { key: 'h1-quality', status: 'pass' },
+ { key: 'llms-txt-presence', status: 'na' },
+ ]),
+ ).toBe(2);
+ expect(failingChecks([])).toBe(0);
+ });
+});
diff --git a/web/src/lib/audit/failing-checks.ts b/web/src/lib/audit/failing-checks.ts
new file mode 100644
index 000000000..7b4db7b2d
--- /dev/null
+++ b/web/src/lib/audit/failing-checks.ts
@@ -0,0 +1,12 @@
+import type { AuditSignal } from '@/lib/actions/audits';
+
+/**
+ * The checks a page fails, as the Action Center's page check reads them
+ * (learning D2; server action-center/from-audit.js): a fail, and a warning
+ * only for JSON-LD validity, whose warning is a broken block.
+ */
+export function failingChecks(signals: Pick<AuditSignal, 'key' | 'status'>[]): number {
+ return signals.filter(
+ (s) => s.status === 'fail' || (s.status === 'warn' && s.key === 'json-ld-validity'),
+ ).length;
+}