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
+13
View File
@@ -82,6 +82,19 @@ func (c *Client) NewPages(ctx context.Context, siteURL string, since time.Time)
return out, nil
}
// AllPages returns every page a sitemap lists, from the given sitemap
// address (or the site's /sitemap.xml when it's empty).
func (c *Client) AllPages(ctx context.Context, siteURL, mapURL string) ([]Page, error) {
u, err := url.Parse(strings.TrimSpace(siteURL))
if err != nil || u.Host == "" {
return nil, fmt.Errorf("%q isn't a website address", siteURL)
}
if mapURL == "" {
mapURL = u.Scheme + "://" + u.Host + "/sitemap.xml"
}
return c.read(ctx, mapURL, u.Host, 0)
}
func (c *Client) read(ctx context.Context, mapURL, host string, depth int) ([]Page, error) {
data, err := c.get(ctx, mapURL, maxSitemapBytes)
if err != nil {
+13
View File
@@ -404,6 +404,19 @@ CREATE TABLE seo_reports (
data TEXT NOT NULL, -- the report, as JSON
PRIMARY KEY (site, week_to)
);
`,
// 14: technical audits of the websites.
`
CREATE TABLE seo_audits (
id INTEGER PRIMARY KEY,
site TEXT NOT NULL, -- the website's address
status TEXT NOT NULL DEFAULT 'running', -- running, done, failed
started_at TEXT NOT NULL,
finished_at TEXT,
error TEXT NOT NULL DEFAULT '',
data TEXT NOT NULL DEFAULT '{}' -- pages, issues and checks, as JSON
);
CREATE INDEX seo_audits_by_site ON seo_audits (site, id);
`,
}
+1
View File
@@ -42,6 +42,7 @@ const (
GoogleClientID = "google.client_id"
GoogleClientSecret = "google.client_secret"
GoogleRefreshToken = "google.refresh_token" // Search Console, read-only
PageSpeedAPIKey = "pagespeed.api_key"
PlausibleAPIKey = "plausible.api_key"
StripeAPIKey = "stripe.api_key" // restricted, read-only
+774
View File
@@ -0,0 +1,774 @@
package seo
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strings"
"sync"
"time"
"golang.org/x/net/html"
"supermarket/internal/api/sitemap"
"supermarket/internal/db"
)
// MaxAuditPages is how many pages one audit reads.
const MaxAuditPages = 300
// maxExternalLinks is how many outside links an audit checks.
const maxExternalLinks = 150
// Severity of an issue.
const (
SevError = "error" // the page can't rank, or visitors hit a wall
SevWarning = "warning" // it ranks or gets clicked less than it could
SevNotice = "notice" // worth fixing when you're there
)
// Issue is one problem on one page.
type Issue struct {
Page string `json:"page"`
Code string `json:"code"`
Severity string `json:"severity"`
Title string `json:"title"` // what's wrong, short
Detail string `json:"detail"` // the specifics: the text, the length, the link
Traffic Numbers `json:"traffic"`
}
// PageReport is what the audit read on one page.
type PageReport struct {
URL string `json:"url"`
Status int `json:"status"`
FinalURL string `json:"final_url,omitempty"` // after redirects
Redirects int `json:"redirects,omitempty"`
Title string `json:"title"`
Description string `json:"description"`
H1 []string `json:"h1"`
Canonical string `json:"canonical"`
Noindex bool `json:"noindex"`
Lang string `json:"lang"`
OG bool `json:"og"`
JSONLD []string `json:"jsonld"` // @types
TextChars int `json:"text_chars"`
ImagesNoAlt int `json:"images_no_alt"`
HeadingSkips []string `json:"heading_skips"`
InSitemap bool `json:"in_sitemap"`
FromGSC bool `json:"from_gsc"`
Error string `json:"error,omitempty"`
internalLinks []string
externalLinks []string
}
// Check is a site-wide pass or fail, for AI visibility and the basics.
type SiteCheck struct {
Group string `json:"group"` // ai, basics
OK bool `json:"ok"`
Title string `json:"title"`
Detail string `json:"detail"`
}
// Audit is one run over a site.
type Audit struct {
ID int64 `json:"-"`
Site string `json:"site"` // the website's address
Property string `json:"property"` // its Search Console property, for traffic
Status string `json:"-"` // running, done, failed
StartedAt time.Time `json:"-"`
FinishedAt time.Time `json:"-"`
Error string `json:"-"`
Pages []PageReport `json:"pages"`
Issues []Issue `json:"issues"`
Checks []SiteCheck `json:"checks"`
Speed []Speed `json:"speed,omitempty"`
}
// Counts is how many issues of each severity.
func (a *Audit) Counts() map[string]int {
out := map[string]int{}
for _, i := range a.Issues {
out[i.Severity]++
}
return out
}
// Fetcher reads web pages; the audit's own HTTP client in the app, a fake
// server's in tests.
type Fetcher struct {
Client *http.Client
UserAgent string
Delay time.Duration // between requests, to be polite
}
// NewFetcher returns a fetcher that doesn't follow redirects itself, so
// they can be counted.
func NewFetcher(userAgent string) *Fetcher {
return &Fetcher{
Client: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
}},
UserAgent: userAgent,
Delay: 150 * time.Millisecond,
}
}
type fetched struct {
status int
final string
redirects int
ctype string
body []byte
}
// get fetches a URL, following up to 5 redirects and counting them.
func (f *Fetcher) get(ctx context.Context, u string, method string, limit int64) (*fetched, error) {
out := &fetched{final: u}
for i := 0; i < 6; i++ {
req, err := http.NewRequestWithContext(ctx, method, out.final, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", f.UserAgent)
res, err := f.Client.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode >= 300 && res.StatusCode < 400 {
res.Body.Close()
loc, err := res.Request.URL.Parse(res.Header.Get("Location"))
if err != nil || res.Header.Get("Location") == "" {
out.status = res.StatusCode
return out, nil
}
out.final = loc.String()
out.redirects++
continue
}
out.status = res.StatusCode
out.ctype = res.Header.Get("Content-Type")
if method == http.MethodGet && limit > 0 {
out.body, _ = io.ReadAll(io.LimitReader(res.Body, limit))
}
res.Body.Close()
return out, nil
}
return nil, errors.New("too many redirects")
}
// RunAudit reads a site and checks every page it can find: the sitemap's,
// Search Console's, and those linked from them. Issues are ranked by the
// page's clicks and impressions over the last 90 days.
func RunAudit(ctx context.Context, d *db.DB, f *Fetcher, siteURL, property string) (*Audit, error) {
base, err := url.Parse(strings.TrimRight(strings.TrimSpace(siteURL), "/") + "/")
if err != nil || base.Host == "" {
return nil, fmt.Errorf("%q isn't a website address", siteURL)
}
a := &Audit{Site: base.String(), Property: property}
host := strings.TrimPrefix(base.Hostname(), "www.")
// robots.txt, llms.txt and the sitemap.
var rob *robots
if r, err := f.get(ctx, base.Scheme+"://"+base.Host+"/robots.txt", http.MethodGet, 512<<10); err == nil && r.status == 200 {
rob = parseRobots(string(r.body))
}
llms, _ := f.get(ctx, base.Scheme+"://"+base.Host+"/llms.txt", http.MethodGet, 64<<10)
smc := sitemap.New(f.UserAgent)
inSitemap := map[string]bool{}
var mapErr error
maps := []string{""}
if rob != nil && len(rob.sitemaps) > 0 {
maps = rob.sitemaps
}
for _, m := range maps {
pages, err := smc.AllPages(ctx, base.String(), m)
if err != nil {
mapErr = err
continue
}
mapErr = nil
for _, p := range pages {
inSitemap[normalize(p.URL)] = true
}
}
// Pages: the home page, the sitemap's, Search Console's, then links.
traffic := map[string]Numbers{}
if property != "" {
if from, to, ok := period(d, property, RanksDays); ok {
if rows, err := pageNumbers(d, property, from, to); err == nil {
for _, p := range rows {
traffic[normalize(p.Page)] = p.Numbers
}
}
}
}
queue := []string{normalize(base.String())}
seen := map[string]bool{queue[0]: true}
add := func(u string) {
n := normalize(u)
if n == "" || seen[n] || len(seen) >= MaxAuditPages {
return
}
if p, err := url.Parse(n); err != nil || strings.TrimPrefix(p.Hostname(), "www.") != host {
return
}
seen[n] = true
queue = append(queue, n)
}
// Busiest pages first, so a big site's cut-off drops the quiet ones.
byTraffic := make([]string, 0, len(traffic))
for u := range traffic {
byTraffic = append(byTraffic, u)
}
slices.SortFunc(byTraffic, func(x, y string) int { return traffic[y].Impressions - traffic[x].Impressions })
for _, u := range byTraffic {
add(u)
}
mapped := make([]string, 0, len(inSitemap))
for u := range inSitemap {
mapped = append(mapped, u)
}
slices.Sort(mapped)
for _, u := range mapped {
add(u)
}
external := map[string][]string{} // link → pages linking to it
internalFrom := map[string][]string{}
for i := 0; i < len(queue); i++ {
if ctx.Err() != nil {
return nil, ctx.Err()
}
u := queue[i]
p := PageReport{URL: u, InSitemap: inSitemap[u], FromGSC: traffic[u].Impressions > 0}
pu, _ := url.Parse(u)
if rob != nil && !rob.allowed(f.UserAgent, pu.EscapedPath()) && !rob.allowed("Googlebot", pu.EscapedPath()) {
p.Error = "robots.txt blocks it"
a.Pages = append(a.Pages, p)
continue
}
r, err := f.get(ctx, u, http.MethodGet, 4<<20)
time.Sleep(f.Delay)
if err != nil {
p.Error = err.Error()
a.Pages = append(a.Pages, p)
continue
}
p.Status, p.Redirects = r.status, r.redirects
if r.redirects > 0 {
p.FinalURL = r.final
}
if r.status == 200 && strings.Contains(r.ctype, "html") {
readPage(&p, r.final, r.body)
for _, l := range p.internalLinks {
internalFrom[l] = append(internalFrom[l], u)
add(l)
}
for _, l := range p.externalLinks {
external[l] = append(external[l], u)
}
}
a.Pages = append(a.Pages, p)
}
// Broken links: internal ones from the pages read, external ones checked.
status := map[string]int{}
for _, p := range a.Pages {
status[p.URL] = p.Status
}
brokenOn := map[string][]string{} // page → its broken links
for link, from := range internalFrom {
if st, ok := status[link]; ok && st >= 400 {
for _, pg := range from {
brokenOn[pg] = append(brokenOn[pg], fmt.Sprintf("%s (%d)", link, st))
}
}
}
links := make([]string, 0, len(external))
for l := range external {
links = append(links, l)
}
slices.Sort(links)
if len(links) > maxExternalLinks {
links = links[:maxExternalLinks]
}
var mu sync.Mutex
sem := make(chan struct{}, 4)
var wg sync.WaitGroup
for _, l := range links {
wg.Add(1)
sem <- struct{}{}
go func(l string) {
defer wg.Done()
defer func() { <-sem }()
check := func() (*fetched, error) {
r, err := f.get(ctx, l, http.MethodHead, 0)
if err == nil && (r.status == 405 || r.status == 403 || r.status == 501) {
r, err = f.get(ctx, l, http.MethodGet, 1)
}
return r, err
}
r, err := check()
if err != nil || r.status >= 500 {
// One failure can be a blip: ask again before calling it broken.
time.Sleep(f.Delay * 10)
r, err = check()
}
if err != nil || r.status == 404 || r.status == 410 || r.status >= 500 {
why := "unreachable"
if err == nil {
why = fmt.Sprint(r.status)
}
mu.Lock()
for _, pg := range external[l] {
brokenOn[pg] = append(brokenOn[pg], fmt.Sprintf("%s (%s)", l, why))
}
mu.Unlock()
}
}(l)
}
wg.Wait()
for i := range a.Pages {
p := &a.Pages[i]
t := traffic[p.URL]
for _, is := range pageIssues(d, property, p, t, brokenOn[p.URL]) {
is.Page, is.Traffic = p.URL, t
a.Issues = append(a.Issues, is)
}
}
rank := map[string]int{SevError: 0, SevWarning: 1, SevNotice: 2}
slices.SortStableFunc(a.Issues, func(x, y Issue) int {
if rank[x.Severity] != rank[y.Severity] {
return rank[x.Severity] - rank[y.Severity]
}
if x.Traffic.Clicks != y.Traffic.Clicks {
return y.Traffic.Clicks - x.Traffic.Clicks
}
if x.Traffic.Impressions != y.Traffic.Impressions {
return y.Traffic.Impressions - x.Traffic.Impressions
}
return strings.Compare(x.Page+x.Code, y.Page+y.Code)
})
a.Checks = siteChecks(a, rob, llms, mapErr, len(inSitemap))
return a, nil
}
// normalize makes page addresses comparable: no fragment, no default
// "index.html", the same trailing slash as written.
func normalize(u string) string {
p, err := url.Parse(strings.TrimSpace(u))
if err != nil || (p.Scheme != "http" && p.Scheme != "https") || p.Host == "" {
return ""
}
p.Fragment = ""
p.Host = strings.ToLower(p.Host)
if p.Path == "" {
p.Path = "/"
}
p.Path = strings.TrimSuffix(p.Path, "index.html")
return p.String()
}
// readPage parses a page's HTML.
func readPage(p *PageReport, pageURL string, body []byte) {
base, _ := url.Parse(pageURL)
doc, err := html.Parse(strings.NewReader(string(body)))
if err != nil {
p.Error = "unreadable HTML: " + err.Error()
return
}
var text strings.Builder
lastLevel := 0
seenLinks := map[string]bool{}
var walk func(n *html.Node, inBody, skip bool)
walk = func(n *html.Node, inBody, skip bool) {
if n.Type == html.ElementNode {
switch n.Data {
case "script", "style", "noscript", "template", "svg":
if n.Data == "script" && attr(n, "type") == "application/ld+json" && n.FirstChild != nil {
p.JSONLD = append(p.JSONLD, ldTypes(n.FirstChild.Data)...)
}
return
case "html":
p.Lang = attr(n, "lang")
case "body":
inBody = true
case "title":
if p.Title == "" && n.FirstChild != nil {
p.Title = strings.Join(strings.Fields(n.FirstChild.Data), " ")
}
case "meta":
name := strings.ToLower(attr(n, "name"))
prop := strings.ToLower(attr(n, "property"))
switch {
case name == "description":
p.Description = strings.Join(strings.Fields(attr(n, "content")), " ")
case name == "robots" || name == "googlebot":
if strings.Contains(strings.ToLower(attr(n, "content")), "noindex") {
p.Noindex = true
}
case strings.HasPrefix(prop, "og:"):
p.OG = true
}
case "link":
if strings.EqualFold(attr(n, "rel"), "canonical") {
if c, err := base.Parse(attr(n, "href")); err == nil {
p.Canonical = normalize(c.String())
}
}
case "h1", "h2", "h3", "h4", "h5", "h6":
level := int(n.Data[1] - '0')
if n.Data == "h1" {
p.H1 = append(p.H1, strings.Join(strings.Fields(nodeText(n)), " "))
}
if lastLevel > 0 && level > lastLevel+1 {
p.HeadingSkips = append(p.HeadingSkips, fmt.Sprintf("h%d → h%d", lastLevel, level))
}
lastLevel = level
case "img":
if _, has := attrOK(n, "alt"); !has {
p.ImagesNoAlt++
}
case "a":
href := attr(n, "href")
if href == "" || strings.HasPrefix(href, "#") || strings.HasPrefix(href, "mailto:") || strings.HasPrefix(href, "tel:") || strings.HasPrefix(href, "javascript:") {
break
}
l, err := base.Parse(href)
if err != nil {
break
}
nl := normalize(l.String())
if nl == "" || seenLinks[nl] {
break
}
seenLinks[nl] = true
if strings.TrimPrefix(l.Hostname(), "www.") == strings.TrimPrefix(base.Hostname(), "www.") {
if !strings.HasSuffix(strings.ToLower(l.Path), ".pdf") {
p.internalLinks = append(p.internalLinks, nl)
}
} else {
p.externalLinks = append(p.externalLinks, nl)
}
}
}
if n.Type == html.TextNode && inBody && !skip {
text.WriteString(n.Data)
text.WriteByte(' ')
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c, inBody, skip)
}
}
walk(doc, false, false)
p.TextChars = len([]rune(strings.Join(strings.Fields(text.String()), " ")))
}
func attr(n *html.Node, key string) string {
v, _ := attrOK(n, key)
return v
}
func attrOK(n *html.Node, key string) (string, bool) {
for _, a := range n.Attr {
if strings.EqualFold(a.Key, key) {
return a.Val, true
}
}
return "", false
}
func nodeText(n *html.Node) string {
var b strings.Builder
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.TextNode {
b.WriteString(n.Data)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(n)
return b.String()
}
// ldTypes are the @type values in a JSON-LD block.
func ldTypes(raw string) []string {
var v any
if err := json.Unmarshal([]byte(raw), &v); err != nil {
return []string{"(invalid JSON-LD)"}
}
var out []string
var walk func(any)
walk = func(v any) {
switch x := v.(type) {
case map[string]any:
switch t := x["@type"].(type) {
case string:
out = append(out, t)
case []any:
for _, s := range t {
if s, ok := s.(string); ok {
out = append(out, s)
}
}
}
if g, ok := x["@graph"]; ok {
walk(g)
}
case []any:
for _, e := range x {
walk(e)
}
}
}
walk(v)
return out
}
// pageIssues finds one page's problems.
func pageIssues(d *db.DB, property string, p *PageReport, t Numbers, broken []string) []Issue {
var out []Issue
add := func(code, sev, title, detail string) {
out = append(out, Issue{Code: code, Severity: sev, Title: title, Detail: detail})
}
switch {
case p.Error != "":
sev := SevWarning
if t.Impressions > 0 {
sev = SevError
}
add("unreachable", sev, "Couldn't be read", p.Error)
return out
case p.Status >= 400:
add("status", SevError, fmt.Sprintf("Answers %d", p.Status), "Visitors and Google get an error page.")
return out
case p.Status != 200:
return out
}
if p.Redirects > 0 {
sev := SevNotice
if p.InSitemap || p.Redirects > 1 {
sev = SevWarning
}
detail := "Redirects to " + p.FinalURL
if p.InSitemap {
detail += "; the sitemap should list the final address."
}
add("redirect", sev, fmt.Sprintf("%d %s", p.Redirects, map[bool]string{true: "redirect", false: "redirects"}[p.Redirects == 1]), detail)
}
if p.Title == "" && p.Error == "" && p.TextChars == 0 && len(p.H1) == 0 {
return out // not an HTML page we could read
}
if p.Noindex {
sev := SevNotice
if t.Impressions > 0 || p.InSitemap {
sev = SevError
}
add("noindex", sev, "Tells search engines not to index it", "A robots meta tag says noindex.")
}
switch tp := TitlePixels(p.Title); {
case p.Title == "":
add("title-missing", SevError, "No title", "")
case tp > TitleMaxPixels:
add("title-long", SevWarning, "Title too long", fmt.Sprintf("“%s”: %d characters, about %d px; Google cuts it off around %d px.", p.Title, len([]rune(p.Title)), tp, TitleMaxPixels))
case len([]rune(p.Title)) < 20:
add("title-short", SevNotice, "Title very short", fmt.Sprintf("“%s”: %d characters. A specific title gets clicked more.", p.Title, len([]rune(p.Title))))
}
switch dp := DescriptionPixels(p.Description); {
case p.Description == "":
add("description-missing", SevWarning, "No meta description", "Google writes its own snippet from the page.")
case dp > DescriptionMaxPixels:
add("description-long", SevNotice, "Meta description too long", fmt.Sprintf("%d characters, about %d px; Google cuts it off around %d px.", len([]rune(p.Description)), dp, DescriptionMaxPixels))
case len([]rune(p.Description)) < 50:
add("description-short", SevNotice, "Meta description very short", fmt.Sprintf("“%s”", p.Description))
}
switch len(p.H1) {
case 0:
add("h1-missing", SevWarning, "No H1 heading", "")
case 1:
default:
add("h1-many", SevNotice, fmt.Sprintf("%d H1 headings", len(p.H1)), strings.Join(p.H1, " · "))
}
if len(p.HeadingSkips) > 0 {
add("heading-order", SevNotice, "Headings skip a level", strings.Join(p.HeadingSkips, ", "))
}
if p.Canonical == "" {
add("canonical-missing", SevNotice, "No canonical address", "")
} else if p.Canonical != p.URL && p.Canonical != normalize(p.FinalURL) {
add("canonical-other", SevWarning, "Canonical points elsewhere", "Google is told the real page is "+p.Canonical+".")
}
if p.ImagesNoAlt > 0 {
add("alt-missing", SevNotice, fmt.Sprintf("%d %s without alt text", p.ImagesNoAlt, map[bool]string{true: "image", false: "images"}[p.ImagesNoAlt == 1]), "")
}
if !p.OG {
add("og-missing", SevNotice, "No Open Graph tags", "Shared on social networks, it shows without a proper title and picture.")
}
if len(p.JSONLD) == 0 {
add("jsonld-missing", SevNotice, "No structured data (JSON-LD)", "Search engines and AI assistants understand pages with it better.")
} else if slices.Contains(p.JSONLD, "(invalid JSON-LD)") {
add("jsonld-invalid", SevWarning, "Structured data that isn't valid JSON", "")
}
if p.TextChars < 200 {
add("thin", SevNotice, "Little text without JavaScript", fmt.Sprintf("%d characters of text in the HTML; crawlers that don't run JavaScript, like most AI ones, see almost nothing.", p.TextChars))
}
if !p.InSitemap && (p.FromGSC || t.Impressions > 0) {
add("not-in-sitemap", SevNotice, "Not in the sitemap", "Google shows it, but the sitemap doesn't list it.")
}
if len(broken) > 0 {
slices.Sort(broken)
add("broken-links", SevWarning, fmt.Sprintf("%d broken %s", len(broken), map[bool]string{true: "link", false: "links"}[len(broken) == 1]), strings.Join(broken, ", "))
}
// The cheapest fix there is: the title doesn't say what people search.
if property != "" && p.Title != "" && t.Impressions >= 50 {
if from, to, ok := period(d, property, RanksDays); ok {
pick := Pick{Page: p.URL, Numbers: t}
if mainQuery(d, property, from, to, &pick) == nil && pick.MainQuery != "" && pick.MainShare >= 30 && covers(p.Title, pick.MainQuery) < 0.75 {
add("title-query", SevWarning, "Its title doesn't say what people search",
fmt.Sprintf("%.0f%% of its impressions come from “%s” (position %.1f), but the title is “%s”.", pick.MainShare, pick.MainQuery, pick.MainPos, p.Title))
}
}
}
return out
}
// siteChecks are the site-wide checks, AI visibility first.
func siteChecks(a *Audit, rob *robots, llms *fetched, mapErr error, mapped int) []SiteCheck {
var out []SiteCheck
var blocked, allowed []string
for _, c := range AICrawlers {
if rob != nil && !rob.allowed(c.Agent, "/") {
blocked = append(blocked, c.Agent+" ("+c.For+")")
} else {
allowed = append(allowed, c.Agent)
}
}
if len(blocked) == 0 {
out = append(out, SiteCheck{"ai", true, "AI crawlers may read the site", "robots.txt blocks none of: " + strings.Join(allowed, ", ") + "."})
} else {
out = append(out, SiteCheck{"ai", false, "robots.txt blocks some AI crawlers", "Blocked: " + strings.Join(blocked, "; ") + ". If you want to be cited by these assistants, allow them."})
}
if llms != nil && llms.status == 200 && len(strings.TrimSpace(string(llms.body))) > 0 {
out = append(out, SiteCheck{"ai", true, "llms.txt is there", "A short guide to the site for AI assistants."})
} else {
out = append(out, SiteCheck{"ai", false, "No llms.txt", "A /llms.txt file (a Markdown summary with links to the key pages) helps AI assistants describe and cite you. It's a proposal, not a standard: cheap to add."})
}
var html, ld, thin int
var org bool
for _, p := range a.Pages {
if p.Status != 200 || (p.Title == "" && p.TextChars == 0) {
continue
}
html++
if len(p.JSONLD) > 0 {
ld++
}
if p.TextChars < 200 {
thin++
}
for _, t := range p.JSONLD {
if t == "Organization" || t == "Corporation" || t == "LocalBusiness" || t == "WebSite" {
org = true
}
}
}
if html > 0 {
out = append(out, SiteCheck{"ai", ld*2 >= html, fmt.Sprintf("Structured data on %d of %d pages", ld, html),
"JSON-LD (Article, Product, FAQ, Organization…) tells search engines and AI assistants what a page is about."})
out = append(out, SiteCheck{"ai", org, map[bool]string{true: "The site says who you are", false: "No Organization or WebSite data"}[org],
"Organization or WebSite structured data names the company, its logo and its profiles, so assistants get it right."})
out = append(out, SiteCheck{"ai", thin == 0, fmt.Sprintf("%d of %d pages readable without JavaScript", html-thin, html),
"Most AI crawlers don't run JavaScript: the text must be in the HTML."})
}
switch {
case mapErr != nil:
out = append(out, SiteCheck{"basics", false, "No readable sitemap", mapErr.Error()})
default:
out = append(out, SiteCheck{"basics", true, fmt.Sprintf("Sitemap lists %d pages", mapped), ""})
}
if rob == nil {
out = append(out, SiteCheck{"basics", false, "No robots.txt", "Not required, but it's where crawlers look for the sitemap."})
} else if len(rob.sitemaps) == 0 {
out = append(out, SiteCheck{"basics", false, "robots.txt doesn't name the sitemap", "Add a line: Sitemap: https://…/sitemap.xml"})
} else {
out = append(out, SiteCheck{"basics", true, "robots.txt names the sitemap", strings.Join(rob.sitemaps, ", ")})
}
return out
}
// --- Storing audits ---
// StartAudit records that an audit began.
func StartAudit(d *db.DB, site string, now time.Time) (int64, error) {
res, err := d.Exec(`INSERT INTO seo_audits (site, status, started_at) VALUES (?, 'running', ?)`, site, now.UTC().Format(time.RFC3339))
if err != nil {
return 0, err
}
return res.LastInsertId()
}
// FinishAudit stores an audit's result, or its error.
func FinishAudit(d *db.DB, id int64, a *Audit, runErr error, now time.Time) error {
status, data, msg := "done", "{}", ""
if runErr != nil {
status, msg = "failed", runErr.Error()
} else {
raw, err := json.Marshal(a)
if err != nil {
return err
}
data = string(raw)
}
_, err := d.Exec(`UPDATE seo_audits SET status = ?, finished_at = ?, error = ?, data = ? WHERE id = ?`,
status, now.UTC().Format(time.RFC3339), msg, data, id)
return err
}
// RecoverAudits marks audits a stopped app left running as failed.
func RecoverAudits(d *db.DB) error {
_, err := d.Exec(`UPDATE seo_audits SET status = 'failed', error = 'Supermarket stopped during the audit' WHERE status = 'running'`)
return err
}
// LatestAudit is a site's newest audit (running, done or failed), or nil.
func LatestAudit(d *db.DB, site string) (*Audit, error) {
var a Audit
var started string
var finished sql.NullString
var data string
err := d.QueryRow(`SELECT id, status, started_at, finished_at, error, data FROM seo_audits WHERE site = ? ORDER BY id DESC LIMIT 1`, site).
Scan(&a.ID, &a.Status, &started, &finished, &a.Error, &data)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
if a.Status == "done" {
if err := json.Unmarshal([]byte(data), &a); err != nil {
return nil, err
}
}
a.StartedAt, _ = time.Parse(time.RFC3339, started)
if finished.Valid {
a.FinishedAt, _ = time.Parse(time.RFC3339, finished.String)
}
return &a, nil
}
// LastDoneAudit is when a site was last audited successfully.
func LastDoneAudit(d *db.DB, site string) time.Time {
var s sql.NullString
_ = d.QueryRow(`SELECT max(finished_at) FROM seo_audits WHERE site = ? AND status = 'done'`, site).Scan(&s)
t, _ := time.Parse(time.RFC3339, s.String)
return t
}
+155
View File
@@ -0,0 +1,155 @@
package seo
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestRobots(t *testing.T) {
r := parseRobots("User-agent: *\nDisallow: /private/\nAllow: /private/ok$\n\nUser-agent: GPTBot\nUser-agent: CCBot\nDisallow: /\n\nUser-agent: ClaudeBot\nDisallow:\n\nSitemap: https://x.example/sitemap.xml\n")
for _, c := range []struct {
agent, path string
want bool
}{
{"Googlebot", "/", true}, {"Googlebot", "/private/x", false}, {"Googlebot", "/private/ok", true},
{"GPTBot", "/", false}, {"CCBot", "/blog", false}, {"ClaudeBot", "/private/x", true},
} {
if got := r.allowed(c.agent, c.path); got != c.want {
t.Errorf("%s %s: %v", c.agent, c.path, got)
}
}
if len(r.sitemaps) != 1 {
t.Errorf("sitemaps: %v", r.sitemaps)
}
}
func TestPixelsAndCovers(t *testing.T) {
if w := TitlePixels("Whey Protein Price Comparison: Cost per 20 g of Protein"); w < 450 || w > 600 {
t.Errorf("title width: %d", w)
}
if TitlePixels(strings.Repeat("W", 40)) <= TitleMaxPixels {
t.Error("40 W's fit in a title")
}
if covers("Best whey protein for bulking", "whey protein price comparison") >= 0.75 {
t.Error("a bulking title covers a price search")
}
if covers("Nextcloud hosting: our prices", "nextcloud hosting price") < 1 {
t.Error("a matching title doesn't cover its search")
}
}
func TestAudit(t *testing.T) {
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
page := func(head, body string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, `<!doctype html><html lang="en"><head>%s</head><body>%s</body></html>`, head, body)
}
long := strings.Repeat("Words people can read without JavaScript. ", 10)
switch r.URL.Path {
case "/robots.txt":
fmt.Fprintf(w, "User-agent: *\nDisallow: /admin/\n\nUser-agent: GPTBot\nDisallow: /\n\nSitemap: %s/sitemap.xml\n", srv.URL)
case "/sitemap.xml":
fmt.Fprintf(w, `<urlset><url><loc>%[1]s/</loc></url><url><loc>%[1]s/bulking/</loc></url><url><loc>%[1]s/old/</loc></url><url><loc>%[1]s/gone/</loc></url></urlset>`, srv.URL)
case "/":
page(`<title>Whey reviews and price comparisons, by people who buy it</title><meta name="description" content="We compare whey protein prices per 20 g every month, with the method and the date, so you can buy the best value tub.">
<link rel="canonical" href="`+srv.URL+`/"><meta property="og:title" content="x"><script type="application/ld+json">{"@context":"https://schema.org","@type":"Organization","name":"W"}</script>`,
`<h1>Whey</h1><h2>Prices</h2><p>`+long+`</p><a href="/bulking/">bulk</a><a href="/missing/">x</a><a href="/admin/">a</a><a href="`+srv.URL+`/ext-dead">dead</a><img src="a.png">`)
case "/bulking/":
page(`<title>Best whey protein for bulking</title>`, `<h1>Bulking</h1><h1>Again</h1><h2>a</h2><h4>b</h4><p>short</p>`)
case "/old/":
http.Redirect(w, r, "/bulking/", http.StatusMovedPermanently)
case "/gone/", "/missing/", "/ext-dead":
http.NotFound(w, r)
case "/hidden/":
page(`<title>Hidden page with a perfectly fine title here</title><meta name="robots" content="noindex">`, `<h1>Hidden</h1><p>`+long+`</p>`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
d := openDB(t)
site := "sc-domain:whey.example"
// Search Console: /bulking/ is shown for a price search; /hidden/ is
// shown but marked noindex and not linked.
week(t, d, site, "2026-11-13", row{clicks: 10, impr: 2600, pos: 7}, []row{
{srv.URL + "/", "whey", 10, 100, 2},
{srv.URL + "/bulking/", "whey protein price comparison", 0, 2244, 7.6},
{srv.URL + "/bulking/", "bulking whey", 0, 232, 12},
{srv.URL + "/hidden/", "hidden", 0, 60, 30},
})
d.PutJSON(throughKey(site), "2026-11-19")
f := NewFetcher("SupermarketTest")
f.Delay = 0
a, err := RunAudit(context.Background(), d, f, srv.URL, site)
if err != nil {
t.Fatal(err)
}
pages := map[string]PageReport{}
for _, p := range a.Pages {
pages[strings.TrimPrefix(p.URL, srv.URL)] = p
}
if _, ok := pages["/admin/"]; !ok || pages["/admin/"].Error != "robots.txt blocks it" {
t.Errorf("admin: %+v", pages["/admin/"])
}
if p := pages["/old/"]; p.Redirects != 1 || p.Status != 200 {
t.Errorf("old: %+v", p)
}
if p := pages["/"]; p.Lang != "en" || !p.OG || len(p.JSONLD) != 1 || p.ImagesNoAlt != 1 || p.TextChars < 200 {
t.Errorf("home: %+v", p)
}
issues := map[string]Issue{}
for _, is := range a.Issues {
issues[strings.TrimPrefix(is.Page, srv.URL)+" "+is.Code] = is
}
for _, want := range []string{
"/bulking/ title-query", "/bulking/ h1-many", "/bulking/ heading-order", "/bulking/ description-missing", "/bulking/ thin",
"/old/ redirect", "/gone/ status", "/missing/ status", "/hidden/ noindex", "/hidden/ not-in-sitemap", "/ broken-links", "/ alt-missing",
} {
if _, ok := issues[want]; !ok {
t.Errorf("missing issue %q", want)
}
}
tq := issues["/bulking/ title-query"]
if tq.Severity != SevWarning || !strings.Contains(tq.Detail, "91% of its impressions come from “whey protein price comparison”") || tq.Traffic.Impressions != 2476 {
t.Errorf("title-query: %+v", tq)
}
if b := issues["/ broken-links"]; !strings.Contains(b.Detail, "/missing/ (404)") || !strings.Contains(b.Detail, "/ext-dead") {
t.Errorf("broken links: %+v", b)
}
if issues["/hidden/ noindex"].Severity != SevError {
t.Error("noindex on a page Google shows isn't an error")
}
// Ranked by severity, then traffic: the first warning is on the page with
// the most clicks or impressions.
if a.Issues[0].Severity != SevError {
t.Errorf("first issue: %+v", a.Issues[0])
}
checks := map[string]SiteCheck{}
for _, c := range a.Checks {
checks[c.Title] = c
}
if c, ok := checks["robots.txt blocks some AI crawlers"]; !ok || !strings.Contains(c.Detail, "GPTBot") || strings.Contains(c.Detail, "ClaudeBot") {
t.Errorf("AI crawlers: %+v", a.Checks)
}
if c := checks["No llms.txt"]; c.OK {
t.Error("llms.txt found")
}
if !checks["The site says who you are"].OK || !checks["robots.txt names the sitemap"].OK {
t.Errorf("checks: %+v", a.Checks)
}
id, _ := StartAudit(d, srv.URL+"/", now)
if err := FinishAudit(d, id, a, nil, now); err != nil {
t.Fatal(err)
}
got, err := LatestAudit(d, srv.URL+"/")
if err != nil || got.Status != "done" || len(got.Issues) != len(a.Issues) || LastDoneAudit(d, srv.URL+"/").IsZero() {
t.Errorf("stored: %+v %v", got, err)
}
}
+105
View File
@@ -0,0 +1,105 @@
package seo
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
// Speed is a page's Core Web Vitals from PageSpeed Insights: real Chrome
// users' numbers when Google has enough of them, and the lab score.
type Speed struct {
Page string `json:"page"`
Field bool `json:"field"` // real users' data exists
LCP int `json:"lcp_ms"`
INP int `json:"inp_ms"`
CLS int `json:"cls_x100"` // CLS × 100
Overall string `json:"overall"` // FAST, AVERAGE, SLOW
Score int `json:"score"` // Lighthouse performance, 0 to 100
Error string `json:"error,omitempty"`
}
// PageSpeedURL is the API's address; tests replace it.
var PageSpeedURL = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"
// CheckSpeed asks PageSpeed Insights about a page, on mobile. The key is
// optional; without one Google allows only a few requests.
func CheckSpeed(ctx context.Context, page, key string) Speed {
s := Speed{Page: page}
q := url.Values{"url": {page}, "strategy": {"mobile"}, "category": {"performance"}}
if key != "" {
q.Set("key", key)
}
ctx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, PageSpeedURL+"?"+q.Encode(), nil)
if err != nil {
s.Error = err.Error()
return s
}
res, err := http.DefaultClient.Do(req)
if err != nil {
s.Error = err.Error()
return s
}
defer res.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(res.Body, 16<<20))
if res.StatusCode != http.StatusOK {
var e struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
_ = json.Unmarshal(raw, &e)
s.Error = fmt.Sprintf("PageSpeed Insights: HTTP %d %s", res.StatusCode, e.Error.Message)
return s
}
var out struct {
Loading struct {
Metrics map[string]struct {
Percentile int `json:"percentile"`
} `json:"metrics"`
Overall string `json:"overall_category"`
} `json:"loadingExperience"`
Lighthouse struct {
Categories struct {
Performance struct {
Score float64 `json:"score"`
} `json:"performance"`
} `json:"categories"`
} `json:"lighthouseResult"`
}
if err := json.Unmarshal(raw, &out); err != nil {
s.Error = err.Error()
return s
}
m := out.Loading.Metrics
if len(m) > 0 {
s.Field = true
s.LCP = m["LARGEST_CONTENTFUL_PAINT_MS"].Percentile
s.INP = m["INTERACTION_TO_NEXT_PAINT"].Percentile
s.CLS = m["CUMULATIVE_LAYOUT_SHIFT_SCORE"].Percentile
s.Overall = out.Loading.Overall
}
s.Score = int(out.Lighthouse.Categories.Performance.Score*100 + 0.5)
return s
}
// Good, needs improvement or poor, by Google's Core Web Vitals limits.
func (s Speed) LCPRating() string { return rate(float64(s.LCP), 2500, 4000) }
func (s Speed) INPRating() string { return rate(float64(s.INP), 200, 500) }
func (s Speed) CLSRating() string { return rate(float64(s.CLS)/100, 0.1, 0.25) }
func rate(v, good, poor float64) string {
switch {
case v <= good:
return "good"
case v <= poor:
return "needs improvement"
}
return "poor"
}
+2 -2
View File
@@ -63,7 +63,7 @@ func Through(d *db.DB, site string) string {
// that, from a few days before the last final day.
func Sync(ctx context.Context, d *db.DB, c *gsc.Client, site string, now time.Time) (*SyncResult, error) {
res := &SyncResult{Site: site, At: now}
err := sync(ctx, d, c, site, now, res)
err := syncSite(ctx, d, c, site, now, res)
if err != nil {
res.Error = err.Error()
}
@@ -73,7 +73,7 @@ func Sync(ctx context.Context, d *db.DB, c *gsc.Client, site string, now time.Ti
return res, err
}
func sync(ctx context.Context, d *db.DB, c *gsc.Client, site string, now time.Time, res *SyncResult) error {
func syncSite(ctx context.Context, d *db.DB, c *gsc.Client, site string, now time.Time, res *SyncResult) error {
today := now.UTC().Truncate(24 * time.Hour)
from := today.AddDate(0, 0, -historyDays)
if t := Through(d, site); t != "" {
+196
View File
@@ -0,0 +1,196 @@
package seo
import (
"strings"
"unicode"
)
// Arial's character widths, in thousandths of an em, for printable ASCII
// (32 to 126). Google shows titles in Arial at about 20px and descriptions
// at about 14px, so these give a title's width as it shows in results.
var arial = [95]int{
278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, // space to /
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, // 0-9
278, 278, 584, 584, 584, 556, 1015, // : to @
667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, // A-O
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, // P-Z
278, 278, 278, 469, 556, 333, // [ to `
556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, // a-o
556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, // p-z
334, 260, 334, 584, // { to ~
}
// widthAt is a text's width in pixels at a font size, in Arial. Characters
// outside ASCII count as a digit's width; wide scripts count double.
func widthAt(s string, px float64) int {
var units int
for _, r := range s {
switch {
case r >= 32 && r <= 126:
units += arial[r-32]
case unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hiragana, r) || unicode.Is(unicode.Katakana, r) || unicode.Is(unicode.Hangul, r):
units += 1000
default:
units += 556
}
}
return int(float64(units)*px/1000 + 0.5)
}
// TitlePixels is about how wide a title shows in Google's results.
func TitlePixels(s string) int { return widthAt(s, 20) }
// DescriptionPixels is about how wide a meta description shows.
func DescriptionPixels(s string) int { return widthAt(s, 14) }
// Where Google cuts titles and descriptions off on desktop, about.
const (
TitleMaxPixels = 600
DescriptionMaxPixels = 920
)
var stopWords = map[string]bool{
"the": true, "and": true, "for": true, "with": true, "you": true, "your": true, "are": true, "how": true,
"what": true, "can": true, "that": true, "this": true, "from": true, "into": true, "les": true, "des": true,
"une": true, "der": true, "die": true, "das": true, "und": true, "best": false,
}
// words are a text's significant words, lower case.
func words(s string) []string {
var out []string
for _, w := range strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) }) {
if len([]rune(w)) >= 3 && !stopWords[w] {
out = append(out, w)
}
}
return out
}
// covers is the share of a query's significant words a title contains
// (as a word, or the start of one: "host" covers "hosting").
func covers(title, query string) float64 {
q := words(query)
if len(q) == 0 {
return 1
}
t := words(title)
hit := 0
for _, w := range q {
for _, tw := range t {
if tw == w || strings.HasPrefix(tw, w) || strings.HasPrefix(w, tw) && len(tw) >= 4 {
hit++
break
}
}
}
return float64(hit) / float64(len(q))
}
// --- robots.txt ---
// robots is a robots.txt's rules by user agent (lower case; "*" for all).
type robots struct {
groups map[string][]rule
sitemaps []string
found bool
}
type rule struct {
allow bool
path string
}
func parseRobots(txt string) *robots {
r := &robots{groups: map[string][]rule{}, found: true}
var agents []string
inRules := false
for _, line := range strings.Split(txt, "\n") {
if i := strings.Index(line, "#"); i >= 0 {
line = line[:i]
}
k, v, ok := strings.Cut(line, ":")
if !ok {
continue
}
k, v = strings.ToLower(strings.TrimSpace(k)), strings.TrimSpace(v)
switch k {
case "user-agent":
if inRules {
agents, inRules = nil, false
}
agents = append(agents, strings.ToLower(v))
case "allow", "disallow":
inRules = true
if k == "disallow" && v == "" {
// "Disallow:" with nothing allows everything; it still
// makes the group exist.
for _, a := range agents {
r.groups[a] = append(r.groups[a], rule{allow: true, path: "/"})
}
continue
}
for _, a := range agents {
r.groups[a] = append(r.groups[a], rule{allow: k == "allow", path: v})
}
case "sitemap":
r.sitemaps = append(r.sitemaps, v)
}
}
return r
}
// allowed reports whether an agent may fetch a path: the group for its name
// if there is one, else "*"; the longest matching rule wins, Allow on ties.
func (r *robots) allowed(agent, path string) bool {
if r == nil {
return true
}
rules, ok := r.groups[strings.ToLower(agent)]
if !ok {
rules = r.groups["*"]
}
best, allow := -1, true
for _, ru := range rules {
if ru.path == "" || !matchPath(ru.path, path) {
continue
}
if l := len(ru.path); l > best || (l == best && ru.allow) {
best, allow = l, ru.allow
}
}
return allow
}
// matchPath matches a robots.txt path pattern, with * and a final $.
func matchPath(pattern, path string) bool {
end := strings.HasSuffix(pattern, "$")
pattern = strings.TrimSuffix(pattern, "$")
parts := strings.Split(pattern, "*")
if !strings.HasPrefix(path, parts[0]) {
return false
}
rest := path[len(parts[0]):]
for _, p := range parts[1:] {
i := strings.Index(rest, p)
if i < 0 {
return false
}
rest = rest[i+len(p):]
}
return !end || rest == "" || strings.HasSuffix(pattern, "*")
}
// AICrawlers are the crawlers AI assistants and their training use, with
// what each is for.
var AICrawlers = []struct{ Agent, For string }{
{"GPTBot", "OpenAI's training crawler"},
{"OAI-SearchBot", "ChatGPT search"},
{"ChatGPT-User", "ChatGPT reading a page for a user"},
{"ClaudeBot", "Anthropic's crawler"},
{"Claude-User", "Claude reading a page for a user"},
{"Claude-SearchBot", "Claude search"},
{"PerplexityBot", "Perplexity"},
{"Google-Extended", "Gemini and Google's AI training"},
{"Applebot-Extended", "Apple Intelligence"},
{"CCBot", "Common Crawl, used by many models"},
}
+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}}