Phase 3 part 3: the audit, ranked by traffic, with AI visibility

A polite crawl of each website (Search Console's busiest pages, the
sitemap, then links; up to 300 pages; robots.txt honoured) checks titles
and descriptions (characters and pixels), headings, canonical, noindex,
status and redirects, broken links (outside ones twice), alt text, Open
Graph, JSON-LD, text without JavaScript, and whether the title says what
the page's main search asks. Issues are ranked by severity, then the
page's clicks and impressions. AI visibility: AI crawlers in robots.txt,
llms.txt, structured data, Organization data. Optional PageSpeed checks.
Weekly in the background, or Audit now. Schema 14.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 07:53:10 -07:00
co-authored by Claude Opus 5.5
parent a7de13087e
commit 43a7b42126
21 changed files with 1643 additions and 17 deletions
+64
View File
@@ -0,0 +1,64 @@
package web
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"supermarket/internal/profile"
"supermarket/internal/seo"
)
func TestAuditPage(t *testing.T) {
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<html><head><title>Home</title></head><body><h1>Hi</h1><a href="/nope/">x</a></body></html>`)
case "/sitemap.xml":
fmt.Fprintf(w, `<urlset><url><loc>%s/</loc></url></urlset>`, srv.URL)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: srv.URL}}})
if body := do(h, http.MethodGet, "/seo/audit", nil, nil).Body.String(); !strings.Contains(body, "Not audited yet") {
t.Fatal("no empty state")
}
if rec := postForm(h, "/seo/audit?site=0", nil); rec.Code != http.StatusSeeOther {
t.Fatalf("start: %d %s", rec.Code, rec.Body)
}
deadline := time.Now().Add(10 * time.Second)
for {
a, _ := seo.LatestAudit(s.DB, srv.URL)
if a != nil && a.Status != "running" {
if a.Status != "done" {
t.Fatalf("audit: %+v", a)
}
break
}
if time.Now().After(deadline) {
t.Fatal("the audit didn't finish")
}
time.Sleep(50 * time.Millisecond)
}
if rec := do(h, http.MethodGet, "/seo/audit/status?site=0", nil, nil); rec.Header().Get("HX-Refresh") != "true" {
t.Error("the status poll doesn't reload when done")
}
body := do(h, http.MethodGet, "/seo/audit", nil, nil).Body.String()
for _, want := range []string{"AI visibility", "No llms.txt", "Answers 404", "/nope/", "Title very short", "pages read"} {
if !strings.Contains(body, want) {
t.Errorf("audit page lacks %q", want)
}
}
if body := do(h, http.MethodGet, "/seo/audit?severity=error", nil, nil).Body.String(); strings.Contains(body, "Title very short") {
t.Error("the severity filter shows notices")
}
}
+160 -1
View File
@@ -5,6 +5,7 @@ import (
"errors"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"sync"
@@ -112,6 +113,8 @@ func (s *Server) searchSettingsPage(w http.ResponseWriter, r *http.Request) {
func (s *Server) renderSearchSettings(w http.ResponseWriter, r *http.Request, errMsg string) {
data := map[string]any{
"Fields": googleFields,
"Speed": pageSpeedKey,
"SpeedSet": s.Secrets.Has(secrets.PageSpeedAPIKey),
"Set": s.secretState(secrets.GoogleClientID, secrets.GoogleClientSecret, secrets.GoogleRefreshToken),
"Redirect": s.callbackURL("google"),
"Sites": s.seoSites(),
@@ -136,7 +139,7 @@ func (s *Server) searchSettingsSave(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.saveSecrets(r, googleFields); err != nil {
if err := s.saveSecrets(r, append(googleFields, pageSpeedKey)); err != nil {
s.serverError(w, err)
return
}
@@ -220,9 +223,13 @@ func (s *Server) syncSearchConsole(ctx context.Context) error {
// RunSEO syncs Search Console twice a day.
func (s *Server) RunSEO(ctx context.Context) {
if err := seo.RecoverAudits(s.DB); err != nil {
s.Log.Error("seo: recovering audits", "err", err)
}
tick := time.NewTicker(30 * time.Minute)
defer tick.Stop()
for {
s.weeklyAudits(time.Now())
if s.gsc() != nil {
due := false
for _, site := range s.seoSites() {
@@ -418,3 +425,155 @@ func (s *Server) weeklyReports(ctx context.Context, now time.Time) {
}
}
}
// --- The audit ---
var pageSpeedKey = secretField{"pagespeed", secrets.PageSpeedAPIKey, "PageSpeed Insights API key (optional)",
"Free. In Google Cloud, enable the PageSpeed Insights API and create an API key under Credentials. Without one, Google allows only a few speed checks.", googleCreds}
// auditing marks the sites being audited now.
var auditing sync.Map
// auditSites are every website in the profile (an audit doesn't need
// Search Console; with it, issues are ranked by traffic).
func (s *Server) auditSites(r *http.Request) ([]seoSite, *seoSite) {
sites := s.seoSites()
if i, err := strconv.Atoi(r.URL.Query().Get("site")); err == nil {
for j := range sites {
if sites[j].Index == i {
return sites, &sites[j]
}
}
}
if len(sites) > 0 {
return sites, &sites[0]
}
return sites, nil
}
func (s *Server) seoAuditPage(w http.ResponseWriter, r *http.Request) {
sites, cur := s.auditSites(r)
data := map[string]any{"Sites": sites, "Current": cur, "Path": "/seo/audit", "Connected": true,
"MaxPages": seo.MaxAuditPages, "Severity": r.URL.Query().Get("severity")}
if cur != nil {
a, err := seo.LatestAudit(s.DB, cur.URL)
if err != nil {
s.serverError(w, err)
return
}
data["Audit"] = a
if a != nil && a.Status == "done" {
sev := r.URL.Query().Get("severity")
var shown []seo.Issue
for _, is := range a.Issues {
if sev == "" || is.Severity == sev {
shown = append(shown, is)
}
}
if len(shown) > 300 {
data["More"] = len(shown) - 300
shown = shown[:300]
}
data["Shown"] = shown
}
}
s.render(w, r, "seo-audit", page{Title: "Audit", Nav: "seo/audit", Data: data})
}
// seoAuditRun starts an audit in the background.
func (s *Server) seoAuditRun(w http.ResponseWriter, r *http.Request) {
_, cur := s.auditSites(r)
if cur == nil {
http.NotFound(w, r)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.startAudit(*cur, r.PostFormValue("speed") == "on")
redirect(w, r, "/seo/audit?site="+strconv.Itoa(cur.Index), "auditing")
}
// startAudit runs one in the background, unless one is running for the
// site.
func (s *Server) startAudit(site seoSite, speed bool) {
if _, busy := auditing.LoadOrStore(site.URL, true); busy {
return
}
id, err := seo.StartAudit(s.DB, site.URL, time.Now())
if err != nil {
auditing.Delete(site.URL)
s.Log.Error("seo: starting the audit", "err", err)
return
}
go func() {
defer auditing.Delete(site.URL)
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Minute)
defer cancel()
a, err := seo.RunAudit(ctx, s.DB, seo.NewFetcher("Supermarket/"+s.Version+" (SEO audit)"), site.URL, site.Property)
if err == nil && speed {
for _, p := range busiest(a, 5) {
a.Speed = append(a.Speed, seo.CheckSpeed(ctx, p, s.Secrets.Get(secrets.PageSpeedAPIKey)))
}
}
if ferr := seo.FinishAudit(s.DB, id, a, err, time.Now()); ferr != nil {
s.Log.Error("seo: saving the audit", "err", ferr)
}
if err != nil {
s.Log.Warn("seo: audit failed", "site", site.URL, "err", err)
}
}()
}
// busiest are an audit's pages with the most impressions (the home page
// first when there's no traffic data).
func busiest(a *seo.Audit, n int) []string {
traffic := map[string]int{}
for _, is := range a.Issues {
traffic[is.Page] = is.Traffic.Impressions
}
var pages []string
for _, p := range a.Pages {
if p.Status == 200 {
pages = append(pages, p.URL)
}
}
sort.SliceStable(pages, func(i, j int) bool { return traffic[pages[i]] > traffic[pages[j]] })
if len(pages) > n {
pages = pages[:n]
}
return pages
}
// seoAuditStatus is polled while an audit runs; it reloads the page when
// the audit is done.
func (s *Server) seoAuditStatus(w http.ResponseWriter, r *http.Request) {
_, cur := s.auditSites(r)
if cur == nil {
http.NotFound(w, r)
return
}
a, err := seo.LatestAudit(s.DB, cur.URL)
if err != nil {
s.serverError(w, err)
return
}
if a == nil || a.Status != "running" {
w.Header().Set("HX-Refresh", "true")
}
w.Write([]byte(""))
}
// weeklyAudits audits each website once a week.
func (s *Server) weeklyAudits(now time.Time) {
for _, site := range s.seoSites() {
if site.URL != "" && now.Sub(seo.LastDoneAudit(s.DB, site.URL)) > 7*24*time.Hour {
if a, _ := seo.LatestAudit(s.DB, site.URL); a != nil && a.Status == "failed" && now.Sub(a.StartedAt) < 24*time.Hour {
continue // don't retry a failing site more than daily
}
s.startAudit(site, false)
return // one at a time
}
}
}
+5
View File
@@ -161,6 +161,9 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest)
mux.HandleFunc("GET /seo", s.seoPage)
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
mux.HandleFunc("GET /seo/audit", s.seoAuditPage)
mux.HandleFunc("POST /seo/audit", s.seoAuditRun)
mux.HandleFunc("GET /seo/audit/status", s.seoAuditStatus)
mux.HandleFunc("GET /seo/report", s.seoReportPage)
mux.HandleFunc("POST /seo/report", s.seoReportWrite)
mux.HandleFunc("GET /settings/search", s.searchSettingsPage)
@@ -286,6 +289,7 @@ func (s *Server) loadTemplates() error {
// money shows cents as dollars: $1,234 or $12.50.
"money": money,
"num": seo.Thousands,
"cls": func(x100 int) float64 { return float64(x100) / 100 },
"dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
"pagePath": pagePath,
"stage": signals.StageLabel,
@@ -409,6 +413,7 @@ var flashes = map[string]string{
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
"synced": "Synced from Search Console.",
"report-written": "This week's report is written.",
"auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.",
"no-data": "There isn't two weeks of Search Console data yet.",
"reddit-connected": "Reddit is connected.",
"crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).",
+1 -1
View File
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
"/content/scheduled", "/content/published",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
+3
View File
@@ -431,3 +431,6 @@ table.runs { margin-top: 0.75rem; }
.message-body { white-space: pre-wrap; margin: 0.5rem 0; }
.message .reply blockquote { white-space: pre-wrap; margin: 0.25rem 0 0; padding: 0.5rem 0.75rem; border-left: 3px solid hsl(var(--border)); }
.status-line p { margin: 0.25rem 0; }
/* Long addresses in tables and check lists wrap instead of widening the page. */
.checks li, .list td .small, .list td a { overflow-wrap: anywhere; }
+1
View File
@@ -43,6 +43,7 @@
<a href="/seo/check" {{if eq $nav "seo/check"}}aria-current="page"{{end}}>Morning check</a>
<a href="/seo/report" {{if eq $nav "seo/report"}}aria-current="page"{{end}}>Monday report</a>
<a href="/seo" {{if eq $nav "seo/ranks"}}aria-current="page"{{end}}>What ranks</a>
<a href="/seo/audit" {{if eq $nav "seo/audit"}}aria-current="page"{{end}}>Audit</a>
</div>
{{end}}
{{if eq .ID "prospects"}}
@@ -7,6 +7,7 @@
<h3>Google Search Console</h3>
{{range .Fields}}{{template "key-field" (dict "F" . "Set" (index $d.Set .Name))}}{{end}}
<p class="help">Redirect URI to register on the OAuth client: <code id="google-redirect">{{.Redirect}}</code> <button type="button" class="link small" data-copy="google-redirect">Copy</button></p>
{{template "key-field" (dict "F" .Speed "Set" .SpeedSet)}}
{{if .Connected}}
<p class="ok">Connected{{with .Account}} as {{.}}{{end}}.</p>
<label class="check small"><input type="checkbox" name="remove:google.refresh_token"> disconnect</label>
+78
View File
@@ -0,0 +1,78 @@
{{define "content"}}{{with .Data}}{{$d := .}}
<div class="heading">
<h1>Audit</h1>
</div>
<p class="lede">Every page Supermarket can find on the site (the sitemap's, the ones Google shows, and the pages they link to, up to {{.MaxPages}}), checked for what keeps a page from ranking or being clicked, and whether AI assistants can read and cite the site. Issues on the pages that bring traffic come first: their clicks and impressions are from Search Console's last 90 days. It runs on its own once a week.</p>
{{if not .Sites}}
<section class="card empty"><p>Add your websites to the <a href="/settings/profile">profile</a> first.</p></section>
{{else}}
{{if gt (len .Sites) 1}}<nav class="tabs">{{range .Sites}}<a href="/seo/audit?site={{.Index}}" {{if eq .Index $d.Current.Index}}aria-current="page"{{end}}>{{.URL}}</a>{{end}}</nav>{{end}}
<form method="post" action="/seo/audit?site={{.Current.Index}}" class="card row wrap" data-busy="Starting…">
<span>{{.Current.URL}}{{if not .Current.Property}} <span class="muted small">(no Search Console property: issues aren't ranked by traffic)</span>{{end}}</span>
<label class="check small"><input type="checkbox" name="speed"> Also check the speed of the 5 busiest pages (PageSpeed Insights, about a minute each)</label>
<button type="submit" {{with .Audit}}{{if eq .Status "running"}}disabled{{end}}{{end}}>Audit now</button>
</form>
{{with .Audit}}
{{if eq .Status "running"}}
<section class="card" hx-get="/seo/audit/status?site={{$d.Current.Index}}" hx-trigger="every 4s" hx-swap="none">
<p><span class="badge scheduled">auditing…</span> Started {{ago .StartedAt}}. This page updates when it's done.</p>
</section>
{{else if eq .Status "failed"}}
<section class="card"><p><span class="badge failed">failed</span> {{ago .StartedAt}}: {{.Error}}</p></section>
{{else}}
{{$c := .Counts}}
<section class="card">
<p class="small muted">Audited {{ago .FinishedAt}} · {{len .Pages}} pages read</p>
<div class="funnel">
<a class="step" href="/seo/audit?site={{$d.Current.Index}}&amp;severity=error"><span class="label">Errors</span><strong>{{or (index $c "error") 0}}</strong></a>
<a class="step" href="/seo/audit?site={{$d.Current.Index}}&amp;severity=warning"><span class="label">Warnings</span><strong>{{or (index $c "warning") 0}}</strong></a>
<a class="step" href="/seo/audit?site={{$d.Current.Index}}&amp;severity=notice"><span class="label">Notices</span><strong>{{or (index $c "notice") 0}}</strong></a>
<a class="step" href="/seo/audit?site={{$d.Current.Index}}"><span class="label">All</span><strong>{{len .Issues}}</strong></a>
</div>
</section>
<div class="grid">
<section class="card">
<h2>AI visibility</h2>
<ul class="checks">{{range .Checks}}{{if eq .Group "ai"}}<li class="{{if .OK}}ok{{else}}bad{{end}}"><strong>{{.Title}}</strong>{{with .Detail}}<br><span class="small">{{.}}</span>{{end}}</li>{{end}}{{end}}</ul>
</section>
<section class="card">
<h2>The basics</h2>
<ul class="checks">{{range .Checks}}{{if eq .Group "basics"}}<li class="{{if .OK}}ok{{else}}bad{{end}}"><strong>{{.Title}}</strong>{{with .Detail}}<br><span class="small">{{.}}</span>{{end}}</li>{{end}}{{end}}</ul>
</section>
</div>
{{if .Speed}}
<h2>Speed (mobile)</h2>
<table class="list">
<thead><tr><th>Page</th><th>Largest paint</th><th>Interaction</th><th>Layout shift</th><th class="num">Lab score</th></tr></thead>
<tbody>{{range .Speed}}<tr><td><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a></td>
{{if .Error}}<td colspan="4" class="small error-text">{{.Error}}</td>
{{else if .Field}}<td>{{.LCP}} ms <span class="small muted">{{.LCPRating}}</span></td><td>{{.INP}} ms <span class="small muted">{{.INPRating}}</span></td><td>{{dec1 (cls .CLS)}} <span class="small muted">{{.CLSRating}}</span></td><td class="num">{{.Score}}</td>
{{else}}<td colspan="3" class="small muted">Not enough real visitors for Google's field data.</td><td class="num">{{.Score}}</td>{{end}}</tr>{{end}}</tbody>
</table>
{{end}}
<h2>Issues{{with $d.Severity}}: {{.}}s{{end}}</h2>
{{if $d.Shown}}
<table class="list">
<thead><tr><th></th><th>Issue</th><th>Page</th><th class="num">Clicks</th><th class="num">Impressions</th></tr></thead>
<tbody>{{range $d.Shown}}<tr>
<td><span class="badge {{if eq .Severity "error"}}failed{{else if eq .Severity "warning"}}scheduled{{end}}">{{.Severity}}</span></td>
<td><strong>{{.Title}}</strong>{{with .Detail}}<br><span class="small">{{truncate 400 .}}</span>{{end}}</td>
<td class="small"><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a></td>
<td class="num">{{if .Traffic.Impressions}}{{num .Traffic.Clicks}}{{else}}<span class="muted">·</span>{{end}}</td>
<td class="num">{{if .Traffic.Impressions}}{{num .Traffic.Impressions}}{{else}}<span class="muted">·</span>{{end}}</td>
</tr>{{end}}</tbody>
</table>
{{with $d.More}}<p class="help">And {{.}} more.</p>{{end}}
{{else}}<p class="help">No issues{{with $d.Severity}} of this kind{{end}}.</p>{{end}}
{{end}}
{{else}}
<section class="card empty"><p>Not audited yet. <em>Audit now</em> reads the site; it takes a few minutes.</p></section>
{{end}}
{{end}}
{{end}}{{end}}