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
+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"},
}