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): Site Audit — 47-signal AEO/GEO page scoring with AI fixes (#259)

Gökhan Geyikdc3ccf5e2b5b
diff --git a/server/.env.example b/server/.env.example
index 98b607a90..9dcdda659 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -14,6 +14,12 @@ DEFAULT_SUGGESTION_MODEL=google/gemini-3-flash-preview
TOPIC_SUGGESTION_MODEL=google/gemini-3-flash-preview
PROMPT_SUGGESTION_MODEL=google/gemini-3-flash-preview
COMPETITOR_SUGGESTION_MODEL=google/gemini-3-flash-preview
+# Model used for the Site Audit LLM-judged signals (provider/model). Cheap by
+# default; point it at anthropic/claude-... or openai/... if you prefer.
+AUDIT_LLM_MODEL=google/gemini-3-flash-preview
+
+# Site Audit page fetching (proxy + JS render)
+SCRAPEDO_API_KEY=
# CORS
ALLOWED_ORIGINS=http://localhost:3000
diff --git a/server/package-lock.json b/server/package-lock.json
index b8c787e4d..ab2e97bee 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@ansvisor/ansvisor-server",
- "version": "0.1.2",
+ "version": "0.1.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@ansvisor/ansvisor-server",
- "version": "0.1.2",
+ "version": "0.1.3",
"license": "MIT",
"dependencies": {
"@ai-sdk/anthropic": "^3.0.58",
@@ -16,6 +16,7 @@
"@supabase/supabase-js": "^2.49.1",
"ai": "^6.0.116",
"body-parser": "^1.20.2",
+ "cheerio": "^1.2.0",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
@@ -2126,6 +2127,12 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
+ "node_modules/boolbase": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
+ "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==",
+ "license": "ISC"
+ },
"node_modules/brace-expansion": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.4.tgz",
@@ -2282,6 +2289,48 @@
"node": ">= 16"
}
},
+ "node_modules/cheerio": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.2.0.tgz",
+ "integrity": "sha512-WDrybc/gKFpTYQutKIK6UvfcuxijIZfMfXaYm8NMsPQxSYvf+13fXUJ4rztGGbJcBQ/GF55gvrZ0Bc0bj/mqvg==",
+ "license": "MIT",
+ "dependencies": {
+ "cheerio-select": "^2.1.0",
+ "dom-serializer": "^2.0.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.2.2",
+ "encoding-sniffer": "^0.2.1",
+ "htmlparser2": "^10.1.0",
+ "parse5": "^7.3.0",
+ "parse5-htmlparser2-tree-adapter": "^7.1.0",
+ "parse5-parser-stream": "^7.1.2",
+ "undici": "^7.19.0",
+ "whatwg-mimetype": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=20.18.1"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/cheerio?sponsor=1"
+ }
+ },
+ "node_modules/cheerio-select": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz",
+ "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "boolbase": "^1.0.0",
+ "css-select": "^5.1.0",
+ "css-what": "^6.1.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
"node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
@@ -2422,6 +2471,34 @@
"node": ">= 8"
}
},
+ "node_modules/css-select": {
+ "version": "5.2.2",
+ "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz",
+ "integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "boolbase": "^1.0.0",
+ "css-what": "^6.1.0",
+ "domhandler": "^5.0.2",
+ "domutils": "^3.0.1",
+ "nth-check": "^2.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
+ "node_modules/css-what": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz",
+ "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">= 6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
"node_modules/culvert": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/culvert/-/culvert-0.1.2.tgz",
@@ -2502,6 +2579,61 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
+ "node_modules/dom-serializer": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "entities": "^4.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/domelementtype": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/domhandler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "domelementtype": "^2.3.0"
+ },
+ "engines": {
+ "node": ">= 4"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/domutils": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
+ "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "dom-serializer": "^2.0.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
@@ -2543,6 +2675,31 @@
"node": ">= 0.8"
}
},
+ "node_modules/encoding-sniffer": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.1.tgz",
+ "integrity": "sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw==",
+ "license": "MIT",
+ "dependencies": {
+ "iconv-lite": "^0.6.3",
+ "whatwg-encoding": "^3.1.1"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/encoding-sniffer?sponsor=1"
+ }
+ },
+ "node_modules/encoding-sniffer/node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/engine.io": {
"version": "6.6.6",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.6.tgz",
@@ -2629,6 +2786,18 @@
"node": ">=8.6"
}
},
+ "node_modules/entities": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@@ -3492,6 +3661,37 @@
"node": ">=16.0.0"
}
},
+ "node_modules/htmlparser2": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
+ "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==",
+ "funding": [
+ "https://github.com/fb55/htmlparser2?sponsor=1",
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.2.2",
+ "entities": "^7.0.1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/entities": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
@@ -4191,6 +4391,18 @@
"integrity": "sha512-K7J4xq5xAD5jHsGM5ReWXRTFa3JRGofHiMcVgQ8PRwgWxzjHpMWCIzsmyf60+mh8KLsqYPcjUMa0AC4hd6lPyQ==",
"license": "MIT"
},
+ "node_modules/nth-check": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz",
+ "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "boolbase": "^1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/nth-check?sponsor=1"
+ }
+ },
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@@ -4369,6 +4581,55 @@
"node": ">=6"
}
},
+ "node_modules/parse5": {
+ "version": "7.3.0",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
+ "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
+ "license": "MIT",
+ "dependencies": {
+ "entities": "^6.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/parse5-htmlparser2-tree-adapter": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.1.0.tgz",
+ "integrity": "sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==",
+ "license": "MIT",
+ "dependencies": {
+ "domhandler": "^5.0.3",
+ "parse5": "^7.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/parse5-parser-stream": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-7.1.2.tgz",
+ "integrity": "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==",
+ "license": "MIT",
+ "dependencies": {
+ "parse5": "^7.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/parse5/node_modules/entities": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
+ "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@@ -5763,6 +6024,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/undici": {
+ "version": "7.27.2",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.27.2.tgz",
+ "integrity": "sha512-uZsKNuzQxDMUY6M3pIMvy5tvlGmtq8XJ2oLAkfRKGNu+1VQAIvLy2xIVG5ATZl5wDXl/tddByAWCizRbOme+TA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.18.1"
+ }
+ },
"node_modules/undici-types": {
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
@@ -6108,6 +6378,40 @@
"lodash": "^4.17.14"
}
},
+ "node_modules/whatwg-encoding": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
+ "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
+ "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation",
+ "license": "MIT",
+ "dependencies": {
+ "iconv-lite": "0.6.3"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/whatwg-encoding/node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/whatwg-mimetype": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
+ "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
diff --git a/server/package.json b/server/package.json
index 01ca8629a..2f289f82f 100644
--- a/server/package.json
+++ b/server/package.json
@@ -30,6 +30,7 @@
"@supabase/supabase-js": "^2.49.1",
"ai": "^6.0.116",
"body-parser": "^1.20.2",
+ "cheerio": "^1.2.0",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
diff --git a/server/src/config/plans.js b/server/src/config/plans.js
index 38309f50f..f5de4bb77 100644
--- a/server/src/config/plans.js
+++ b/server/src/config/plans.js
@@ -15,6 +15,7 @@ export const PLANS = {
maxDomainsPerBrand: -1,
maxVolumeAnalyses: -1,
maxBriefGenerations: -1,
+ maxSiteAudits: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
features: [
@@ -43,6 +44,7 @@ export const PLANS = {
maxDomainsPerBrand: 3,
maxVolumeAnalyses: 4,
maxBriefGenerations: 10,
+ maxSiteAudits: 100,
maxDailyOnDemand: 3,
onDemandCooldownMinutes: 15,
allowedScrapers: ['chatgpt-web', 'perplexity-web'],
@@ -72,6 +74,7 @@ export const PLANS = {
maxDomainsPerBrand: 10,
maxVolumeAnalyses: 10,
maxBriefGenerations: 50,
+ maxSiteAudits: 500,
maxDailyOnDemand: 10,
onDemandCooldownMinutes: 5,
features: [
@@ -101,6 +104,7 @@ export const PLANS = {
maxVolumeAnalyses: -1,
// Per-customer: override via organizations.plan_overrides in the DB.
maxBriefGenerations: -1,
+ maxSiteAudits: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
features: [
diff --git a/server/src/lib/audit/audit.test.js b/server/src/lib/audit/audit.test.js
new file mode 100644
index 000000000..35fcf348d
--- /dev/null
+++ b/server/src/lib/audit/audit.test.js
@@ -0,0 +1,125 @@
+import { describe, it, expect } from 'vitest';
+import * as cheerio from 'cheerio';
+import { scoreAudit } from './scorer.js';
+import { fleschReadingEase, classifyLinks, jsonLd, countPhrases } from './signals/helpers.js';
+import { jsonLdPresence, h1Quality } from './signals/structure.js';
+import { https, metaDescription } from './signals/trust.js';
+import { length } from './signals/content.js';
+
+/** Build a minimal audit context from an HTML string (no network). */
+function ctxFromHtml(html, extra = {}) {
+ const text = cheerio.load(html)('body').text().replace(/\s+/g, ' ').trim();
+ return {
+ url: 'https://example.com/page',
+ origin: 'https://example.com',
+ protocol: 'https',
+ statusCode: 200,
+ html,
+ htmlBytes: Buffer.byteLength(html, 'utf8'),
+ $: cheerio.load(html),
+ text,
+ wordCount: text ? text.split(/\s+/).length : 0,
+ robotsTxt: null,
+ llmsTxt: null,
+ now: Date.UTC(2026, 0, 1),
+ ...extra,
+ };
+}
+
+describe('scoreAudit', () => {
+ it('averages within a category and normalizes the total over evaluated categories', () => {
+ const results = [
+ { key: 'json-ld-presence', status: 'pass', score: 1 }, // structure
+ { key: 'h1-quality', status: 'fail', score: 0 }, // structure
+ { key: 'https', status: 'pass', score: 1 }, // trust
+ ];
+ const { totalScore, categoryScores } = scoreAudit(results);
+
+ expect(categoryScores.structure.score).toBeCloseTo(0.5, 5);
+ expect(categoryScores.structure.evaluated).toBe(2);
+ expect(categoryScores.structure.total).toBe(13);
+ expect(categoryScores.trust.score).toBe(1);
+ // (0.25*0.5 + 0.10*1) / (0.25 + 0.10) = 0.643
+ expect(totalScore).toBeCloseTo(0.6428, 3);
+ });
+
+ it('excludes na signals and reports null for categories with no evaluated signals', () => {
+ const results = [
+ { key: 'https', status: 'pass', score: 1 },
+ { key: 'json-ld-presence', status: 'na', score: null },
+ ];
+ const { categoryScores } = scoreAudit(results);
+ expect(categoryScores.structure.score).toBeNull();
+ expect(categoryScores.structure.evaluated).toBe(0);
+ expect(categoryScores.trust.score).toBe(1);
+ });
+});
+
+describe('helpers', () => {
+ it('fleschReadingEase returns null for short text and a number for enough text', () => {
+ expect(fleschReadingEase('Too short.')).toBeNull();
+ const text = Array.from({ length: 40 }, () => 'the cat sat on the mat').join('. ') + '.';
+ expect(typeof fleschReadingEase(text)).toBe('number');
+ });
+
+ it('classifyLinks splits internal vs external', () => {
+ const ctx = ctxFromHtml(
+ `<a href="/about">a</a><a href="https://example.com/x">b</a>
+ <a href="https://other.com/y">c</a><a href="#frag">d</a><a href="mailto:[email protected]">e</a>`,
+ );
+ const { internal, external } = classifyLinks(ctx);
+ expect(internal.length).toBe(2); // /about + example.com/x
+ expect(external.length).toBe(1); // other.com
+ });
+
+ it('jsonLd parses blocks and counts valid ones', () => {
+ const ctx = ctxFromHtml(
+ `<script type="application/ld+json">{"@type":"Article"}</script>
+ <script type="application/ld+json">not json</script>`,
+ );
+ const { total, valid, nodes } = jsonLd(ctx);
+ expect(total).toBe(2);
+ expect(valid).toBe(1);
+ expect(nodes).toHaveLength(1);
+ });
+
+ it('countPhrases counts case-insensitive occurrences', () => {
+ expect(countPhrases('We tested it. Then WE TESTED again.', ['we tested'])).toBe(2);
+ });
+});
+
+describe('deterministic signals', () => {
+ it('h1-quality: pass for one well-sized H1, fail for none', () => {
+ const good = h1Quality.evaluate(ctxFromHtml('<h1>The Best Running Shoes for Marathons</h1>'));
+ expect(good.status).toBe('pass');
+ expect(good.score).toBe(1);
+ expect(h1Quality.evaluate(ctxFromHtml('<p>no heading</p>')).status).toBe('fail');
+ });
+
+ it('json-ld-presence: pass when a block exists', () => {
+ const r = jsonLdPresence.evaluate(
+ ctxFromHtml('<script type="application/ld+json">{"@type":"Article"}</script>'),
+ );
+ expect(r.status).toBe('pass');
+ });
+
+ it('https: pass over TLS without mixed content, warn with an http asset', () => {
+ expect(https.evaluate(ctxFromHtml('<img src="https://x/i.png">')).status).toBe('pass');
+ const mixed = https.evaluate(ctxFromHtml('<img src="http://x/i.png">'));
+ expect(mixed.status).toBe('warn');
+ expect(https.evaluate(ctxFromHtml('<p>x</p>', { protocol: 'http' })).status).toBe('fail');
+ });
+
+ it('meta-description: pass for 80–160 chars, fail when absent', () => {
+ const desc = 'x'.repeat(120);
+ expect(
+ metaDescription.evaluate(ctxFromHtml(`<meta name="description" content="${desc}">`)).status,
+ ).toBe('pass');
+ expect(metaDescription.evaluate(ctxFromHtml('<p>x</p>')).status).toBe('fail');
+ });
+
+ it('length: pass for 800–3000 words', () => {
+ expect(length.evaluate(ctxFromHtml('<p>x</p>', { wordCount: 1200 })).status).toBe('pass');
+ expect(length.evaluate(ctxFromHtml('<p>x</p>', { wordCount: 100 })).status).toBe('fail');
+ });
+});
diff --git a/server/src/lib/audit/context.js b/server/src/lib/audit/context.js
new file mode 100644
index 000000000..dc7ec16c2
--- /dev/null
+++ b/server/src/lib/audit/context.js
@@ -0,0 +1,96 @@
+/**
+ * Build the evaluation context every signal reads from. One fetch of the
+ * target page (via Scrape.do) plus the public robots.txt / llms.txt, parsed
+ * once into a shared cheerio document and an extracted plain-text body.
+ *
+ * Signals MUST treat `$` as read-only — text extraction runs on a separate
+ * parse so removing <script>/<style> doesn't strip the JSON-LD blocks that
+ * structural signals need.
+ */
+
+import * as cheerio from 'cheerio';
+import { fetchViaScrapeDo, fetchText } from './fetcher.js';
+
+/**
+ * Normalize user-supplied input into an absolute http(s) URL.
+ * @param {string} raw
+ * @returns {string}
+ */
+export function normalizeUrl(raw) {
+ const trimmed = String(raw || '').trim();
+ if (!trimmed) {
+ throw Object.assign(new Error('A URL is required'), { status: 400 });
+ }
+ const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
+ try {
+ const u = new URL(withScheme);
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') {
+ throw new Error('bad protocol');
+ }
+ return u.toString();
+ } catch {
+ throw Object.assign(new Error(`Invalid URL: ${raw}`), { status: 400 });
+ }
+}
+
+/**
+ * @typedef {Object} AuditContext
+ * @property {string} url normalized, fetched URL
+ * @property {string} origin scheme + host
+ * @property {string} protocol 'https' | 'http'
+ * @property {number} statusCode Scrape.do response status
+ * @property {string} html raw page HTML
+ * @property {number} htmlBytes HTML size in bytes
+ * @property {import('cheerio').CheerioAPI} $ parsed DOM (read-only)
+ * @property {string} text extracted body text (scripts/styles stripped)
+ * @property {number} wordCount word count of `text`
+ * @property {string|null} robotsTxt
+ * @property {string|null} llmsTxt
+ * @property {string|null} query optional target buyer query (later phases)
+ */
+
+/**
+ * @param {string} rawUrl
+ * @param {{ query?: string|null }} [opts]
+ * @returns {Promise<AuditContext>}
+ */
+export async function buildAuditContext(rawUrl, { query = null } = {}) {
+ const url = normalizeUrl(rawUrl);
+ const u = new URL(url);
+ const origin = `${u.protocol}//${u.host}`;
+
+ const page = await fetchViaScrapeDo(url, { render: true });
+ if (!page.ok || !page.html) {
+ throw Object.assign(new Error(`Failed to fetch page (status ${page.status})`), { status: 502 });
+ }
+
+ const $ = cheerio.load(page.html);
+
+ // Plain-text extraction on a throwaway parse so the shared `$` keeps its
+ // <script type="application/ld+json"> blocks intact for structural signals.
+ const $text = cheerio.load(page.html);
+ $text('script, style, noscript, template, svg').remove();
+ const text = $text('body').text().replace(/\s+/g, ' ').trim();
+ const wordCount = text ? text.split(/\s+/).length : 0;
+
+ const [robotsTxt, llmsTxt] = await Promise.all([
+ fetchText(`${origin}/robots.txt`),
+ fetchText(`${origin}/llms.txt`),
+ ]);
+
+ return {
+ url,
+ origin,
+ protocol: u.protocol.replace(':', ''),
+ statusCode: page.status,
+ html: page.html,
+ htmlBytes: Buffer.byteLength(page.html, 'utf8'),
+ $,
+ text,
+ wordCount,
+ robotsTxt,
+ llmsTxt,
+ query,
+ now: Date.now(),
+ };
+}
diff --git a/server/src/lib/audit/engine.js b/server/src/lib/audit/engine.js
new file mode 100644
index 000000000..0ca038d07
--- /dev/null
+++ b/server/src/lib/audit/engine.js
@@ -0,0 +1,34 @@
+/**
+ * Run every implemented signal over an audit context. A signal that throws is
+ * recorded as 'na' (not applicable / errored) rather than aborting the run, so
+ * one bad check never sinks the whole audit.
+ */
+
+import { signalRegistry } from './signals/index.js';
+
+/**
+ * @param {import('./context.js').AuditContext} ctx
+ * @returns {Promise<Array<{ key: string, status: string, score: number|null, evidence: object }>>}
+ */
+export async function runSignals(ctx) {
+ const results = [];
+ for (const signal of signalRegistry) {
+ try {
+ const verdict = await signal.evaluate(ctx);
+ results.push({
+ key: signal.key,
+ status: verdict.status,
+ score: verdict.score,
+ evidence: verdict.evidence ?? {},
+ });
+ } catch (err) {
+ results.push({
+ key: signal.key,
+ status: 'na',
+ score: null,
+ evidence: { error: err.message },
+ });
+ }
+ }
+ return results;
+}
diff --git a/server/src/lib/audit/external-signals.js b/server/src/lib/audit/external-signals.js
new file mode 100644
index 000000000..e762f4a7b
--- /dev/null
+++ b/server/src/lib/audit/external-signals.js
@@ -0,0 +1,70 @@
+/**
+ * External-data audit signals (Faz 2). Currently just brand-entity, which
+ * checks whether the brand has a Wikidata entity (a Q-number) that AI engines
+ * can dereference as a trust anchor. No LLM — a single Wikidata search API
+ * call. Degrades to 'na' on any failure so it never sinks the audit.
+ */
+
+const WIKIDATA_API = 'https://www.wikidata.org/w/api.php';
+
+/**
+ * @param {string|null|undefined} brandName
+ * @returns {Promise<{ key: string, status: string, score: number|null, evidence: object }>}
+ */
+export async function evaluateBrandEntity(brandName) {
+ const key = 'brand-entity';
+ const name = (brandName || '').trim();
+ if (!name) {
+ return { key, status: 'na', score: null, evidence: { reason: 'no brand name' } };
+ }
+
+ const params = new URLSearchParams({
+ action: 'wbsearchentities',
+ search: name,
+ language: 'en',
+ format: 'json',
+ limit: '5',
+ type: 'item',
+ });
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 8000);
+ try {
+ const res = await fetch(`${WIKIDATA_API}?${params.toString()}`, {
+ signal: controller.signal,
+ headers: { 'user-agent': 'AnsvisorSiteAudit/1.0 (+https://ansvisor.com)' },
+ });
+ if (!res.ok) {
+ return { key, status: 'na', score: null, evidence: { error: `wikidata ${res.status}` } };
+ }
+ const data = await res.json();
+ const hits = Array.isArray(data.search) ? data.search : [];
+
+ // Case-insensitive exact label match → confident entity; near match → warn.
+ const lower = name.toLowerCase();
+ const exact = hits.find((h) => (h.label || '').toLowerCase() === lower);
+ const match = exact || hits[0];
+
+ if (exact) {
+ return {
+ key,
+ status: 'pass',
+ score: 1,
+ evidence: { qid: exact.id, label: exact.label, description: exact.description ?? null },
+ };
+ }
+ if (match) {
+ return {
+ key,
+ status: 'warn',
+ score: 0.5,
+ evidence: { qid: match.id, label: match.label, note: 'no exact label match' },
+ };
+ }
+ return { key, status: 'fail', score: 0, evidence: { matches: 0 } };
+ } catch (err) {
+ return { key, status: 'na', score: null, evidence: { error: err.message } };
+ } finally {
+ clearTimeout(timer);
+ }
+}
diff --git a/server/src/lib/audit/fetcher.js b/server/src/lib/audit/fetcher.js
new file mode 100644
index 000000000..a9722ebcd
--- /dev/null
+++ b/server/src/lib/audit/fetcher.js
@@ -0,0 +1,98 @@
+/**
+ * Page fetching for the Site Audit. The target page goes through Scrape.do
+ * (proxy + JS render), so we get the same HTML an AI render bot would. Small
+ * auxiliary files (robots.txt, llms.txt) are fetched directly — they're public
+ * by convention and not worth a Scrape.do credit each.
+ */
+
+const SCRAPEDO_API = 'https://api.scrape.do';
+
+function getToken() {
+ const token = process.env.SCRAPEDO_API_KEY;
+ if (!token) throw new Error('SCRAPEDO_API_KEY must be configured');
+ return token;
+}
+
+/**
+ * Fetch a URL through Scrape.do and return the rendered HTML.
+ *
+ * @param {string} targetUrl
+ * @param {{ render?: boolean }} [opts]
+ * @returns {Promise<{ ok: boolean, status: number, html: string, contentType: string|null }>}
+ */
+export async function fetchViaScrapeDo(targetUrl, { render = true, retries = 1 } = {}) {
+ const params = new URLSearchParams({ token: getToken(), url: targetUrl });
+ if (render) params.set('render', 'true');
+ const endpoint = `${SCRAPEDO_API}/?${params.toString()}`;
+
+ let last = { ok: false, status: 0, html: '', contentType: null };
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
+ try {
+ const res = await fetch(endpoint);
+ const html = await res.text();
+ last = { ok: res.ok, status: res.status, html, contentType: res.headers.get('content-type') };
+ // Retry only on proxy-side 5xx (transient); 4xx is the target's verdict.
+ if (res.ok || res.status < 500) return last;
+ } catch (err) {
+ last = { ok: false, status: 0, html: '', contentType: null, error: err.message };
+ }
+ }
+ return last;
+}
+
+/**
+ * Direct fetch of a small text resource (robots.txt / llms.txt). Returns null
+ * on any failure or non-2xx so the caller can decide whether to fall back.
+ *
+ * @param {string} url
+ * @param {{ timeoutMs?: number }} [opts]
+ * @returns {Promise<string|null>}
+ */
+async function fetchTextDirect(url, { timeoutMs = 8000 } = {}) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const res = await fetch(url, {
+ signal: controller.signal,
+ headers: { 'user-agent': 'AnsvisorSiteAudit/1.0 (+https://ansvisor.com)' },
+ redirect: 'follow',
+ });
+ if (res.ok) return { body: await res.text(), blocked: false };
+ // 404 / 410 → the file genuinely isn't there (don't waste a proxy credit).
+ // 401/403/405/406/429/503 → smells like an anti-bot block, worth a retry.
+ const blocked = [401, 403, 405, 406, 429, 503].includes(res.status);
+ return { body: null, blocked };
+ } catch {
+ // Timeout / TLS / network error — could be a block; let the caller retry.
+ return { body: null, blocked: true };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/**
+ * Fetch a small text resource (robots.txt / llms.txt), trying a cheap direct
+ * request first and falling back to Scrape.do when the site blocks us (so
+ * Cloudflare-style anti-bot doesn't produce a false "absent" reading). Returns
+ * null only when both paths fail.
+ *
+ * @param {string} url
+ * @returns {Promise<string|null>}
+ */
+export async function fetchText(url) {
+ const direct = await fetchTextDirect(url);
+ if (direct.body !== null) return direct.body;
+ // Clean 404 → the file is genuinely absent; no point spending a proxy credit.
+ if (!direct.blocked) return null;
+
+ // Direct request looked blocked — retry through Scrape.do (no JS render
+ // needed for a text file). Treat HTML error pages as "absent".
+ try {
+ const viaProxy = await fetchViaScrapeDo(url, { render: false, retries: 0 });
+ if (!viaProxy.ok || !viaProxy.html) return null;
+ if (/<html[\s>]/i.test(viaProxy.html)) return null;
+ return viaProxy.html;
+ } catch {
+ return null;
+ }
+}
diff --git a/server/src/lib/audit/llm-signals.js b/server/src/lib/audit/llm-signals.js
new file mode 100644
index 000000000..e5b1e64c2
--- /dev/null
+++ b/server/src/lib/audit/llm-signals.js
@@ -0,0 +1,118 @@
+/**
+ * LLM-judged audit signals (Faz 2). The 13 rubric signals that can't be
+ * measured by parsing alone — they need semantic judgment and, for some, a
+ * target buyer query. We run them in a SINGLE structured-output call (one
+ * model round-trip per audit, not one per signal) for cost + latency.
+ *
+ * Model is provider-flexible via resolveModel; default is a cheap Gemini Flash
+ * (`AUDIT_LLM_MODEL`, e.g. google/gemini-3-flash-preview). Self-hosters can
+ * point it at Claude/OpenAI. If the call fails the signals degrade to 'na' so
+ * one bad LLM round-trip never sinks the deterministic audit.
+ */
+
+import { generateObject } from 'ai';
+import { z } from 'zod';
+import { resolveModel } from '../ai-provider.js';
+import { signalsByKey } from './rubric.js';
+
+const DEFAULT_MODEL = 'google/gemini-3-flash-preview';
+
+// The rubric signals judged by the model. brand-entity (Wikidata) and the
+// already-deterministic signals are handled elsewhere.
+export const LLM_SIGNAL_KEYS = [
+ 'direct-answer',
+ 'bluf-answer',
+ 'query-coverage',
+ 'sub-query-coverage',
+ 'entity-coverage',
+ 'info-density',
+ 'mega-page-coverage',
+ 'definitions',
+ 'technical-terms',
+ 'case-study-evidence',
+ 'author-credentials',
+ 'byline-depth',
+ 'press-mentions',
+];
+
+const verdictSchema = z.object({
+ status: z.enum(['pass', 'warn', 'fail', 'na']),
+ score: z.number().min(0).max(1).nullable(),
+ reason: z.string().max(300),
+});
+
+const responseSchema = z.object(Object.fromEntries(LLM_SIGNAL_KEYS.map((k) => [k, verdictSchema])));
+
+const SYSTEM_PROMPT = `You are an AEO/GEO content auditor. You judge whether a web page satisfies scoring signals that AI answer engines (ChatGPT, Gemini, Perplexity, Google AI Overviews) use when deciding what to cite.
+
+CRITICAL: Evaluate the page ENTIRELY ON ITS OWN TERMS. First infer, from the page's own title and content, what topic/query this specific page is trying to serve. Judge every signal against THAT inferred intent. Never assume the page should be about some other topic, and never import outside subject matter.
+
+Be strict and evidence-based. For each signal return:
+- status: "pass" (clearly satisfied), "warn" (partially), "fail" (not satisfied), or "na" (genuinely not applicable to this page type).
+- score: 0..1 (1 = fully satisfied), or null when status is "na".
+- reason: ONE short sentence citing what you saw on THIS page (or its absence). No markdown.
+
+Judge only from the provided page text and facts. Do not assume content you cannot see.`;
+
+function buildPrompt(ctx) {
+ const defs = LLM_SIGNAL_KEYS.map((k) => {
+ const s = signalsByKey[k] ?? {};
+ return `- ${k}: ${s.what ?? ''}`;
+ }).join('\n');
+
+ const pageText = ctx.text.slice(0, 8000);
+
+ return `PAGE URL: ${ctx.url}
+PAGE WORD COUNT: ${ctx.wordCount}
+
+First, infer this page's own primary topic/query from its title and content. Then judge each signal against that inferred intent — the query-related signals (direct-answer, query-coverage, sub-query-coverage, entity-coverage) are about how well the page serves ITS OWN topic, not any external one.
+
+SIGNALS TO JUDGE:
+${defs}
+
+PAGE TEXT (truncated):
+"""
+${pageText}
+"""
+
+Return a verdict for every signal key.`;
+}
+
+/**
+ * @param {import('./context.js').AuditContext} ctx
+ * @returns {Promise<Array<{ key: string, status: string, score: number|null, evidence: object }>>}
+ */
+export async function evaluateLlmSignals(ctx) {
+ const modelString = process.env.AUDIT_LLM_MODEL || DEFAULT_MODEL;
+
+ try {
+ const { object } = await generateObject({
+ model: resolveModel(modelString),
+ schema: responseSchema,
+ system: SYSTEM_PROMPT,
+ prompt: buildPrompt(ctx),
+ });
+
+ return LLM_SIGNAL_KEYS.map((key) => {
+ const v = object[key];
+ if (!v) {
+ return { key, status: 'na', score: null, evidence: { reason: 'no verdict returned' } };
+ }
+ return {
+ key,
+ status: v.status,
+ score: v.status === 'na' ? null : v.score,
+ evidence: { reason: v.reason, model: modelString },
+ };
+ });
+ } catch (err) {
+ console.error('[audit] LLM signals failed:', err.message, { model: modelString });
+ // Degrade gracefully — deterministic signals still score the page.
+ return LLM_SIGNAL_KEYS.map((key) => ({
+ key,
+ status: 'na',
+ score: null,
+ evidence: { error: 'LLM evaluation unavailable' },
+ }));
+ }
+}
diff --git a/server/src/lib/audit/recommendations.js b/server/src/lib/audit/recommendations.js
new file mode 100644
index 000000000..37f511d07
--- /dev/null
+++ b/server/src/lib/audit/recommendations.js
@@ -0,0 +1,137 @@
+/**
+ * AI fix recommendations (Faz 3). After an audit scores the page, we send the
+ * failing/warning signals that an LLM can genuinely help with to one batched
+ * call and get back prioritized, page-specific recommendations — including
+ * ready-to-paste drafts (a meta description, an H1, a BLUF paragraph, FAQ
+ * Q&A + JSON-LD, suggested citations, etc.).
+ *
+ * Mechanical/config signals (add a video, enable HTTPS, fix viewport,
+ * alt-text…) are excluded — their generic howToFix is already actionable and
+ * the LLM can't add page-specific value.
+ */
+
+import { generateObject } from 'ai';
+import { z } from 'zod';
+import { resolveModel } from '../ai-provider.js';
+import { signalsByKey } from './rubric.js';
+
+const DEFAULT_MODEL = 'google/gemini-3-flash-preview';
+
+// Signals where a tailored recommendation / drafted content is worthwhile.
+export const RECOMMENDABLE_SIGNALS = new Set([
+ // structure (draftable)
+ 'h1-quality',
+ 'h2-coverage',
+ 'faq-schema',
+ 'json-ld-relevance',
+ 'open-graph',
+ 'meta-description',
+ // authority
+ 'outbound-authority-links',
+ 'citation-density',
+ 'statistic-density',
+ 'quotations',
+ 'author-byline',
+ // content
+ 'direct-answer',
+ 'bluf-answer',
+ 'query-coverage',
+ 'sub-query-coverage',
+ 'entity-coverage',
+ 'info-density',
+ 'mega-page-coverage',
+ 'definitions',
+ 'technical-terms',
+ 'readability',
+ 'length',
+ // e-e-a-t
+ 'first-person',
+ 'case-study-evidence',
+ 'author-credentials',
+ 'byline-depth',
+ 'press-mentions',
+]);
+
+const recommendationsSchema = z.object({
+ recommendations: z.array(
+ z.object({
+ signalKey: z.string(),
+ priority: z.enum(['high', 'medium', 'low']),
+ recommendation: z.string().max(600),
+ draft: z.string().max(2000).nullable(),
+ }),
+ ),
+});
+
+const SYSTEM_PROMPT = `You are an AEO/GEO content strategist. For each failing signal you are given, write ONE concrete recommendation tailored specifically to THIS page — never generic boilerplate, never restate the rule.
+
+When the fix is content the user can paste, put the ready-to-use text in "draft":
+- meta-description → a 130–155 char description
+- h1-quality → a single improved H1
+- bluf-answer / direct-answer → an opening paragraph that leads with the answer
+- faq-schema → 3–5 Q&A pairs AND a valid FAQPage JSON-LD block
+- definitions → the key terms defined inline
+- outbound-authority-links / citation-density → specific authoritative sources to cite
+- readability → a simplified rewrite of one representative paragraph (shorter sentences, plainer words)
+- length → which specific sections to expand or trim (draft can be null)
+
+Keep "recommendation" to 1–3 sentences. Set "draft" to null when the fix isn't a paste-able snippet. Prioritize by impact. Only return items you can make genuinely specific and useful.`;
+
+/**
+ * @param {import('./context.js').AuditContext} ctx
+ * @param {{ results: Array<{key:string,status:string,evidence:object}>, queries?: string[] }} opts
+ * @returns {Promise<Array<{ signalKey: string, label: string, category: string|null, priority: string, recommendation: string, draft: string|null }>>}
+ */
+export async function generateRecommendations(ctx, { results } = {}) {
+ const failing = (results || []).filter(
+ (r) => RECOMMENDABLE_SIGNALS.has(r.key) && (r.status === 'fail' || r.status === 'warn'),
+ );
+ if (failing.length === 0) return [];
+
+ const modelString = process.env.AUDIT_LLM_MODEL || DEFAULT_MODEL;
+
+ const issues = failing
+ .map((r) => {
+ const s = signalsByKey[r.key] ?? {};
+ const finding = r.evidence?.reason ? ` | finding: ${r.evidence.reason}` : '';
+ return `- ${r.key} [${r.status}, impact: ${s.impactTier ?? 'standard'}]: ${s.what ?? ''}${finding}`;
+ })
+ .join('\n');
+
+ const pageText = ctx.text.slice(0, 6000);
+
+ try {
+ const { object } = await generateObject({
+ model: resolveModel(modelString),
+ schema: recommendationsSchema,
+ system: SYSTEM_PROMPT,
+ prompt: `PAGE URL: ${ctx.url}
+
+Improve THIS page for its own topic/intent (infer it from the content below). Never introduce subject matter the page isn't already about.
+
+FAILING SIGNALS TO FIX:
+${issues}
+
+PAGE TEXT (truncated):
+"""
+${pageText}
+"""
+
+Return prioritized, page-specific recommendations.`,
+ });
+
+ return (object.recommendations || [])
+ .filter((r) => RECOMMENDABLE_SIGNALS.has(r.signalKey))
+ .map((r) => ({
+ signalKey: r.signalKey,
+ label: signalsByKey[r.signalKey]?.label ?? r.signalKey,
+ category: signalsByKey[r.signalKey]?.category ?? null,
+ priority: r.priority,
+ recommendation: r.recommendation,
+ draft: r.draft || null,
+ }));
+ } catch (err) {
+ console.error('[audit] recommendations failed:', err.message, { model: modelString });
+ return [];
+ }
+}
diff --git a/server/src/lib/audit/rubric.js b/server/src/lib/audit/rubric.js
new file mode 100644
index 000000000..59c759e29
--- /dev/null
+++ b/server/src/lib/audit/rubric.js
@@ -0,0 +1,31 @@
+/**
+ * AEO/GEO scoring rubric we implement for the Site Audit feature. We run the
+ * checks ourselves rather than calling any third-party API; this module just
+ * exposes the rubric's metadata (categories, weights, and the per-signal
+ * label / what / why / howToFix / impactTier copy) so the engine and the UI
+ * can describe each signal.
+ */
+
+import { createRequire } from 'module';
+
+const require = createRequire(import.meta.url);
+const rubric = require('./rubric.json');
+
+export const RUBRIC_VERSION = rubric.version;
+
+/** Category descriptors with their scoring weights (sum to 1.0). */
+export const categories = rubric.categories;
+
+/** signalKey -> full signal descriptor ({ key, category, label, what, why, howToFix, source, impactTier }). */
+export const signalsByKey = Object.fromEntries(rubric.signals.map((s) => [s.key, s]));
+
+/** Total number of signals in the standard (47), regardless of how many we've implemented. */
+export const TOTAL_SIGNALS = rubric.signals.length;
+
+/**
+ * @param {string} key
+ * @returns {object|null}
+ */
+export function describeSignal(key) {
+ return signalsByKey[key] ?? null;
+}
diff --git a/server/src/lib/audit/rubric.json b/server/src/lib/audit/rubric.json
new file mode 100644
index 000000000..470286adf
--- /dev/null
+++ b/server/src/lib/audit/rubric.json
@@ -0,0 +1,514 @@
+{
+ "version": "v1",
+ "description": "47-signal AEO/GEO scoring rubric for measuring whether a page will get cited by AI answer engines.",
+ "totalSignals": 47,
+ "categories": [
+ {
+ "key": "structure",
+ "label": "Structure",
+ "weight": 0.25,
+ "description": "How parseable your page is to an AI engine. Schema, headings, lists, tables, alt-text, OG meta. The substrate that makes everything else legible.",
+ "signalCount": 13
+ },
+ {
+ "key": "authority",
+ "label": "Authority",
+ "weight": 0.2,
+ "description": "Whether your page reads as authored by an expert, citing real sources. Bylines, citations, statistics, quotations, freshness, technical terms.",
+ "signalCount": 8
+ },
+ {
+ "key": "content",
+ "label": "Content",
+ "weight": 0.25,
+ "description": "Whether the page actually answers the buyer query — directly, completely, in the right register. BLUF, query coverage, sub-question coverage, readability.",
+ "signalCount": 11
+ },
+ {
+ "key": "trust",
+ "label": "Trust",
+ "weight": 0.1,
+ "description": "Crawl-time + share-time trust signals: HTTPS, canonical, viewport, AI-bot access via robots/llms.txt, Twitter card, meta description.",
+ "signalCount": 7
+ },
+ {
+ "key": "eeat",
+ "label": "E-E-A-T",
+ "weight": 0.2,
+ "description": "Google's framework for Experience, Expertise, Authoritativeness, Trustworthiness. First-person evidence, case studies, author credentials, brand entity in Wikidata, press mentions, privacy policy, contact info.",
+ "signalCount": 8
+ }
+ ],
+ "signals": [
+ {
+ "key": "structural-depth",
+ "category": "structure",
+ "label": "Structural depth (GEO-SFE)",
+ "what": "Heading hierarchy + nested structure depth — H1→H2→H3 nesting that mirrors a real outline.",
+ "why": "arXiv:2603.29979 shows a +17.3% citation lift for pages with measurable structural depth vs flat documents.",
+ "howToFix": "Group your content under named H2 subsections. Use H3 for sub-points. Don't skip levels.",
+ "source": "GEO-SFE (arXiv:2603.29979) + Aggarwal et al. NeurIPS 2024",
+ "impactTier": "high"
+ },
+ {
+ "key": "internal-linking",
+ "category": "structure",
+ "label": "Internal linking",
+ "what": "Links from this page to other pages on your site — signal of a navigable graph.",
+ "why": "AI crawlers expand context via internal links the same way they crawl. Isolated pages get under-indexed.",
+ "howToFix": "Add 5–10 internal links per page to related concepts, glossary terms, or supporting pages.",
+ "source": "Anthropic web-search retrieval docs",
+ "impactTier": "medium"
+ },
+ {
+ "key": "page-weight",
+ "category": "structure",
+ "label": "Page weight",
+ "what": "Total HTML size, lower is better. We flag pages over 500 KB.",
+ "why": "AI render bots have shorter timeouts than humans. Heavy pages get truncated or skipped.",
+ "howToFix": "Strip unused JS, defer below-the-fold images, kill render-blocking third-party scripts.",
+ "source": "Google SGE crawler docs",
+ "impactTier": "standard"
+ },
+ {
+ "key": "json-ld-presence",
+ "category": "structure",
+ "label": "JSON-LD presence",
+ "what": "Whether the page ships at least one schema.org JSON-LD block.",
+ "why": "Schema.org is the single highest-leverage signal for AI Overview eligibility — engines parse it before text.",
+ "howToFix": "Add at minimum an Organization or Article block. Our /tools/schema-generator outputs valid JSON-LD.",
+ "source": "Google SGE evaluation guide",
+ "impactTier": "high"
+ },
+ {
+ "key": "json-ld-validity",
+ "category": "structure",
+ "label": "JSON-LD validity",
+ "what": "Whether the JSON-LD parses, has @context = schema.org, and a valid @type.",
+ "why": "Malformed JSON-LD is worse than absent — engines log a parse error and downrank trust.",
+ "howToFix": "Run your JSON-LD through Google's Rich Results Test before shipping.",
+ "source": "Google SGE evaluation guide",
+ "impactTier": "medium"
+ },
+ {
+ "key": "json-ld-relevance",
+ "category": "structure",
+ "label": "JSON-LD type relevance",
+ "what": "Whether the @type matches the page intent (Article on a blog, Product on a PDP, FAQPage on a FAQ).",
+ "why": "Wrong-type schema gets ignored — Article markup on a homepage is parsed as noise.",
+ "howToFix": "Pick the closest schema.org type for the page's actual content, not a generic catch-all.",
+ "source": "schema.org documentation",
+ "impactTier": "medium"
+ },
+ {
+ "key": "faq-schema",
+ "category": "structure",
+ "label": "FAQ schema",
+ "what": "FAQPage JSON-LD with at least 2 Q&A pairs.",
+ "why": "FAQPage is the highest single-type lift for AI Overview citations per Google's own SGE guidance.",
+ "howToFix": "Add FAQPage schema with 3–5 question/answer pairs that mirror real buyer queries.",
+ "source": "Google SGE evaluation guide",
+ "impactTier": "medium"
+ },
+ {
+ "key": "h1-quality",
+ "category": "structure",
+ "label": "H1 quality",
+ "what": "Exactly one H1, length 20–70 chars, contains a primary query token.",
+ "why": "AI engines treat H1 as the page's claim — multiple H1s confuse the topical model.",
+ "howToFix": "One H1 per page, descriptive, 30–60 chars, includes the page's primary topic.",
+ "source": "Google SGE crawler docs",
+ "impactTier": "medium"
+ },
+ {
+ "key": "h2-coverage",
+ "category": "structure",
+ "label": "H2 coverage",
+ "what": "≥3 H2 subsections that segment the content for skim-readability.",
+ "why": "AI engines extract H2s as section anchors — pages without them are harder to summarize.",
+ "howToFix": "Break content into 3–6 H2 subsections, each addressing a sub-question.",
+ "source": "Aggarwal et al. NeurIPS 2024",
+ "impactTier": "medium"
+ },
+ {
+ "key": "lists",
+ "category": "structure",
+ "label": "Lists",
+ "what": "≥1 <ul> or <ol> with ≥3 items.",
+ "why": "Lists are the unit AI engines preferentially extract for 'how to X' and 'best Y' queries.",
+ "howToFix": "Convert at least one paragraph of enumerated reasons or steps into a real <ul>/<ol>.",
+ "source": "Aggarwal et al. NeurIPS 2024",
+ "impactTier": "standard"
+ },
+ {
+ "key": "tables",
+ "category": "structure",
+ "label": "Tables",
+ "what": "≥1 <table> with proper <thead>/<tbody> for structured data.",
+ "why": "Tables are the highest-extraction-rate format for comparison and spec-sheet queries.",
+ "howToFix": "If you have specs, prices, or comparisons, render them as real <table>s, not images.",
+ "source": "Aggarwal et al. NeurIPS 2024",
+ "impactTier": "standard"
+ },
+ {
+ "key": "alt-text",
+ "category": "structure",
+ "label": "Alt-text",
+ "what": "≥80% of <img> tags have non-empty alt attributes.",
+ "why": "Multi-modal engines (Gemini, Claude, GPT-4o) read alt-text as page semantic context.",
+ "howToFix": "Add descriptive alt to every meaningful image. Decorative images get alt=\"\".",
+ "source": "Google SGE evaluation guide",
+ "impactTier": "standard"
+ },
+ {
+ "key": "open-graph",
+ "category": "structure",
+ "label": "Open Graph metadata",
+ "what": "og:title, og:description, og:image, og:type all present.",
+ "why": "AI engine link previews + social shares use OG meta as the citation card.",
+ "howToFix": "Add the 4 OG tags. Use 1200×630 og:image. Our /tools/og-checker validates them.",
+ "source": "Open Graph Protocol",
+ "impactTier": "medium"
+ },
+ {
+ "key": "outbound-authority-links",
+ "category": "authority",
+ "label": "Outbound authority links",
+ "what": "Links to .edu, .gov, Wikipedia, peer-reviewed journals, or top-tier news sources.",
+ "why": "Linking out to trusted sources transfers authority backwards (citation graph effect).",
+ "howToFix": "Cite primary sources with real <a> tags, not bare-text references. Aim for 2–3 per long page.",
+ "source": "GEO paper §4.2 + Anthropic retrieval docs",
+ "impactTier": "medium"
+ },
+ {
+ "key": "citation-density",
+ "category": "authority",
+ "label": "Citation density",
+ "what": "Inline citations per 1000 words (target ≥2).",
+ "why": "Pages that cite sources get cited as sources. Citation density is the strongest non-link authority signal.",
+ "howToFix": "Replace 'studies show' with 'a 2024 Stanford study (link)'. Specificity wins.",
+ "source": "GEO paper §4.2",
+ "impactTier": "medium"
+ },
+ {
+ "key": "statistic-density",
+ "category": "authority",
+ "label": "Statistic density",
+ "what": "Quantitative claims with numbers per 1000 words (target ≥3).",
+ "why": "AI engines preferentially cite content with measurable claims over hand-wavy text.",
+ "howToFix": "Add real numbers — percentages, dollar amounts, time durations — to your claims.",
+ "source": "Aggarwal et al. NeurIPS 2024",
+ "impactTier": "medium"
+ },
+ {
+ "key": "quotations",
+ "category": "authority",
+ "label": "Direct quotations",
+ "what": "Inline <blockquote> or quoted attributions.",
+ "why": "Quotations imply primary research. They lift citation rates ~12% in the GEO paper test set.",
+ "howToFix": "Quote one customer, one expert, or one primary source per long page.",
+ "source": "GEO paper",
+ "impactTier": "standard"
+ },
+ {
+ "key": "author-byline",
+ "category": "authority",
+ "label": "Author byline",
+ "what": "A named author with at least a real name in the byline area.",
+ "why": "Anonymous content is treated as low-E-E-A-T. AI engines surface authored content.",
+ "howToFix": "Add 'By [Name]' at the top. Link to a real author bio page. Use Person schema.",
+ "source": "Google SGE + E-E-A-T docs",
+ "impactTier": "medium"
+ },
+ {
+ "key": "date-markup",
+ "category": "authority",
+ "label": "Date markup",
+ "what": "datePublished + dateModified in JSON-LD or <time datetime>.",
+ "why": "Engines penalize undated content as potentially stale. Dated content gets freshness scoring.",
+ "howToFix": "Add JSON-LD datePublished + dateModified, or a visible <time datetime> tag.",
+ "source": "Google SGE evaluation guide",
+ "impactTier": "standard"
+ },
+ {
+ "key": "freshness",
+ "category": "authority",
+ "label": "Freshness",
+ "what": "Date modified within the last 365 days.",
+ "why": "Stale content gets downranked for time-sensitive queries. Re-publishing dates resets the clock.",
+ "howToFix": "Refresh top pages at least annually. Bump dateModified when you do.",
+ "source": "Google freshness algorithm docs",
+ "impactTier": "standard"
+ },
+ {
+ "key": "technical-terms",
+ "category": "authority",
+ "label": "Technical term density",
+ "what": "Domain-specific terminology indicating real expertise vs surface-level writing.",
+ "why": "Pages that use precise technical vocabulary signal genuine expertise.",
+ "howToFix": "Use the field's actual technical language. Glossary-link or define the first occurrence.",
+ "source": "GEO paper §4.3",
+ "impactTier": "standard"
+ },
+ {
+ "key": "direct-answer",
+ "category": "content",
+ "label": "Direct answer to query",
+ "what": "Whether the buyer query appears answered in the first 200 chars.",
+ "why": "AI engines preferentially extract direct answers. Burying the answer = no citation.",
+ "howToFix": "Lead the page with a 1–2 sentence direct answer to the primary query. Then expand.",
+ "source": "GEO paper §3.2",
+ "impactTier": "high"
+ },
+ {
+ "key": "bluf-answer",
+ "category": "content",
+ "label": "BLUF (Bottom Line Up Front)",
+ "what": "A clear thesis statement in the first paragraph stating the page's main claim.",
+ "why": "Military-doctrine writing style — BLUF dramatically improves AI extractability.",
+ "howToFix": "Open with 'The answer is X. Here's why.' Don't bury the lede.",
+ "source": "U.S. military writing doctrine + adopted by Anthropic prompt eng team",
+ "impactTier": "medium"
+ },
+ {
+ "key": "query-coverage",
+ "category": "content",
+ "label": "Query token coverage",
+ "what": "Fraction of query tokens that appear in the page body (target ≥80%).",
+ "why": "Coverage is a baseline relevance signal — missing tokens means the page misses the query.",
+ "howToFix": "Make sure every meaningful query token appears at least once in body content.",
+ "source": "BM25 + cosine retrieval fundamentals",
+ "impactTier": "medium"
+ },
+ {
+ "key": "entity-coverage",
+ "category": "content",
+ "label": "Entity coverage",
+ "what": "Named entities mentioned that match the query's entity space.",
+ "why": "AI engines build an entity graph per page — missing related entities reduces topical authority.",
+ "howToFix": "If the page is about X, mention X's known related entities (people, places, products).",
+ "source": "Knowledge graph extraction literature",
+ "impactTier": "medium"
+ },
+ {
+ "key": "readability",
+ "category": "content",
+ "label": "Readability (Flesch)",
+ "what": "Flesch Reading Ease score (target 50–70 for general audiences).",
+ "why": "Engines extract from content humans can read. Sub-30 (academic) and 80+ (childlike) both underperform.",
+ "howToFix": "Shorten sentences. Cut adverbs. Aim for 16-word average sentence length.",
+ "source": "Flesch (1948) + adapted by SGE",
+ "impactTier": "standard"
+ },
+ {
+ "key": "length",
+ "category": "content",
+ "label": "Page length",
+ "what": "Word count in the main content (target 800–3000).",
+ "why": "Too short = thin; too long = engines truncate. Sweet spot is medium-long form.",
+ "howToFix": "If under 600 words, expand with examples + sub-sections. If over 4000, split into hub + spokes.",
+ "source": "Empirical GEO paper data",
+ "impactTier": "standard"
+ },
+ {
+ "key": "info-density",
+ "category": "content",
+ "label": "Information density",
+ "what": "Ratio of substantive content to filler.",
+ "why": "Dense content gets preferentially cited. Engines model 'value per token' implicitly.",
+ "howToFix": "Cut throat-clearing sentences. Replace 'It is important to note that' with the actual point.",
+ "source": "Empirical GEO paper data",
+ "impactTier": "standard"
+ },
+ {
+ "key": "mega-page-coverage",
+ "category": "content",
+ "label": "Mega-page coverage",
+ "what": "Whether the page covers multiple closely-related sub-topics under one URL.",
+ "why": "Mega-pages outrank thin pages on AI engines because they cover entity neighborhoods.",
+ "howToFix": "Consolidate 3 thin pages into one comprehensive page with H2-segmented sub-topics.",
+ "source": "Ahrefs research + Cleartopic.io",
+ "impactTier": "medium"
+ },
+ {
+ "key": "youtube-embed",
+ "category": "content",
+ "label": "YouTube embed",
+ "what": "Embedded YouTube video alongside the article.",
+ "why": "Multi-modal engines weight pages with on-topic video. 0.737 correlation with citation rate.",
+ "howToFix": "Create or embed a 2–4 minute video on the page topic. Mark up with VideoObject schema.",
+ "source": "Ahrefs 2025 study",
+ "impactTier": "standard"
+ },
+ {
+ "key": "sub-query-coverage",
+ "category": "content",
+ "label": "Sub-query coverage",
+ "what": "Fraction of decomposed sub-questions answered in body content.",
+ "why": "Engines decompose seed queries into 4–6 sub-queries (Profound 'fanouts') — missing answers = missing citations.",
+ "howToFix": "Add a Q&A section that explicitly addresses the top 5 sub-questions for your topic.",
+ "source": "Profound Query Fanouts methodology",
+ "impactTier": "medium"
+ },
+ {
+ "key": "definitions",
+ "category": "content",
+ "label": "In-line definitions",
+ "what": "First-mention terms defined inline ('X (definition…)').",
+ "why": "Defined-in-place pages get cited as glossary sources. AI engines preferentially link to them.",
+ "howToFix": "Define the key 3–5 terms on first use, in-line.",
+ "source": "Stanford NLP citation extraction work",
+ "impactTier": "standard"
+ },
+ {
+ "key": "ai-bot-access",
+ "category": "trust",
+ "label": "AI bot access (robots.txt)",
+ "what": "Whether robots.txt explicitly addresses GPTBot/ClaudeBot/PerplexityBot.",
+ "why": "Default-allow gets you crawled, but explicit allow signals intent + unlocks niche AI bots.",
+ "howToFix": "Add User-agent: GPTBot/ClaudeBot/OAI-SearchBot/PerplexityBot rules to robots.txt.",
+ "source": "OpenAI / Anthropic / Perplexity bot docs",
+ "impactTier": "medium"
+ },
+ {
+ "key": "llms-txt-presence",
+ "category": "trust",
+ "label": "llms.txt presence",
+ "what": "Whether /llms.txt exists per llmstxt.org spec.",
+ "why": "Explicit channel for telling AI engines exactly which content to ingest. 2026 frontier signal.",
+ "howToFix": "Generate llms.txt via our /audit/llms-txt tool. Add to site root.",
+ "source": "llmstxt.org spec",
+ "impactTier": "medium"
+ },
+ {
+ "key": "https",
+ "category": "trust",
+ "label": "HTTPS",
+ "what": "Site responds correctly over TLS without mixed content.",
+ "why": "AI crawlers refuse to crawl mixed-content pages. HTTPS is table stakes.",
+ "howToFix": "Migrate to HTTPS. Force redirect with HSTS. Fix mixed-content warnings.",
+ "source": "Web standards + Google ranking docs",
+ "impactTier": "standard"
+ },
+ {
+ "key": "canonical",
+ "category": "trust",
+ "label": "Canonical URL",
+ "what": "<link rel=canonical> pointing to the page's preferred URL.",
+ "why": "Without canonical, AI engines may split citations across duplicate URLs and downrank each.",
+ "howToFix": "Add <link rel=canonical href=…> to every page. Self-canonical on canonical pages.",
+ "source": "Google canonical docs",
+ "impactTier": "standard"
+ },
+ {
+ "key": "viewport",
+ "category": "trust",
+ "label": "Viewport meta",
+ "what": "<meta name=viewport content=…> present.",
+ "why": "Mobile rendering signal — AI crawlers favor mobile-first content.",
+ "howToFix": "Add <meta name=viewport content=\"width=device-width, initial-scale=1\">.",
+ "source": "Google mobile-first indexing docs",
+ "impactTier": "standard"
+ },
+ {
+ "key": "twitter-card",
+ "category": "trust",
+ "label": "Twitter card",
+ "what": "<meta name=twitter:card> + twitter:image present.",
+ "why": "AI engines fall back to Twitter card on platforms without OG support.",
+ "howToFix": "Add twitter:card=summary_large_image + twitter:image (can reuse og:image).",
+ "source": "X (Twitter) card docs",
+ "impactTier": "standard"
+ },
+ {
+ "key": "meta-description",
+ "category": "trust",
+ "label": "Meta description",
+ "what": "<meta name=description> with 80–160 chars of summary text.",
+ "why": "AI engines use meta description as a primary summary candidate when generating cites.",
+ "howToFix": "Write a 130-char meta description for every page. Include the primary query.",
+ "source": "Google docs + SGE evaluation guide",
+ "impactTier": "standard"
+ },
+ {
+ "key": "first-person",
+ "category": "eeat",
+ "label": "First-person evidence",
+ "what": "First-person language indicating real experience ('we tested', 'I built').",
+ "why": "Google's E-E-A-T update prioritizes lived experience. First-person signals it.",
+ "howToFix": "Use first-person sparingly but precisely — 'we tested', 'in our experience', 'I found that…'.",
+ "source": "Google E-E-A-T quality rater guidelines",
+ "impactTier": "medium"
+ },
+ {
+ "key": "case-study-evidence",
+ "category": "eeat",
+ "label": "Case study evidence",
+ "what": "Named customer outcomes, numbers, or before/after evidence in-line.",
+ "why": "Case studies are the highest-conversion E-E-A-T signal — prove it, don't just claim it.",
+ "howToFix": "Name one customer. Quote one outcome with numbers. 'We helped X go from Y → Z.'",
+ "source": "Google E-E-A-T guidelines",
+ "impactTier": "medium"
+ },
+ {
+ "key": "author-credentials",
+ "category": "eeat",
+ "label": "Author credentials",
+ "what": "Author has visible credentials — years of experience, prior role, education, certifications.",
+ "why": "Anonymous bylines fail E-E-A-T. Credentialed authors get treated as expert sources.",
+ "howToFix": "Each author page lists credentials, prior roles, years in field, links to LinkedIn/Twitter.",
+ "source": "Google E-E-A-T guidelines (Quality Rater Guidelines §3.2)",
+ "impactTier": "medium"
+ },
+ {
+ "key": "byline-depth",
+ "category": "eeat",
+ "label": "Byline depth",
+ "what": "Byline links to a real author bio page with sufficient detail.",
+ "why": "Byline → bio page → credentialed author chain is the E-E-A-T graph engines trace.",
+ "howToFix": "Make every byline link to /authors/[name] with bio, photo, credentials, prior work.",
+ "source": "Google E-E-A-T guidelines",
+ "impactTier": "standard"
+ },
+ {
+ "key": "brand-entity",
+ "category": "eeat",
+ "label": "Brand entity in Wikidata",
+ "what": "Brand has a Wikidata entity (Q-number) that AI engines can dereference.",
+ "why": "Wikidata is the canonical entity database — engines use it to validate brand identity. No entity = no trust anchor.",
+ "howToFix": "Get a Wikidata entry: requires 2–3 press mentions as citations. Submit at wikidata.org.",
+ "source": "Wikidata + knowledge graph literature",
+ "impactTier": "medium"
+ },
+ {
+ "key": "press-mentions",
+ "category": "eeat",
+ "label": "Press mentions",
+ "what": "References to or links from top-tier press (NYT, WaPo, Bloomberg, FT, etc.).",
+ "why": "Press mentions transfer authority across the citation graph and validate brand entity claims.",
+ "howToFix": "Earn press. Display logos. Link back to the original article (not your case study).",
+ "source": "Empirical brand-citation research",
+ "impactTier": "standard"
+ },
+ {
+ "key": "privacy-terms",
+ "category": "eeat",
+ "label": "Privacy + terms",
+ "what": "Linked privacy policy + terms of service from every page.",
+ "why": "YMYL (Your-Money-Your-Life) categories require these — and engines treat them as legitimacy signals everywhere.",
+ "howToFix": "Footer-link privacy and terms on every page. Real pages, not coming-soon stubs.",
+ "source": "Google YMYL + E-E-A-T guidelines",
+ "impactTier": "standard"
+ },
+ {
+ "key": "contact-info",
+ "category": "eeat",
+ "label": "Contact info",
+ "what": "Real contact info — email, phone, or address visible on the page or linked /contact.",
+ "why": "Anonymous brands fail E-E-A-T. Real contact info signals real entity behind the content.",
+ "howToFix": "Add an email + physical address (real or registered office) to the footer.",
+ "source": "Google E-E-A-T guidelines",
+ "impactTier": "standard"
+ }
+ ]
+}
diff --git a/server/src/lib/audit/scorer.js b/server/src/lib/audit/scorer.js
new file mode 100644
index 000000000..afb887c57
--- /dev/null
+++ b/server/src/lib/audit/scorer.js
@@ -0,0 +1,52 @@
+/**
+ * Aggregate per-signal verdicts into category scores and a single total,
+ * using the rubric's category weights.
+ *
+ * Partial-coverage rule: a category's score is the mean of its *evaluated*
+ * signals only (status !== 'na'); unimplemented signals don't drag it down.
+ * The total re-normalizes over the weight of categories that had at least one
+ * evaluated signal, so the headline number stays a true 0..1 even mid-rollout.
+ * Each result also reports `evaluated / total` so the UI can show coverage.
+ */
+
+import { categories, signalsByKey } from './rubric.js';
+
+/**
+ * @param {Array<{ key: string, status: string, score: number|null }>} results
+ * @returns {{ totalScore: number|null, categoryScores: Record<string, { score: number|null, evaluated: number, total: number }> }}
+ */
+export function scoreAudit(results) {
+ const byKey = new Map(results.map((r) => [r.key, r]));
+ const categoryScores = {};
+
+ let weightSum = 0;
+ let weightedSum = 0;
+
+ for (const cat of categories) {
+ const catSignalKeys = Object.values(signalsByKey)
+ .filter((s) => s.category === cat.key)
+ .map((s) => s.key);
+
+ const evaluated = catSignalKeys
+ .map((k) => byKey.get(k))
+ .filter((r) => r && r.status !== 'na' && typeof r.score === 'number');
+
+ if (evaluated.length === 0) {
+ categoryScores[cat.key] = { score: null, evaluated: 0, total: catSignalKeys.length };
+ continue;
+ }
+
+ const score = evaluated.reduce((acc, r) => acc + r.score, 0) / evaluated.length;
+ categoryScores[cat.key] = {
+ score,
+ evaluated: evaluated.length,
+ total: catSignalKeys.length,
+ };
+
+ weightSum += cat.weight;
+ weightedSum += cat.weight * score;
+ }
+
+ const totalScore = weightSum > 0 ? weightedSum / weightSum : null;
+ return { totalScore, categoryScores };
+}
diff --git a/server/src/lib/audit/signals/authority.js b/server/src/lib/audit/signals/authority.js
new file mode 100644
index 000000000..713162d25
--- /dev/null
+++ b/server/src/lib/audit/signals/authority.js
@@ -0,0 +1,207 @@
+/**
+ * Authority-category signal evaluators (8 signals; technical-terms is deferred
+ * to a later LLM phase). See structure.js for the evaluator shape.
+ */
+
+import { jsonLd, classifyLinks, metaContent } from './helpers.js';
+
+// Hosts / suffixes that count as authoritative outbound targets.
+const AUTHORITY_PATTERNS = [
+ /(^|\.)edu$/,
+ /(^|\.)gov$/,
+ /(^|\.)wikipedia\.org$/,
+ /(^|\.)who\.int$/,
+ /(^|\.)nih\.gov$/,
+ /ncbi\.nlm\.nih\.gov$/,
+ /(^|\.)nature\.com$/,
+ /sciencedirect\.com$/,
+ /(^|\.)doi\.org$/,
+ /arxiv\.org$/,
+ /(^|\.)nytimes\.com$/,
+ /(^|\.)washingtonpost\.com$/,
+ /(^|\.)bloomberg\.com$/,
+ /(^|\.)reuters\.com$/,
+ /(^|\.)ft\.com$/,
+ /(^|\.)bbc\.(com|co\.uk)$/,
+];
+
+function isAuthorityHost(host) {
+ return AUTHORITY_PATTERNS.some((re) => re.test(host));
+}
+
+/** Collect candidate dates (ms) from JSON-LD, <time datetime>, and OG meta. */
+function collectDates(ctx) {
+ const out = [];
+ const push = (v) => {
+ if (!v || typeof v !== 'string') return;
+ const t = Date.parse(v);
+ if (!Number.isNaN(t)) out.push(t);
+ };
+
+ const { nodes } = jsonLd(ctx);
+ for (const n of nodes) {
+ push(n.datePublished);
+ push(n.dateModified);
+ }
+ ctx.$('time[datetime]').each((_, el) => push(ctx.$(el).attr('datetime')));
+ push(metaContent(ctx, 'article:published_time'));
+ push(metaContent(ctx, 'article:modified_time'));
+
+ return out;
+}
+
+export const outboundAuthorityLinks = {
+ key: 'outbound-authority-links',
+ evaluate(ctx) {
+ const { external } = classifyLinks(ctx);
+ const authority = [
+ ...new Set(external.filter((u) => isAuthorityHost(u.host)).map((u) => u.host)),
+ ];
+ const count = authority.length;
+ let status = 'fail';
+ let score = 0;
+ if (count >= 2) {
+ status = 'pass';
+ score = 1;
+ } else if (count === 1) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { authorityHosts: authority.slice(0, 8), count } };
+ },
+};
+
+export const citationDensity = {
+ key: 'citation-density',
+ evaluate(ctx) {
+ const { external } = classifyLinks(ctx);
+ const per1000 = ctx.wordCount > 0 ? (external.length / ctx.wordCount) * 1000 : 0;
+ let status = 'fail';
+ let score = 0;
+ if (per1000 >= 2) {
+ status = 'pass';
+ score = 1;
+ } else if (per1000 >= 1) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return {
+ status,
+ score,
+ evidence: {
+ outboundLinks: external.length,
+ words: ctx.wordCount,
+ per1000Words: Number(per1000.toFixed(1)),
+ },
+ };
+ },
+};
+
+export const statisticDensity = {
+ key: 'statistic-density',
+ evaluate(ctx) {
+ // Quantitative tokens: percentages, currency, or standalone numbers.
+ const matches =
+ ctx.text.match(/(\$|€|£|₺|%)?\s?\d[\d.,]*\s?(%|percent|million|billion|k\b)?/gi) || [];
+ const numeric = matches.filter((m) => /\d/.test(m)).length;
+ const per1000 = ctx.wordCount > 0 ? (numeric / ctx.wordCount) * 1000 : 0;
+ let status = 'fail';
+ let score = 0;
+ if (per1000 >= 3) {
+ status = 'pass';
+ score = 1;
+ } else if (per1000 >= 1.5) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return {
+ status,
+ score,
+ evidence: { numericClaims: numeric, per1000Words: Number(per1000.toFixed(1)) },
+ };
+ },
+};
+
+export const quotations = {
+ key: 'quotations',
+ evaluate(ctx) {
+ const count = ctx.$('blockquote, q').length;
+ return {
+ status: count >= 1 ? 'pass' : 'fail',
+ score: count >= 1 ? 1 : 0,
+ evidence: { quotations: count },
+ };
+ },
+};
+
+export const authorByline = {
+ key: 'author-byline',
+ evaluate(ctx) {
+ const { nodes } = jsonLd(ctx);
+ const schemaAuthor = nodes.some((n) => {
+ const a = n.author;
+ if (!a) return false;
+ const list = Array.isArray(a) ? a : [a];
+ return list.some((x) => (typeof x === 'string' ? x.trim() : x?.name));
+ });
+ const metaAuthor = Boolean(metaContent(ctx, 'author'));
+ const relAuthor = ctx.$('a[rel="author"], [class*="byline" i], [class*="author" i]').length > 0;
+ const textByline = /\bby\s+[A-Z][a-z]+(?:\s+[A-Z][a-z]+)?/.test(ctx.text.slice(0, 2000));
+
+ const found = schemaAuthor || metaAuthor || relAuthor || textByline;
+ return {
+ status: found ? 'pass' : 'fail',
+ score: found ? 1 : 0,
+ evidence: { schemaAuthor, metaAuthor, relAuthor, textByline },
+ };
+ },
+};
+
+export const dateMarkup = {
+ key: 'date-markup',
+ evaluate(ctx) {
+ const dates = collectDates(ctx);
+ const found = dates.length > 0;
+ return {
+ status: found ? 'pass' : 'fail',
+ score: found ? 1 : 0,
+ evidence: { dateSignals: dates.length },
+ };
+ },
+};
+
+export const freshness = {
+ key: 'freshness',
+ evaluate(ctx) {
+ const dates = collectDates(ctx);
+ if (dates.length === 0) {
+ return { status: 'fail', score: 0, evidence: { reason: 'no date markup' } };
+ }
+ const newest = Math.max(...dates);
+ const ageDays = Math.floor((ctx.now - newest) / (1000 * 60 * 60 * 24));
+ let status = 'fail';
+ let score = 0;
+ if (ageDays <= 365) {
+ status = 'pass';
+ score = 1;
+ } else if (ageDays <= 730) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return {
+ status,
+ score,
+ evidence: { ageDays, newest: new Date(newest).toISOString().slice(0, 10) },
+ };
+ },
+};
+
+export const authoritySignals = [
+ outboundAuthorityLinks,
+ citationDensity,
+ statisticDensity,
+ quotations,
+ authorByline,
+ dateMarkup,
+ freshness,
+];
diff --git a/server/src/lib/audit/signals/content.js b/server/src/lib/audit/signals/content.js
new file mode 100644
index 000000000..41ff71f3b
--- /dev/null
+++ b/server/src/lib/audit/signals/content.js
@@ -0,0 +1,66 @@
+/**
+ * Content-category signal evaluators — Faz 1 ships the 3 deterministic ones
+ * (readability, length, youtube-embed). The query-dependent / LLM-judged
+ * signals (direct-answer, BLUF, query / sub-query / entity coverage,
+ * info-density, mega-page, definitions) land in a later phase that feeds the
+ * brand's tracked prompts in as the target query.
+ *
+ * See structure.js for the evaluator shape.
+ */
+
+import { fleschReadingEase } from './helpers.js';
+
+export const readability = {
+ key: 'readability',
+ evaluate(ctx) {
+ const flesch = fleschReadingEase(ctx.text);
+ if (flesch === null) {
+ return { status: 'na', score: null, evidence: { reason: 'not enough text' } };
+ }
+ const rounded = Math.round(flesch);
+ let status = 'fail';
+ let score = 0;
+ if (flesch >= 50 && flesch <= 70) {
+ status = 'pass';
+ score = 1;
+ } else if ((flesch >= 30 && flesch < 50) || (flesch > 70 && flesch <= 80)) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { fleschReadingEase: rounded } };
+ },
+};
+
+export const length = {
+ key: 'length',
+ evaluate(ctx) {
+ const words = ctx.wordCount;
+ let status = 'fail';
+ let score = 0;
+ if (words >= 800 && words <= 3000) {
+ status = 'pass';
+ score = 1;
+ } else if ((words >= 400 && words < 800) || (words > 3000 && words <= 5000)) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { words } };
+ },
+};
+
+export const youtubeEmbed = {
+ key: 'youtube-embed',
+ evaluate(ctx) {
+ const hasEmbed =
+ ctx.$(
+ 'iframe[src*="youtube.com"], iframe[src*="youtube-nocookie.com"], iframe[src*="youtu.be"]',
+ ).length > 0;
+ return {
+ status: hasEmbed ? 'pass' : 'fail',
+ score: hasEmbed ? 1 : 0,
+ evidence: { youtubeEmbed: hasEmbed },
+ };
+ },
+};
+
+export const contentSignals = [readability, length, youtubeEmbed];
diff --git a/server/src/lib/audit/signals/eeat.js b/server/src/lib/audit/signals/eeat.js
new file mode 100644
index 000000000..8882ca45c
--- /dev/null
+++ b/server/src/lib/audit/signals/eeat.js
@@ -0,0 +1,93 @@
+/**
+ * E-E-A-T-category signal evaluators — Faz 1 ships the 3 deterministic ones
+ * (first-person, privacy-terms, contact-info). The LLM / external-data signals
+ * (case-study-evidence, author-credentials, byline-depth, brand-entity via
+ * Wikidata, press-mentions) land in later phases.
+ *
+ * See structure.js for the evaluator shape.
+ */
+
+import { countPhrases } from './helpers.js';
+
+const FIRST_PERSON_PHRASES = [
+ 'we tested',
+ 'we built',
+ 'we found',
+ 'we measured',
+ 'we analyzed',
+ 'we analysed',
+ 'in our experience',
+ 'in our testing',
+ 'our team',
+ 'i tested',
+ 'i built',
+ 'i found',
+ 'we ran',
+ 'we compared',
+ 'when we',
+];
+
+export const firstPerson = {
+ key: 'first-person',
+ evaluate(ctx) {
+ const hits = countPhrases(ctx.text, FIRST_PERSON_PHRASES);
+ let status = 'fail';
+ let score = 0;
+ if (hits >= 2) {
+ status = 'pass';
+ score = 1;
+ } else if (hits === 1) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { evidencePhrases: hits } };
+ },
+};
+
+export const privacyTerms = {
+ key: 'privacy-terms',
+ evaluate(ctx) {
+ let privacy = false;
+ let terms = false;
+ ctx.$('a[href]').each((_, el) => {
+ const href = (ctx.$(el).attr('href') || '').toLowerCase();
+ const text = ctx.$(el).text().toLowerCase();
+ const blob = `${href} ${text}`;
+ if (/privacy/.test(blob)) privacy = true;
+ if (/terms|tos\b|conditions/.test(blob)) terms = true;
+ });
+ let status = 'fail';
+ let score = 0;
+ if (privacy && terms) {
+ status = 'pass';
+ score = 1;
+ } else if (privacy || terms) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { privacy, terms } };
+ },
+};
+
+export const contactInfo = {
+ key: 'contact-info',
+ evaluate(ctx) {
+ const hasMailto = ctx.$('a[href^="mailto:"]').length > 0;
+ const hasTel = ctx.$('a[href^="tel:"]').length > 0;
+ let contactLink = false;
+ ctx.$('a[href]').each((_, el) => {
+ const blob = `${(ctx.$(el).attr('href') || '').toLowerCase()} ${ctx.$(el).text().toLowerCase()}`;
+ if (/contact|iletişim|kontakt/.test(blob)) contactLink = true;
+ });
+ const emailInText = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/i.test(ctx.text);
+
+ const found = hasMailto || hasTel || contactLink || emailInText;
+ return {
+ status: found ? 'pass' : 'fail',
+ score: found ? 1 : 0,
+ evidence: { mailto: hasMailto, tel: hasTel, contactLink, emailInText },
+ };
+ },
+};
+
+export const eeatSignals = [firstPerson, privacyTerms, contactInfo];
diff --git a/server/src/lib/audit/signals/helpers.js b/server/src/lib/audit/signals/helpers.js
new file mode 100644
index 000000000..e2ebaf9a6
--- /dev/null
+++ b/server/src/lib/audit/signals/helpers.js
@@ -0,0 +1,130 @@
+/**
+ * Shared helpers for signal evaluators — JSON-LD extraction, link analysis,
+ * and readability math. Kept dependency-free (cheerio + plain JS) so signals
+ * stay fast and deterministic.
+ */
+
+/**
+ * Parse every <script type="application/ld+json"> block and flatten @graph /
+ * arrays into a single list of typed nodes. Returns `{ nodes, total, valid }`.
+ */
+export function jsonLd(ctx) {
+ const nodes = [];
+ let total = 0;
+ let valid = 0;
+
+ ctx.$('script[type="application/ld+json"]').each((_, el) => {
+ total += 1;
+ const raw = ctx.$(el).text();
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return;
+ }
+ valid += 1;
+ const items = Array.isArray(parsed) ? parsed : [parsed];
+ for (const item of items) {
+ if (!item || typeof item !== 'object') continue;
+ if (Array.isArray(item['@graph'])) {
+ for (const n of item['@graph']) {
+ if (n && typeof n === 'object') nodes.push(n);
+ }
+ } else {
+ nodes.push(item);
+ }
+ }
+ });
+
+ return { nodes, total, valid };
+}
+
+/** Normalize a node's @type into a lowercase string array. */
+export function typesOf(node) {
+ const t = node?.['@type'];
+ if (!t) return [];
+ return (Array.isArray(t) ? t : [t])
+ .filter((x) => typeof x === 'string')
+ .map((x) => x.toLowerCase());
+}
+
+/** Split the page's anchors into internal vs external absolute URLs. */
+export function classifyLinks(ctx) {
+ const host = (() => {
+ try {
+ return new URL(ctx.url).host;
+ } catch {
+ return '';
+ }
+ })();
+
+ const internal = [];
+ const external = [];
+
+ ctx.$('a[href]').each((_, el) => {
+ const href = (ctx.$(el).attr('href') || '').trim();
+ if (
+ !href ||
+ href.startsWith('#') ||
+ href.startsWith('mailto:') ||
+ href.startsWith('tel:') ||
+ href.startsWith('javascript:')
+ ) {
+ return;
+ }
+ try {
+ const u = new URL(href, ctx.url);
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return;
+ if (u.host === host) internal.push(u);
+ else external.push(u);
+ } catch {
+ /* ignore malformed hrefs */
+ }
+ });
+
+ return { internal, external };
+}
+
+/** Lowercased content of a <meta> by name or property attribute. */
+export function metaContent(ctx, key) {
+ const el = ctx.$(`meta[name="${key}"], meta[property="${key}"]`).first();
+ const v = el.attr('content');
+ return typeof v === 'string' ? v.trim() : null;
+}
+
+// --- Readability (Flesch Reading Ease) ---
+
+function countSyllables(word) {
+ const w = word.toLowerCase().replace(/[^a-z]/g, '');
+ if (!w) return 0;
+ if (w.length <= 3) return 1;
+ const stripped = w.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '').replace(/^y/, '');
+ const groups = stripped.match(/[aeiouy]{1,2}/g);
+ return groups ? groups.length : 1;
+}
+
+/**
+ * Flesch Reading Ease for an English-ish body of text. Returns null when there
+ * isn't enough text to score.
+ */
+export function fleschReadingEase(text) {
+ const words = text.split(/\s+/).filter(Boolean);
+ if (words.length < 30) return null;
+ const sentences = (text.match(/[.!?]+(?:\s|$)/g) || []).length || 1;
+ const syllables = words.reduce((acc, w) => acc + countSyllables(w), 0);
+ return 206.835 - 1.015 * (words.length / sentences) - 84.6 * (syllables / words.length);
+}
+
+/** Count occurrences of a list of phrases (case-insensitive) in text. */
+export function countPhrases(text, phrases) {
+ const lower = text.toLowerCase();
+ let count = 0;
+ for (const p of phrases) {
+ let idx = lower.indexOf(p);
+ while (idx !== -1) {
+ count += 1;
+ idx = lower.indexOf(p, idx + p.length);
+ }
+ }
+ return count;
+}
diff --git a/server/src/lib/audit/signals/index.js b/server/src/lib/audit/signals/index.js
new file mode 100644
index 000000000..7e75e3133
--- /dev/null
+++ b/server/src/lib/audit/signals/index.js
@@ -0,0 +1,24 @@
+/**
+ * Registry of implemented signal evaluators. Each category file exports its
+ * own array; new signals are added there and surface here automatically.
+ *
+ * Faz 1 implements the 33 deterministic signals (Structure 13, Trust 7,
+ * Authority 7, Content 3, E-E-A-T 3) of the 47-signal rubric. The remaining 14
+ * need a target query, an LLM judge, or an external lookup (Wikidata / press)
+ * and land in later phases. The scorer reports coverage (evaluated / total) so
+ * partial implementation never penalizes a page for signals we haven't built.
+ */
+
+import { structureSignals } from './structure.js';
+import { authoritySignals } from './authority.js';
+import { contentSignals } from './content.js';
+import { trustSignals } from './trust.js';
+import { eeatSignals } from './eeat.js';
+
+export const signalRegistry = [
+ ...structureSignals,
+ ...authoritySignals,
+ ...contentSignals,
+ ...trustSignals,
+ ...eeatSignals,
+];
diff --git a/server/src/lib/audit/signals/structure.js b/server/src/lib/audit/signals/structure.js
new file mode 100644
index 000000000..557a25758
--- /dev/null
+++ b/server/src/lib/audit/signals/structure.js
@@ -0,0 +1,316 @@
+/**
+ * Structure-category signal evaluators (13 signals).
+ *
+ * Each evaluator is `{ key, evaluate(ctx) => { status, score, evidence } }`:
+ * - status: 'pass' | 'warn' | 'fail' | 'na'
+ * - score: 0..1 (null when 'na')
+ * - evidence: small object surfaced in the UI to explain the verdict
+ *
+ * Rubric copy (label/what/why/howToFix) is merged in from rubric.js at
+ * response-assembly time, so evaluators stay purely about measurement.
+ */
+
+import { jsonLd, typesOf, classifyLinks, metaContent } from './helpers.js';
+
+// schema.org types that signal a specific, AI-citable content intent.
+const HIGH_VALUE_TYPES = new Set([
+ 'article',
+ 'newsarticle',
+ 'blogposting',
+ 'product',
+ 'faqpage',
+ 'howto',
+ 'recipe',
+ 'review',
+ 'qapage',
+ 'techarticle',
+ 'medicalwebpage',
+ 'event',
+ 'softwareapplication',
+]);
+
+export const structuralDepth = {
+ key: 'structural-depth',
+ evaluate(ctx) {
+ const levels = ctx.$('h1, h2, h3, h4, h5, h6');
+ const present = new Set();
+ let skips = 0;
+ let prev = 0;
+ levels.each((_, el) => {
+ const lvl = Number(el.tagName.replace(/[^1-6]/g, ''));
+ present.add(lvl);
+ if (prev && lvl > prev + 1) skips += 1;
+ prev = lvl;
+ });
+ const depth = present.size;
+ const hasNesting = present.has(1) && present.has(2) && present.has(3);
+
+ let status = 'fail';
+ let score = 0.2;
+ if (hasNesting && skips === 0) {
+ status = 'pass';
+ score = 1;
+ } else if (depth >= 2) {
+ status = 'warn';
+ score = 0.6;
+ }
+ return { status, score, evidence: { depth, levelSkips: skips, levels: [...present].sort() } };
+ },
+};
+
+export const internalLinking = {
+ key: 'internal-linking',
+ evaluate(ctx) {
+ const { internal } = classifyLinks(ctx);
+ const count = internal.length;
+ let status = 'fail';
+ let score = 0;
+ if (count >= 5) {
+ status = 'pass';
+ score = 1;
+ } else if (count >= 1) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { internalLinks: count } };
+ },
+};
+
+export const pageWeight = {
+ key: 'page-weight',
+ evaluate(ctx) {
+ const kb = Math.round(ctx.htmlBytes / 1024);
+ let status = 'pass';
+ let score = 1;
+ if (kb > 1024) {
+ status = 'fail';
+ score = 0;
+ } else if (kb > 500) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { htmlKb: kb } };
+ },
+};
+
+export const jsonLdPresence = {
+ key: 'json-ld-presence',
+ evaluate(ctx) {
+ const { total } = jsonLd(ctx);
+ return {
+ status: total > 0 ? 'pass' : 'fail',
+ score: total > 0 ? 1 : 0,
+ evidence: { blockCount: total },
+ };
+ },
+};
+
+export const jsonLdValidity = {
+ key: 'json-ld-validity',
+ evaluate(ctx) {
+ const { nodes, total, valid } = jsonLd(ctx);
+ if (total === 0) {
+ return { status: 'fail', score: 0, evidence: { reason: 'no JSON-LD blocks' } };
+ }
+ // Among parsed nodes, how many declare a schema.org @context + a @type?
+ const wellFormed = nodes.filter((n) => {
+ const ctxStr = JSON.stringify(n['@context'] ?? '').toLowerCase();
+ return ctxStr.includes('schema.org') && typesOf(n).length > 0;
+ }).length;
+
+ let status = 'fail';
+ let score = 0;
+ if (valid === total && wellFormed > 0) {
+ status = 'pass';
+ score = 1;
+ } else if (valid > 0 && wellFormed > 0) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return {
+ status,
+ score,
+ evidence: { blocks: total, parsed: valid, wellFormedNodes: wellFormed },
+ };
+ },
+};
+
+export const jsonLdRelevance = {
+ key: 'json-ld-relevance',
+ evaluate(ctx) {
+ const { nodes } = jsonLd(ctx);
+ const allTypes = nodes.flatMap(typesOf);
+ if (allTypes.length === 0) {
+ return { status: 'fail', score: 0, evidence: { types: [] } };
+ }
+ const hasHighValue = allTypes.some((t) => HIGH_VALUE_TYPES.has(t));
+ return {
+ status: hasHighValue ? 'pass' : 'warn',
+ score: hasHighValue ? 1 : 0.5,
+ evidence: { types: [...new Set(allTypes)].slice(0, 8) },
+ };
+ },
+};
+
+export const faqSchema = {
+ key: 'faq-schema',
+ evaluate(ctx) {
+ const { nodes } = jsonLd(ctx);
+ const faq = nodes.find((n) => typesOf(n).includes('faqpage'));
+ const qa = faq && Array.isArray(faq.mainEntity) ? faq.mainEntity.length : 0;
+ const ok = Boolean(faq) && qa >= 2;
+ return {
+ status: ok ? 'pass' : 'fail',
+ score: ok ? 1 : 0,
+ evidence: { faqPage: Boolean(faq), questionCount: qa },
+ };
+ },
+};
+
+export const h1Quality = {
+ key: 'h1-quality',
+ evaluate(ctx) {
+ const h1s = ctx.$('h1');
+ const count = h1s.length;
+ const text = h1s.first().text().replace(/\s+/g, ' ').trim();
+ const length = text.length;
+ const exactlyOne = count === 1;
+ const idealLength = length >= 20 && length <= 70;
+
+ let status = 'fail';
+ let score = 0;
+ if (exactlyOne && idealLength) {
+ status = 'pass';
+ score = 1;
+ } else if (count >= 1 && length >= 10 && length <= 90) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { count, length, text: text.slice(0, 120) } };
+ },
+};
+
+export const h2Coverage = {
+ key: 'h2-coverage',
+ evaluate(ctx) {
+ const count = ctx.$('h2').length;
+ let status = 'fail';
+ let score = 0;
+ if (count >= 3) {
+ status = 'pass';
+ score = 1;
+ } else if (count >= 1) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { h2Count: count } };
+ },
+};
+
+export const lists = {
+ key: 'lists',
+ evaluate(ctx) {
+ let withThree = 0;
+ let any = 0;
+ ctx.$('ul, ol').each((_, el) => {
+ any += 1;
+ if (ctx.$(el).children('li').length >= 3) withThree += 1;
+ });
+ let status = 'fail';
+ let score = 0;
+ if (withThree >= 1) {
+ status = 'pass';
+ score = 1;
+ } else if (any >= 1) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { lists: any, listsWith3PlusItems: withThree } };
+ },
+};
+
+export const tables = {
+ key: 'tables',
+ evaluate(ctx) {
+ const total = ctx.$('table').length;
+ const structured = ctx.$('table').filter((_, el) => {
+ const $t = ctx.$(el);
+ return $t.find('thead').length > 0 && $t.find('tbody').length > 0;
+ }).length;
+ let status = 'fail';
+ let score = 0;
+ if (structured >= 1) {
+ status = 'pass';
+ score = 1;
+ } else if (total >= 1) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { tables: total, structuredTables: structured } };
+ },
+};
+
+export const altText = {
+ key: 'alt-text',
+ evaluate(ctx) {
+ const imgs = ctx.$('img');
+ const total = imgs.length;
+ if (total === 0) {
+ return { status: 'na', score: null, evidence: { images: 0 } };
+ }
+ let withAlt = 0;
+ imgs.each((_, el) => {
+ const alt = ctx.$(el).attr('alt');
+ if (typeof alt === 'string' && alt.trim().length > 0) withAlt += 1;
+ });
+ const ratio = withAlt / total;
+ let status = 'fail';
+ let score = ratio;
+ if (ratio >= 0.8) status = 'pass';
+ else if (ratio >= 0.5) status = 'warn';
+ return {
+ status,
+ score: Number(score.toFixed(2)),
+ evidence: { images: total, withAlt, ratio: Number(ratio.toFixed(2)) },
+ };
+ },
+};
+
+export const openGraph = {
+ key: 'open-graph',
+ evaluate(ctx) {
+ const tags = ['og:title', 'og:description', 'og:image', 'og:type'];
+ const present = tags.filter((t) => metaContent(ctx, t));
+ const n = present.length;
+ let status = 'fail';
+ let score = 0;
+ if (n === 4) {
+ status = 'pass';
+ score = 1;
+ } else if (n >= 1) {
+ status = 'warn';
+ score = n / 4;
+ }
+ return {
+ status,
+ score: Number(score.toFixed(2)),
+ evidence: { present, missing: tags.filter((t) => !present.includes(t)) },
+ };
+ },
+};
+
+export const structureSignals = [
+ structuralDepth,
+ internalLinking,
+ pageWeight,
+ jsonLdPresence,
+ jsonLdValidity,
+ jsonLdRelevance,
+ faqSchema,
+ h1Quality,
+ h2Coverage,
+ lists,
+ tables,
+ altText,
+ openGraph,
+];
diff --git a/server/src/lib/audit/signals/trust.js b/server/src/lib/audit/signals/trust.js
new file mode 100644
index 000000000..3c5c3c572
--- /dev/null
+++ b/server/src/lib/audit/signals/trust.js
@@ -0,0 +1,152 @@
+/**
+ * Trust-category signal evaluators (7 signals). See structure.js for the
+ * evaluator shape.
+ */
+
+import { metaContent } from './helpers.js';
+
+const AI_BOTS = [
+ 'gptbot',
+ 'oai-searchbot',
+ 'chatgpt-user',
+ 'claudebot',
+ 'anthropic-ai',
+ 'perplexitybot',
+ 'google-extended',
+];
+
+export const https = {
+ key: 'https',
+ evaluate(ctx) {
+ const isHttps = ctx.protocol === 'https';
+ let mixedContentRefs = 0;
+ if (isHttps) {
+ ctx.$('script[src], link[href], img[src], iframe[src], source[src]').each((_, el) => {
+ const ref = ctx.$(el).attr('src') || ctx.$(el).attr('href') || '';
+ if (/^http:\/\//i.test(ref)) mixedContentRefs += 1;
+ });
+ }
+ let status = 'fail';
+ let score = 0;
+ if (isHttps && mixedContentRefs === 0) {
+ status = 'pass';
+ score = 1;
+ } else if (isHttps) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { https: isHttps, mixedContentRefs } };
+ },
+};
+
+export const aiBotAccess = {
+ key: 'ai-bot-access',
+ evaluate(ctx) {
+ if (!ctx.robotsTxt) {
+ // No robots.txt → still crawlable by default, but no explicit signal.
+ return { status: 'warn', score: 0.5, evidence: { robotsTxt: false } };
+ }
+ const lower = ctx.robotsTxt.toLowerCase();
+ const mentioned = AI_BOTS.filter((b) => lower.includes(b));
+ // Detect an explicit block: a mentioned AI UA followed by "disallow: /".
+ const blocked = mentioned.some((b) => {
+ const idx = lower.indexOf(b);
+ const after = lower.slice(idx, idx + 200);
+ return /disallow:\s*\/\s*(\n|$)/.test(after);
+ });
+
+ let status = 'warn';
+ let score = 0.5;
+ if (blocked) {
+ status = 'fail';
+ score = 0;
+ } else if (mentioned.length > 0) {
+ status = 'pass';
+ score = 1;
+ }
+ return { status, score, evidence: { aiBotsMentioned: mentioned, blocked } };
+ },
+};
+
+export const llmsTxtPresence = {
+ key: 'llms-txt-presence',
+ evaluate(ctx) {
+ const present = Boolean(ctx.llmsTxt && ctx.llmsTxt.trim().length > 0);
+ return {
+ status: present ? 'pass' : 'fail',
+ score: present ? 1 : 0,
+ evidence: { llmsTxt: present },
+ };
+ },
+};
+
+export const canonical = {
+ key: 'canonical',
+ evaluate(ctx) {
+ const href = ctx.$('link[rel="canonical"]').first().attr('href');
+ const present = Boolean(href && href.trim());
+ return {
+ status: present ? 'pass' : 'fail',
+ score: present ? 1 : 0,
+ evidence: { canonical: href || null },
+ };
+ },
+};
+
+export const viewport = {
+ key: 'viewport',
+ evaluate(ctx) {
+ const present = Boolean(metaContent(ctx, 'viewport'));
+ return {
+ status: present ? 'pass' : 'fail',
+ score: present ? 1 : 0,
+ evidence: { viewport: present },
+ };
+ },
+};
+
+export const twitterCard = {
+ key: 'twitter-card',
+ evaluate(ctx) {
+ const card = metaContent(ctx, 'twitter:card');
+ const image = metaContent(ctx, 'twitter:image');
+ let status = 'fail';
+ let score = 0;
+ if (card && image) {
+ status = 'pass';
+ score = 1;
+ } else if (card) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { card: card || null, hasImage: Boolean(image) } };
+ },
+};
+
+export const metaDescription = {
+ key: 'meta-description',
+ evaluate(ctx) {
+ const desc = metaContent(ctx, 'description');
+ const len = desc ? desc.length : 0;
+ let status = 'fail';
+ let score = 0;
+ if (len >= 80 && len <= 160) {
+ status = 'pass';
+ score = 1;
+ } else if (len > 0) {
+ status = 'warn';
+ score = 0.5;
+ }
+ return { status, score, evidence: { length: len } };
+ },
+};
+
+export const trustSignals = [
+ https,
+ aiBotAccess,
+ llmsTxtPresence,
+ canonical,
+ viewport,
+ twitterCard,
+ metaDescription,
+];
diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.js
index 80e22121f..2525cb384 100644
--- a/server/src/lib/plan-guard.js
+++ b/server/src/lib/plan-guard.js
@@ -236,6 +236,50 @@ export async function getBriefQuotaStatus(orgId) {
return { used, limit: max, remaining: Math.max(0, max - used) };
}
+async function countSiteAuditUsageThisMonth(orgId) {
+ const { count } = await supabaseAdmin
+ .from('site_audit_usage')
+ .select('*', { count: 'exact', head: true })
+ .eq('organization_id', orgId)
+ .gte('used_at', startOfCurrentMonth().toISOString());
+ return count || 0;
+}
+
+/**
+ * Enforce the monthly Site Audit quota for an organization. Counts completed
+ * audits this calendar month against plan.limits.maxSiteAudits (Starter 100,
+ * Growth 500, Enterprise/Self-hosted unlimited). Throws PlanLimitError (429)
+ * when exhausted; returns { plan, remaining } otherwise.
+ */
+export async function enforceSiteAuditQuota(orgId) {
+ const plan = await resolveOrgPlanByOrgId(orgId);
+ const max = plan.limits.maxSiteAudits;
+ if (max === -1) return { plan, remaining: -1 };
+
+ const used = await countSiteAuditUsageThisMonth(orgId);
+ if (used >= max) {
+ throw new PlanLimitError(
+ `Monthly Site Audit limit reached (${used}/${max}) on the ${plan.name} plan. Resets on the 1st of next month — upgrade for more.`,
+ 429,
+ );
+ }
+
+ return { plan, remaining: max - used };
+}
+
+/**
+ * Get current Site Audit quota status without enforcing.
+ * Returns { used, limit, remaining }.
+ */
+export async function getSiteAuditQuotaStatus(orgId) {
+ const plan = await resolveOrgPlanByOrgId(orgId);
+ const max = plan.limits.maxSiteAudits;
+ if (max === -1) return { used: 0, limit: -1, remaining: -1 };
+
+ const used = await countSiteAuditUsageThisMonth(orgId);
+ return { used, limit: max, remaining: Math.max(0, max - used) };
+}
+
/**
* Express middleware that attaches req.plan from the authenticated user.
* Must run after auth middleware (req.user must exist).
diff --git a/server/src/routes/audits.js b/server/src/routes/audits.js
new file mode 100644
index 000000000..845958682
--- /dev/null
+++ b/server/src/routes/audits.js
@@ -0,0 +1,281 @@
+/**
+ * Site Audit routes — implements the AEO/GEO scoring rubric ourselves rather
+ * than calling any third-party API.
+ *
+ * POST /api/audits { url, brandId } → run a single-page audit
+ * GET /api/audits/:id → fetch a stored audit + signals
+ * GET /api/audits?brandId=… → recent audits for a brand
+ *
+ * The audit runs synchronously: one Scrape.do fetch, the deterministic signal
+ * engine, one batched LLM round-trip for the semantic signals, and a Wikidata
+ * lookup — a few seconds total. Crawl / multi-page moves to a job later.
+ */
+
+import { Router } from 'express';
+import supabaseAdmin from '../config/supabase.js';
+import { assertBrandAccess } from '../lib/access.js';
+import { requireFeature, enforceSiteAuditQuota, PlanLimitError } from '../lib/plan-guard.js';
+import { buildAuditContext } from '../lib/audit/context.js';
+import { runSignals } from '../lib/audit/engine.js';
+import { evaluateLlmSignals } from '../lib/audit/llm-signals.js';
+import { evaluateBrandEntity } from '../lib/audit/external-signals.js';
+import { generateRecommendations } from '../lib/audit/recommendations.js';
+import { scoreAudit } from '../lib/audit/scorer.js';
+import { signalsByKey, TOTAL_SIGNALS, RUBRIC_VERSION } from '../lib/audit/rubric.js';
+
+const router = Router();
+
+/**
+ * Merge a stored audit row + its signal results with the rubric copy the UI
+ * needs (label / what / why / howToFix / impactTier).
+ */
+function assembleAudit(audit, signalRows) {
+ const signals = signalRows.map((row) => {
+ const meta = signalsByKey[row.signal_key] ?? {};
+ return {
+ key: row.signal_key,
+ category: row.category ?? meta.category ?? null,
+ status: row.status,
+ score: row.score === null ? null : Number(row.score),
+ evidence: row.evidence ?? {},
+ label: meta.label ?? row.signal_key,
+ what: meta.what ?? null,
+ why: meta.why ?? null,
+ howToFix: meta.howToFix ?? null,
+ impactTier: meta.impactTier ?? null,
+ };
+ });
+
+ return {
+ id: audit.id,
+ brandId: audit.brand_id,
+ url: audit.url,
+ finalUrl: audit.final_url ?? null,
+ status: audit.status,
+ totalScore: audit.total_score === null ? null : Number(audit.total_score),
+ categoryScores: audit.category_scores ?? {},
+ signalsEvaluated: audit.signals_evaluated ?? null,
+ signalsTotal: audit.signals_total ?? TOTAL_SIGNALS,
+ rubricVersion: audit.rubric_version ?? RUBRIC_VERSION,
+ error: audit.error ?? null,
+ createdAt: audit.created_at,
+ completedAt: audit.completed_at ?? null,
+ signals,
+ recommendations: audit.recommendations ?? [],
+ };
+}
+
+/**
+ * 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) {
+ try {
+ // The brand name is only needed for the Wikidata brand-entity lookup. The
+ // page is otherwise evaluated entirely on its own terms — the LLM infers
+ // the page's own target topic from its content, so an arbitrary URL (a
+ // competitor blog, any page) is never judged against this brand's topics.
+ const { data: brandRow } = await supabaseAdmin
+ .from('brands')
+ .select('name')
+ .eq('id', brandId)
+ .single();
+
+ const ctx = await buildAuditContext(url);
+
+ // Deterministic engine, the batched LLM pass, and the Wikidata lookup run
+ // concurrently. The latter two degrade to 'na' internally on failure.
+ const [deterministic, llm, brandEntity] = await Promise.all([
+ runSignals(ctx),
+ evaluateLlmSignals(ctx),
+ evaluateBrandEntity(brandRow?.name),
+ ]);
+ const results = [...deterministic, ...llm, brandEntity];
+
+ const { totalScore, categoryScores } = scoreAudit(results);
+ const signalsEvaluated = results.filter((r) => r.status !== 'na').length;
+
+ const signalRows = results.map((r) => ({
+ audit_id: auditId,
+ signal_key: r.key,
+ category: signalsByKey[r.key]?.category ?? null,
+ status: r.status,
+ score: r.score,
+ evidence: r.evidence ?? {},
+ }));
+ const { error: sigErr } = await supabaseAdmin.from('audit_signal_results').insert(signalRows);
+ if (sigErr) throw sigErr;
+
+ // AI fix recommendations for the fixable failing signals (own LLM call;
+ // degrades to [] on failure so it never blocks completion).
+ const recommendations = await generateRecommendations(ctx, { results });
+
+ const { error: completeErr } = await supabaseAdmin
+ .from('site_audits')
+ .update({
+ status: 'completed',
+ final_url: ctx.url,
+ total_score: totalScore,
+ category_scores: categoryScores,
+ signals_evaluated: signalsEvaluated,
+ signals_total: TOTAL_SIGNALS,
+ recommendations,
+ completed_at: new Date().toISOString(),
+ })
+ .eq('id', auditId);
+ // 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.
+ if (orgId) {
+ await supabaseAdmin
+ .from('site_audit_usage')
+ .insert({ organization_id: orgId, audit_id: auditId });
+ }
+ } catch (err) {
+ console.error('[audit] run failed:', err.message);
+ await supabaseAdmin
+ .from('site_audits')
+ .update({ status: 'failed', error: err.message, completed_at: new Date().toISOString() })
+ .eq('id', auditId);
+ }
+}
+
+// POST /api/audits — start an audit. Returns immediately with a `running`
+// row; the client polls GET /:id until it flips to completed/failed.
+router.post('/', requireFeature('content_optimization'), async (req, res) => {
+ const userId = req.user?.id;
+ const { url, brandId } = req.body || {};
+
+ if (!url || !brandId) {
+ return res.status(400).json({ success: false, message: 'url and brandId are required' });
+ }
+
+ try {
+ const { orgId } = await assertBrandAccess(brandId, userId);
+
+ // Enforce the monthly Site Audit quota (Starter 100 / Growth 500;
+ // Enterprise & self-hosted unlimited). Throws PlanLimitError when exhausted.
+ await enforceSiteAuditQuota(orgId);
+
+ const { data: created, error: insErr } = await supabaseAdmin
+ .from('site_audits')
+ .insert({ brand_id: brandId, url, status: 'running', rubric_version: RUBRIC_VERSION })
+ .select('*')
+ .single();
+ if (insErr) throw insErr;
+
+ // Fire-and-forget — the work continues after the response is sent.
+ runAuditJob(created.id, brandId, url, orgId).catch((err) =>
+ console.error('[audit] background job crashed:', err.message),
+ );
+
+ return res.status(202).json({ success: true, audit: assembleAudit(created, []) });
+ } catch (err) {
+ if (err instanceof PlanLimitError) {
+ return res
+ .status(err.statusCode)
+ .json({ success: false, error: 'quota_exceeded', message: err.message });
+ }
+ if (err.status) {
+ return res.status(err.status).json({ success: false, message: err.message });
+ }
+ console.error('[audit] start failed:', err.message);
+ return res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+// GET /api/audits/:id — fetch one stored audit with its signals
+router.get('/:id', async (req, res) => {
+ const userId = req.user?.id;
+ const { id } = req.params;
+
+ try {
+ const { data: audit } = await supabaseAdmin
+ .from('site_audits')
+ .select('*')
+ .eq('id', id)
+ .single();
+ if (!audit) {
+ return res.status(404).json({ success: false, message: 'Audit not found' });
+ }
+
+ await assertBrandAccess(audit.brand_id, userId);
+
+ const { data: signalRows } = await supabaseAdmin
+ .from('audit_signal_results')
+ .select('*')
+ .eq('audit_id', id);
+
+ return res.json({ success: true, audit: assembleAudit(audit, signalRows ?? []) });
+ } catch (err) {
+ if (err.status) {
+ return res.status(err.status).json({ success: false, message: err.message });
+ }
+ console.error('[audit] fetch failed:', err.message);
+ return res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+// GET /api/audits?brandId=… — recent audits for a brand (list, no signals)
+router.get('/', async (req, res) => {
+ const userId = req.user?.id;
+ const { brandId } = req.query;
+
+ if (!brandId) {
+ return res.status(400).json({ success: false, message: 'brandId is required' });
+ }
+
+ try {
+ await assertBrandAccess(brandId, userId);
+
+ const { data: audits } = await supabaseAdmin
+ .from('site_audits')
+ .select('id, url, status, total_score, signals_evaluated, signals_total, created_at')
+ .eq('brand_id', brandId)
+ .order('created_at', { ascending: false })
+ .limit(50);
+
+ return res.json({ success: true, audits: audits ?? [] });
+ } catch (err) {
+ if (err.status) {
+ return res.status(err.status).json({ success: false, message: err.message });
+ }
+ console.error('[audit] list failed:', err.message);
+ return res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+// DELETE /api/audits/:id — remove an audit (signal rows cascade via FK)
+router.delete('/:id', async (req, res) => {
+ const userId = req.user?.id;
+ const { id } = req.params;
+
+ try {
+ const { data: audit } = await supabaseAdmin
+ .from('site_audits')
+ .select('id, brand_id')
+ .eq('id', id)
+ .single();
+ if (!audit) {
+ return res.status(404).json({ success: false, message: 'Audit not found' });
+ }
+
+ await assertBrandAccess(audit.brand_id, userId);
+
+ const { error } = await supabaseAdmin.from('site_audits').delete().eq('id', id);
+ if (error) throw error;
+
+ return res.json({ success: true });
+ } catch (err) {
+ if (err.status) {
+ return res.status(err.status).json({ success: false, message: err.message });
+ }
+ console.error('[audit] delete failed:', err.message);
+ return res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+export default router;
diff --git a/server/src/routes/index.js b/server/src/routes/index.js
index 59a3320b6..c7615f690 100644
--- a/server/src/routes/index.js
+++ b/server/src/routes/index.js
@@ -5,6 +5,7 @@ import volumeRoutes from './volumes.js';
import contentRoutes from './content.js';
import competitorRoutes from './competitors.js';
import topicRoutes from './topics.js';
+import auditRoutes from './audits.js';
const router = Router();
@@ -14,6 +15,7 @@ router.use('/volumes', volumeRoutes);
router.use('/content', contentRoutes);
router.use('/competitors', competitorRoutes);
router.use('/topics', topicRoutes);
+router.use('/audits', auditRoutes);
router.get('/health', (req, res) => {
res.json({ status: 'ok', user: req.user?.id });
diff --git a/supabase/migrations/00017_site_audit.sql b/supabase/migrations/00017_site_audit.sql
new file mode 100644
index 000000000..797449e6f
--- /dev/null
+++ b/supabase/migrations/00017_site_audit.sql
@@ -0,0 +1,107 @@
+-- Site Audit (VectorCite AEO/GEO rubric, MIT open standard).
+-- One row per audit run + one row per evaluated signal.
+-- Writes happen server-side via the service_role key; member policies below
+-- keep direct authenticated-client reads org-scoped, mirroring competitors/topics.
+
+CREATE TABLE IF NOT EXISTS site_audits (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES brands(id) ON DELETE CASCADE,
+ url text NOT NULL,
+ final_url text,
+ status text NOT NULL DEFAULT 'running', -- running | completed | failed
+ total_score numeric,
+ category_scores jsonb NOT NULL DEFAULT '{}'::jsonb,
+ signals_evaluated integer,
+ signals_total integer,
+ rubric_version text,
+ error text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ completed_at timestamptz
+);
+
+CREATE INDEX IF NOT EXISTS site_audits_brand_id_idx ON site_audits (brand_id, created_at DESC);
+
+CREATE TABLE IF NOT EXISTS audit_signal_results (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ audit_id uuid NOT NULL REFERENCES site_audits(id) ON DELETE CASCADE,
+ signal_key text NOT NULL,
+ category text,
+ status text NOT NULL, -- pass | warn | fail | na
+ score numeric,
+ evidence jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (audit_id, signal_key)
+);
+
+CREATE INDEX IF NOT EXISTS audit_signal_results_audit_id_idx ON audit_signal_results (audit_id);
+
+-- RLS: org-membership scoped, mirroring content_opportunities / competitors.
+ALTER TABLE site_audits ENABLE ROW LEVEL SECURITY;
+ALTER TABLE audit_signal_results ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY site_audits_member_select ON site_audits FOR SELECT
+ USING (
+ brand_id IN (
+ SELECT b.id FROM brands b
+ JOIN profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
+
+CREATE POLICY site_audits_member_insert ON site_audits FOR INSERT
+ WITH CHECK (
+ brand_id IN (
+ SELECT b.id FROM brands b
+ JOIN profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
+
+CREATE POLICY site_audits_member_update ON site_audits FOR UPDATE
+ USING (
+ brand_id IN (
+ SELECT b.id FROM brands b
+ JOIN profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
+
+CREATE POLICY site_audits_member_delete ON site_audits FOR DELETE
+ USING (
+ brand_id IN (
+ SELECT b.id FROM brands b
+ JOIN profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
+
+-- audit_signal_results inherit access through their parent audit's brand.
+CREATE POLICY audit_signal_results_member_select ON audit_signal_results FOR SELECT
+ USING (
+ audit_id IN (
+ SELECT sa.id FROM site_audits sa
+ JOIN brands b ON b.id = sa.brand_id
+ JOIN profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
+
+CREATE POLICY audit_signal_results_member_insert ON audit_signal_results FOR INSERT
+ WITH CHECK (
+ audit_id IN (
+ SELECT sa.id FROM site_audits sa
+ JOIN brands b ON b.id = sa.brand_id
+ JOIN profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
+
+CREATE POLICY audit_signal_results_member_delete ON audit_signal_results FOR DELETE
+ USING (
+ audit_id IN (
+ SELECT sa.id FROM site_audits sa
+ JOIN brands b ON b.id = sa.brand_id
+ JOIN profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
diff --git a/supabase/migrations/00018_site_audit_recommendations.sql b/supabase/migrations/00018_site_audit_recommendations.sql
new file mode 100644
index 000000000..f28b8599d
--- /dev/null
+++ b/supabase/migrations/00018_site_audit_recommendations.sql
@@ -0,0 +1,6 @@
+-- AI fix recommendations for a Site Audit: a prioritized list of page-specific
+-- suggestions (with ready-to-paste drafts) generated by the audit's LLM pass.
+-- Stored on the audit so they persist when the report is re-opened.
+
+ALTER TABLE site_audits
+ ADD COLUMN IF NOT EXISTS recommendations jsonb NOT NULL DEFAULT '[]'::jsonb;
diff --git a/supabase/migrations/00019_site_audit_usage.sql b/supabase/migrations/00019_site_audit_usage.sql
new file mode 100644
index 000000000..3ee0e4f5f
--- /dev/null
+++ b/supabase/migrations/00019_site_audit_usage.sql
@@ -0,0 +1,31 @@
+-- Site Audit quota tracking. One row per completed audit, counted per
+-- organization per calendar month against plan.limits.maxSiteAudits
+-- (Starter 100, Growth 500, Enterprise/Self-hosted unlimited). Mirrors the
+-- brief_usage pattern. Self-hosted instances bypass quota (IS_CLOUD !== "true").
+
+CREATE TABLE IF NOT EXISTS "public"."site_audit_usage" (
+ "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
+ "organization_id" "uuid" NOT NULL,
+ "audit_id" "uuid",
+ "used_at" timestamp with time zone DEFAULT "now"() NOT NULL,
+ "created_at" timestamp with time zone DEFAULT "now"()
+);
+
+ALTER TABLE ONLY "public"."site_audit_usage"
+ ADD CONSTRAINT "site_audit_usage_pkey" PRIMARY KEY ("id");
+
+ALTER TABLE ONLY "public"."site_audit_usage"
+ ADD CONSTRAINT "site_audit_usage_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE CASCADE;
+
+ALTER TABLE ONLY "public"."site_audit_usage"
+ ADD CONSTRAINT "site_audit_usage_audit_id_fkey" FOREIGN KEY ("audit_id") REFERENCES "public"."site_audits"("id") ON DELETE SET NULL;
+
+CREATE INDEX "idx_site_audit_usage_org_month" ON "public"."site_audit_usage" USING "btree" ("organization_id", "used_at");
+
+-- RLS enabled with no policies: only the service role (aeo-server) reads/writes
+-- usage rows — same posture as brief_usage / volume_usage.
+ALTER TABLE "public"."site_audit_usage" ENABLE ROW LEVEL SECURITY;
+
+GRANT ALL ON TABLE "public"."site_audit_usage" TO "anon";
+GRANT ALL ON TABLE "public"."site_audit_usage" TO "authenticated";
+GRANT ALL ON TABLE "public"."site_audit_usage" TO "service_role";
diff --git a/web/messages/en.json b/web/messages/en.json
index 770d2fd2c..776abd84e 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -23,12 +23,44 @@
"prompts": "Prompts",
"topics": "Topics",
"content": "Content Optimization",
+ "audit": "Site Audit",
"competitors": "Competitors",
"citations": "Citations",
"shopping": "Shopping",
"reports": "Reports",
"settings": "Settings"
},
+ "audit": {
+ "title": "Site Audit",
+ "description": "Score any page against the 47-signal AEO/GEO",
+ "runAudit": "Run Audit",
+ "running": "Auditing…",
+ "recent": "Recent Audits",
+ "deleteAudit": "Delete audit",
+ "noBrand": "Select a brand first.",
+ "urlRequired": "Enter a URL to audit.",
+ "failed": "Audit failed. Please try again.",
+ "grade": {
+ "good": "Good",
+ "needsWork": "Needs work",
+ "poor": "Poor"
+ },
+ "summary": {
+ "passed": "passed",
+ "warnings": "warnings",
+ "failed": "failed"
+ },
+ "onlyIssues": "Issues only",
+ "allSignals": "All signals",
+ "noIssues": "No issues found — every evaluated signal passed.",
+ "stages": {
+ "fetch": "Fetching the page…",
+ "analyze": "Analyzing 47 signals…",
+ "recommend": "Generating AI recommendations…"
+ },
+ "emptyTitle": "Audit any page for AI search readiness",
+ "emptyBody": "Enter a URL above to score it against 47 AEO/GEO signals and get AI-written fixes."
+ },
"auth": {
"signIn": "Sign in",
"signUp": "Sign up",
@@ -550,4 +582,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
new file mode 100644
index 000000000..a1a496044
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/audit/page.tsx
@@ -0,0 +1,580 @@
+'use client';
+
+import { useState, useEffect, useCallback } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import {
+ Search,
+ Loader2,
+ ChevronDown,
+ CheckCircle2,
+ AlertTriangle,
+ XCircle,
+ Minus,
+ Trash2,
+ Sparkles,
+ Copy,
+} from 'lucide-react';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Badge } from '@/components/ui/badge';
+import { useBrandStore } from '@/stores/use-brand-store';
+import {
+ runAudit,
+ getAudit,
+ getAudits,
+ deleteAudit,
+ type AuditResult,
+ type AuditSignal,
+ type AuditSummary,
+ type AuditRecommendation,
+} from '@/lib/actions/audits';
+import { cn } from '@/lib/utils';
+
+// Display order + labels for the five rubric categories (keys come from the
+// server's categoryScores). Mirrors the rubric category weights.
+const CATEGORY_META: { key: string; label: string; weight: number }[] = [
+ { key: 'structure', label: 'Structure', weight: 0.25 },
+ { key: 'content', label: 'Content', weight: 0.25 },
+ { key: 'authority', label: 'Authority', weight: 0.2 },
+ { key: 'eeat', label: 'E-E-A-T', weight: 0.2 },
+ { key: 'trust', label: 'Trust', weight: 0.1 },
+];
+
+function pct(score: number | null): number | null {
+ return score === null ? null : Math.round(score * 100);
+}
+
+function scoreColor(score: number | null): string {
+ if (score === null) return 'text-muted-foreground';
+ if (score >= 0.7) return 'text-green-600';
+ if (score >= 0.4) return 'text-amber-500';
+ return 'text-destructive';
+}
+
+function barColor(score: number | null): string {
+ if (score === null) return 'bg-muted';
+ if (score >= 0.7) return 'bg-green-600';
+ if (score >= 0.4) return 'bg-amber-500';
+ return 'bg-destructive';
+}
+
+const STATUS_ICON = {
+ pass: CheckCircle2,
+ warn: AlertTriangle,
+ fail: XCircle,
+ na: Minus,
+} as const;
+
+const STATUS_COLOR = {
+ pass: 'text-green-600',
+ warn: 'text-amber-500',
+ fail: 'text-destructive',
+ na: 'text-muted-foreground',
+} as const;
+
+function gradeKey(score: number | null): 'good' | 'needsWork' | 'poor' | null {
+ if (score === null) return null;
+ if (score >= 0.7) return 'good';
+ if (score >= 0.4) return 'needsWork';
+ return 'poor';
+}
+
+function ScoreGauge({ score }: { score: number | null }) {
+ const p = pct(score) ?? 0;
+ const radius = 52;
+ const circ = 2 * Math.PI * radius;
+ const dash = (p / 100) * circ;
+ const stroke =
+ score === null
+ ? 'stroke-muted-foreground'
+ : score >= 0.7
+ ? 'stroke-green-600'
+ : score >= 0.4
+ ? 'stroke-amber-500'
+ : 'stroke-destructive';
+ return (
+ <div className="relative h-32 w-32 shrink-0">
+ <svg viewBox="0 0 120 120" className="h-full w-full -rotate-90">
+ <circle cx="60" cy="60" r={radius} fill="none" strokeWidth="10" className="stroke-muted" />
+ <circle
+ cx="60"
+ cy="60"
+ r={radius}
+ fill="none"
+ strokeWidth="10"
+ strokeLinecap="round"
+ className={cn('transition-all duration-700', stroke)}
+ strokeDasharray={`${dash} ${circ}`}
+ />
+ </svg>
+ <div className="absolute inset-0 flex flex-col items-center justify-center">
+ <span className={cn('text-4xl font-bold tabular-nums', scoreColor(score))}>
+ {pct(score) ?? '—'}
+ </span>
+ <span className="text-[11px] text-muted-foreground">/ 100</span>
+ </div>
+ </div>
+ );
+}
+
+function DraftBlock({ draft }: { draft: string }) {
+ const copy = () => {
+ navigator.clipboard.writeText(draft).then(
+ () => toast.success('Copied'),
+ () => toast.error('Copy failed'),
+ );
+ };
+ return (
+ <div className="relative rounded-md border bg-muted/50 p-3">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="absolute right-1 top-1 h-7 w-7"
+ onClick={copy}
+ aria-label="Copy draft"
+ >
+ <Copy className="h-3.5 w-3.5" />
+ </Button>
+ <pre className="whitespace-pre-wrap pr-8 text-xs leading-relaxed text-foreground">
+ {draft}
+ </pre>
+ </div>
+ );
+}
+
+function SignalRow({
+ signal,
+ recommendation,
+}: {
+ signal: AuditSignal;
+ recommendation?: AuditRecommendation;
+}) {
+ const [open, setOpen] = useState(false);
+ const Icon = STATUS_ICON[signal.status] ?? Minus;
+
+ return (
+ <div className="border-b last:border-b-0">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ className="flex w-full items-center gap-3 py-3 text-left hover:bg-muted/40"
+ aria-expanded={open}
+ >
+ <Icon className={cn('h-4 w-4 shrink-0', STATUS_COLOR[signal.status])} />
+ <span className="flex-1 text-sm font-medium">{signal.label}</span>
+ {signal.impactTier && (
+ <Badge
+ variant={signal.impactTier === 'high' ? 'default' : 'secondary'}
+ className="text-[10px]"
+ >
+ {signal.impactTier}
+ </Badge>
+ )}
+ <ChevronDown
+ className={cn('h-4 w-4 text-muted-foreground transition-transform', open && 'rotate-180')}
+ />
+ </button>
+ {open && (
+ <div className="space-y-2 pb-4 pl-7 text-sm text-muted-foreground">
+ {typeof signal.evidence?.reason === 'string' && signal.evidence.reason && (
+ <p>
+ <span className="font-medium text-foreground">Finding: </span>
+ {signal.evidence.reason as string}
+ </p>
+ )}
+ {signal.what && <p>{signal.what}</p>}
+ {signal.why && (
+ <p>
+ <span className="font-medium text-foreground">Why: </span>
+ {signal.why}
+ </p>
+ )}
+ {/* Prefer the page-specific AI recommendation when we have one; fall
+ back to the rubric's generic fix otherwise. */}
+ {recommendation ? (
+ <div className="space-y-2">
+ <p>
+ <span className="inline-flex items-center gap-1 font-medium text-primary">
+ <Sparkles className="h-3.5 w-3.5" /> Recommended fix:
+ </span>{' '}
+ {recommendation.recommendation}
+ </p>
+ {recommendation.draft && <DraftBlock draft={recommendation.draft} />}
+ </div>
+ ) : (
+ signal.status !== 'pass' &&
+ signal.howToFix && (
+ <p>
+ <span className="font-medium text-foreground">Fix: </span>
+ {signal.howToFix}
+ </p>
+ )
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+const PRIORITY_ORDER = { high: 0, medium: 1, low: 2 } as const;
+
+function RecommendationItem({ rec }: { rec: AuditRecommendation }) {
+ return (
+ <div className="space-y-2 border-b py-4 last:border-b-0">
+ <div className="flex items-center gap-2">
+ <Badge variant={rec.priority === 'high' ? 'default' : 'secondary'} className="text-[10px]">
+ {rec.priority}
+ </Badge>
+ <span className="text-sm font-medium">{rec.label}</span>
+ </div>
+ <p className="text-sm text-muted-foreground">{rec.recommendation}</p>
+ {rec.draft && <DraftBlock draft={rec.draft} />}
+ </div>
+ );
+}
+
+function AuditReport({ audit }: { audit: AuditResult }) {
+ const t = useTranslations('audit');
+ const [onlyIssues, setOnlyIssues] = useState(false);
+ const recBySignal = new Map(audit.recommendations.map((r) => [r.signalKey, r]));
+
+ const counts = audit.signals.reduce(
+ (acc, s) => {
+ if (s.status === 'pass') acc.pass += 1;
+ else if (s.status === 'warn') acc.warn += 1;
+ else if (s.status === 'fail') acc.fail += 1;
+ return acc;
+ },
+ { pass: 0, warn: 0, fail: 0 },
+ );
+ const hasIssues = counts.fail + counts.warn > 0;
+ const grade = gradeKey(audit.totalScore);
+
+ const visibleSignals = (cat: string) =>
+ audit.signals.filter(
+ (s) => s.category === cat && (!onlyIssues || s.status === 'fail' || s.status === 'warn'),
+ );
+
+ return (
+ <div className="space-y-6">
+ {/* Headline: gauge + grade + pass/warn/fail summary */}
+ <Card>
+ <CardContent className="flex flex-col items-center gap-6 py-6 sm:flex-row sm:items-center">
+ <ScoreGauge score={audit.totalScore} />
+ <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>
+ )}
+ <div className="flex flex-wrap justify-center gap-2 sm:justify-start">
+ <span className="inline-flex items-center gap-1 rounded-full bg-green-600/10 px-2 py-0.5 text-xs font-medium text-green-700">
+ <CheckCircle2 className="h-3.5 w-3.5" /> {counts.pass} {t('summary.passed')}
+ </span>
+ <span className="inline-flex items-center gap-1 rounded-full bg-amber-500/10 px-2 py-0.5 text-xs font-medium text-amber-600">
+ <AlertTriangle className="h-3.5 w-3.5" /> {counts.warn} {t('summary.warnings')}
+ </span>
+ <span className="inline-flex items-center gap-1 rounded-full bg-destructive/10 px-2 py-0.5 text-xs font-medium text-destructive">
+ <XCircle className="h-3.5 w-3.5" /> {counts.fail} {t('summary.failed')}
+ </span>
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {audit.signalsEvaluated}/{audit.signalsTotal} signals evaluated
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* AI fix recommendations */}
+ {audit.recommendations.length > 0 && (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2 text-base">
+ <Sparkles className="h-4 w-4 text-primary" />
+ AI Recommendations
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0">
+ {[...audit.recommendations]
+ .sort((a, b) => PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority])
+ .map((rec, i) => (
+ <RecommendationItem key={`${rec.signalKey}-${i}`} rec={rec} />
+ ))}
+ </CardContent>
+ </Card>
+ )}
+
+ {/* Category breakdown */}
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base">Category breakdown</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {CATEGORY_META.map((cat) => {
+ const cs = audit.categoryScores[cat.key];
+ const score = cs?.score ?? null;
+ const p = pct(score);
+ return (
+ <div key={cat.key}>
+ <div className="mb-1 flex items-center justify-between text-sm">
+ <span className="font-medium">{cat.label}</span>
+ <span className="text-muted-foreground">
+ {p === null ? 'n/a' : `${p}/100`}
+ {cs ? ` · ${cs.evaluated}/${cs.total}` : ''}
+ </span>
+ </div>
+ <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
+ <div
+ className={cn('h-full rounded-full transition-all', barColor(score))}
+ style={{ width: `${p ?? 0}%` }}
+ />
+ </div>
+ </div>
+ );
+ })}
+ </CardContent>
+ </Card>
+
+ {/* Signals header + issues-only filter */}
+ <div className="flex items-center justify-between">
+ <h2 className="text-base font-semibold">Signals</h2>
+ <Button variant="outline" size="sm" onClick={() => setOnlyIssues((v) => !v)}>
+ {onlyIssues ? t('allSignals') : t('onlyIssues')}
+ </Button>
+ </div>
+
+ {onlyIssues && !hasIssues ? (
+ <Card>
+ <CardContent className="py-8 text-center text-sm text-muted-foreground">
+ {t('noIssues')}
+ </CardContent>
+ </Card>
+ ) : (
+ CATEGORY_META.map((cat) => {
+ const sigs = visibleSignals(cat.key);
+ if (sigs.length === 0) return null;
+ return (
+ <Card key={cat.key}>
+ <CardHeader>
+ <CardTitle className="text-base">{cat.label}</CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0">
+ {sigs.map((s) => (
+ <SignalRow key={s.key} signal={s} recommendation={recBySignal.get(s.key)} />
+ ))}
+ </CardContent>
+ </Card>
+ );
+ })
+ )}
+ </div>
+ );
+}
+
+export default function SiteAuditPage() {
+ const t = useTranslations('audit');
+ const activeBrandId = useBrandStore((s) => s.activeBrandId);
+ const activeBrand = useBrandStore((s) => s.brands.find((b) => b.id === s.activeBrandId) ?? null);
+
+ const [url, setUrl] = useState('');
+ const [running, setRunning] = useState(false);
+ const [stage, setStage] = useState(0);
+ const [audit, setAudit] = useState<AuditResult | null>(null);
+ const [history, setHistory] = useState<AuditSummary[]>([]);
+
+ // Advance the running-state stage label so the ~30s wait reads as progress.
+ useEffect(() => {
+ if (!running) {
+ setStage(0);
+ return;
+ }
+ const id = setInterval(() => setStage((s) => Math.min(s + 1, 2)), 8000);
+ return () => clearInterval(id);
+ }, [running]);
+
+ // Prefill the URL with the brand's primary domain.
+ useEffect(() => {
+ if (!activeBrand) return;
+ const primary = activeBrand.domains?.find((d) => d.isPrimary) ?? activeBrand.domains?.[0];
+ if (primary?.domain) setUrl(`https://${primary.domain.replace(/^https?:\/\//, '')}`);
+ }, [activeBrand]);
+
+ const loadHistory = useCallback(async () => {
+ if (!activeBrandId) return;
+ try {
+ setHistory(await getAudits(activeBrandId));
+ } catch (err) {
+ console.error('Failed to load audit history:', err);
+ }
+ }, [activeBrandId]);
+
+ useEffect(() => {
+ loadHistory();
+ }, [loadHistory]);
+
+ const handleRun = async () => {
+ if (!activeBrandId) {
+ toast.error(t('noBrand'));
+ return;
+ }
+ if (!url.trim()) {
+ toast.error(t('urlRequired'));
+ return;
+ }
+ setRunning(true);
+ setAudit(null);
+ try {
+ // The audit runs in the background; poll until it flips to completed/failed.
+ const started = await runAudit(activeBrandId, url.trim());
+ let result = started;
+ const deadline = Date.now() + 120_000; // give up after 2 minutes
+ while (result.status === 'running' && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 3000));
+ result = await getAudit(started.id);
+ }
+ setAudit(result);
+ if (result.status === 'failed') {
+ toast.error(result.error || t('failed'));
+ }
+ loadHistory();
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : t('failed'));
+ } finally {
+ setRunning(false);
+ }
+ };
+
+ const handleOpen = async (id: string) => {
+ setRunning(true);
+ try {
+ setAudit(await getAudit(id));
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : t('failed'));
+ } finally {
+ setRunning(false);
+ }
+ };
+
+ const handleDelete = async (id: string) => {
+ // Optimistic removal; restore on failure.
+ const prev = history;
+ setHistory((h) => h.filter((a) => a.id !== id));
+ if (audit?.id === id) setAudit(null);
+ try {
+ await deleteAudit(id);
+ } catch (err) {
+ setHistory(prev);
+ toast.error(err instanceof Error ? err.message : t('failed'));
+ }
+ };
+
+ 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>
+
+ {/* Run bar */}
+ <Card>
+ <CardContent className="flex flex-col gap-3 py-4 sm:flex-row sm:items-center">
+ <Input
+ type="url"
+ inputMode="url"
+ placeholder="https://example.com/page"
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && !running && handleRun()}
+ disabled={running}
+ className="flex-1"
+ />
+ <Button onClick={handleRun} disabled={running} className="shrink-0">
+ {running ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ {t('running')}
+ </>
+ ) : (
+ <>
+ <Search className="mr-2 h-4 w-4" />
+ {t('runAudit')}
+ </>
+ )}
+ </Button>
+ </CardContent>
+ </Card>
+
+ {running && !audit && (
+ <Card>
+ <CardContent className="flex flex-col items-center gap-3 py-10 text-center">
+ <Loader2 className="h-6 w-6 animate-spin text-primary" />
+ <div className="text-sm font-medium">
+ {[t('stages.fetch'), t('stages.analyze'), t('stages.recommend')][stage]}
+ </div>
+ <div className="text-xs text-muted-foreground">~30s</div>
+ </CardContent>
+ </Card>
+ )}
+
+ {!running && !audit && (
+ <Card>
+ <CardContent className="flex flex-col items-center gap-2 py-12 text-center">
+ <Sparkles className="h-7 w-7 text-primary" />
+ <div className="text-base font-semibold">{t('emptyTitle')}</div>
+ <p className="max-w-md text-sm text-muted-foreground">{t('emptyBody')}</p>
+ </CardContent>
+ </Card>
+ )}
+
+ {audit && <AuditReport audit={audit} />}
+
+ {/* Recent audits */}
+ {history.length > 0 && (
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base">{t('recent')}</CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0">
+ {history.map((h) => (
+ <div
+ key={h.id}
+ className="flex items-center gap-3 border-b py-1 last:border-b-0 hover:bg-muted/40"
+ >
+ <button
+ type="button"
+ onClick={() => handleOpen(h.id)}
+ className="flex flex-1 items-center gap-3 py-2 text-left"
+ >
+ <span className="flex-1 truncate text-sm">{h.url}</span>
+ <span className="text-xs text-muted-foreground">
+ {new Date(h.created_at).toLocaleDateString()}
+ </span>
+ <span
+ className={cn(
+ 'w-12 text-right text-sm font-semibold tabular-nums',
+ scoreColor(h.total_score),
+ )}
+ >
+ {h.status === 'completed' ? (pct(h.total_score) ?? '—') : h.status}
+ </span>
+ </button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
+ onClick={() => handleDelete(h.id)}
+ aria-label={t('deleteAudit')}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ ))}
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsx
index e256400ef..6500ad4a6 100644
--- a/web/src/components/layout/sidebar.tsx
+++ b/web/src/components/layout/sidebar.tsx
@@ -55,6 +55,7 @@ export function Sidebar() {
Prompts: () => t('prompts'),
Topics: () => t('topics'),
'Content Optimization': () => t('content'),
+ 'Site Audit': () => t('audit'),
Competitors: () => t('competitors'),
Citations: () => t('citations'),
Shopping: () => t('shopping'),
diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.ts
index e7aeba0c3..0a6d90378 100644
--- a/web/src/config/dashboard.ts
+++ b/web/src/config/dashboard.ts
@@ -2,6 +2,7 @@ import {
BarChart3,
Building2,
FileText,
+ Gauge,
Globe,
LineChart,
Quote,
@@ -107,6 +108,12 @@ export const dashboardNav: NavGroup[] = [
icon: FileText,
requiredFeature: 'content_optimization',
},
+ {
+ title: 'Site Audit',
+ href: '/dashboard/audit',
+ icon: Gauge,
+ requiredFeature: 'content_optimization',
+ },
],
},
];
diff --git a/web/src/config/plans.ts b/web/src/config/plans.ts
index 44c68636a..04116c8b0 100644
--- a/web/src/config/plans.ts
+++ b/web/src/config/plans.ts
@@ -39,6 +39,11 @@ export interface PlanLimits {
* organizations.plan_overrides.maxBriefGenerations in the DB.
*/
maxBriefGenerations: number;
+ /**
+ * Monthly Site Audit runs. -1 = unlimited (self-hosted / enterprise).
+ * Starter 100, Growth 500.
+ */
+ maxSiteAudits: number;
maxDailyOnDemand: number;
onDemandCooldownMinutes: number;
features: readonly Feature[];
@@ -75,6 +80,7 @@ export const PLANS: Record<PlanId, Plan> = {
maxDomainsPerBrand: -1,
maxVolumeAnalyses: -1,
maxBriefGenerations: -1,
+ maxSiteAudits: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
features: [
@@ -107,6 +113,7 @@ export const PLANS: Record<PlanId, Plan> = {
maxDomainsPerBrand: 3,
maxVolumeAnalyses: 4,
maxBriefGenerations: 10,
+ maxSiteAudits: 100,
maxDailyOnDemand: 3,
onDemandCooldownMinutes: 15,
allowedScrapers: ['chatgpt-web', 'perplexity-web'],
@@ -143,6 +150,7 @@ export const PLANS: Record<PlanId, Plan> = {
maxDomainsPerBrand: 10,
maxVolumeAnalyses: 10,
maxBriefGenerations: 50,
+ maxSiteAudits: 500,
maxDailyOnDemand: 10,
onDemandCooldownMinutes: 5,
features: [
@@ -174,6 +182,7 @@ export const PLANS: Record<PlanId, Plan> = {
maxVolumeAnalyses: -1,
// Per-customer: override via organizations.plan_overrides in the DB.
maxBriefGenerations: -1,
+ maxSiteAudits: -1,
maxDailyOnDemand: -1,
onDemandCooldownMinutes: 0,
features: [
diff --git a/web/src/lib/actions/audits.ts b/web/src/lib/actions/audits.ts
new file mode 100644
index 000000000..89d80cfee
--- /dev/null
+++ b/web/src/lib/actions/audits.ts
@@ -0,0 +1,143 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+
+const AEO_SERVER_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost';
+
+export type AuditSignalStatus = 'pass' | 'warn' | 'fail' | 'na';
+
+export interface AuditSignal {
+ key: string;
+ category: string | null;
+ status: AuditSignalStatus;
+ score: number | null;
+ evidence: Record<string, unknown>;
+ label: string;
+ what: string | null;
+ why: string | null;
+ howToFix: string | null;
+ impactTier: 'high' | 'medium' | 'standard' | null;
+}
+
+export interface CategoryScore {
+ score: number | null;
+ evaluated: number;
+ total: number;
+}
+
+export interface AuditRecommendation {
+ signalKey: string;
+ label: string;
+ category: string | null;
+ priority: 'high' | 'medium' | 'low';
+ recommendation: string;
+ draft: string | null;
+}
+
+export interface AuditResult {
+ id: string;
+ brandId: string;
+ url: string;
+ finalUrl: string | null;
+ status: 'running' | 'completed' | 'failed';
+ totalScore: number | null;
+ categoryScores: Record<string, CategoryScore>;
+ signalsEvaluated: number | null;
+ signalsTotal: number;
+ rubricVersion: string;
+ error: string | null;
+ createdAt: string;
+ completedAt: string | null;
+ signals: AuditSignal[];
+ recommendations: AuditRecommendation[];
+}
+
+export interface AuditSummary {
+ id: string;
+ url: string;
+ status: 'running' | 'completed' | 'failed';
+ total_score: number | null;
+ signals_evaluated: number | null;
+ signals_total: number;
+ created_at: string;
+}
+
+async function getSession() {
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) throw new Error('Not authenticated');
+ return session;
+}
+
+/** Run a new single-page audit (synchronous — returns the completed result). */
+export async function runAudit(brandId: string, url: string): Promise<AuditResult> {
+ const session = await getSession();
+
+ const res = await fetch(`${AEO_SERVER_URL}/api/audits`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${session.access_token}`,
+ },
+ body: JSON.stringify({ brandId, url }),
+ });
+
+ 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.audit;
+}
+
+/** Fetch a single stored audit with all its signal results. */
+export async function getAudit(auditId: string): Promise<AuditResult> {
+ const session = await getSession();
+
+ const res = await fetch(`${AEO_SERVER_URL}/api/audits/${auditId}`, {
+ 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.audit;
+}
+
+/** Delete a stored audit (its signal rows cascade away). */
+export async function deleteAudit(auditId: string): Promise<void> {
+ const session = await getSession();
+
+ const res = await fetch(`${AEO_SERVER_URL}/api/audits/${auditId}`, {
+ method: 'DELETE',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.message || `Server error: ${res.status}`);
+ }
+}
+
+/** List recent audits for a brand (summaries, no signal detail). */
+export async function getAudits(brandId: string): Promise<AuditSummary[]> {
+ const session = await getSession();
+
+ const res = await fetch(`${AEO_SERVER_URL}/api/audits?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.audits ?? [];
+}