Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(audit): show score change since previous completed audit (#916) (#1461)

Sanjeev Kumar18a7aad8634f
diff --git a/server/src/lib/audit/history.js b/server/src/lib/audit/history.js
index c4bb6152c..d0fbb257b 100644
--- a/server/src/lib/audit/history.js
+++ b/server/src/lib/audit/history.js
@@ -76,6 +76,17 @@ export function pageKey(url) {
}
}
+/**
+ * The shared page identity used by the Pages list and a report's comparison.
+ * Prefer the final URL because redirects should group with audits of their
+ * destination; pageKey then ignores www, scheme, query, fragment and trailing
+ * slash in the same way as buildAuditPages.
+ */
+function pageIdentityForAudit(row) {
+ const url = row.final_url ?? row.url;
+ return { url, ...(pageKey(url) ?? { key: url, host: null, path: url }) };
+}
+
/**
* How long a run may stay `running`. An audit takes a minute or two and a
* queued bulk run waits longer; one older than this was cut short by a
@@ -116,8 +127,7 @@ export function buildAuditPages(rowsNewestFirst, now = Date.now()) {
for (const r of rowsNewestFirst ?? []) {
if (seen.has(r.id)) continue;
seen.add(r.id);
- const url = r.final_url ?? r.url;
- const page = pageKey(url) ?? { key: url, host: null, path: url };
+ const { url, ...page } = pageIdentityForAudit(r);
if (!groups.has(page.key)) groups.set(page.key, { ...page, runs: [] });
groups.get(page.key).runs.push({
id: r.id,
@@ -157,3 +167,48 @@ export function buildAuditPages(rowsNewestFirst, now = Date.now()) {
};
});
}
+
+/**
+ * Find the immediately previous completed, scored audit for one audit's page.
+ * This assumes the same created_at / id descending order used by readBrandAudits.
+ * Strictly earlier created_at timestamps are required; a failed, running, or
+ * unscored audit never becomes the comparison point.
+ */
+export function findPreviousCompletedAudit(rowsNewestFirst, auditId) {
+ const seen = new Set();
+ let currentKey = null;
+ let currentCreatedAt = null;
+ let foundCurrent = false;
+
+ for (const row of rowsNewestFirst ?? []) {
+ // A paged read can repeat the same row at a slice boundary.
+ if (seen.has(row.id)) continue;
+ seen.add(row.id);
+
+ const { key } = pageIdentityForAudit(row);
+
+ if (!foundCurrent) {
+ if (row.id !== auditId) continue;
+ if (row.status !== 'completed' || row.total_score == null) return null;
+
+ currentCreatedAt = Date.parse(row.created_at);
+ if (!Number.isFinite(currentCreatedAt)) return null;
+ currentKey = key;
+ foundCurrent = true;
+ continue;
+ }
+
+ const createdAt = Date.parse(row.created_at);
+ if (!Number.isFinite(createdAt) || createdAt >= currentCreatedAt) continue;
+ if (key !== currentKey) continue;
+ if (row.status !== 'completed' || row.total_score == null) continue;
+
+ return {
+ auditId: row.id,
+ totalScore: Number(row.total_score),
+ createdAt: row.created_at,
+ };
+ }
+
+ return null;
+}
diff --git a/server/src/lib/audit/history.test.js b/server/src/lib/audit/history.test.js
index 71d9c70ab..81b5712ef 100644
--- a/server/src/lib/audit/history.test.js
+++ b/server/src/lib/audit/history.test.js
@@ -3,6 +3,7 @@ import {
AUDIT_RUN_TIMEOUT_MS,
buildAuditPages,
buildTrendPoints,
+ findPreviousCompletedAudit,
pageKey,
pageStatus,
parseListPage,
@@ -243,3 +244,74 @@ describe('buildAuditPages', () => {
expect(page.trend[0]).toBeCloseTo(0.81);
});
});
+
+describe('findPreviousCompletedAudit', () => {
+ const row = (id, url, created_at, total_score, status = 'completed', final_url = url) => ({
+ id,
+ url,
+ final_url,
+ status,
+ total_score,
+ created_at,
+ });
+
+ it('chooses the nearest earlier completed audit of the same normalized URL', () => {
+ const rows = [
+ row('later', 'https://acme.com/pricing', '2026-10-20T09:00:00Z', '0.8'),
+ row('current', 'https://www.acme.com/pricing/?campaign=x', '2026-10-10T09:00:00Z', '0.7'),
+ row('failed', 'https://acme.com/pricing/', '2026-10-09T09:00:00Z', '0.99', 'failed'),
+ row('previous', 'http://ACME.com/pricing?utm_source=x', '2026-10-08T09:00:00Z', '0.61'),
+ row('older', 'https://acme.com/pricing', '2026-09-20T09:00:00Z', '0.55'),
+ row('other-page', 'https://acme.com/blog', '2026-10-09T09:00:00Z', '0.9'),
+ ];
+
+ expect(findPreviousCompletedAudit(rows, 'current')).toEqual({
+ auditId: 'previous',
+ totalScore: 0.61,
+ createdAt: '2026-10-08T09:00:00Z',
+ });
+ });
+
+ it('uses final_url for page identity when an audit followed a redirect', () => {
+ const rows = [
+ row(
+ 'current',
+ 'http://acme.com/old',
+ '2026-10-10T09:00:00Z',
+ '0.7',
+ 'completed',
+ 'https://acme.com/new',
+ ),
+ row('previous', 'https://www.acme.com/new/?utm_source=x', '2026-10-01T09:00:00Z', '0.6'),
+ ];
+
+ expect(findPreviousCompletedAudit(rows, 'current')?.auditId).toBe('previous');
+ });
+
+ it('ignores unscored rows and rows with the same or later created_at', () => {
+ const rows = [
+ row('current', 'https://acme.com/', '2026-10-10T09:00:00Z', '0.7'),
+ row('same-time', 'https://acme.com/', '2026-10-10T09:00:00Z', '0.8'),
+ row('unscored', 'https://acme.com/', '2026-10-09T09:00:00Z', null),
+ row('later', 'https://acme.com/', '2026-10-11T09:00:00Z', '0.9'),
+ ];
+
+ expect(findPreviousCompletedAudit(rows, 'current')).toBeNull();
+ });
+
+ it('returns null when the current audit is missing, unfinished, or has no score', () => {
+ expect(findPreviousCompletedAudit([], 'missing')).toBeNull();
+ expect(
+ findPreviousCompletedAudit(
+ [row('running', 'https://acme.com/', '2026-10-10T09:00:00Z', null, 'running')],
+ 'running',
+ ),
+ ).toBeNull();
+ expect(
+ findPreviousCompletedAudit(
+ [row('unscored', 'https://acme.com/', '2026-10-10T09:00:00Z', null)],
+ 'unscored',
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/server/src/routes/audits.js b/server/src/routes/audits.js
index b67a5fd67..dac169d3d 100644
--- a/server/src/routes/audits.js
+++ b/server/src/routes/audits.js
@@ -28,6 +28,7 @@ import { normStoredDomain } from '../lib/audit/host.js';
import {
buildAuditPages,
buildTrendPoints,
+ findPreviousCompletedAudit,
pageKey,
parseListPage,
TREND_LIMIT,
@@ -1197,12 +1198,37 @@ router.get('/:id', async (req, res) => {
await assertBrandAccess(audit.brand_id, userId);
- const { data: signalRows } = await supabaseAdmin
- .from('audit_signal_results')
- .select('*')
- .eq('audit_id', id);
+ // The history read is best-effort and can run alongside the signal read.
+ // Its result uses the same page grouping as GET /pages.
+ const historyPromise =
+ audit.status === 'completed' && audit.total_score != null
+ ? readBrandAudits(audit.brand_id).catch((historyErr) => {
+ req.log.warn({ err: historyErr, auditId: id }, 'audit previous score lookup failed');
+ return null;
+ })
+ : Promise.resolve(null);
+
+ const [{ data: signalRows }, historyResult] = await Promise.all([
+ supabaseAdmin.from('audit_signal_results').select('*').eq('audit_id', id),
+ historyPromise,
+ ]);
+
+ if (historyResult?.error) {
+ req.log.warn({ err: historyResult.error, auditId: id }, 'audit previous score lookup failed');
+ }
+ const previous =
+ historyResult && !historyResult.error
+ ? findPreviousCompletedAudit(historyResult.data ?? [], id)
+ : null;
- return res.json({ success: true, audit: assembleAudit(audit, signalRows ?? []) });
+ return res.json({
+ success: true,
+ audit: {
+ ...assembleAudit(audit, signalRows ?? []),
+ previousScore: previous?.totalScore ?? null,
+ previousCreatedAt: previous?.createdAt ?? null,
+ },
+ });
} catch (err) {
if (err.status) {
return res.status(err.status).json({ success: false, message: err.message });
diff --git a/web/messages/en.json b/web/messages/en.json
index 1bebd7376..b5463430f 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -2793,6 +2793,7 @@
"failed": "Audit failed. Please try again.",
"takingLongerThanExpected": "This audit is taking longer than expected.",
"checkAgain": "Check again",
+ "scoreChange": "{change} since {date}",
"grade": {
"good": "Good",
"needsWork": "Needs work",
diff --git a/web/src/components/audit/audit-report.test.tsx b/web/src/components/audit/audit-report.test.tsx
index e24a9da95..c19232997 100644
--- a/web/src/components/audit/audit-report.test.tsx
+++ b/web/src/components/audit/audit-report.test.tsx
@@ -24,7 +24,10 @@ const rec = (over: Partial<AuditRecommendation> = {}): AuditRecommendation => ({
...over,
});
-const audit = (recommendations: AuditRecommendation[]): AuditResult => ({
+const audit = (
+ recommendations: AuditRecommendation[],
+ previous: Pick<AuditResult, 'previousScore' | 'previousCreatedAt'> = {},
+): AuditResult => ({
id: 'a1',
brandId: 'b1',
url: 'https://ansvisor.com/pricing',
@@ -40,16 +43,20 @@ const audit = (recommendations: AuditRecommendation[]): AuditResult => ({
completedAt: '2026-10-17T09:01:00.000Z',
signals: [],
recommendations,
+ ...previous,
});
let container: HTMLDivElement;
let root: Root;
-function render(recommendations: AuditRecommendation[]) {
+function render(
+ recommendations: AuditRecommendation[],
+ previous: Pick<AuditResult, 'previousScore' | 'previousCreatedAt'> = {},
+) {
act(() => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
- <AuditReport audit={audit(recommendations)} />
+ <AuditReport audit={audit(recommendations, previous)} />
</NextIntlClientProvider>,
);
});
@@ -108,3 +115,36 @@ describe('AuditReport recommendations', () => {
expect(container.textContent).not.toContain(NOTE);
});
});
+
+describe('AuditReport score change', () => {
+ it('shows a positive percentage-point delta and the previous audit date', () => {
+ render([], {
+ previousScore: 0.56,
+ previousCreatedAt: '2026-09-28T09:00:00.000Z',
+ });
+
+ expect(container.textContent).toContain('+7 since Sep 28');
+ });
+
+ it('shows negative and zero deltas accurately', () => {
+ render([], {
+ previousScore: 0.7,
+ previousCreatedAt: '2026-09-28T09:00:00.000Z',
+ });
+ expect(container.textContent).toContain('-7 since Sep 28');
+
+ render([], {
+ previousScore: 0.63,
+ previousCreatedAt: '2026-09-28T09:00:00.000Z',
+ });
+ expect(container.textContent).toContain('0 since Sep 28');
+ });
+
+ it('does not show a delta when there is no prior completed score/date', () => {
+ render([]);
+ expect(container.textContent).not.toContain('since');
+
+ render([], { previousScore: 0.56 });
+ expect(container.textContent).not.toContain('since');
+ });
+});
diff --git a/web/src/components/audit/audit-report.tsx b/web/src/components/audit/audit-report.tsx
index 8fcee28d3..aa05c5ef2 100644
--- a/web/src/components/audit/audit-report.tsx
+++ b/web/src/components/audit/audit-report.tsx
@@ -16,6 +16,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import type { AuditResult, AuditSignal, AuditRecommendation } from '@/lib/actions/audits';
+import { formatMonthDay } from '@/lib/format';
import { cn } from '@/lib/utils';
// Display order + labels for the five rubric categories (keys come from the
@@ -276,6 +277,14 @@ export function AuditReport({ audit }: { audit: AuditResult }) {
);
const hasIssues = counts.fail + counts.warn > 0;
const grade = gradeKey(audit.totalScore);
+ const scoreDelta =
+ audit.totalScore !== null && audit.previousScore != null
+ ? Math.round(audit.totalScore * 100) - Math.round(audit.previousScore * 100)
+ : null;
+ const previousDate =
+ audit.previousCreatedAt && Number.isFinite(Date.parse(audit.previousCreatedAt))
+ ? formatMonthDay(audit.previousCreatedAt)
+ : null;
const visibleSignals = (cat: string) =>
audit.signals.filter(
@@ -291,8 +300,27 @@ export function AuditReport({ audit }: { audit: AuditResult }) {
<div className="flex-1 space-y-2 text-center sm:text-left">
<div className="text-sm font-medium break-all">{audit.finalUrl || audit.url}</div>
{grade && (
- <div className={cn('text-lg font-semibold', scoreColor(audit.totalScore))}>
- {t(`grade.${grade}`)}
+ <div className="flex flex-wrap items-center justify-center gap-2 sm:justify-start">
+ <div className={cn('text-lg font-semibold', scoreColor(audit.totalScore))}>
+ {t(`grade.${grade}`)}
+ </div>
+ {scoreDelta !== null && previousDate && (
+ <Badge
+ variant="outline"
+ className={cn(
+ 'text-xs font-medium tabular-nums',
+ scoreDelta > 0 &&
+ 'border-green-600/30 bg-green-600/10 text-green-700 dark:text-green-400',
+ scoreDelta < 0 && 'border-destructive/30 bg-destructive/10 text-destructive',
+ scoreDelta === 0 && 'text-muted-foreground',
+ )}
+ >
+ {t('scoreChange', {
+ change: scoreDelta > 0 ? `+${scoreDelta}` : String(scoreDelta),
+ date: previousDate,
+ })}
+ </Badge>
+ )}
</div>
)}
<div className="flex flex-wrap justify-center gap-2 sm:justify-start">
diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.ts
index e419a7764..f43fb56b9 100644
--- a/web/src/lib/actions/audits.ts
+++ b/web/src/lib/actions/audits.ts
@@ -45,6 +45,9 @@ export interface AuditResult {
finalUrl: string | null;
status: 'running' | 'completed' | 'failed';
totalScore: number | null;
+ /** Nearest earlier completed audit of the same normalized page, for the report delta. */
+ previousScore?: number | null;
+ previousCreatedAt?: string | null;
categoryScores: Record<string, CategoryScore>;
signalsEvaluated: number | null;
signalsTotal: number;