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(audit): audit top-priority pages automatically each billing week (#1139)
Cihanb7b901e90e1e
diff --git a/server/src/lib/audit/auto-audit-email.js b/server/src/lib/audit/auto-audit-email.jsnew file mode 100644index 000000000..91176f1c0--- /dev/null+++ b/server/src/lib/audit/auto-audit-email.js@@ -0,0 +1,102 @@+import supabaseAdmin from '../../config/supabase.js';+import { sendEmail } from '../email.js';++/**+ * The e-mail after an auto-audit run (SA-006), when the org turned it on in+ * Site Audit settings: "25 pages audited · 6 critical issues · next run Oct+ * 28", per brand when the run covered several. Sent through Resend+ * (email.js), a silent no-op where it isn't configured.+ */++/** The dashboard's origin, for the e-mail's links. */+function appOrigin() {+ const raw = process.env.PUBLIC_APP_URL || 'http://localhost:3000';+ try {+ return new URL(raw).origin;+ } catch {+ return raw.replace(/\/$/, '');+ }+}++function escapeHtml(value) {+ return String(value ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;+const monthDay = (iso) =>+ new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });++/** "25 pages audited · 6 critical issues" */+function summary({ completed, criticalIssues }) {+ return `${plural(completed, 'page', 'pages')} audited · ${plural(criticalIssues, 'critical issue', 'critical issues')}`;+}++/**+ * @param {{ brands: Array<{ name: string, pages: number, completed: number, criticalIssues: number }>, nextRunAt: string }} run+ * @returns {{ subject: string, html: string }}+ */+export function renderAutoAuditEmail({ brands, nextRunAt }) {+ const total = {+ pages: brands.reduce((n, b) => n + b.pages, 0),+ completed: brands.reduce((n, b) => n + b.completed, 0),+ criticalIssues: brands.reduce((n, b) => n + b.criticalIssues, 0),+ };+ const failed = total.pages - total.completed;+ const url = `${appOrigin()}/dashboard/audit`;++ const brandItems =+ brands.length > 1+ ? `<ul style="margin:0 0 16px 0;padding-left:20px;">${brands+ .map(+ (b) =>+ `<li style="margin:0 0 6px 0;color:#374151;font-size:14px;">${escapeHtml(b.name)}: ${escapeHtml(summary(b))}</li>`,+ )+ .join('')}</ul>`+ : '';+ const failedNote = failed+ ? `<p style="font-size:13px;color:#6b7280;margin:0 0 16px 0;">${escapeHtml(plural(failed, "page couldn't", "pages couldn't"))} be audited; they're left to the next run.</p>`+ : '';++ const html = `<div style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;max-width:600px;margin:0 auto;padding:24px;">+ <h1 style="font-size:18px;color:#111827;margin:0 0 8px 0;">Auto-audit finished</h1>+ <p style="font-size:14px;color:#111827;margin:0 0 16px 0;">${escapeHtml(summary(total))} · next run ${escapeHtml(monthDay(nextRunAt))}</p>+ ${brandItems}+ ${failedNote}+ <div style="margin:24px 0;">+ <a href="${escapeHtml(url)}" style="background:#111827;color:#ffffff;text-decoration:none;padding:10px 18px;border-radius:8px;font-size:14px;display:inline-block;">Open Site Audit</a>+ </div>+ <p style="font-size:12px;color:#9ca3af;border-top:1px solid #e5e7eb;padding-top:16px;">+ You're receiving this because auto-audit e-mails are on in Site Audit settings.+ <a href="${escapeHtml(url)}" style="color:#6b7280;">Change them</a>+ </p>+</div>`;++ return { subject: `Site Audit: ${summary(total)}`, html };+}++/** Every member's e-mail address, as Daily Pulse sends to by default. */+async function orgMemberEmails(orgId) {+ const { data: members, error } = await supabaseAdmin+ .from('profiles')+ .select('id')+ .eq('organization_id', orgId);+ if (error) throw new Error(error.message);+ const emails = [];+ for (const member of members ?? []) {+ const { data } = await supabaseAdmin.auth.admin.getUserById(member.id);+ if (data?.user?.email) emails.push(data.user.email);+ }+ return emails;+}++/** Render and send the run's e-mail to the org's members. True when accepted. */+export async function sendAutoAuditEmail(orgId, run) {+ const to = await orgMemberEmails(orgId);+ if (to.length === 0) return false;+ const { subject, html } = renderAutoAuditEmail(run);+ return sendEmail({ to, subject, html });+}diff --git a/server/src/lib/audit/auto-audit-email.test.js b/server/src/lib/audit/auto-audit-email.test.jsnew file mode 100644index 000000000..326345543--- /dev/null+++ b/server/src/lib/audit/auto-audit-email.test.js@@ -0,0 +1,34 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('../../config/supabase.js', () => ({ default: {} }));++const { renderAutoAuditEmail } = await import('./auto-audit-email.js');++describe('renderAutoAuditEmail', () => {+ it('sums up the run, with the next run date', () => {+ const { subject, html } = renderAutoAuditEmail({+ brands: [{ name: 'Acme Coffee', pages: 25, completed: 25, criticalIssues: 6 }],+ nextRunAt: '2026-10-28T09:00:00.000Z',+ });+ expect(subject).toBe('Site Audit: 25 pages audited · 6 critical issues');+ expect(html).toContain('25 pages audited · 6 critical issues · next run Oct 28');+ expect(html).toContain('http://localhost:3000/dashboard/audit');+ // One brand: no per-brand list, nothing failed.+ expect(html).not.toContain('<ul');+ expect(html).not.toContain("couldn't");+ });++ it('lists each brand, says what failed and escapes names', () => {+ const { subject, html } = renderAutoAuditEmail({+ brands: [+ { name: 'Acme <Coffee>', pages: 3, completed: 2, criticalIssues: 1 },+ { name: 'Acme Tea', pages: 1, completed: 1, criticalIssues: 0 },+ ],+ nextRunAt: '2026-11-01T00:00:00.000Z',+ });+ expect(subject).toBe('Site Audit: 3 pages audited · 1 critical issue');+ expect(html).toContain('Acme <Coffee>: 2 pages audited · 1 critical issue');+ expect(html).toContain('Acme Tea: 1 page audited · 0 critical issues');+ expect(html).toContain("1 page couldn't be audited");+ });+});diff --git a/server/src/lib/audit/auto-audit-sweep.js b/server/src/lib/audit/auto-audit-sweep.jsnew file mode 100644index 000000000..3854e5452--- /dev/null+++ b/server/src/lib/audit/auto-audit-sweep.js@@ -0,0 +1,213 @@+/**+ * The daily auto-audit sweep (SA-006). For each organization whose run is+ * due, it claims the run (one site_audit_auto_runs row per org, period and+ * run day, so a second sweep the same day does nothing), audits the top+ * pages of its brands' Opportunities inboxes, and once every audit has+ * finished, records the run and, when the team asked for it, e-mails them.+ *+ * The inbox read and the audit start live in routes/audits.js; they're+ * passed in, so this module doesn't import a route (and tests stand them in).+ */++import supabaseAdmin from '../../config/supabase.js';+import { getSiteAuditQuotaStatus, PlanLimitError } from '../plan-guard.js';+import { readAllRpcRows } from '../rpc-pages.js';+import { logger } from '../logger.js';+import { AUTO_AUDIT, pickRunPages } from './auto-audit.js';+import { sendAutoAuditEmail } from './auto-audit-email.js';+import { opportunityKey } from './opportunities.js';++/**+ * @typedef {object} SweepDeps+ * @property {(brandId: string) => Promise<{ opportunities: object[] }>} readInbox+ * @property {(brandId: string, urls: string[], orgId: string) => Promise<{ auditIds: string[], done: Promise<unknown> }>} startAudits+ * @property {Date} [now]+ * @property {string[]} [orgIds] only these organizations (the manual script)+ */++/**+ * Start every due run; resolves when they have all finished.+ *+ * @param {SweepDeps} deps+ * @returns {Promise<{ runs: number }>}+ */+export async function sweepAutoAudits({ readInbox, startAudits, now = new Date(), orgIds }) {+ const { data: brands, error } = await readAllRpcRows('brands', (from, to) => {+ let query = supabaseAdmin+ .from('brands')+ .select('id, name, organization_id')+ .eq('is_active', true);+ if (orgIds) query = query.in('organization_id', orgIds);+ return query.order('id', { ascending: true }).range(from, to);+ });+ if (error) throw new Error(error.message);++ const byOrg = new Map();+ const seen = new Set();+ for (const brand of brands ?? []) {+ // A slice boundary can repeat a row (rpc-pages.js).+ if (!brand.organization_id || seen.has(brand.id)) continue;+ seen.add(brand.id);+ if (!byOrg.has(brand.organization_id)) byOrg.set(brand.organization_id, []);+ byOrg.get(brand.organization_id).push(brand);+ }++ // Runs are started one org at a time, then finish together: their audits+ // share the auto pool, so starting is quick and finishing is not.+ const finishing = [];+ for (const [orgId, orgBrands] of byOrg) {+ try {+ const run = await startRun(orgId, orgBrands, { readInbox, startAudits, now });+ if (run) finishing.push(run.finished);+ } catch (err) {+ logger.error({ err, orgId }, '[auto-audit] run failed to start');+ }+ }+ await Promise.all(finishing);+ return { runs: finishing.length };+}++/**+ * Claim and start the org's due run. Returns { finished }, a promise that+ * settles once the run is recorded (wrapped, so awaiting the start doesn't+ * wait for it), or null when nothing is due.+ */+async function startRun(orgId, brands, { readInbox, startAudits, now }) {+ let quota;+ try {+ quota = await getSiteAuditQuotaStatus(orgId, { now });+ } catch (err) {+ // An org without an active subscription has nothing to run.+ if (err instanceof PlanLimitError) return null;+ throw err;+ }+ const { auto } = quota;+ if (!auto.enabled || !auto.due) return null;++ // The run's share, or what's left of the whole quota when that's less.+ const free = quota.limit === -1 ? auto.perRun : quota.limit - quota.used - quota.running;+ const slots = Math.max(0, Math.min(auto.perRun, free));++ const { data: claimed, error } = await supabaseAdmin+ .from('site_audit_auto_runs')+ .upsert(+ {+ organization_id: orgId,+ period_start: auto.periodStart,+ run_day: auto.due.day,+ slots,+ started_at: now.toISOString(),+ },+ { onConflict: 'organization_id,period_start,run_day', ignoreDuplicates: true },+ )+ .select('id');+ if (error) throw new Error(error.message);+ const runId = claimed?.[0]?.id;+ // Another sweep claimed it first.+ if (!runId) return null;++ const inboxes = [];+ let triedKeys = new Set();+ if (slots > 0) {+ triedKeys = await recentlyTriedPages(brands, now);+ for (const brand of brands) {+ try {+ const { opportunities } = await readInbox(brand.id);+ inboxes.push({ brandId: brand.id, opportunities });+ } catch (err) {+ logger.warn({ err, orgId, brandId: brand.id }, '[auto-audit] inbox read failed');+ }+ }+ }+ const pages = pickRunPages(inboxes, slots, now, triedKeys);++ const auditIds = [];+ const audits = [];+ for (const brand of brands) {+ const urls = pages.filter((p) => p.brandId === brand.id).map((p) => p.url);+ if (urls.length === 0) continue;+ try {+ const started = await startAudits(brand.id, urls, orgId);+ auditIds.push(...started.auditIds);+ audits.push(started.done);+ } catch (err) {+ // The quota filled up meanwhile (a user's audits): the run keeps what it started.+ logger.warn({ err, orgId, brandId: brand.id }, '[auto-audit] audits not started');+ }+ }+ if (auditIds.length > 0) {+ const { error: idsErr } = await supabaseAdmin+ .from('site_audit_auto_runs')+ .update({ audit_ids: auditIds })+ .eq('id', runId);+ if (idsErr) throw new Error(idsErr.message);+ }++ const nextRunAt = auto.runs.find((r) => r.day > auto.due.day)?.at ?? auto.periodEnd;+ const finished = Promise.all(audits)+ .then(() =>+ finishRun({ runId, orgId, brands, auditIds, emailAfterRun: auto.emailAfterRun, nextRunAt }),+ )+ .catch((err) => logger.error({ err, orgId, runId }, '[auto-audit] run failed to finish'));+ return { finished };+}++/** Pages the org's runs audited in the last 30 days, completed or not. */+async function recentlyTriedPages(brands, now) {+ const since = new Date(now.getTime() - AUTO_AUDIT.freshDays * 24 * 60 * 60 * 1000);+ const { data, error } = await supabaseAdmin+ .from('site_audits')+ .select('url')+ .in(+ 'brand_id',+ brands.map((b) => b.id),+ )+ .eq('source', 'auto')+ .gte('created_at', since.toISOString());+ if (error) throw new Error(error.message);+ return new Set((data ?? []).map((row) => opportunityKey(row.url)).filter(Boolean));+}++/** Record the finished run and, when the org asked for it, e-mail what it found. */+async function finishRun({ runId, orgId, brands, auditIds, emailAfterRun, nextRunAt }) {+ const { data: rows, error } = auditIds.length+ ? await supabaseAdmin.from('site_audits').select('id, brand_id, status').in('id', auditIds)+ : { data: [], error: null };+ if (error) throw new Error(error.message);++ const perBrand = [];+ for (const brand of brands) {+ const own = (rows ?? []).filter((r) => r.brand_id === brand.id);+ if (own.length === 0) continue;+ const completed = own.filter((r) => r.status === 'completed').map((r) => r.id);+ let criticalIssues = 0;+ if (completed.length > 0) {+ // Critical issues: the signals the audits failed.+ const { count, error: countErr } = await supabaseAdmin+ .from('audit_signal_results')+ .select('audit_id', { count: 'exact', head: true })+ .in('audit_id', completed)+ .eq('status', 'fail');+ if (countErr) throw new Error(countErr.message);+ criticalIssues = count ?? 0;+ }+ perBrand.push({+ name: brand.name,+ pages: own.length,+ completed: completed.length,+ criticalIssues,+ });+ }++ const { error: doneErr } = await supabaseAdmin+ .from('site_audit_auto_runs')+ .update({ status: 'completed', finished_at: new Date().toISOString() })+ .eq('id', runId);+ if (doneErr) throw new Error(doneErr.message);++ const emailed =+ emailAfterRun && perBrand.length > 0+ ? await sendAutoAuditEmail(orgId, { brands: perBrand, nextRunAt })+ : false;+ logger.info({ orgId, runId, brands: perBrand, emailed }, '[auto-audit] run finished');+}diff --git a/server/src/lib/audit/auto-audit-sweep.test.js b/server/src/lib/audit/auto-audit-sweep.test.jsnew file mode 100644index 000000000..a0a2ce5fd--- /dev/null+++ b/server/src/lib/audit/auto-audit-sweep.test.js@@ -0,0 +1,277 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The daily auto-audit sweep (SA-006): which orgs run, how many pages, which+ * ones, and what the run records and e-mails.+ */++const NOW = new Date('2026-10-10T06:00:00Z');++let quotas;+let brandRows;+let claimed;+let ops;+let auditRows;+let triedRows;+let failCounts;++class PlanLimitError extends Error {}++function query(table) {+ const op = { table, filters: [] };+ const builder = {+ select: (cols, opts) => {+ op.select = cols;+ op.head = opts?.head ?? false;+ return builder;+ },+ upsert: (row, opts) => {+ op.upsert = row;+ op.opts = opts;+ return builder;+ },+ update: (row) => {+ op.update = row;+ return builder;+ },+ eq: (col, val) => {+ op.filters.push(['eq', col, val]);+ return builder;+ },+ in: (col, val) => {+ op.filters.push(['in', col, val]);+ return builder;+ },+ gte: (col, val) => {+ op.filters.push(['gte', col, val]);+ return builder;+ },+ then: (resolve) => {+ ops.push(op);+ if (table === 'site_audit_auto_runs' && op.upsert) {+ return resolve({ data: claimed ? [{ id: 'run-1' }] : [], error: null });+ }+ if (table === 'site_audits') {+ // The pages runs tried in the last 30 days, else the run's own audits.+ return resolve({ data: op.select === 'url' ? triedRows : auditRows, error: null });+ }+ if (table === 'audit_signal_results') {+ const ids = op.filters.find(([, col]) => col === 'audit_id')[2];+ return resolve({ count: ids.reduce((n, id) => n + (failCounts[id] ?? 0), 0), error: null });+ }+ return resolve({ data: null, error: null });+ },+ };+ return builder;+}++const auto = (over = {}) => ({+ enabled: true,+ emailAfterRun: true,+ perRun: 5,+ due: { day: 7 },+ periodStart: '2026-10-01T00:00:00.000Z',+ periodEnd: '2026-11-01T00:00:00.000Z',+ runs: [+ { day: 1, at: '2026-10-01T00:00:00.000Z', done: true },+ { day: 7, at: '2026-10-07T00:00:00.000Z', done: false },+ { day: 14, at: '2026-10-14T00:00:00.000Z', done: false },+ { day: 21, at: '2026-10-21T00:00:00.000Z', done: false },+ { day: 28, at: '2026-10-28T00:00:00.000Z', done: false },+ ],+ ...over,+});++const row = (path, priority, over = {}) => ({+ key: `acme.com${path}`,+ url: `https://acme.com${path}`,+ path,+ pinned: false,+ running: false,+ priority,+ lastAudit: null,+ ...over,+});++const inboxes = {+ 'brand-a': [row('/pinned', 10, { pinned: true }), row('/a-90', 90), row('/a-40', 40)],+ 'brand-b': [row('/b-80', 80), row('/b-70', 70), row('/b-20', 20)],+};++let sweep;+let sendAutoAuditEmail;+let readInbox;+let startAudits;++beforeEach(async () => {+ vi.resetModules();+ quotas = { 'org-1': { limit: 100, used: 10, running: 0, auto: auto() } };+ brandRows = [+ { id: 'brand-a', name: 'Acme Coffee', organization_id: 'org-1' },+ { id: 'brand-b', name: 'Acme Tea', organization_id: 'org-1' },+ ];+ claimed = true;+ ops = [];+ auditRows = [];+ triedRows = [];+ failCounts = {};+ sendAutoAuditEmail = vi.fn().mockResolvedValue(true);+ readInbox = vi.fn(async (brandId) => ({ opportunities: inboxes[brandId] ?? [] }));+ startAudits = vi.fn(async (brandId, urls) => ({+ auditIds: urls.map((u) => `${brandId}:${u.slice('https://acme.com'.length)}`),+ done: Promise.resolve(),+ }));++ vi.doMock('../../config/supabase.js', () => ({ default: { from: (t) => query(t) } }));+ vi.doMock('../rpc-pages.js', () => ({+ readAllRpcRows: async () => ({ data: brandRows, error: null }),+ }));+ vi.doMock('../plan-guard.js', () => ({+ PlanLimitError,+ getSiteAuditQuotaStatus: vi.fn(async (orgId) => {+ const quota = quotas[orgId];+ if (quota instanceof Error) throw quota;+ return quota;+ }),+ }));+ vi.doMock('./auto-audit-email.js', () => ({ sendAutoAuditEmail }));+ ({ sweepAutoAudits: sweep } = await import('./auto-audit-sweep.js'));+});++afterEach(() => {+ vi.doUnmock('../../config/supabase.js');+ vi.doUnmock('../rpc-pages.js');+ vi.doUnmock('../plan-guard.js');+ vi.doUnmock('./auto-audit-email.js');+});++const run = () => sweep({ readInbox, startAudits, now: NOW });+const runOps = () => ops.filter((op) => op.table === 'site_audit_auto_runs');++describe('sweepAutoAudits', () => {+ it("claims the due run, audits the top pages across the org's brands, records and e-mails it", async () => {+ auditRows = [+ { id: 'brand-a:/pinned', brand_id: 'brand-a', status: 'completed' },+ { id: 'brand-a:/a-90', brand_id: 'brand-a', status: 'completed' },+ { id: 'brand-a:/a-40', brand_id: 'brand-a', status: 'failed' },+ { id: 'brand-b:/b-80', brand_id: 'brand-b', status: 'completed' },+ { id: 'brand-b:/b-70', brand_id: 'brand-b', status: 'completed' },+ ];+ failCounts = { 'brand-a:/pinned': 2, 'brand-a:/a-90': 1, 'brand-b:/b-80': 3 };++ expect(await run()).toEqual({ runs: 1 });++ // Five slots: the pinned page, then priority 90, 80, 70, 40.+ expect(startAudits.mock.calls).toEqual([+ [+ 'brand-a',+ ['https://acme.com/pinned', 'https://acme.com/a-90', 'https://acme.com/a-40'],+ 'org-1',+ ],+ ['brand-b', ['https://acme.com/b-80', 'https://acme.com/b-70'], 'org-1'],+ ]);+ const [claim, ids, done] = runOps();+ expect(claim.upsert).toEqual({+ organization_id: 'org-1',+ period_start: '2026-10-01T00:00:00.000Z',+ run_day: 7,+ slots: 5,+ started_at: NOW.toISOString(),+ });+ expect(claim.opts).toMatchObject({ ignoreDuplicates: true });+ expect(ids.update.audit_ids).toHaveLength(5);+ expect(done.update).toMatchObject({ status: 'completed', finished_at: expect.any(String) });++ expect(sendAutoAuditEmail).toHaveBeenCalledWith('org-1', {+ brands: [+ { name: 'Acme Coffee', pages: 3, completed: 2, criticalIssues: 3 },+ { name: 'Acme Tea', pages: 2, completed: 2, criticalIssues: 3 },+ ],+ nextRunAt: '2026-10-14T00:00:00.000Z',+ });+ });++ it("starts every org's run before any of them finishes", async () => {+ brandRows = [+ { id: 'brand-a', name: 'Acme Coffee', organization_id: 'org-1' },+ { id: 'brand-b', name: 'Beta Beans', organization_id: 'org-2' },+ ];+ quotas['org-2'] = { limit: 500, used: 0, running: 0, auto: auto({ perRun: 25 }) };+ let finishFirst;+ startAudits.mockImplementationOnce(async (brandId, urls) => ({+ auditIds: urls,+ done: new Promise((resolve) => {+ finishFirst = resolve;+ }),+ }));++ const sweeping = run();+ await vi.waitFor(() => expect(startAudits).toHaveBeenCalledTimes(2));+ expect(startAudits.mock.calls.map(([brandId]) => brandId)).toEqual(['brand-a', 'brand-b']);+ finishFirst();+ expect(await sweeping).toEqual({ runs: 2 });+ });++ it("skips the pages the org's runs tried in the last 30 days", async () => {+ triedRows = [{ url: 'https://acme.com/a-90' }, { url: 'https://www.acme.com/b-80/' }];+ await run();+ const tried = ops.find((op) => op.table === 'site_audits' && op.select === 'url');+ expect(tried.filters).toEqual(+ expect.arrayContaining([+ ['in', 'brand_id', ['brand-a', 'brand-b']],+ ['eq', 'source', 'auto'],+ ]),+ );+ expect(startAudits.mock.calls.flatMap(([, urls]) => urls)).toEqual([+ 'https://acme.com/pinned',+ 'https://acme.com/a-40',+ 'https://acme.com/b-70',+ 'https://acme.com/b-20',+ ]);+ });++ it('starts nothing when auto-audit is off, no run is due, or another sweep claimed it', async () => {+ quotas['org-1'].auto = auto({ enabled: false });+ await run();+ quotas['org-1'].auto = auto({ due: null });+ await run();+ expect(runOps()).toEqual([]);++ quotas['org-1'].auto = auto();+ claimed = false;+ expect(await run()).toEqual({ runs: 0 });+ expect(readInbox).not.toHaveBeenCalled();+ expect(startAudits).not.toHaveBeenCalled();+ });++ it("caps the run at what's left of the quota, and records an empty run without e-mail", async () => {+ quotas['org-1'].used = 98;+ auditRows = [{ id: 'brand-a:/pinned', brand_id: 'brand-a', status: 'completed' }];+ await run();+ expect(runOps()[0].upsert.slots).toBe(2);+ expect(startAudits.mock.calls.map(([brand, urls]) => [brand, urls.length])).toEqual([+ ['brand-a', 2],+ ]);++ ops = [];+ startAudits.mockClear();+ quotas['org-1'].used = 100;+ await run();+ expect(runOps().map((op) => op.upsert?.slots ?? op.update?.status)).toEqual([0, 'completed']);+ expect(startAudits).not.toHaveBeenCalled();+ expect(sendAutoAuditEmail).toHaveBeenCalledTimes(1);+ });++ it('e-mails only when the org asked, and skips an org without a subscription', async () => {+ quotas['org-1'].auto = auto({ emailAfterRun: false });+ auditRows = [{ id: 'brand-a:/pinned', brand_id: 'brand-a', status: 'completed' }];+ await run();+ expect(runOps().at(-1).update).toMatchObject({ status: 'completed' });+ expect(sendAutoAuditEmail).not.toHaveBeenCalled();++ ops = [];+ quotas['org-1'] = new PlanLimitError('An active subscription or free trial is required.');+ expect(await run()).toEqual({ runs: 0 });+ expect(runOps()).toEqual([]);+ });+});diff --git a/server/src/lib/audit/auto-audit.js b/server/src/lib/audit/auto-audit.jsnew file mode 100644index 000000000..3f8d9a29b--- /dev/null+++ b/server/src/lib/audit/auto-audit.js@@ -0,0 +1,122 @@+/**+ * Site Audit auto-audit (SA-006): 25% of the monthly quota audits the+ * Opportunities inbox's top pages by itself, in five runs of 5% on days 1,+ * 7, 14, 21 and 28 of the billing month. Pure: the schedule, the share kept+ * for the runs to come, and which pages a run takes. auto-audit-sweep.js+ * reads and writes; plan-guard.js keeps the reserved share out of the+ * user's pool.+ */++export const AUTO_AUDIT = Object.freeze({+ runDays: Object.freeze([1, 7, 14, 21, 28]),+ /** Each run's share of the monthly quota. */+ share: 0.05,+ /** A run on a plan without a monthly limit (Self-hosted, Enterprise): Growth's 5% of 500. */+ unlimitedPerRun: 25,+ /** A page audited this recently is left to later runs. */+ freshDays: 30,+});++const DAY_MS = 24 * 60 * 60 * 1000;++/** Pages one run audits: 5% of the quota rounded down, at least one. */+export function perRunSlots(limit) {+ if (limit === -1) return AUTO_AUDIT.unlimitedPerRun;+ if (!(limit > 0)) return 0;+ return Math.max(1, Math.floor(limit * AUTO_AUDIT.share));+}++/**+ * Whether the org's runs happen: its own choice when it made one, else on+ * for a plan with a monthly quota and off for one without (it would spend a+ * self-hosted install's own keys unasked).+ *+ * @param {boolean|null} setting site_audit_settings.auto_audit+ * @param {number} limit the plan's maxSiteAudits (-1 unlimited)+ */+export function autoAuditEnabled(setting, limit) {+ if (typeof setting === 'boolean') return setting;+ return limit > 0;+}++const startOfUtcDay = (ms) => ms - (((ms % DAY_MS) + DAY_MS) % DAY_MS);++/**+ * The period's five runs. Day N is the (UTC) day N − 1 days after the period+ * starts, from its first hour, so the morning sweep runs it on that day+ * whatever time of day the subscription renewed; day 1 starts with the+ * period. A period shorter than N days runs day N on its last day. A run's+ * turn lasts until the next run starts (the last one's until the period+ * ends), so a sweep that misses a run's day still does it within that week.+ *+ * @returns {Array<{ day: number, at: Date, until: Date }>}+ */+export function runSchedule(periodStart, periodEnd) {+ const start = new Date(periodStart).getTime();+ const end = new Date(periodEnd).getTime();+ const lastDay = Math.max(start, startOfUtcDay(end - 1));+ const starts = AUTO_AUDIT.runDays.map((day) => {+ const at = Math.max(start, startOfUtcDay(start + (day - 1) * DAY_MS));+ return { day, at: at < end ? at : lastDay };+ });+ return starts.map((run, i) => ({+ day: run.day,+ at: new Date(run.at),+ until: new Date(i + 1 < starts.length ? starts[i + 1].at : end),+ }));+}++/** The run whose turn it is at `now`, or null. */+export function dueRun(schedule, now) {+ const t = new Date(now).getTime();+ return schedule.find((run) => run.at.getTime() <= t && t < run.until.getTime()) ?? null;+}++/**+ * The runs still to come: not recorded yet, and their turn not over (the+ * current run counts until it is recorded). Each keeps its slots out of the+ * user's pool; a run's unused slots return when it is recorded.+ *+ * @param {Array<{ day: number, at: Date, until: Date }>} schedule+ * @param {number[]} recordedDays run days already recorded this period+ */+export function pendingRuns(schedule, recordedDays, now) {+ const t = new Date(now).getTime();+ const done = new Set(recordedDays);+ return schedule.filter((run) => run.until.getTime() > t && !done.has(run.day));+}++/**+ * The pages a run audits: from every brand's inbox (ordered by priority.js),+ * the pages not being audited and not audited in the last 30 days, nor tried+ * by a run in that time (an audit that failed, say on a page that blocks+ * bots, would otherwise take a slot every run); pinned pages first, then the+ * highest priority across the brands, at most `slots`. A tie keeps the+ * inboxes' own order.+ *+ * @param {Array<{ brandId: string, opportunities: Array<{ key: string, url: string, path: string, pinned: boolean, running: boolean, priority: number, lastAudit: { at: string }|null }> }>} inboxes+ * @param {number} slots+ * @param {Date} now+ * @param {Set<string>} [triedKeys] page keys a run audited in the last 30 days+ * @returns {Array<{ brandId: string, url: string, path: string, pinned: boolean, priority: number }>}+ */+export function pickRunPages(inboxes, slots, now, triedKeys = new Set()) {+ const freshSince = new Date(now).getTime() - AUTO_AUDIT.freshDays * DAY_MS;+ const candidates = [];+ for (const { brandId, opportunities } of inboxes) {+ for (const row of opportunities) {+ if (row.running || triedKeys.has(row.key)) continue;+ if (row.lastAudit && Date.parse(row.lastAudit.at) >= freshSince) continue;+ candidates.push({+ brandId,+ url: row.url,+ path: row.path,+ pinned: row.pinned,+ priority: row.priority,+ });+ }+ }+ return candidates+ .sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.priority - a.priority)+ .slice(0, Math.max(0, slots));+}diff --git a/server/src/lib/audit/auto-audit.test.js b/server/src/lib/audit/auto-audit.test.jsnew file mode 100644index 000000000..9a37e1c39--- /dev/null+++ b/server/src/lib/audit/auto-audit.test.js@@ -0,0 +1,148 @@+import { describe, expect, it } from 'vitest';+import {+ autoAuditEnabled,+ dueRun,+ pendingRuns,+ perRunSlots,+ pickRunPages,+ runSchedule,+} from './auto-audit.js';++const START = new Date('2026-10-03T14:00:00Z');+const END = new Date('2026-11-03T14:00:00Z');+const at = (iso) => new Date(iso);++describe('perRunSlots', () => {+ it('takes 5% of the quota, rounded down, at least one', () => {+ expect(perRunSlots(100)).toBe(5);+ expect(perRunSlots(500)).toBe(25);+ expect(perRunSlots(2010)).toBe(100);+ expect(perRunSlots(10)).toBe(1);+ // Without a monthly limit, Growth's run; without audits, none.+ expect(perRunSlots(-1)).toBe(25);+ expect(perRunSlots(0)).toBe(0);+ });+});++describe('autoAuditEnabled', () => {+ it("follows the org's choice, else the plan: on with a quota, off without", () => {+ expect(autoAuditEnabled(null, 100)).toBe(true);+ expect(autoAuditEnabled(null, -1)).toBe(false);+ expect(autoAuditEnabled(false, 500)).toBe(false);+ expect(autoAuditEnabled(true, -1)).toBe(true);+ });+});++describe('runSchedule', () => {+ it('counts the days from the period start, each run lasting until the next', () => {+ // A subscription renewed at 14:00: day 1 starts then, the others with their day.+ const schedule = runSchedule(START, END);+ expect(schedule.map((r) => [r.day, r.at.toISOString(), r.until.toISOString()])).toEqual([+ [1, '2026-10-03T14:00:00.000Z', '2026-10-09T00:00:00.000Z'],+ [7, '2026-10-09T00:00:00.000Z', '2026-10-16T00:00:00.000Z'],+ [14, '2026-10-16T00:00:00.000Z', '2026-10-23T00:00:00.000Z'],+ [21, '2026-10-23T00:00:00.000Z', '2026-10-30T00:00:00.000Z'],+ [28, '2026-10-30T00:00:00.000Z', '2026-11-03T14:00:00.000Z'],+ ]);+ });++ it('runs day 28 on the last day of a shorter period', () => {+ const schedule = runSchedule(at('2026-02-01T00:00:00Z'), at('2026-02-26T00:00:00Z'));+ expect(schedule.at(-1).at.toISOString()).toBe('2026-02-25T00:00:00.000Z');+ });+});++describe('dueRun', () => {+ const schedule = runSchedule(START, END);+ it('finds the run whose turn it is, a missed day included, and none outside the period', () => {+ expect(dueRun(schedule, at('2026-10-03T14:00:00Z')).day).toBe(1);+ // The morning sweep of day 7 runs it, though the period renews at 14:00.+ expect(dueRun(schedule, at('2026-10-09T06:00:00Z')).day).toBe(7);+ expect(dueRun(schedule, at('2026-10-11T06:00:00Z')).day).toBe(7);+ expect(dueRun(schedule, at('2026-11-02T06:00:00Z')).day).toBe(28);+ expect(dueRun(schedule, at('2026-10-03T13:59:00Z'))).toBeNull();+ expect(dueRun(schedule, END)).toBeNull();+ });+});++describe('pendingRuns', () => {+ const schedule = runSchedule(START, END);+ it('keeps the current run until it is recorded, and the ones to come', () => {+ const days = (recorded, now) => pendingRuns(schedule, recorded, now).map((r) => r.day);+ // Day 8: day 1 ran; day 7's turn is now.+ expect(days([1], at('2026-10-10T06:00:00Z'))).toEqual([7, 14, 21, 28]);+ expect(days([1, 7], at('2026-10-10T06:00:00Z'))).toEqual([14, 21, 28]);+ // A run whose turn passed unrecorded (auto-audit was off) keeps nothing.+ expect(days([], at('2026-10-17T06:00:00Z'))).toEqual([14, 21, 28]);+ expect(days([1, 7, 14, 21, 28], at('2026-10-31T06:00:00Z'))).toEqual([]);+ });+});++describe('pickRunPages', () => {+ const NOW = at('2026-10-17T06:00:00Z');+ const row = (path, over = {}) => ({+ key: `acme.com${path}`,+ url: `https://acme.com${path}`,+ path,+ pinned: false,+ running: false,+ priority: 50,+ lastAudit: null,+ ...over,+ });++ it('takes pinned pages first, then the highest priority across brands', () => {+ const pages = pickRunPages(+ [+ {+ brandId: 'a',+ opportunities: [+ row('/pinned', { pinned: true, priority: 20 }),+ row('/a-80', { priority: 80 }),+ ],+ },+ {+ brandId: 'b',+ opportunities: [row('/b-90', { priority: 90 }), row('/b-40', { priority: 40 })],+ },+ ],+ 3,+ NOW,+ );+ expect(pages.map((p) => [p.brandId, p.path])).toEqual([+ ['a', '/pinned'],+ ['b', '/b-90'],+ ['a', '/a-80'],+ ]);+ });++ it('skips pages being audited or audited in the last 30 days', () => {+ const pages = pickRunPages(+ [+ {+ brandId: 'a',+ opportunities: [+ row('/running', { running: true }),+ row('/fresh', { pinned: true, lastAudit: { at: '2026-09-20T00:00:00Z' } }),+ row('/old', { lastAudit: { at: '2026-09-10T00:00:00Z' } }),+ row('/never'),+ ],+ },+ ],+ 5,+ NOW,+ );+ expect(pages.map((p) => p.path)).toEqual(['/old', '/never']);+ expect(pickRunPages([{ brandId: 'a', opportunities: [row('/x')] }], 0, NOW)).toEqual([]);+ });++ it('leaves a page a run tried in the last 30 days to later runs, even if its audit failed', () => {+ const pages = pickRunPages(+ [{ brandId: 'a', opportunities: [row('/blocked', { priority: 99 }), row('/next')] }],+ 5,+ NOW,+ new Set(['acme.com/blocked']),+ );+ expect(pages.map((p) => p.path)).toEqual(['/next']);+ });+});diff --git a/server/src/lib/audit/opportunities.js b/server/src/lib/audit/opportunities.jsindex 52db00a8b..ad8c6b5ed 100644--- a/server/src/lib/audit/opportunities.js+++ b/server/src/lib/audit/opportunities.js@@ -13,7 +13,8 @@* to it (the prompt's target URL, else the best site_pages match).** Pinned pages always show. Excluded pages are left out of the rows and- * listed apart, so they can be put back. The order is the priority score's+ * listed apart, so they can be put back; pages under the brand's exclude+ * patterns (SA-006 settings) are left out. The order is the priority score's* (priority.js rankOpportunities); here rows come pinned first, then by path.*/@@ -35,6 +36,34 @@ export function opportunityKey(url) {const pathOf = (url) => pageKey(url)?.path ?? '/';+/** Longest exclude pattern kept, and how many a brand may have. */+export const EXCLUDE_PATTERN_MAX_LENGTH = 200;+export const EXCLUDE_PATTERNS_MAX = 50;++/**+ * A brand's exclude pattern as stored (SA-006): a path such as "/legal/*",+ * lowercased, without a trailing slash. `*` stands for any characters,+ * slashes included. Null for something that isn't a path.+ */+export function normalizeExcludePattern(raw) {+ const pattern = String(raw ?? '')+ .trim()+ .toLowerCase();+ if (!pattern.startsWith('/') || pattern.length > EXCLUDE_PATTERN_MAX_LENGTH) return null;+ if (/\s/.test(pattern)) return null;+ return pattern.replace(/\/+$/, '') || '/';+}++const escapeRegExp = (s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&');++/** A test of a page path against the brand's exclude patterns. */+export function excludePatternMatcher(patterns = []) {+ const regexes = patterns.map(+ (pattern) => new RegExp(`^${pattern.split('*').map(escapeRegExp).join('.*')}$`),+ );+ return (path) => regexes.some((re) => re.test(path.toLowerCase()));+}+/*** The brand pages closest to the prompts a competitor is cited on and the* brand never is: the prompt's target URLs when it has any (a customer said@@ -95,6 +124,7 @@ export function competitorGapPages({* @param {Array<{ url: string, prompts: number, competitors: string[] }>} [input.competitorPages]* competitorGapPages output* @param {Array<{ page_key: string, url: string, state: 'pinned'|'excluded' }>} input.prefs+ * @param {string[]} [input.excludePatterns] the brand's stored patterns (normalizeExcludePattern)* @param {number} input.staleDays an audit older than this no longer counts* @param {number} [input.now]*/@@ -105,9 +135,11 @@ export function buildOpportunities({auditPages = [],competitorPages = [],prefs = [],+ excludePatterns = [],staleDays,now = Date.now(),}) {+ const excludedByPattern = excludePatternMatcher(excludePatterns);const audits = new Map(auditPages.map((p) => [p.key.toLowerCase(), p]));// A page listed for another reason still takes its title and traffic from site_pages.const sitePagesByKey = new Map(sitePages.map((p) => [opportunityKey(p.url), p]));@@ -191,8 +223,9 @@ export function buildOpportunities({excluded.push({ key: page.key, url: page.url, path: page.path, title: page.title });continue;}- // Checkout, login, legal and the like carry no opportunity, unless a team pinned one.- if (!page.pinned && isExcludedPath(page.path)) continue;+ // Checkout, login, legal and the like carry no opportunity, nor do the+ // brand's exclude patterns, unless a team pinned the page.+ if (!page.pinned && (isExcludedPath(page.path) || excludedByPattern(page.path))) continue;if (!page.pinned && page.reasons.length === 0) continue;const audit = audits.get(page.key);diff --git a/server/src/lib/audit/opportunities.test.js b/server/src/lib/audit/opportunities.test.jsindex 0e769caee..45f569458 100644--- a/server/src/lib/audit/opportunities.test.js+++ b/server/src/lib/audit/opportunities.test.js@@ -3,6 +3,8 @@ import {aiVisitsByPage,buildOpportunities,competitorGapPages,+ excludePatternMatcher,+ normalizeExcludePattern,opportunityKey,} from './opportunities.js';@@ -166,6 +168,50 @@ describe('buildOpportunities', () => {});});+describe('exclude patterns', () => {+ it('stores a pattern as a lowercased path without a trailing slash', () => {+ expect(normalizeExcludePattern(' /Legal/* ')).toBe('/legal/*');+ expect(normalizeExcludePattern('/blog/')).toBe('/blog');+ expect(normalizeExcludePattern('/')).toBe('/');+ expect(normalizeExcludePattern('legal/*')).toBeNull();+ expect(normalizeExcludePattern('/a b')).toBeNull();+ expect(normalizeExcludePattern(`/${'x'.repeat(200)}`)).toBeNull();+ });++ it('matches the whole path, * standing for anything, in any case', () => {+ const excluded = excludePatternMatcher(['/legal/*', '/tag/*/page', '/about.html']);+ expect(excluded('/legal/terms')).toBe(true);+ expect(excluded('/Legal/privacy/eu')).toBe(true);+ expect(excluded('/legal')).toBe(false);+ expect(excluded('/tag/coffee/page')).toBe(true);+ expect(excluded('/about.html')).toBe(true);+ // The dot is a dot, not any character.+ expect(excluded('/aboutxhtml')).toBe(false);+ expect(excludePatternMatcher([])('/x')).toBe(false);+ });++ it('leaves pages under a pattern out of the inbox, unless pinned', () => {+ const { rows, excluded } = build({+ sitePages: [+ { url: 'https://acme.com/stories/old', title: 'Old', ga_sessions: 1, ai_citations: 0 },+ { url: 'https://acme.com/stories/best', title: 'Best', ga_sessions: 1, ai_citations: 0 },+ { url: 'https://acme.com/pricing', title: 'Pricing', ga_sessions: 9, ai_citations: 0 },+ ],+ prefs: [+ {+ page_key: 'acme.com/stories/best',+ url: 'https://acme.com/stories/best',+ state: 'pinned',+ },+ ],+ excludePatterns: ['/stories/*'],+ });+ expect(rows.map((r) => r.path)).toEqual(['/stories/best', '/pricing']);+ // A pattern isn't a page to put back: the Excluded list doesn't show it.+ expect(excluded).toEqual([]);+ });+});+describe('aiVisitsByPage', () => {it('takes Google Analytics where it has the page, else the snippet, never both', () => {const visits = aiVisitsByPage({diff --git a/server/src/lib/plan-guard-site-audit.test.js b/server/src/lib/plan-guard-site-audit.test.jsindex 5d3bfa249..26f9c8f2d 100644--- a/server/src/lib/plan-guard-site-audit.test.js+++ b/server/src/lib/plan-guard-site-audit.test.js@@ -3,12 +3,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/*** The Site Audit quota counts audits still running as well as completed* ones (completed audits are charged when they finish), and a bulk start is- * checked for every page it asks for at once.+ * checked for every page it asks for at once. The auto-audit runs still to+ * come keep their share out of the user's pool (SA-006).*/let used;+let autoUsed;let running;let runningQuery;+let settings;+let recordedDays;function query(table) {const filters = [];@@ -28,22 +32,38 @@ function query(table) {if (table === 'organizations') {return resolve({ data: { plan: 'starter', subscription_status: 'active' }, error: null });}- if (table === 'site_audit_usage') return resolve({ count: used, error: null });+ if (table === 'site_audit_usage') {+ const auto = filters.some(([, col, val]) => col === 'source' && val === 'auto');+ return resolve({ count: auto ? autoUsed : used, error: null });+ }if (table === 'site_audits') {runningQuery = filters;return resolve({ count: running, error: null });}+ if (table === 'site_audit_settings') return resolve({ data: settings, error: null });+ if (table === 'site_audit_auto_runs') {+ return resolve({ data: recordedDays.map((d) => ({ run_day: d })), error: null });+ }return resolve({ data: null, error: null });},};return builder;}+// The 10th of a calendar month: day 1 ran, day 7's run is due.+const now = new Date('2026-10-10T06:00:00Z');+const OFF = { auto_audit: false, email_after_run: false };+let quota;beforeEach(async () => {vi.resetModules();process.env.IS_CLOUD = 'true';+ used = 0;+ autoUsed = 0;+ running = 0;+ settings = null;+ recordedDays = [];vi.doMock('../config/supabase.js', () => ({ default: { from: (t) => query(t) } }));quota = await import('./plan-guard.js');});@@ -55,13 +75,15 @@ afterEach(() => {describe('Site Audit quota', () => {it("takes running audits out of what's left", async () => {+ settings = OFF;used = 90;running = 4;- expect(await quota.getSiteAuditQuotaStatus('org-1')).toEqual({+ expect(await quota.getSiteAuditQuotaStatus('org-1', { now })).toMatchObject({used: 90,running: 4,limit: 100,remaining: 6,+ auto: { enabled: false, reserved: 0 },});// Running audits of the org's brands, started in the last two hours.expect(runningQuery).toEqual(@@ -74,41 +96,111 @@ describe('Site Audit quota', () => {});it('starts a bulk run only when every page fits', async () => {+ settings = OFF;used = 90;running = 4;- await expect(quota.enforceSiteAuditQuota('org-1', 6)).resolves.toMatchObject({ remaining: 6 });- await expect(quota.enforceSiteAuditQuota('org-1', 7)).rejects.toThrow(+ await expect(quota.enforceSiteAuditQuota('org-1', 6, { now })).resolves.toMatchObject({+ remaining: 6,+ });+ await expect(quota.enforceSiteAuditQuota('org-1', 7, { now })).rejects.toThrow('These 7 audits need more than the 6 left this month on the Starter plan. Select up to 6.',);});it('refuses one more audit when completed and running ones fill the quota', async () => {+ settings = OFF;used = 97;running = 3;- await expect(quota.enforceSiteAuditQuota('org-1')).rejects.toMatchObject({+ await expect(quota.enforceSiteAuditQuota('org-1', 1, { now })).rejects.toMatchObject({statusCode: 429,message: expect.stringContaining('(100/100, 3 still running)'),});used = 100;running = 0;- await expect(quota.enforceSiteAuditQuota('org-1')).rejects.toThrow(+ await expect(quota.enforceSiteAuditQuota('org-1', 1, { now })).rejects.toThrow('Monthly Site Audit limit reached (100/100) on the Starter plan.',);});- it('never limits a self-hosted install', async () => {+ it("keeps the auto-audit runs still to come out of the user's pool", async () => {+ // Auto-audit on by default: 5 a run; day 1 ran, days 7–28 are to come.+ recordedDays = [1];+ used = 30;+ autoUsed = 5;+ expect(await quota.getSiteAuditQuotaStatus('org-1', { now })).toMatchObject({+ used: 30,+ limit: 100,+ remaining: 50,+ auto: {+ enabled: true,+ setting: null,+ perRun: 5,+ reserved: 20,+ used: 5,+ due: { day: 7 },+ nextRun: { day: 7, at: now.toISOString() },+ periodStart: '2026-10-01T00:00:00.000Z',+ periodEnd: '2026-11-01T00:00:00.000Z',+ runs: [+ { day: 1, at: '2026-10-01T00:00:00.000Z', done: true },+ { day: 7, at: '2026-10-07T00:00:00.000Z', done: false },+ { day: 14, at: '2026-10-14T00:00:00.000Z', done: false },+ { day: 21, at: '2026-10-21T00:00:00.000Z', done: false },+ { day: 28, at: '2026-10-28T00:00:00.000Z', done: false },+ ],+ },+ });++ // The user can't take the runs' slots; a run can.+ await expect(quota.enforceSiteAuditQuota('org-1', 51, { now })).rejects.toThrow(+ 'These 51 audits need more than the 50 left this month on the Starter plan (20 more are kept for auto-audits). Select up to 50.',+ );+ await expect(+ quota.enforceSiteAuditQuota('org-1', 5, { source: 'auto', now }),+ ).resolves.toMatchObject({ remaining: 70 });++ // Day 7 recorded: its unused slots are back in the user's pool.+ recordedDays = [1, 7];+ expect(await quota.getSiteAuditQuotaStatus('org-1', { now })).toMatchObject({+ remaining: 55,+ auto: { reserved: 15, due: null, nextRun: { day: 14 } },+ });+ });++ it('says which share is left when the user has used theirs', async () => {+ recordedDays = [1];+ used = 80;+ await expect(quota.enforceSiteAuditQuota('org-1', 1, { now })).rejects.toThrow(+ "You've used your 80 Site Audits this month on the Starter plan. 20 auto audits are still scheduled. Turn off auto-audit in Site Audit settings to use them now, or upgrade.",+ );+ // Turned off, the whole quota is the user's.+ settings = OFF;+ await expect(quota.enforceSiteAuditQuota('org-1', 20, { now })).resolves.toMatchObject({+ remaining: 20,+ });+ });++ it('never limits a self-hosted install, where auto-audit starts off', async () => {delete process.env.IS_CLOUD;used = 1000;running = 50;- await expect(quota.enforceSiteAuditQuota('org-1', 50)).resolves.toMatchObject({+ await expect(quota.enforceSiteAuditQuota('org-1', 50, { now })).resolves.toMatchObject({remaining: -1,});- expect(await quota.getSiteAuditQuotaStatus('org-1')).toEqual({+ expect(await quota.getSiteAuditQuotaStatus('org-1', { now })).toMatchObject({used: 0,running: 0,limit: -1,remaining: -1,+ auto: { enabled: false, perRun: 25, reserved: 0, due: null },+ });++ // Turned on, it runs 25 pages a run and keeps nothing back.+ settings = { auto_audit: true, email_after_run: true };+ expect(await quota.getSiteAuditQuotaStatus('org-1', { now })).toMatchObject({+ remaining: -1,+ auto: { enabled: true, emailAfterRun: true, reserved: 0, due: { day: 7 } },});});});diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.jsindex 3c915b424..37e573c0d 100644--- a/server/src/lib/plan-guard.js+++ b/server/src/lib/plan-guard.js@@ -15,6 +15,13 @@ import {} from './improve-cost.js';import { RELEVANCE_BUDGET_SHARE } from './suggestion-relevance.js';import { AUDIT_RUN_TIMEOUT_MS } from './audit/history.js';+import {+ autoAuditEnabled,+ dueRun,+ pendingRuns,+ perRunSlots,+ runSchedule,+} from './audit/auto-audit.js';export class PlanLimitError extends Error {constructor(message, statusCode = 403) {@@ -218,8 +225,8 @@ export async function getVolumeQuotaStatus(userId) {return { used, limit: maxAnalyses, remaining: maxAnalyses - used };}-function startOfCurrentMonth() {- const start = new Date();+function startOfCurrentMonth(now = new Date()) {+ const start = new Date(now);start.setUTCDate(1);start.setUTCHours(0, 0, 0, 0);return start;@@ -237,7 +244,7 @@ function startOfCurrentMonth() {* in quota-period.js.*/export async function quotaPeriodStart(orgId, now = new Date()) {- if (!isCloud() || !orgId) return startOfCurrentMonth();+ if (!isCloud() || !orgId) return startOfCurrentMonth(now);const { data: org } = await supabaseAdmin.from('organizations')@@ -247,7 +254,7 @@ export async function quotaPeriodStart(orgId, now = new Date()) {const endsAt = org?.subscription_ends_at ? new Date(org.subscription_ends_at) : null;if (!endsAt || Number.isNaN(endsAt.getTime()) || !isSubscriptionActive(org.subscription_status)) {- return startOfCurrentMonth();+ return startOfCurrentMonth(now);}return anchoredPeriodStart(endsAt, now);@@ -499,14 +506,22 @@ export async function getContentUsage(orgId) {};}-async function countSiteAuditUsageThisMonth(orgId) {- const periodStart = await quotaPeriodStart(orgId);- const { count } = await supabaseAdmin- .from('site_audit_usage')- .select('*', { count: 'exact', head: true })- .eq('organization_id', orgId)- .gte('used_at', periodStart.toISOString());- return count || 0;+/** Audits charged this period, and those of them auto-audit runs started. */+async function countSiteAuditUsage(orgId, periodStart) {+ const since = periodStart.toISOString();+ const count = (source) => {+ let query = supabaseAdmin+ .from('site_audit_usage')+ .select('*', { count: 'exact', head: true })+ .eq('organization_id', orgId)+ .gte('used_at', since);+ if (source) query = query.eq('source', source);+ return query;+ };+ const [all, auto] = await Promise.all([count(null), count('auto')]);+ if (all.error) throw new Error(all.error.message);+ if (auto.error) throw new Error(auto.error.message);+ return { used: all.count || 0, autoUsed: auto.count || 0 };}// How long a running audit holds a quota slot (AUDIT_RUN_TIMEOUT_MS): one@@ -529,33 +544,126 @@ async function countRunningSiteAudits(orgId) {return count || 0;}+/**+ * The org's Site Audit settings (SA-006). No row is the defaults: auto-audit+ * as the plan has it (null), no e-mail.+ */+async function readSiteAuditSettings(orgId) {+ const { data, error } = await supabaseAdmin+ .from('site_audit_settings')+ .select('auto_audit, email_after_run')+ .eq('organization_id', orgId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ return { autoAudit: data?.auto_audit ?? null, emailAfterRun: data?.email_after_run ?? false };+}++/**+ * Where the org's auto-audit stands this period (SA-006): whether it runs,+ * each run's share, the five runs and which are recorded, the share the runs+ * still to come keep out of the user's pool, and the run whose turn it is.+ */+async function siteAuditAutoStatus(orgId, limit, periodStart, now) {+ const [settings, { data: runRows, error }] = await Promise.all([+ readSiteAuditSettings(orgId),+ supabaseAdmin+ .from('site_audit_auto_runs')+ .select('run_day')+ .eq('organization_id', orgId)+ .eq('period_start', periodStart.toISOString()),+ ]);+ if (error) throw new Error(error.message);++ const enabled = autoAuditEnabled(settings.autoAudit, limit);+ const perRun = perRunSlots(limit);+ const periodEnd = shiftMonthClamped(periodStart, 1);+ const schedule = runSchedule(periodStart, periodEnd);+ const recorded = (runRows ?? []).map((r) => r.run_day);+ const pending = enabled ? pendingRuns(schedule, recorded, now) : [];+ const due = enabled ? dueRun(schedule, now) : null;+ const next = pending[0] ?? null;++ return {+ enabled,+ // The org's own choice; null follows the plan.+ setting: settings.autoAudit,+ emailAfterRun: settings.emailAfterRun,+ perRun,+ // A plan without a monthly limit keeps nothing back.+ reserved: limit === -1 ? 0 : perRun * pending.length,+ periodStart: periodStart.toISOString(),+ periodEnd: periodEnd.toISOString(),+ runs: schedule.map((run) => ({+ day: run.day,+ at: run.at.toISOString(),+ done: recorded.includes(run.day),+ })),+ nextRun: next+ ? { day: next.day, at: new Date(Math.max(next.at.getTime(), now.getTime())).toISOString() }+ : null,+ // The run to start now: its turn, not recorded yet.+ due: due && !recorded.includes(due.day) ? { day: due.day } : null,+ };+}++/**+ * The org's Site Audit quota this period: completed and running audits+ * against plan.limits.maxSiteAudits (Starter 100, Growth 500,+ * Enterprise/Self-hosted unlimited), and the auto-audit share.+ */+async function siteAuditQuota(orgId, now) {+ const plan = await resolveOrgPlanByOrgId(orgId);+ const limit = plan.limits.maxSiteAudits;+ const periodStart = await quotaPeriodStart(orgId, now);+ const [{ used, autoUsed }, running, auto] = await Promise.all([+ limit === -1 ? { used: 0, autoUsed: 0 } : countSiteAuditUsage(orgId, periodStart),+ limit === -1 ? 0 : countRunningSiteAudits(orgId),+ siteAuditAutoStatus(orgId, limit, periodStart, now),+ ]);+ return { plan, limit, used, running, auto: { ...auto, used: autoUsed } };+}+/*** Enforce the monthly Site Audit quota for an organization before starting* `count` audits. Counts completed audits this billing period, plus the ones* still running, against plan.limits.maxSiteAudits (Starter 100, Growth 500,- * Enterprise/Self-hosted unlimited). Throws PlanLimitError (429) when the- * audits don't fit, starting none; returns { plan, remaining } otherwise.+ * Enterprise/Self-hosted unlimited). A user's audits also leave the slots of+ * the auto-audit runs still to come (SA-006); a run's own audits use them.+ * Throws PlanLimitError (429) when the audits don't fit, starting none;+ * returns { plan, remaining } otherwise.+ *+ * @param {string} orgId+ * @param {number} [count]+ * @param {{ source?: 'user'|'auto', now?: Date }} [options]*/-export async function enforceSiteAuditQuota(orgId, count = 1) {- const plan = await resolveOrgPlanByOrgId(orgId);- const max = plan.limits.maxSiteAudits;- if (max === -1) return { plan, remaining: -1 };-- const [used, running] = await Promise.all([- countSiteAuditUsageThisMonth(orgId),- countRunningSiteAudits(orgId),- ]);- const remaining = max - used - running;+export async function enforceSiteAuditQuota(+ orgId,+ count = 1,+ { source = 'user', now = new Date() } = {},+) {+ const { plan, limit, used, running, auto } = await siteAuditQuota(orgId, now);+ if (limit === -1) return { plan, remaining: -1 };++ const reserved = source === 'auto' ? 0 : auto.reserved;+ const remaining = limit - used - running - reserved;+ const inFlight = running > 0 ? `, ${running} still running` : '';+ if (remaining <= 0 && reserved > 0) {+ // The spec's empty-pool message: the user's share is used, the runs' isn't.+ throw new PlanLimitError(+ `You've used your ${limit - reserved} Site Audits this month on the ${plan.name} plan${running > 0 ? ` (${running} still running)` : ''}. ${reserved} auto audits are still scheduled. Turn off auto-audit in Site Audit settings to use them now, or upgrade.`,+ 429,+ );+ }if (remaining <= 0) {- const inFlight = running > 0 ? `, ${running} still running` : '';throw new PlanLimitError(- `Monthly Site Audit limit reached (${used + running}/${max}${inFlight}) on the ${plan.name} plan. Resets when your subscription renews — upgrade for more.`,+ `Monthly Site Audit limit reached (${used + running}/${limit}${inFlight}) on the ${plan.name} plan. Resets when your subscription renews — upgrade for more.`,429,);}if (count > remaining) {+ const kept = reserved > 0 ? ` (${reserved} more are kept for auto-audits)` : '';throw new PlanLimitError(- `These ${count} audits need more than the ${remaining} left this month on the ${plan.name} plan. Select up to ${remaining}.`,+ `These ${count} audits need more than the ${remaining} left this month on the ${plan.name} plan${kept}. Select up to ${remaining}.`,429,);}@@ -565,19 +673,21 @@ export async function enforceSiteAuditQuota(orgId, count = 1) {/*** Get current Site Audit quota status without enforcing.- * Returns { used, running, limit, remaining }; running audits are already- * taken out of what remains.+ * Returns { used, running, limit, remaining, auto }: remaining is the user's+ * pool, with running audits and the auto-audit runs still to come taken out;+ * auto is where auto-audit stands (siteAuditAutoStatus, plus what its runs+ * used this period).*/-export async function getSiteAuditQuotaStatus(orgId) {- const plan = await resolveOrgPlanByOrgId(orgId);- const max = plan.limits.maxSiteAudits;- if (max === -1) return { used: 0, running: 0, limit: -1, remaining: -1 };-- const [used, running] = await Promise.all([- countSiteAuditUsageThisMonth(orgId),- countRunningSiteAudits(orgId),- ]);- return { used, running, limit: max, remaining: Math.max(0, max - used - running) };+export async function getSiteAuditQuotaStatus(orgId, { now = new Date() } = {}) {+ const { limit, used, running, auto } = await siteAuditQuota(orgId, now);+ if (limit === -1) return { used: 0, running: 0, limit: -1, remaining: -1, auto };+ return {+ used,+ running,+ limit,+ remaining: Math.max(0, limit - used - running - auto.reserved),+ auto,+ };}/**diff --git a/server/src/routes/audits-opportunities.test.js b/server/src/routes/audits-opportunities.test.jsindex d505c6e12..16a210f0f 100644--- a/server/src/routes/audits-opportunities.test.js+++ b/server/src/routes/audits-opportunities.test.js@@ -200,6 +200,12 @@ describe('GET /api/audits/opportunities', () => {expect(args.p_pages).toEqual(['https://acme.com/pricing']);});+ it("leaves out pages under the brand's exclude patterns (SA-006)", async () => {+ tables.site_audit_brand_settings = [{ brand_id: brandId, exclude_patterns: ['/pri*'] }];+ const body = await (await fetch(`${baseUrl}/opportunities?brandId=${brandId}`)).json();+ expect(body.opportunities).toEqual([]);+ });+it('reads every GA page past the first 1000', async () => {tables.page_opportunities = Array.from({ length: 1200 }, (_, i) => ({brand_id: brandId,diff --git a/server/src/routes/audits-pages.test.js b/server/src/routes/audits-pages.test.jsindex 9d2e5c9ff..b7789abaa 100644--- a/server/src/routes/audits-pages.test.js+++ b/server/src/routes/audits-pages.test.js@@ -14,6 +14,7 @@ let signalQueries;let inserted;let enforce;let pagesFetched;+let auditsModule;let server;let baseUrl;@@ -30,6 +31,7 @@ function query(table) {select: () => builder,single: () => builder,order: () => builder,+ update: () => builder,eq: (col, val) => {filters.eq[col] = val;return builder;@@ -82,10 +84,12 @@ async function startApp() {getOrgIdForUser: vi.fn(),PlanLimitError: class PlanLimitError extends Error {},}));- // An audit job that never gets its page, so the queue's limit can be seen.+ // An audit job that never gets its page, so the queue's limit can be seen;+ // a /fail page fails at once.vi.doMock('../lib/audit/context.js', () => ({buildAuditContext: (url) => {pagesFetched.push(url);+ if (url.includes('/fail')) return Promise.reject(new Error('blocked'));return new Promise(() => {});},}));@@ -98,7 +102,8 @@ async function startApp() {return { default: logger, logger };});- const { default: router } = await import('./audits.js');+ auditsModule = await import('./audits.js');+ const router = auditsModule.default;const app = express();app.use(express.json());app.use((req, _res, next) => {@@ -257,6 +262,45 @@ describe('POST /api/audits/bulk', () => {});});+describe('startAutoAudits', () => {+ const brandId = '33333333-3333-3333-3333-333333333333';++ it("checks the whole quota as a run's, marks the audits auto and runs them in their own pool", async () => {+ const urls = ['https://acme.com/a', 'https://acme.com/b', 'https://acme.com/c'];+ const { auditIds } = await auditsModule.startAutoAudits(brandId, urls, 'org-1');++ expect(enforce).toHaveBeenCalledWith('org-1', 3, { source: 'auto' });+ expect(auditIds).toEqual(['new-0', 'new-1', 'new-2']);+ expect(inserted.map((r) => [r.url, r.source])).toEqual([+ ['https://acme.com/a', 'auto'],+ ['https://acme.com/b', 'auto'],+ ['https://acme.com/c', 'auto'],+ ]);+ await new Promise((resolve) => setTimeout(resolve, 20));+ // Two at a time, and a user's bulk audit doesn't wait behind them.+ expect(pagesFetched).toEqual(urls.slice(0, 2));+ await fetch(`${baseUrl}/bulk`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ brandId, urls: ['https://acme.com/mine'] }),+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(pagesFetched).toEqual([...urls.slice(0, 2), 'https://acme.com/mine']);+ // A user's audit row keeps the column default.+ expect(inserted.at(-1).source).toBeUndefined();+ });++ it('resolves done once every audit has finished', async () => {+ const { done } = await auditsModule.startAutoAudits(+ brandId,+ ['https://acme.com/fail-1', 'https://acme.com/fail-2', 'https://acme.com/fail-3'],+ 'org-1',+ );+ await expect(done).resolves.toBeDefined();+ expect(pagesFetched).toHaveLength(3);+ });+});+describe('GET /api/audits/overview', () => {it("adds up the primary domain's latest audits: score, change, categories and gaps", async () => {audits[0].category_scores = { authority: { score: 0.4 }, eeat: { score: 0.3 } };diff --git a/server/src/routes/audits-settings.test.js b/server/src/routes/audits-settings.test.jsnew file mode 100644index 000000000..6b22a04ce--- /dev/null+++ b/server/src/routes/audits-settings.test.js@@ -0,0 +1,281 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Route-level tests for SA-006: GET/PUT /api/audits/settings (the org's+ * auto-audit switch and e-mail, the brand's exclude patterns and pinned+ * pages) and GET /api/audits/auto-runs/latest (the in-app notice).+ */++let tables;+let writes;+let quota;+let server;+let baseUrl;++function query(table) {+ const filters = {};+ let write = null;+ let head = false;+ const builder = {+ select: (_cols, opts) => {+ head = opts?.head ?? false;+ return builder;+ },+ eq: (col, val) => {+ filters[col] = val;+ return builder;+ },+ in: (col, vals) => {+ filters[col] = vals;+ return builder;+ },+ gte: () => builder,+ order: () => builder,+ limit: () => builder,+ single: () => {+ builder.one = true;+ return builder;+ },+ maybeSingle: () => {+ builder.one = true;+ return builder;+ },+ upsert: (rows, opts) => {+ write = { op: 'upsert', rows, opts };+ return builder;+ },+ then: (resolve) => {+ if (write) {+ writes.push({ table, ...write });+ return resolve({ data: null, error: null });+ }+ const matches = (row) =>+ Object.entries(filters).every(([col, val]) =>+ Array.isArray(val) ? val.includes(row[col]) : row[col] === val,+ );+ const rows = (tables[table] ?? []).filter(matches);+ if (head) return resolve({ count: rows.length, error: null });+ return resolve({ data: builder.one ? (rows[0] ?? null) : rows, error: null });+ },+ };+ return builder;+}++async function startApp() {+ vi.resetModules();+ vi.doMock('../config/supabase.js', () => ({ default: { from: (t) => query(t) } }));+ vi.doMock('../lib/access.js', () => ({ assertBrandAccess: async () => ({ orgId: 'org-1' }) }));+ vi.doMock('../lib/plan-guard.js', () => ({+ requireFeature: () => (req, res, next) => next(),+ enforceSiteAuditQuota: vi.fn(),+ getSiteAuditQuotaStatus: vi.fn(async () => quota),+ getOrgIdForUser: vi.fn(),+ PlanLimitError: class PlanLimitError extends Error {},+ }));+ vi.doMock('../lib/audit/context.js', () => ({ buildAuditContext: vi.fn() }));+ vi.doMock('../lib/audit/engine.js', () => ({ runSignals: vi.fn() }));+ vi.doMock('../lib/audit/llm-signals.js', () => ({ evaluateLlmSignals: vi.fn() }));+ vi.doMock('../lib/audit/external-signals.js', () => ({ evaluateBrandEntity: vi.fn() }));+ vi.doMock('../lib/audit/recommendations.js', () => ({+ brandFactsFor: vi.fn(),+ generateRecommendations: vi.fn(),+ }));+ vi.doMock('../lib/logger.js', () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };+ return { default: logger, logger };+ });++ const { default: router } = await import('./audits.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/audits', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/audits`;+}++const brandId = '33333333-3333-3333-3333-333333333333';+const otherBrand = '44444444-4444-4444-4444-444444444444';++beforeEach(async () => {+ writes = [];+ quota = {+ used: 10,+ running: 0,+ limit: 100,+ remaining: 70,+ auto: { enabled: true, setting: null, emailAfterRun: false, perRun: 5 },+ };+ tables = {+ profiles: [{ id: 'u1', role: 'admin' }],+ site_audit_brand_settings: [{ brand_id: brandId, exclude_patterns: ['/careers/*'] }],+ site_audit_page_prefs: [+ {+ brand_id: brandId,+ page_key: 'acme.com/about',+ url: 'https://acme.com/about',+ state: 'pinned',+ },+ {+ brand_id: brandId,+ page_key: 'acme.com/old',+ url: 'https://acme.com/old',+ state: 'excluded',+ },+ ],+ site_audit_auto_runs: [],+ site_audits: [],+ audit_signal_results: [],+ };+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+ for (const mod of [+ '../config/supabase.js',+ '../lib/access.js',+ '../lib/plan-guard.js',+ '../lib/audit/context.js',+ '../lib/audit/engine.js',+ '../lib/audit/llm-signals.js',+ '../lib/audit/external-signals.js',+ '../lib/audit/recommendations.js',+ '../lib/logger.js',+ ]) {+ vi.doUnmock(mod);+ }+});++const put = (body) =>+ fetch(`${baseUrl}/settings`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++describe('GET /api/audits/settings', () => {+ it("returns the org's auto-audit and the brand's patterns and pinned pages", async () => {+ const res = await fetch(`${baseUrl}/settings?brandId=${brandId}`);+ expect(res.status).toBe(200);+ expect((await res.json()).settings).toEqual({+ autoAudit: { enabled: true, setting: null, perRun: 5, limit: 100 },+ emailAfterRun: false,+ excludePatterns: ['/careers/*'],+ pinned: [{ key: 'acme.com/about', url: 'https://acme.com/about' }],+ });+ });+});++describe('PUT /api/audits/settings', () => {+ it('saves the switch and e-mail for the org, and the patterns for the brand', async () => {+ const res = await put({+ brandId,+ autoAudit: false,+ emailAfterRun: true,+ excludePatterns: ['/Legal/*', ' /tag/ ', '/legal/*'],+ });+ expect(res.status).toBe(200);+ expect(writes).toEqual([+ expect.objectContaining({+ table: 'site_audit_settings',+ rows: expect.objectContaining({+ organization_id: 'org-1',+ auto_audit: false,+ email_after_run: true,+ updated_by: 'u1',+ }),+ opts: { onConflict: 'organization_id' },+ }),+ expect.objectContaining({+ table: 'site_audit_brand_settings',+ rows: expect.objectContaining({+ brand_id: brandId,+ exclude_patterns: ['/legal/*', '/tag'],+ }),+ opts: { onConflict: 'brand_id' },+ }),+ ]);+ });++ it('writes only what it was sent, and null puts the plan default back', async () => {+ await put({ brandId, autoAudit: null });+ expect(writes).toHaveLength(1);+ expect(writes[0].rows).toEqual({+ organization_id: 'org-1',+ auto_audit: null,+ updated_by: 'u1',+ updated_at: expect.any(String),+ });+ });++ it('refuses a pattern that is not a path, and a member who is not an admin or manager', async () => {+ let res = await put({ brandId, excludePatterns: ['legal/*'] });+ expect(res.status).toBe(400);+ expect((await res.json()).message).toBe(+ '"legal/*" isn\'t a page path. Start it with /, as in /legal/*.',+ );++ tables.profiles = [{ id: 'u1', role: 'viewer' }];+ res = await put({ brandId, autoAudit: false });+ expect(res.status).toBe(403);+ expect(writes).toEqual([]);+ });+});++describe('GET /api/audits/auto-runs/latest', () => {+ const run = (id, auditIds, startedAt, status = 'completed') => ({+ id,+ organization_id: 'org-1',+ run_day: 7,+ status,+ audit_ids: auditIds,+ started_at: startedAt,+ finished_at: status === 'completed' ? startedAt : null,+ });++ it("sums up the latest run that audited this brand's pages", async () => {+ // Newest first, as the route asks: the newest run audited the other brand only.+ tables.site_audit_auto_runs = [+ run('r3', ['b1'], '2026-10-14T06:00:00Z'),+ run('r2', ['a1', 'a2', 'a3', 'b2'], '2026-10-07T06:00:00Z'),+ ];+ tables.site_audits = [+ { id: 'a1', brand_id: brandId, status: 'completed' },+ { id: 'a2', brand_id: brandId, status: 'completed' },+ { id: 'a3', brand_id: brandId, status: 'running' },+ { id: 'b1', brand_id: otherBrand, status: 'completed' },+ { id: 'b2', brand_id: otherBrand, status: 'completed' },+ ];+ tables.audit_signal_results = [+ { audit_id: 'a1', status: 'fail' },+ { audit_id: 'a2', status: 'fail' },+ { audit_id: 'b2', status: 'fail' },+ ];++ const res = await fetch(`${baseUrl}/auto-runs/latest?brandId=${brandId}`);+ expect((await res.json()).run).toEqual({+ id: 'r2',+ day: 7,+ status: 'completed',+ startedAt: '2026-10-07T06:00:00Z',+ finishedAt: '2026-10-07T06:00:00Z',+ pages: 3,+ completed: 2,+ running: 1,+ criticalIssues: 2,+ });+ });++ it('is null when no recent run audited the brand', async () => {+ const res = await fetch(`${baseUrl}/auto-runs/latest?brandId=${brandId}`);+ expect((await res.json()).run).toBeNull();+ });+});diff --git a/server/src/routes/audits.js b/server/src/routes/audits.jsindex 1b5500721..d68382a89 100644--- a/server/src/routes/audits.js+++ b/server/src/routes/audits.js@@ -38,8 +38,12 @@ import {aiVisitsByPage,buildOpportunities,competitorGapPages,+ EXCLUDE_PATTERN_MAX_LENGTH,+ EXCLUDE_PATTERNS_MAX,+ normalizeExcludePattern,opportunityKey,} from '../lib/audit/opportunities.js';+import { AUTO_AUDIT } from '../lib/audit/auto-audit.js';import { rankOpportunities } from '../lib/audit/priority.js';import { ENGINE_THRESHOLDS } from '../config/action-engine.js';import { runSignals } from '../lib/audit/engine.js';@@ -145,13 +149,16 @@ async function countIssues(auditIds) {return counts;}+/** site_audits/site_audit_usage.source for a run's audits; a user's are the column default. */+const sourceColumn = (source) => (source === 'auto' ? { source } : {});+/*** Run the full audit (fetch → deterministic + LLM + Wikidata → score →* persist) for an already-created `running` row. Runs detached from the* request so the client gets an id immediately and polls GET /:id. Always* resolves — on failure it marks the row `failed` rather than throwing.*/-async function runAuditJob(auditId, brandId, url, orgId) {+async function runAuditJob(auditId, brandId, url, orgId, source = 'user') {try {// The brand name is needed for the Wikidata brand-entity lookup. The page// is otherwise evaluated entirely on its own terms — the LLM infers the@@ -212,11 +219,12 @@ async function runAuditJob(auditId, brandId, url, orgId) {// Don't let a failed completion update leave the row stuck in 'running'.if (completeErr) throw completeErr;- // Charge the monthly quota only for audits that actually completed.+ // Charge the monthly quota only for audits that actually completed; an+ // auto-audit run's audits are charged as its own (SA-006).if (orgId) {await supabaseAdmin.from('site_audit_usage')- .insert({ organization_id: orgId, audit_id: auditId });+ .insert({ organization_id: orgId, audit_id: auditId, ...sourceColumn(source) });}} catch (err) {logger.error({ err, auditId, brandId }, 'audit run failed');@@ -259,60 +267,102 @@ export const BULK_AUDIT_MAX = 50;/** Bulk audits run at once; the rest wait their turn, still `running`. */export const BULK_AUDIT_CONCURRENCY = 3;-// One pool for every bulk request, so 50 re-audits don't fetch and score 50-// pages at the same time.-const bulkQueue = [];-let bulkActive = 0;--function drainBulkQueue() {- while (bulkActive < BULK_AUDIT_CONCURRENCY && bulkQueue.length > 0) {- const job = bulkQueue.shift();- bulkActive += 1;- job()- .catch((err) => logger.error({ err }, 'bulk audit job crashed'))- .finally(() => {- bulkActive -= 1;- drainBulkQueue();- });- }-}+/** Auto-audit runs' audits at once: their own pool, so a run doesn't hold up a user's bulk audit. */+export const AUTO_AUDIT_CONCURRENCY = 2;/**- * Start audits of several pages of a brand. The quota is checked for all of- * them first, so either every page is queued or none is (PlanLimitError).- * Repeat spellings of one page are audited once. Returns the running rows.+ * A pool running audit jobs a few at a time; the rest wait their turn. Each+ * job's promise resolves when it has run (runAuditJob never rejects).*/-export async function createAndQueueAudits(brandId, urls, orgId) {- const byPage = new Map();- for (const url of urls) {- const key = pageKey(url)?.key;- if (key && !byPage.has(key)) byPage.set(key, url);- }- const unique = [...byPage.values()];+function auditPool(concurrency, label) {+ const queue = [];+ let active = 0;+ const drain = () => {+ while (active < concurrency && queue.length > 0) {+ const { job, resolve } = queue.shift();+ active += 1;+ job()+ .catch((err) => logger.error({ err }, `${label} audit job crashed`))+ .finally(() => {+ active -= 1;+ resolve();+ drain();+ });+ }+ };+ return (job) =>+ new Promise((resolve) => {+ queue.push({ job, resolve });+ drain();+ });+}- await enforceSiteAuditQuota(orgId, unique.length);+// One pool for every bulk request, so 50 re-audits don't fetch and score 50+// pages at the same time; another for the auto-audit runs.+const runInBulkPool = auditPool(BULK_AUDIT_CONCURRENCY, 'bulk');+const runInAutoPool = auditPool(AUTO_AUDIT_CONCURRENCY, 'auto');- const { data: created, error } = await supabaseAdmin+/** The `running` rows of a brand's audits, one per page. */+async function insertRunningAudits(brandId, urls, source) {+ const { data, error } = await supabaseAdmin.from('site_audits').insert(- unique.map((url) => ({+ urls.map((url) => ({brand_id: brandId,url,status: 'running',rubric_version: RUBRIC_VERSION,+ ...sourceColumn(source),})),).select('*');if (error) throw error;+ return data;+}- for (const row of created) {- bulkQueue.push(() => runAuditJob(row.id, brandId, row.url, orgId));+/** One URL per page: repeat spellings of a page are audited once. */+function uniquePages(urls) {+ const byPage = new Map();+ for (const url of urls) {+ const key = pageKey(url)?.key;+ if (key && !byPage.has(key)) byPage.set(key, url);}- drainBulkQueue();+ return [...byPage.values()];+}+/**+ * Start audits of several pages of a brand. The quota is checked for all of+ * them first, so either every page is queued or none is (PlanLimitError).+ * Repeat spellings of one page are audited once. Returns the running rows.+ */+export async function createAndQueueAudits(brandId, urls, orgId) {+ const unique = uniquePages(urls);+ await enforceSiteAuditQuota(orgId, unique.length);++ const created = await insertRunningAudits(brandId, unique, 'user');+ for (const row of created) {+ runInBulkPool(() => runAuditJob(row.id, brandId, row.url, orgId));+ }return created.map((row) => assembleAudit(row, []));}+/**+ * Start an auto-audit run's audits of a brand's pages (SA-006): checked+ * against the whole quota, the run's reserved slots included, and charged+ * as auto. Returns the running rows' ids, and `done`, which resolves once+ * every one of them has completed or failed.+ */+export async function startAutoAudits(brandId, urls, orgId) {+ const unique = uniquePages(urls);+ await enforceSiteAuditQuota(orgId, unique.length, { source: 'auto' });++ const created = await insertRunningAudits(brandId, unique, 'auto');+ const done = Promise.all(+ created.map((row) => runInAutoPool(() => runAuditJob(row.id, brandId, row.url, orgId, 'auto'))),+ );+ return { auditIds: created.map((row) => row.id), done };+}+const bulkSchema = z.object({brandId: z.guid(),urls: z@@ -641,6 +691,76 @@ async function opportunityAiVisits(brandId, urls) {return aiVisitsByPage(data);}+/** A brand's exclude patterns (SA-006 settings), as stored. */+async function readExcludePatterns(brandId) {+ const { data, error } = await supabaseAdmin+ .from('site_audit_brand_settings')+ .select('exclude_patterns')+ .eq('brand_id', brandId)+ .maybeSingle();+ if (error) throw error;+ return data?.exclude_patterns ?? [];+}++/**+ * The Opportunities inbox of a brand (SA-004): its pages worth auditing,+ * each with why, scored and ordered by priority (SA-005), plus the excluded+ * pages to put back. The route shows it; auto-audit runs take their pages+ * from it (SA-006).+ */+export async function readOpportunityInbox(brandId) {+ const [primary, gaPages, sitePages, audits, prefs, excludePatterns] = await Promise.all([+ primaryDomainOf(brandId),+ // Up to 30% of GA's 5,000 pages a day: past PostgREST's 1000-row page.+ readAllRpcRows('page_opportunities', (from, to) =>+ supabaseAdmin+ .from('page_opportunities')+ .select('landing_page, value_signal, value_percentile, sessions, citation_state, citations')+ .eq('brand_id', brandId)+ .eq('kind', 'no_ai_traffic')+ .is('resolved_at', null)+ .order('landing_page', { ascending: true })+ .range(from, to),+ ),+ supabaseAdmin+ .from('site_pages')+ .select('url, title, h1, description, ga_sessions, ai_citations')+ .eq('brand_id', brandId),+ readBrandAudits(brandId),+ supabaseAdmin+ .from('site_audit_page_prefs')+ .select('page_key, url, state')+ .eq('brand_id', brandId),+ readExcludePatterns(brandId),+ ]);+ for (const read of [gaPages, sitePages, audits, prefs]) if (read.error) throw read.error;++ const competitorPages = await competitorOpportunityPages(brandId, sitePages.data ?? []);+ const { rows, excluded } = buildOpportunities({+ primaryHost: normStoredDomain(primary),+ gaPages: gaPages.data ?? [],+ sitePages: sitePages.data ?? [],+ auditPages: buildAuditPages(audits.data),+ competitorPages,+ prefs: prefs.data ?? [],+ excludePatterns,+ staleDays: ENGINE_THRESHOLDS.detection.auditMaxAgeDays,+ });+ const visits = await opportunityAiVisits(+ brandId,+ rows.map((r) => r.url),+ );++ return {+ // Scored and ordered once each page has its AI visits (SA-005).+ opportunities: rankOpportunities(+ rows.map((r) => ({ ...r, aiVisits: visits === null ? null : (visits.get(r.url) ?? 0) })),+ (sitePages.data ?? []).map((p) => p.ga_sessions),+ ),+ excluded,+ };+}+// GET /api/audits/opportunities?brandId=… — the Opportunities inbox (SA-004):// the brand's pages worth auditing, each with why (Google Analytics pages// without AI traffic, pages never audited or audited long ago), pinned pages@@ -655,56 +775,10 @@ router.get('/opportunities', async (req, res) => {try {await assertBrandAccess(brandId, userId);-- const [primary, gaPages, sitePages, audits, prefs] = await Promise.all([- primaryDomainOf(brandId),- // Up to 30% of GA's 5,000 pages a day: past PostgREST's 1000-row page.- readAllRpcRows('page_opportunities', (from, to) =>- supabaseAdmin- .from('page_opportunities')- .select(- 'landing_page, value_signal, value_percentile, sessions, citation_state, citations',- )- .eq('brand_id', brandId)- .eq('kind', 'no_ai_traffic')- .is('resolved_at', null)- .order('landing_page', { ascending: true })- .range(from, to),- ),- supabaseAdmin- .from('site_pages')- .select('url, title, h1, description, ga_sessions, ai_citations')- .eq('brand_id', brandId),- readBrandAudits(brandId),- supabaseAdmin- .from('site_audit_page_prefs')- .select('page_key, url, state')- .eq('brand_id', brandId),- ]);- for (const read of [gaPages, sitePages, audits, prefs]) if (read.error) throw read.error;-- const competitorPages = await competitorOpportunityPages(brandId, sitePages.data ?? []);- const { rows, excluded } = buildOpportunities({- primaryHost: normStoredDomain(primary),- gaPages: gaPages.data ?? [],- sitePages: sitePages.data ?? [],- auditPages: buildAuditPages(audits.data),- competitorPages,- prefs: prefs.data ?? [],- staleDays: ENGINE_THRESHOLDS.detection.auditMaxAgeDays,- });- const visits = await opportunityAiVisits(- brandId,- rows.map((r) => r.url),- );-+ const { opportunities, excluded } = await readOpportunityInbox(brandId);return res.json({success: true,- // Scored and ordered once each page has its AI visits (SA-005).- opportunities: rankOpportunities(- rows.map((r) => ({ ...r, aiVisits: visits === null ? null : (visits.get(r.url) ?? 0) })),- (sitePages.data ?? []).map((p) => p.ga_sessions),- ),+ opportunities,excluded,staleDays: ENGINE_THRESHOLDS.detection.auditMaxAgeDays,});@@ -775,6 +849,221 @@ router.put('/opportunities/prefs', async (req, res) => {}});+/** Roles that may change Site Audit settings, as for Daily Pulse's. */+const SETTINGS_ROLES = ['admin', 'manager'];++async function canChangeSettings(userId) {+ const { data, error } = await supabaseAdmin+ .from('profiles')+ .select('role')+ .eq('id', userId)+ .single();+ if (error) throw error;+ return SETTINGS_ROLES.includes(data?.role);+}++/**+ * Site Audit settings as the Settings dialog shows them (SA-006): the org's+ * auto-audit switch and e-mail, the brand's exclude patterns and pinned+ * pages.+ */+async function readAuditSettings(brandId, orgId) {+ const [quota, excludePatterns, { data: pinned, error }] = await Promise.all([+ getSiteAuditQuotaStatus(orgId),+ readExcludePatterns(brandId),+ supabaseAdmin+ .from('site_audit_page_prefs')+ .select('page_key, url')+ .eq('brand_id', brandId)+ .eq('state', 'pinned')+ .order('page_key', { ascending: true }),+ ]);+ if (error) throw error;+ return {+ autoAudit: {+ enabled: quota.auto.enabled,+ // The org's own choice; null follows the plan.+ setting: quota.auto.setting,+ perRun: quota.auto.perRun,+ limit: quota.limit,+ },+ emailAfterRun: quota.auto.emailAfterRun,+ excludePatterns,+ pinned: (pinned ?? []).map((p) => ({ key: p.page_key, url: p.url })),+ };+}++/** Express's reply for a failed settings or run read/write. */+function sendAuditError(req, res, err, message) {+ if (err instanceof PlanLimitError) {+ return res.status(err.statusCode).json({ success: false, message: err.message });+ }+ if (err.status) return res.status(err.status).json({ success: false, message: err.message });+ req.log.error({ err }, message);+ return res.status(500).json({ success: false, message: err.message });+}++// GET /api/audits/settings?brandId=… — the Site Audit settings (SA-006).+// Registered before /:id so "settings" isn't matched as an audit id.+router.get('/settings', async (req, res) => {+ const { brandId } = req.query;+ if (!brandId) {+ return res.status(400).json({ success: false, message: 'brandId is required' });+ }+ try {+ const { orgId } = await assertBrandAccess(brandId, req.user?.id);+ return res.json({ success: true, settings: await readAuditSettings(brandId, orgId) });+ } catch (err) {+ return sendAuditError(req, res, err, 'audit settings read failed');+ }+});++const settingsSchema = z.object({+ brandId: z.guid(),+ // null follows the plan's default again.+ autoAudit: z.boolean().nullable().optional(),+ emailAfterRun: z.boolean().optional(),+ excludePatterns: z+ .array(z.string().max(EXCLUDE_PATTERN_MAX_LENGTH * 2))+ .max(EXCLUDE_PATTERNS_MAX)+ .optional(),+});++// PUT /api/audits/settings — change the org's auto-audit switch and e-mail,+// and the brand's exclude patterns ({ brandId, autoAudit?, emailAfterRun?,+// excludePatterns? }). Admins and managers only.+router.put('/settings', async (req, res) => {+ const userId = req.user?.id;+ const parsed = settingsSchema.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res.status(400).json({+ success: false,+ message: parsed.error.issues[0]?.message ?? 'Invalid request',+ });+ }+ const { brandId, autoAudit, emailAfterRun, excludePatterns } = parsed.data;++ const patterns = [];+ for (const raw of excludePatterns ?? []) {+ const pattern = normalizeExcludePattern(raw);+ if (!pattern) {+ return res.status(400).json({+ success: false,+ message: `"${raw.trim()}" isn't a page path. Start it with /, as in /legal/*.`,+ });+ }+ if (!patterns.includes(pattern)) patterns.push(pattern);+ }++ try {+ const { orgId } = await assertBrandAccess(brandId, userId);+ if (!(await canChangeSettings(userId))) {+ return res.status(403).json({+ success: false,+ message: 'Only admins and managers can change Site Audit settings.',+ });+ }++ const now = new Date().toISOString();+ if (autoAudit !== undefined || emailAfterRun !== undefined) {+ const { error } = await supabaseAdmin.from('site_audit_settings').upsert(+ {+ organization_id: orgId,+ ...(autoAudit !== undefined ? { auto_audit: autoAudit } : {}),+ ...(emailAfterRun !== undefined ? { email_after_run: emailAfterRun } : {}),+ updated_by: userId ?? null,+ updated_at: now,+ },+ { onConflict: 'organization_id' },+ );+ if (error) throw error;+ }+ if (excludePatterns !== undefined) {+ const { error } = await supabaseAdmin.from('site_audit_brand_settings').upsert(+ {+ brand_id: brandId,+ exclude_patterns: patterns,+ updated_by: userId ?? null,+ updated_at: now,+ },+ { onConflict: 'brand_id' },+ );+ if (error) throw error;+ }++ return res.json({ success: true, settings: await readAuditSettings(brandId, orgId) });+ } catch (err) {+ return sendAuditError(req, res, err, 'audit settings update failed');+ }+});++/** Runs the latest-run summary looks back over, newest first. */+const LATEST_RUNS_READ = 5;++// GET /api/audits/auto-runs/latest?brandId=… — the org's latest auto-audit+// run that audited pages of this brand, in the last 30 days, with what it+// found there (SA-006's in-app notice). run is null when there's none.+router.get('/auto-runs/latest', async (req, res) => {+ const { brandId } = req.query;+ if (!brandId) {+ return res.status(400).json({ success: false, message: 'brandId is required' });+ }+ try {+ const { orgId } = await assertBrandAccess(brandId, req.user?.id);+ const since = new Date(Date.now() - AUTO_AUDIT.freshDays * 24 * 60 * 60 * 1000);+ const { data: runs, error } = await supabaseAdmin+ .from('site_audit_auto_runs')+ .select('id, run_day, status, audit_ids, started_at, finished_at')+ .eq('organization_id', orgId)+ .gte('started_at', since.toISOString())+ .order('started_at', { ascending: false })+ .limit(LATEST_RUNS_READ);+ if (error) throw error;++ const ids = [...new Set((runs ?? []).flatMap((r) => r.audit_ids ?? []))];+ const audits = await readByAuditIds(ids, 100, (chunk) =>+ supabaseAdmin+ .from('site_audits')+ .select('id, status')+ .in('id', chunk)+ .eq('brand_id', brandId),+ );+ const statusById = new Map(audits.map((a) => [a.id, a.status]));+ const run = (runs ?? []).find((r) => (r.audit_ids ?? []).some((id) => statusById.has(id)));+ if (!run) return res.json({ success: true, run: null });++ const own = run.audit_ids.filter((id) => statusById.has(id));+ const completed = own.filter((id) => statusById.get(id) === 'completed');+ let criticalIssues = 0;+ if (completed.length > 0) {+ const { count, error: countErr } = await supabaseAdmin+ .from('audit_signal_results')+ .select('audit_id', { count: 'exact', head: true })+ .in('audit_id', completed)+ .eq('status', 'fail');+ if (countErr) throw countErr;+ criticalIssues = count ?? 0;+ }++ return res.json({+ success: true,+ run: {+ id: run.id,+ day: run.run_day,+ status: run.status,+ startedAt: run.started_at,+ finishedAt: run.finished_at,+ pages: own.length,+ completed: completed.length,+ running: own.filter((id) => statusById.get(id) === 'running').length,+ criticalIssues,+ },+ });+ } catch (err) {+ return sendAuditError(req, res, err, 'auto-audit run read failed');+ }+});+// GET /api/audits/:id — fetch one stored audit with its signalsrouter.get('/:id', async (req, res) => {const userId = req.user?.id;diff --git a/server/src/scripts/run-auto-audits.js b/server/src/scripts/run-auto-audits.jsnew file mode 100644index 000000000..b297c43bc--- /dev/null+++ b/server/src/scripts/run-auto-audits.js@@ -0,0 +1,35 @@+/**+ * Run the auto-audit sweep now (SA-006), as the daily job does after the+ * Google Analytics sync: every organization whose run is due audits its+ * share of the quota. A run is claimed once per org, billing period and run+ * day, so running this twice on one day starts nothing the second time.+ *+ * Run: `node src/scripts/run-auto-audits.js`+ *+ * Options via env:+ * - AUTO_AUDIT_ORG limit the sweep to one organization id+ * - AUTO_AUDIT_NOW take this time (ISO) as now, to try another run day+ *+ * Waits for the runs' audits to finish before it exits.+ */++import 'dotenv/config';+import { readOpportunityInbox, startAutoAudits } from '../routes/audits.js';+import { sweepAutoAudits } from '../lib/audit/auto-audit-sweep.js';++const ONLY_ORG = process.env.AUTO_AUDIT_ORG || null;+const NOW = process.env.AUTO_AUDIT_NOW ? new Date(process.env.AUTO_AUDIT_NOW) : new Date();++if (Number.isNaN(NOW.getTime())) {+ console.error(`AUTO_AUDIT_NOW isn't a date: ${process.env.AUTO_AUDIT_NOW}`);+ process.exit(1);+}++const { runs } = await sweepAutoAudits({+ readInbox: readOpportunityInbox,+ startAudits: startAutoAudits,+ now: NOW,+ orgIds: ONLY_ORG ? [ONLY_ORG] : undefined,+});+console.log(`Auto-audit: ${runs} run(s) done.`);+process.exit(0);diff --git a/server/src/server.js b/server/src/server.jsindex cd46e68ea..17751ae88 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -29,7 +29,8 @@ import { handleScraperResult } from './lib/cloro-result-handler.js';import { verifyCloroWebhook } from './lib/cloro-webhook-verify.js';import { generateBriefForOpportunity } from './routes/content.js';import { sendImproveActionForKeyUser } from './routes/prompts.js';-import { startSiteAuditForBrand } from './routes/audits.js';+import { readOpportunityInbox, startAutoAudits, startSiteAuditForBrand } from './routes/audits.js';+import { sweepAutoAudits } from './lib/audit/auto-audit-sweep.js';import { getSiteAuditQuotaStatus } from './lib/plan-guard.js';import { recountBrandCitations } from './lib/citation-recount.js';import supabaseAdmin from './config/supabase.js';@@ -261,6 +262,9 @@ async function runDailyTracking() {// alongside: it reads the tables the sync writes, so running the two// concurrently would score yesterday's window. A sync failure skips// detection instead of letting it publish findings from stale data.+ //+ // The auto-audit runs (SA-006) come after both, so a run audits the pages+ // this week's data ranks highest; they run whether or not the sync did.runGaSync().then(() =>runPageOpportunityDetection().catch((err) => {@@ -269,7 +273,14 @@ async function runDailyTracking() {).catch((err) => {logger.error({ err }, '[ga-sync] daily run failed');- });+ })+ .finally(() =>+ sweepAutoAudits({ readInbox: readOpportunityInbox, startAudits: startAutoAudits }).catch(+ (err) => {+ logger.error({ err }, '[auto-audit] daily sweep crashed');+ },+ ),+ );return { triggered, total: brands.length };}diff --git a/supabase/migrations/00167_site_audit_auto.sql b/supabase/migrations/00167_site_audit_auto.sqlnew file mode 100644index 000000000..3463df996--- /dev/null+++ b/supabase/migrations/00167_site_audit_auto.sql@@ -0,0 +1,82 @@+-- Site Audit auto-audit (SA-006): 25% of the monthly audit quota audits the+-- Opportunities inbox's top pages by itself, in five runs of 5% on days 1, 7,+-- 14, 21 and 28 of the billing month.+--+-- site_audit_settings: the organization's switch and e-mail choice. No row,+-- or a null auto_audit, is the plan's default: on for a plan with a monthly+-- quota, off for one without (Self-hosted, Enterprise without a contract+-- limit).+--+-- site_audit_brand_settings: a brand's exclude patterns ("/legal/*"), kept+-- out of the inbox and the runs.+--+-- site_audit_auto_runs: one row per organization, billing period and run+-- day. The sweep claims a run by inserting its row, so a second sweep the+-- same day does nothing; the runs still to come keep their share of the+-- quota out of the user's pool.+--+-- source on site_audits and site_audit_usage tells the audits a run started+-- from the ones a user did, for the quota card (auto used / you used).++create table if not exists public.site_audit_settings (+ organization_id uuid primary key references public.organizations(id) on delete cascade,+ auto_audit boolean,+ email_after_run boolean not null default false,+ updated_by uuid references auth.users(id) on delete set null,+ updated_at timestamptz not null default now()+);++create table if not exists public.site_audit_brand_settings (+ brand_id uuid primary key references public.brands(id) on delete cascade,+ exclude_patterns text[] not null default '{}',+ updated_by uuid references auth.users(id) on delete set null,+ updated_at timestamptz not null default now()+);++create table if not exists public.site_audit_auto_runs (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ period_start timestamptz not null,+ run_day smallint not null check (run_day in (1, 7, 14, 21, 28)),+ -- The run's share of the quota, and the audits it started.+ slots integer not null check (slots >= 0),+ audit_ids uuid[] not null default '{}',+ status text not null default 'running' check (status in ('running', 'completed')),+ started_at timestamptz not null default now(),+ finished_at timestamptz,+ unique (organization_id, period_start, run_day)+);++alter table public.site_audits+ add column if not exists source text not null default 'user'+ check (source in ('user', 'auto'));++alter table public.site_audit_usage+ add column if not exists source text not null default 'user'+ check (source in ('user', 'auto'));++alter table public.site_audit_settings enable row level security;+alter table public.site_audit_brand_settings enable row level security;+alter table public.site_audit_auto_runs enable row level security;++-- Org members may read; the server writes with the service role.+create policy site_audit_settings_member_select on public.site_audit_settings+ for select using (+ organization_id in (select p.organization_id from public.profiles p where p.id = auth.uid())+ );++create policy site_audit_brand_settings_member_select on public.site_audit_brand_settings+ for select using (+ brand_id in (+ select b.id from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ )+ );++create policy site_audit_auto_runs_member_select on public.site_audit_auto_runs+ for select using (+ organization_id in (select p.organization_id from public.profiles p where p.id = auth.uid())+ );++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex f676eaf34..e74f1c199 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -22455,6 +22455,92 @@ grant execute on function public.audit_competitor_cited_prompts(uuid, timestamptnotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00167_site_audit_auto.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Site Audit auto-audit (SA-006): 25% of the monthly audit quota audits the+-- Opportunities inbox's top pages by itself, in five runs of 5% on days 1, 7,+-- 14, 21 and 28 of the billing month.+--+-- site_audit_settings: the organization's switch and e-mail choice. No row,+-- or a null auto_audit, is the plan's default: on for a plan with a monthly+-- quota, off for one without (Self-hosted, Enterprise without a contract+-- limit).+--+-- site_audit_brand_settings: a brand's exclude patterns ("/legal/*"), kept+-- out of the inbox and the runs.+--+-- site_audit_auto_runs: one row per organization, billing period and run+-- day. The sweep claims a run by inserting its row, so a second sweep the+-- same day does nothing; the runs still to come keep their share of the+-- quota out of the user's pool.+--+-- source on site_audits and site_audit_usage tells the audits a run started+-- from the ones a user did, for the quota card (auto used / you used).++create table if not exists public.site_audit_settings (+ organization_id uuid primary key references public.organizations(id) on delete cascade,+ auto_audit boolean,+ email_after_run boolean not null default false,+ updated_by uuid references auth.users(id) on delete set null,+ updated_at timestamptz not null default now()+);++create table if not exists public.site_audit_brand_settings (+ brand_id uuid primary key references public.brands(id) on delete cascade,+ exclude_patterns text[] not null default '{}',+ updated_by uuid references auth.users(id) on delete set null,+ updated_at timestamptz not null default now()+);++create table if not exists public.site_audit_auto_runs (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ period_start timestamptz not null,+ run_day smallint not null check (run_day in (1, 7, 14, 21, 28)),+ -- The run's share of the quota, and the audits it started.+ slots integer not null check (slots >= 0),+ audit_ids uuid[] not null default '{}',+ status text not null default 'running' check (status in ('running', 'completed')),+ started_at timestamptz not null default now(),+ finished_at timestamptz,+ unique (organization_id, period_start, run_day)+);++alter table public.site_audits+ add column if not exists source text not null default 'user'+ check (source in ('user', 'auto'));++alter table public.site_audit_usage+ add column if not exists source text not null default 'user'+ check (source in ('user', 'auto'));++alter table public.site_audit_settings enable row level security;+alter table public.site_audit_brand_settings enable row level security;+alter table public.site_audit_auto_runs enable row level security;++-- Org members may read; the server writes with the service role.+create policy site_audit_settings_member_select on public.site_audit_settings+ for select using (+ organization_id in (select p.organization_id from public.profiles p where p.id = auth.uid())+ );++create policy site_audit_brand_settings_member_select on public.site_audit_brand_settings+ for select using (+ brand_id in (+ select b.id from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ )+ );++create policy site_audit_auto_runs_member_select on public.site_audit_auto_runs+ for select using (+ organization_id in (select p.organization_id from public.profiles p where p.id = auth.uid())+ );++notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00168_actions_soft_delete.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 1289b38ee..f4f79a7ee 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2188,14 +2188,47 @@"noPages": "No pages audited yet","gapPages": "{pages} of {total}","auditsThisMonth": "Audits this month",- "auditsTip": "Your plan's audits this billing month. Audits still running already count; failed ones don't.",+ "auditsTip": "Your plan's audits this billing month. Audits still running already count; failed ones don't. Auto-audit keeps its share for the runs still to come.","ofLeft": "of {limit} left","used": "{used} used","usedRunning": "{used} used · {running} running",+ "usedReserved": "{used} used · {reserved} for auto-audit",+ "usedRunningReserved": "{used} used · {running} running · {reserved} auto","quotaBar": "{used} of {limit} audits used","unlimited": "Unlimited","unlimitedSub": "no monthly limit"},+ "settings": {+ "button": "Settings",+ "title": "Site Audit settings",+ "autoAudit": "Auto-audit",+ "autoAuditLabel": "Audit top-priority pages automatically",+ "autoAuditOn": "{perRun} pages on days 1, 7, 14, 21 and 28 of your billing month: {total} of your {limit} audits.",+ "autoAuditOff": "Off: all {limit} audits a month are yours.",+ "autoAuditUnlimited": "{perRun} pages on days 1, 7, 14, 21 and 28 of the month.",+ "orgWide": "Applies to every brand in your organization.",+ "emailLabel": "E-mail the team after each run",+ "excludeTitle": "Excluded pages",+ "excludeHelp": "One path per line, * for anything. These pages stay out of Opportunities and auto-audits.",+ "pinnedTitle": "Pinned pages",+ "pinnedHelp": "Pinned pages always go first in auto-audits.",+ "noPinned": "No pinned pages. Pin them from Opportunities.",+ "unpin": "Unpin",+ "unpinned": "Page unpinned",+ "readOnly": "Only admins and managers can change these settings.",+ "cancel": "Cancel",+ "save": "Save",+ "saved": "Site Audit settings saved",+ "saveFailed": "Couldn't save the settings",+ "loadFailed": "Couldn't load the settings"+ },+ "autoRun": {+ "label": "Auto-audit",+ "done": "{pages, plural, one {# page} other {# pages}} audited · {issues, plural, one {# critical issue} other {# critical issues}}",+ "running": "Auditing {pages, plural, one {# page} other {# pages}} · {completed} done",+ "nextRun": "next run {date}",+ "dismiss": "Dismiss"+ },"bulk": {"toolbar": "Actions for the selected pages","selected": "{count} selected",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.test.tsxnew file mode 100644index 000000000..eff7b1650--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.test.tsx@@ -0,0 +1,96 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { AutoAuditRun } from '@/lib/actions/audits';+import { AutoRunNotice } from './_auto-run-notice';++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const BRAND = 'brand-1';++const run = (over: Partial<AutoAuditRun> = {}): AutoAuditRun => ({+ id: 'run-1',+ day: 7,+ status: 'completed',+ startedAt: '2026-10-07T12:00:00.000Z',+ finishedAt: '2026-10-07T12:20:00.000Z',+ pages: 3,+ completed: 2,+ running: 0,+ criticalIssues: 3,+ ...over,+});++let container: HTMLDivElement;+let root: Root;++function render(value: AutoAuditRun | null, nextRunAt: string | null = '2026-10-14T12:00:00.000Z') {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <AutoRunNotice brandId={BRAND} run={value} nextRunAt={nextRunAt} />+ </NextIntlClientProvider>,+ );+ });+}++// An in-memory localStorage: the test environment has none.+const store = new Map<string, string>();+Object.defineProperty(window, 'localStorage', {+ configurable: true,+ value: {+ getItem: (key: string) => store.get(key) ?? null,+ setItem: (key: string, value: string) => void store.set(key, value),+ removeItem: (key: string) => void store.delete(key),+ clear: () => store.clear(),+ },+});++beforeEach(() => {+ window.localStorage.clear();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('AutoRunNotice', () => {+ it('sums up the run with the next run date', () => {+ render(run());+ expect(container.textContent).toBe(+ 'Auto-audit · Oct 7 · 2 pages audited · 3 critical issues · next run Oct 14',+ );+ });++ it('shows a run still going, and no next run when there is none', () => {+ render(run({ status: 'running', pages: 3, completed: 1, running: 2, criticalIssues: 0 }), null);+ expect(container.textContent).toBe('Auto-audit · Oct 7 · Auditing 3 pages · 1 done');+ });++ it('stays dismissed for that run, and shows the next one', () => {+ render(run());+ act(() => container.querySelector('button')!.click());+ expect(container.textContent).toBe('');+ expect(window.localStorage.getItem(`audit-auto-run-dismissed:${BRAND}`)).toBe('run-1');++ render(run());+ expect(container.textContent).toBe('');+ render(run({ id: 'run-2', startedAt: '2026-10-14T12:00:00.000Z' }));+ expect(container.textContent).toContain('Oct 14');+ });++ it('shows nothing without a run', () => {+ render(null);+ expect(container.textContent).toBe('');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.tsxnew file mode 100644index 000000000..8b8abe5e7--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_auto-run-notice.tsx@@ -0,0 +1,76 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { CalendarClock, X } from 'lucide-react';+import { Button } from '@/components/ui/button';+import type { AutoAuditRun } from '@/lib/actions/audits';+import { formatMonthDay } from '@/lib/format';++const dismissKey = (brandId: string) => `audit-auto-run-dismissed:${brandId}`;++function readDismissed(brandId: string): string | null {+ try {+ return window.localStorage.getItem(dismissKey(brandId));+ } catch {+ return null;+ }+}++/**+ * The in-app notice after an auto-audit run (SA-006): "Auto-audit · Oct 21 ·+ * 25 pages audited · 6 critical issues · next run Oct 28", for the brand's+ * pages the run audited. Dismissed per run, in this browser.+ */+export function AutoRunNotice({+ brandId,+ run,+ nextRunAt,+}: {+ brandId: string;+ run: AutoAuditRun | null;+ nextRunAt: string | null;+}) {+ const t = useTranslations('audit.autoRun');+ const [dismissed, setDismissed] = useState(() => readDismissed(brandId));++ if (!run || dismissed === run.id) return null;++ const dismiss = () => {+ try {+ window.localStorage.setItem(dismissKey(brandId), run.id);+ } catch {+ // Private mode: it stays dismissed until the page is opened again.+ }+ setDismissed(run.id);+ };++ const parts = [+ t('label'),+ formatMonthDay(run.startedAt),+ run.status === 'running'+ ? t('running', { pages: run.pages, completed: run.completed })+ : t('done', { pages: run.completed, issues: run.criticalIssues }),+ ...(nextRunAt ? [t('nextRun', { date: formatMonthDay(nextRunAt) })] : []),+ ];++ return (+ <div+ role="status"+ className="flex items-center gap-2 rounded-lg border bg-card py-1.5 pr-1.5 pl-3 text-sm"+ >+ <CalendarClock className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />+ <p className="min-w-0 flex-1 truncate">+ {parts.map((part, i) => (+ <span key={i}>+ {i > 0 && <span className="text-muted-foreground"> · </span>}+ {i === 0 ? <span className="font-medium">{part}</span> : part}+ </span>+ ))}+ </p>+ <Button variant="ghost" size="icon-sm" onClick={dismiss} aria-label={t('dismiss')}>+ <X className="h-4 w-4" />+ </Button>+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsxindex fcf5090c4..163175385 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.test.tsx@@ -112,6 +112,26 @@ describe('AuditOverviewCards', () => {expect(cards()[2]).toContain('No pages audited yet');});+ it('says what auto-audit keeps for the runs still to come (SA-006)', () => {+ const auto = {+ enabled: true,+ setting: null,+ emailAfterRun: false,+ perRun: 25,+ reserved: 75,+ used: 50,+ periodStart: '2026-10-01T00:00:00.000Z',+ periodEnd: '2026-11-01T00:00:00.000Z',+ runs: [],+ nextRun: { day: 14, at: '2026-10-14T00:00:00.000Z' },+ };+ render(overview(), { used: 245, running: 0, limit: 500, remaining: 180, auto });+ expect(cards()[3]).toContain('180of 500 left');+ expect(cards()[3]).toContain('245 used · 75 for auto-audit');+ render(overview(), { used: 245, running: 5, limit: 500, remaining: 175, auto });+ expect(cards()[3]).toContain('245 used · 5 running · 75 auto');+ });+it('shows an unlimited plan without a bar', () => {render(overview(), { used: 0, running: 0, limit: -1, remaining: -1 });expect(cards()[3]).toContain('Unlimited');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsxindex b55cad814..193262f5a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_overview-cards.tsx@@ -64,6 +64,19 @@ export function AuditOverviewCards({const domain = overview.primaryHost ?? t('yourDomain');const limited = quota !== null && quota.limit !== -1;const running = quota?.running ?? 0;+ // What the auto-audit runs still to come keep out of what's left (SA-006).+ const reserved = quota?.auto?.reserved ?? 0;+ const usedSub = () => {+ if (!quota) return '';+ if (!limited) return t('unlimitedSub');+ const used = quota.used;+ if (running > 0) {+ return reserved > 0+ ? t('usedRunningReserved', { used, running, reserved })+ : t('usedRunning', { used, running });+ }+ return reserved > 0 ? t('usedReserved', { used, reserved }) : t('used', { used });+ };const gapsSub =overview.pages === 0 ? t('noPages') : overview.gaps.length > 0 ? t('gapsSub') : t('noGaps');@@ -106,15 +119,7 @@ export function AuditOverviewCards({? { text: t('ofLeft', { limit: formatNumber(quota.limit) }), tone: 'neutral' }: null}- sub={- !quota- ? ''- : !limited- ? t('unlimitedSub')- : running > 0- ? t('usedRunning', { used: quota.used, running })- : t('used', { used: quota.used })- }+ sub={usedSub()}quota={limited? {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsxnew file mode 100644index 000000000..0ba6eeff8--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.test.tsx@@ -0,0 +1,155 @@+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 type { AuditSettings } from '@/lib/actions/audits';+import { AuditSettingsDialog, parsePatterns } from './_settings-dialog';++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const actions = vi.hoisted(() => ({+ getAuditSettings: vi.fn(),+ saveAuditSettings: vi.fn(),+ setOpportunityPrefs: vi.fn(),+}));+vi.mock('@/lib/actions/audits', () => actions);+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++const BRAND = '33333333-3333-3333-3333-333333333333';++const settings = (over: Partial<AuditSettings> = {}): AuditSettings => ({+ autoAudit: { enabled: true, setting: null, perRun: 5, limit: 100 },+ emailAfterRun: false,+ excludePatterns: ['/careers/*'],+ pinned: [{ key: 'acme.com/about', url: 'https://acme.com/about' }],+ ...over,+});++let container: HTMLDivElement;+let root: Root;+const onSaved = vi.fn();+const onOpenChange = vi.fn();++async function render(canManage = true) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <AuditSettingsDialog+ brandId={BRAND}+ open+ onOpenChange={onOpenChange}+ canManage={canManage}+ onSaved={onSaved}+ />+ </NextIntlClientProvider>,+ );+ });+}++const dialog = () => document.body.querySelector('[role="dialog"]') as HTMLElement;+const button = (text: string) =>+ [...dialog().querySelectorAll('button')].find((b) => b.textContent?.trim() === text)!;++function type(el: HTMLTextAreaElement, value: string) {+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!;+ act(() => {+ setter.call(el, value);+ el.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ actions.getAuditSettings.mockResolvedValue(settings());+ actions.saveAuditSettings.mockImplementation(async () => settings());+ actions.setOpportunityPrefs.mockResolvedValue(undefined);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('parsePatterns', () => {+ it('takes one pattern per line and drops blank ones', () => {+ expect(parsePatterns(' /careers/*\n\n/tag/* \n')).toEqual(['/careers/*', '/tag/*']);+ });+});++describe('AuditSettingsDialog', () => {+ it("shows the org's auto-audit share, the brand's patterns and its pinned pages", async () => {+ await render();+ expect(actions.getAuditSettings).toHaveBeenCalledWith(BRAND);+ const text = dialog().textContent;+ expect(text).toContain(+ '5 pages on days 1, 7, 14, 21 and 28 of your billing month: 25 of your 100 audits.',+ );+ expect(text).toContain('Applies to every brand in your organization.');+ expect(dialog().querySelector('textarea')!.value).toBe('/careers/*');+ expect(dialog().querySelector('li')!.textContent).toContain('/about');+ // Nothing changed yet.+ expect(button('Save').disabled).toBe(true);+ });++ it('saves only what changed, then reads the page again', async () => {+ await render();+ const [auto] = dialog().querySelectorAll('[role="checkbox"]');+ act(() => (auto as HTMLElement).click());+ expect(dialog().textContent).toContain('Off: all 100 audits a month are yours.');+ type(dialog().querySelector('textarea')!, '/careers/*\n/tag/*\n');++ await act(async () => button('Save').click());+ expect(actions.saveAuditSettings).toHaveBeenCalledWith(BRAND, {+ autoAudit: false,+ excludePatterns: ['/careers/*', '/tag/*'],+ });+ expect(toast.success).toHaveBeenCalledWith('Site Audit settings saved');+ expect(onSaved).toHaveBeenCalled();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it("shows the server's message when a pattern is refused", async () => {+ actions.saveAuditSettings.mockRejectedValue(+ new Error('"careers" isn\'t a page path. Start it with /, as in /legal/*.'),+ );+ await render();+ type(dialog().querySelector('textarea')!, 'careers');+ await act(async () => button('Save').click());+ expect(toast.error).toHaveBeenCalledWith(+ '"careers" isn\'t a page path. Start it with /, as in /legal/*.',+ );+ expect(onOpenChange).not.toHaveBeenCalledWith(false);+ });++ it("is read-only for members who can't manage it, who can still unpin", async () => {+ await render(false);+ expect(dialog().textContent).toContain('Only admins and managers can change these settings.');+ expect(dialog().querySelector('textarea')!.disabled).toBe(true);+ expect(button('Save').disabled).toBe(true);++ await act(async () => button('Unpin').click());+ expect(actions.setOpportunityPrefs).toHaveBeenCalledWith(+ BRAND,+ ['https://acme.com/about'],+ null,+ );+ expect(dialog().textContent).toContain('No pinned pages. Pin them from Opportunities.');+ });++ it('says what a plan without a monthly limit runs', async () => {+ actions.getAuditSettings.mockResolvedValue(+ settings({ autoAudit: { enabled: false, setting: null, perRun: 25, limit: -1 } }),+ );+ await render();+ expect(dialog().textContent).toContain('25 pages on days 1, 7, 14, 21 and 28 of the month.');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsxnew file mode 100644index 000000000..8fa8c97ec--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/_settings-dialog.tsx@@ -0,0 +1,263 @@+'use client';++import { useEffect, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Loader2 } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Label } from '@/components/ui/label';+import { Skeleton } from '@/components/ui/skeleton';+import { Textarea } from '@/components/ui/textarea';+import {+ getAuditSettings,+ saveAuditSettings,+ setOpportunityPrefs,+ type AuditSettings,+ type AuditSettingsChanges,+} from '@/lib/actions/audits';+import { formatNumber } from '@/lib/format';++/** One pattern per line, blank lines dropped. */+export function parsePatterns(text: string): string[] {+ return text+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean);+}++const pathOf = (url: string) => {+ try {+ return new URL(url).pathname;+ } catch {+ return url;+ }+};++function Section({ title, children }: { title: string; children: React.ReactNode }) {+ return (+ <section className="space-y-2">+ <h3 className="text-sm font-semibold">{title}</h3>+ {children}+ </section>+ );+}++/**+ * Site Audit › Settings (SA-006): the organization's auto-audit switch and+ * e-mail, the brand's exclude patterns and its pinned pages. Admins and+ * managers change them; everyone else reads them.+ */+export function AuditSettingsDialog({+ brandId,+ open,+ onOpenChange,+ canManage,+ onSaved,+}: {+ brandId: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ canManage: boolean;+ /** Read the page's quota and inbox again: the reserved share or the inbox may change. */+ onSaved: () => void;+}) {+ const t = useTranslations('audit.settings');+ const [settings, setSettings] = useState<AuditSettings | null>(null);+ const [autoAudit, setAutoAudit] = useState(false);+ const [emailAfterRun, setEmailAfterRun] = useState(false);+ const [patterns, setPatterns] = useState('');+ const [saving, setSaving] = useState(false);+ const [unpinning, setUnpinning] = useState<string | null>(null);++ const apply = (next: AuditSettings) => {+ setSettings(next);+ setAutoAudit(next.autoAudit.enabled);+ setEmailAfterRun(next.emailAfterRun);+ setPatterns(next.excludePatterns.join('\n'));+ };++ useEffect(() => {+ if (!open) return;+ let cancelled = false;+ setSettings(null);+ getAuditSettings(brandId)+ .then((next) => {+ if (!cancelled) apply(next);+ })+ .catch((err) => {+ console.error('Failed to load the Site Audit settings:', err);+ if (!cancelled) {+ toast.error(t('loadFailed'));+ onOpenChange(false);+ }+ });+ return () => {+ cancelled = true;+ };+ }, [open, brandId, t, onOpenChange]);++ // Only what changed is sent: the switch stays on the plan's default until+ // someone turns it.+ const changes: AuditSettingsChanges = {};+ if (settings) {+ if (autoAudit !== settings.autoAudit.enabled) changes.autoAudit = autoAudit;+ if (emailAfterRun !== settings.emailAfterRun) changes.emailAfterRun = emailAfterRun;+ const next = parsePatterns(patterns);+ if (next.join('\n') !== settings.excludePatterns.join('\n')) changes.excludePatterns = next;+ }+ const changed = Object.keys(changes).length > 0;++ const handleSave = async () => {+ if (!changed) return;+ setSaving(true);+ try {+ apply(await saveAuditSettings(brandId, changes));+ toast.success(t('saved'));+ onSaved();+ onOpenChange(false);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : t('saveFailed'));+ } finally {+ setSaving(false);+ }+ };++ const handleUnpin = async (url: string) => {+ setUnpinning(url);+ try {+ await setOpportunityPrefs(brandId, [url], null);+ setSettings((prev) =>+ prev ? { ...prev, pinned: prev.pinned.filter((p) => p.url !== url) } : prev,+ );+ toast.success(t('unpinned'));+ onSaved();+ } catch (err) {+ toast.error(err instanceof Error ? err.message : t('saveFailed'));+ } finally {+ setUnpinning(null);+ }+ };++ const auto = settings?.autoAudit;+ const autoLine = !auto+ ? null+ : auto.limit === -1+ ? t('autoAuditUnlimited', { perRun: auto.perRun })+ : autoAudit+ ? t('autoAuditOn', {+ perRun: auto.perRun,+ total: formatNumber(auto.perRun * 5),+ limit: formatNumber(auto.limit),+ })+ : t('autoAuditOff', { limit: formatNumber(auto.limit) });++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ </DialogHeader>++ {!settings ? (+ <div className="space-y-3" aria-busy="true">+ <Skeleton className="h-16 w-full" />+ <Skeleton className="h-24 w-full" />+ </div>+ ) : (+ <div className="space-y-5">+ <Section title={t('autoAudit')}>+ <div className="flex items-start gap-2">+ <Checkbox+ id="audit-auto"+ checked={autoAudit}+ onCheckedChange={(on) => setAutoAudit(on === true)}+ disabled={!canManage}+ className="mt-0.5"+ />+ <div className="space-y-0.5">+ <Label htmlFor="audit-auto">{t('autoAuditLabel')}</Label>+ <p className="text-xs text-muted-foreground">{autoLine}</p>+ <p className="text-xs text-muted-foreground">{t('orgWide')}</p>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <Checkbox+ id="audit-email"+ checked={emailAfterRun}+ onCheckedChange={(on) => setEmailAfterRun(on === true)}+ disabled={!canManage}+ />+ <Label htmlFor="audit-email">{t('emailLabel')}</Label>+ </div>+ </Section>++ <Section title={t('excludeTitle')}>+ <Textarea+ aria-label={t('excludeTitle')}+ value={patterns}+ onChange={(e) => setPatterns(e.target.value)}+ placeholder={'/careers/*\n/tag/*'}+ rows={3}+ disabled={!canManage}+ />+ <p className="text-xs text-muted-foreground">{t('excludeHelp')}</p>+ </Section>++ <Section title={t('pinnedTitle')}>+ {settings.pinned.length === 0 ? (+ <p className="text-xs text-muted-foreground">{t('noPinned')}</p>+ ) : (+ <>+ <ul className="divide-y rounded-md border">+ {settings.pinned.map((page) => (+ <li+ key={page.key}+ className="flex items-center justify-between gap-3 px-3 py-1.5"+ >+ <span className="truncate" title={page.url}>+ {pathOf(page.url)}+ </span>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => handleUnpin(page.url)}+ disabled={unpinning !== null}+ >+ {unpinning === page.url && (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ )}+ {t('unpin')}+ </Button>+ </li>+ ))}+ </ul>+ <p className="text-xs text-muted-foreground">{t('pinnedHelp')}</p>+ </>+ )}+ </Section>++ {!canManage && <p className="text-xs text-muted-foreground">{t('readOnly')}</p>}+ </div>+ )}++ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t('cancel')}+ </Button>+ <Button onClick={handleSave} disabled={!canManage || !changed || saving}>+ {saving && <Loader2 className="h-4 w-4 animate-spin" />}+ {t('save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsxindex f97f2c562..8c651bb28 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx@@ -13,6 +13,7 @@ import {RefreshCw,Pin,EyeOff,+ Settings,} from 'lucide-react';import { useRouter } from '@/i18n/navigation';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';@@ -21,6 +22,7 @@ import { Input } from '@/components/ui/input';import { Skeleton } from '@/components/ui/skeleton';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import { useBrandStore } from '@/stores/use-brand-store';+import { useUserRole } from '@/hooks/use-user-role';import {runAudit,runAuditsBulk,@@ -30,7 +32,9 @@ import {setOpportunityPrefs,getAuditQuota,getAuditTrend,+ getLatestAutoRun,deleteAudit,+ type AutoAuditRun,type AuditedPage,type AuditOverview,type AuditOpportunities,@@ -44,6 +48,8 @@ import { AuditPagesTable } from './_pages-table';import { AuditBulkBar, ExportMenu } from './_bulk-bar';import { AuditOverviewCards } from './_overview-cards';import { OpportunitiesTable } from './_opportunities-table';+import { AuditSettingsDialog } from './_settings-dialog';+import { AutoRunNotice } from './_auto-run-notice';import { usePagesExport } from './_use-pages-export';import { cn } from '@/lib/utils';@@ -70,6 +76,16 @@ async function readOpportunities(brandId: string): Promise<AuditOpportunities |}}+/** The latest auto-audit run on the brand's pages; no notice when it can't be read. */+async function readLatestRun(brandId: string): Promise<AutoAuditRun | null> {+ try {+ return await getLatestAutoRun(brandId);+ } catch (err) {+ console.error('Failed to load the latest auto-audit run:', err);+ return null;+ }+}+type ListTab = 'opportunities' | 'pages';/** A tab's count, as the mockup's grey pill. */@@ -95,6 +111,7 @@ export default function SiteAuditPage() {const t = useTranslations('audit');const router = useRouter();const activeBrandId = useBrandStore((s) => s.activeBrandId);+ const { canManage } = useUserRole();// Prefill the URL with the active brand's primary domain (read once at init).const [url, setUrl] = useState(() => {@@ -121,6 +138,8 @@ export default function SiteAuditPage() {// Opportunities when it lists pages, else Pages; chosen once per brand.const [tab, setTab] = useState<ListTab | null>(null);const [startingBulk, setStartingBulk] = useState(false);+ const [latestRun, setLatestRun] = useState<AutoAuditRun | null>(null);+ const [settingsOpen, setSettingsOpen] = useState(false);const { exporting, exportAll, exportPages } = usePagesExport(activeBrandId);// Capture "now" once (impure call belongs in a lazy initializer, not render).const [nowMs] = useState(() => Date.now());@@ -137,14 +156,16 @@ export default function SiteAuditPage() {setSelected(new Set());setOppSelected(new Set());setTab(null);+ setLatestRun(null);(async () => {try {- const [data, q, tr, ov, op] = await Promise.all([+ const [data, q, tr, ov, op, run] = await Promise.all([getAuditPages(activeBrandId),getAuditQuota(),getAuditTrend(activeBrandId),readOverview(activeBrandId),readOpportunities(activeBrandId),+ readLatestRun(activeBrandId),]);if (!cancelled) {setPages(data.pages);@@ -154,6 +175,7 @@ export default function SiteAuditPage() {setTrend(tr);setOverview(ov);setOpps(op);+ setLatestRun(run);setTab((current) =>current ?? ((op?.opportunities.length ?? 0) > 0 ? 'opportunities' : 'pages'),@@ -268,12 +290,13 @@ export default function SiteAuditPage() {shownRef.current = pages.length;}, [pages.length]);const reloadInPlace = async (brandId: string) => {- const [data, q, tr, ov, op] = await Promise.all([+ const [data, q, tr, ov, op, run] = await Promise.all([getAuditPages(brandId, 0, Math.min(Math.max(shownRef.current, 50), 100)),getAuditQuota(),getAuditTrend(brandId),readOverview(brandId),readOpportunities(brandId),+ readLatestRun(brandId),]);setPages(data.pages);setPagesTotal(data.total);@@ -282,6 +305,7 @@ export default function SiteAuditPage() {setTrend(tr);setOverview(ov);setOpps(op);+ setLatestRun(run);const oppSelectable = new Set((op?.opportunities ?? []).filter((o) => !o.running).map((o) => o.key),);@@ -427,10 +451,27 @@ export default function SiteAuditPage() {return (<div className="space-y-6">- <div>- <h1 className="text-2xl font-bold">{t('title')}</h1>- <p className="text-sm text-muted-foreground">{t('description')}</p>+ <div className="flex items-start justify-between gap-4">+ <div>+ <h1 className="text-2xl font-bold">{t('title')}</h1>+ <p className="text-sm text-muted-foreground">{t('description')}</p>+ </div>+ <Button variant="outline" className="shrink-0" onClick={() => setSettingsOpen(true)}>+ <Settings className="h-4 w-4" />+ {t('settings.button')}+ </Button></div>+ <AuditSettingsDialog+ brandId={activeBrandId}+ open={settingsOpen}+ onOpenChange={setSettingsOpen}+ canManage={canManage}+ onSaved={() =>+ void reloadInPlace(activeBrandId).catch((err) =>+ console.error('Failed to refresh after saving the settings:', err),+ )+ }+ />{/* Run bar */}<Card>@@ -468,6 +509,14 @@ export default function SiteAuditPage() {</CardContent></Card>+ {/* The latest auto-audit run on this brand's pages (SA-006) */}+ <AutoRunNotice+ key={activeBrandId}+ brandId={activeBrandId}+ run={latestRun}+ nextRunAt={quota?.auto?.enabled ? (quota.auto.nextRun?.at ?? null) : null}+ />+{/* KPI cards, as in the v2 mockup (SA-018) */}{(loading || overview) && (<AuditOverviewCards overview={loading ? null : overview} quota={quota} />diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.tsindex a192cca88..a9356e050 100644--- a/web/src/lib/actions/audits.ts+++ b/web/src/lib/actions/audits.ts@@ -58,10 +58,71 @@ export interface AuditResult {export interface AuditQuota {used: number;limit: number;- /** What's left this month, the running audits already taken out. */+ /**+ * What's left this month for the user: the running audits and the+ * auto-audit runs still to come already taken out.+ */remaining: number;/** Audits started and not finished yet: they're charged when they complete. */running?: number;+ /** Where auto-audit stands this billing period (SA-006). */+ auto?: AuditAutoStatus;+}++/** Auto-audit this billing period (SA-006): 5% of the quota on days 1, 7, 14, 21 and 28. */+export interface AuditAutoStatus {+ enabled: boolean;+ /** The org's own choice; null follows the plan (on with a monthly quota). */+ setting: boolean | null;+ emailAfterRun: boolean;+ /** Pages one run audits. */+ perRun: number;+ /** Audits the runs still to come keep out of `remaining`. */+ reserved: number;+ /** Audits the runs used this period. */+ used: number;+ periodStart: string;+ periodEnd: string;+ runs: { day: number; at: string; done: boolean }[];+ nextRun: { day: number; at: string } | null;+}++/** Site Audit settings (SA-006): the org's auto-audit, the brand's patterns and pins. */+export interface AuditSettings {+ autoAudit: {+ enabled: boolean;+ /** The org's own choice; null follows the plan. */+ setting: boolean | null;+ perRun: number;+ /** The plan's monthly audits; -1 unlimited. */+ limit: number;+ };+ emailAfterRun: boolean;+ /** Paths such as /legal/*, kept out of Opportunities and the runs. */+ excludePatterns: string[];+ pinned: { key: string; url: string }[];+}++export interface AuditSettingsChanges {+ /** null follows the plan's default again. */+ autoAudit?: boolean | null;+ emailAfterRun?: boolean;+ excludePatterns?: string[];+}++/** The latest auto-audit run that audited the brand's pages, for the in-app notice. */+export interface AutoAuditRun {+ id: string;+ day: number;+ status: 'running' | 'completed';+ startedAt: string;+ finishedAt: string | null;+ /** The brand's pages the run audited, how many completed, and still running. */+ pages: number;+ completed: number;+ running: number;+ /** Signals those audits failed. */+ criticalIssues: number;}export interface AuditTrendPoint {@@ -369,6 +430,65 @@ export async function setOpportunityPrefs(}}+export async function getAuditSettings(brandId: string): Promise<AuditSettings> {+ const session = await getSession();++ const res = await fetch(+ `${AEO_SERVER_URL}/api/audits/settings?brandId=${encodeURIComponent(brandId)}`,+ { headers: { Authorization: `Bearer ${session.access_token}` } },+ );++ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.message || `Server error: ${res.status}`);+ }++ const data = await res.json();+ return data.settings;+}++/** Save the settings sent; returns them all as saved. */+export async function saveAuditSettings(+ brandId: string,+ changes: AuditSettingsChanges,+): Promise<AuditSettings> {+ const session = await getSession();++ const res = await fetch(`${AEO_SERVER_URL}/api/audits/settings`, {+ method: 'PUT',+ headers: {+ Authorization: `Bearer ${session.access_token}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ brandId, ...changes }),+ });++ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.message || `Server error: ${res.status}`);+ }++ const data = await res.json();+ return data.settings;+}++export async function getLatestAutoRun(brandId: string): Promise<AutoAuditRun | null> {+ const session = await getSession();++ const res = await fetch(+ `${AEO_SERVER_URL}/api/audits/auto-runs/latest?brandId=${encodeURIComponent(brandId)}`,+ { headers: { Authorization: `Bearer ${session.access_token}` } },+ );++ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.message || `Server error: ${res.status}`);+ }++ const data = await res.json();+ return data.run ?? null;+}+export interface AuditedPages {pages: AuditedPage[];/** Pages audited for the brand, across all pages of the list. */