From 43a7b4212611378ca37b16558c809c446d1ea9a5 Mon Sep 17 00:00:00 2001 From: David Young Date: Sun, 22 Nov 2026 07:53:10 -0700 Subject: [PATCH] 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 --- PLAN.md | 27 + README.md | 12 + TEST.md | 18 + go.mod | 7 +- go.sum | 20 +- internal/api/sitemap/sitemap.go | 13 + internal/db/db.go | 13 + internal/secrets/secrets.go | 1 + internal/seo/audit.go | 774 +++++++++++++++++++++ internal/seo/audit_test.go | 155 +++++ internal/seo/speed.go | 105 +++ internal/seo/sync.go | 4 +- internal/seo/text.go | 196 ++++++ internal/web/audit_test.go | 64 ++ internal/web/seo.go | 161 ++++- internal/web/server.go | 5 + internal/web/server_test.go | 2 +- internal/web/static/app.css | 3 + internal/web/templates/layout.html | 1 + internal/web/templates/search-engines.html | 1 + internal/web/templates/seo-audit.html | 78 +++ 21 files changed, 1643 insertions(+), 17 deletions(-) create mode 100644 internal/seo/audit.go create mode 100644 internal/seo/audit_test.go create mode 100644 internal/seo/speed.go create mode 100644 internal/seo/text.go create mode 100644 internal/web/audit_test.go create mode 100644 internal/web/templates/seo-audit.html diff --git a/PLAN.md b/PLAN.md index ae3a236..7569d85 100644 --- a/PLAN.md +++ b/PLAN.md @@ -783,6 +783,33 @@ into `main`. - One more check, from job 3: a page's biggest query compared with its title. When they don't say the same thing, that's the cheapest fix there is. + - **Built 2026-11-22** (schema 14: `seo_audits`): + - `seo.RunAudit` reads robots.txt, llms.txt and the sitemaps. It then + reads up to 300 pages, in this order: the busiest pages from Search + Console, the sitemap's pages, then pages found through internal + links. A page robots.txt disallows is skipped. + - Redirects are counted. It checks up to 150 outside links (HEAD, + with GET as a fallback). + - Pages are parsed with `golang.org/x/net/html`. + - Issues have a severity: + - Error: 4xx/5xx, noindex on a page Google shows or the sitemap + lists, no title. + - Warning: title over about 600 px (Arial widths), no description, + no H1, a canonical pointing elsewhere, broken links, invalid + JSON-LD, and a title that covers under 3/4 of the main search's + words when that search brings 30%+ of the impressions. + - Notice: the rest. + - Issues are sorted by severity, then the page's 90-day clicks and + impressions. + - The AI checks: AI crawlers in robots.txt (GPTBot, OAI-SearchBot, + ChatGPT-User, ClaudeBot, Claude-User, Claude-SearchBot, + PerplexityBot, Google-Extended, Applebot-Extended, CCBot), + llms.txt, JSON-LD coverage, Organization or WebSite data, and text + in the HTML without JavaScript. + - Optionally, PageSpeed Insights (mobile, field data when there is + some) for the 5 busiest pages, with an optional API key. + - It runs in the background, once a week on its own or with *Audit + now*. The page is SEO → Audit. 4. **Changes, approval and pull requests (job 5), with before/after.** - The AI proposes the exact change: a title, a meta description or an H1. Each one comes with the number that pays for it and the title's diff --git a/README.md b/README.md index 4307063..313574c 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,18 @@ To check the connection, open **Core & Hermes** in Supermarket and ask Hermes th **SEO: the morning check and the Monday report.** *Morning check* compares the last 7 days of final Search Console data with the 7 before, by page and by search, and lists only real moves. A move means more than 5 clicks, or more than 3 positions on at least 300 impressions; the thresholds are editable under Settings → Search engines. Otherwise it says "Nothing real moved". For each move it shows the numbers before and after, and what the data shows about the cause: which search's clicks changed, and whether a position change is real or only Google showing the page for a different mix of searches. A search with no row this week is "no data", not a drop to zero. The *Monday report* is one page, the same every week: clicks, impressions and position against the week before, with a sentence on where the change came from; the 3 pages that moved most; and "Waiting for your yes", at most 3 pages to act on. It's written every Monday, kept for comparison, and can be emailed to you through the outreach mailbox. +**SEO: the audit (SEO → Audit).** Once a week, or with *Audit now*, Supermarket reads your website politely. It takes the busiest pages from Search Console first, then the sitemap's, then the pages they link to: up to 300, honoring robots.txt. On every page it checks: +- the title and meta description, with their length in characters and in pixels as Google shows them; +- the H1 and heading order; +- the canonical and noindex tags; +- errors and redirects, and broken links, outside ones included; +- images without alt text; +- Open Graph and structured data; +- whether the text is there without JavaScript; +- whether the title says what people actually search for, from the page's main Search Console query. + +Issues are ranked by severity, then by the page's clicks and impressions, so the pages that bring traffic come first. An *AI visibility* section checks whether robots.txt lets AI assistants' crawlers in, whether you have an `llms.txt`, and whether your pages carry structured data and say who you are. Optionally it checks the speed (Core Web Vitals) of the 5 busiest pages with PageSpeed Insights; an API key for that is optional, under Settings → Search engines. + **The end of the funnel (Settings → Website & sales).** When writing posts on Content, choose *For a buying signal*: the posts speak to that situation, and their links carry the signal's campaign tag. Each signal's page lists its posts and gives your websites' addresses tagged with it, for landing pages, the shopping cart or links you share. With a Plausible Stats API key (Plausible on your Core by default), Supermarket reads yesterday's visitors on tagged links once a day and counts them as Visited for the signal, by channel; visits are counted per signal, never per person. With a restricted, read-only Stripe key, it reads new checkouts and paid invoices every hour: a checkout with nothing to pay (a trial or a free plan) counts as Signed up, and money paid as Paid, with the amount. A customer is tied to a signal by the `utm_campaign` your shopping cart saves in the Checkout Session's metadata, or else by their email (a prospect's, or one at a prospect company's domain). Your Core's Cal.com has no API, so bookings are read from Cal.com's booking emails in the outreach mailbox: give Cal.com's sending address under Settings → Email, and each new booking counts as Booked for the person who booked. **Prospects (Prospects → Review).** Companies and people who may fit your targets wait here for review; for now you add them by hand, and finding them for you comes next. Each keeps where and when it was found. Accepting a company queues an EspoCRM Account, accepting a person queues a Lead at their company, with the source, date and why they fit in the record's description. Before you decide, the page warns about records already in your CRM (as of the last sync). *Set aside* keeps a prospect out of the way; the **suppression list** (Prospects → Suppression list) holds emails and domains that must never be added, and is checked when a prospect is added and again before anything is queued. diff --git a/TEST.md b/TEST.md index 0b5d062..c73c53d 100644 --- a/TEST.md +++ b/TEST.md @@ -312,6 +312,24 @@ Throughout, also notice: - [ ] **(real)** With *Email me the Monday report* on and email set up, the report arrives on Monday morning. +### Audit + +- [ ] SEO → Audit: *Audit now* shows "auditing…" and the page updates by + itself when done (a few minutes). +- [ ] The number of pages read is close to your site's real number of pages + (up to 300). +- [ ] Open three issues on different pages and check them on the live page + (view source): the title length, a missing description, a broken + link, a redirect. +- [ ] With Search Console connected, issues on pages with traffic come first, + with their clicks and impressions. +- [ ] "Its title doesn't say what people search" names a search that really + is the page's biggest one in Search Console. +- [ ] AI visibility: what it says about robots.txt matches your robots.txt + file, and llms.txt is found if you have one. +- [ ] The severity boxes filter the issues. +- [ ] With *Also check the speed*, the 5 busiest pages get Core Web Vitals. + ## 8. Search - [ ] Searching for an inventory entry, a fetched item, a post, a prospect diff --git a/go.mod b/go.mod index 1d0a881..2700825 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/emersion/go-imap v1.2.1 github.com/emersion/go-message v0.18.2 github.com/modelcontextprotocol/go-sdk v1.8.0 + golang.org/x/net v0.63.0 gopkg.in/yaml.v3 v3.0.1 modernc.org/sqlite v1.62.0 ) @@ -39,9 +40,9 @@ require ( go.opentelemetry.io/otel/trace v1.33.0 // indirect go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect golang.org/x/oauth2 v0.35.0 // indirect - golang.org/x/sync v0.24.0 // indirect - golang.org/x/sys v0.49.0 // indirect - golang.org/x/text v0.27.0 // indirect + golang.org/x/sync v0.25.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/text v0.44.0 // indirect golang.org/x/time v0.15.0 // indirect modernc.org/libc v1.80.1 // indirect modernc.org/mathutil v1.7.1 // indirect diff --git a/go.sum b/go.sum index 4ab7ce2..6d5dbbc 100644 --- a/go.sum +++ b/go.sum @@ -140,8 +140,8 @@ go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s= go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= -golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= @@ -150,23 +150,23 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= -golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= +golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= +golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= -golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= -golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -176,8 +176,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= -golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/internal/api/sitemap/sitemap.go b/internal/api/sitemap/sitemap.go index da2afba..b98f125 100644 --- a/internal/api/sitemap/sitemap.go +++ b/internal/api/sitemap/sitemap.go @@ -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 { diff --git a/internal/db/db.go b/internal/db/db.go index 94c161d..fde41c1 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -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); `, } diff --git a/internal/secrets/secrets.go b/internal/secrets/secrets.go index c7f6af7..88ad8de 100644 --- a/internal/secrets/secrets.go +++ b/internal/secrets/secrets.go @@ -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 diff --git a/internal/seo/audit.go b/internal/seo/audit.go new file mode 100644 index 0000000..21d6fbb --- /dev/null +++ b/internal/seo/audit.go @@ -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 +} diff --git a/internal/seo/audit_test.go b/internal/seo/audit_test.go new file mode 100644 index 0000000..2d26881 --- /dev/null +++ b/internal/seo/audit_test.go @@ -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, `%s%s`, 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, `%[1]s/%[1]s/bulking/%[1]s/old/%[1]s/gone/`, srv.URL) + case "/": + page(`Whey reviews and price comparisons, by people who buy it + `, + `

Whey

Prices

`+long+`

bulkxadead`) + case "/bulking/": + page(`Best whey protein for bulking`, `

Bulking

Again

a

b

short

`) + case "/old/": + http.Redirect(w, r, "/bulking/", http.StatusMovedPermanently) + case "/gone/", "/missing/", "/ext-dead": + http.NotFound(w, r) + case "/hidden/": + page(`Hidden page with a perfectly fine title here`, `

Hidden

`+long+`

`) + 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) + } +} diff --git a/internal/seo/speed.go b/internal/seo/speed.go new file mode 100644 index 0000000..81e139a --- /dev/null +++ b/internal/seo/speed.go @@ -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" +} diff --git a/internal/seo/sync.go b/internal/seo/sync.go index 3907cf1..27eadc2 100644 --- a/internal/seo/sync.go +++ b/internal/seo/sync.go @@ -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 != "" { diff --git a/internal/seo/text.go b/internal/seo/text.go new file mode 100644 index 0000000..085cf45 --- /dev/null +++ b/internal/seo/text.go @@ -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"}, +} diff --git a/internal/web/audit_test.go b/internal/web/audit_test.go new file mode 100644 index 0000000..04c7f80 --- /dev/null +++ b/internal/web/audit_test.go @@ -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, `Home

Hi

x`) + case "/sitemap.xml": + fmt.Fprintf(w, `%s/`, 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") + } +} diff --git a/internal/web/seo.go b/internal/web/seo.go index e26abf7..97a9966 100644 --- a/internal/web/seo.go +++ b/internal/web/seo.go @@ -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 + } + } +} diff --git a/internal/web/server.go b/internal/web/server.go index 3640896..ae4bcc5 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -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).", diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 1017e43..02d4f5b 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -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 { diff --git a/internal/web/static/app.css b/internal/web/static/app.css index 0f7b550..b18d5b7 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -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; } diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 0d432ae..b9f8a2c 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -43,6 +43,7 @@ Morning check Monday report What ranks + Audit {{end}} {{if eq .ID "prospects"}} diff --git a/internal/web/templates/search-engines.html b/internal/web/templates/search-engines.html index 88e74a6..4aad153 100644 --- a/internal/web/templates/search-engines.html +++ b/internal/web/templates/search-engines.html @@ -7,6 +7,7 @@

Google Search Console

{{range .Fields}}{{template "key-field" (dict "F" . "Set" (index $d.Set .Name))}}{{end}}

Redirect URI to register on the OAuth client: {{.Redirect}}

+ {{template "key-field" (dict "F" .Speed "Set" .SpeedSet)}} {{if .Connected}}

Connected{{with .Account}} as {{.}}{{end}}.

diff --git a/internal/web/templates/seo-audit.html b/internal/web/templates/seo-audit.html new file mode 100644 index 0000000..64a9cac --- /dev/null +++ b/internal/web/templates/seo-audit.html @@ -0,0 +1,78 @@ +{{define "content"}}{{with .Data}}{{$d := .}} +
+

Audit

+
+

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.

+ +{{if not .Sites}} +

Add your websites to the profile first.

+{{else}} +{{if gt (len .Sites) 1}}{{end}} + +
+ {{.Current.URL}}{{if not .Current.Property}} (no Search Console property: issues aren't ranked by traffic){{end}} + + +
+ +{{with .Audit}} +{{if eq .Status "running"}} +
+

auditing… Started {{ago .StartedAt}}. This page updates when it's done.

+
+{{else if eq .Status "failed"}} +

failed {{ago .StartedAt}}: {{.Error}}

+{{else}} +{{$c := .Counts}} +
+

Audited {{ago .FinishedAt}} · {{len .Pages}} pages read

+ +
+ +
+
+

AI visibility

+
    {{range .Checks}}{{if eq .Group "ai"}}
  • {{.Title}}{{with .Detail}}
    {{.}}{{end}}
  • {{end}}{{end}}
+
+
+

The basics

+
    {{range .Checks}}{{if eq .Group "basics"}}
  • {{.Title}}{{with .Detail}}
    {{.}}{{end}}
  • {{end}}{{end}}
+
+
+ +{{if .Speed}} +

Speed (mobile)

+ + + {{range .Speed}} + {{if .Error}} + {{else if .Field}} + {{else}}{{end}}{{end}} +
PageLargest paintInteractionLayout shiftLab score
{{pagePath .Page}}{{.Error}}{{.LCP}} ms {{.LCPRating}}{{.INP}} ms {{.INPRating}}{{dec1 (cls .CLS)}} {{.CLSRating}}{{.Score}}Not enough real visitors for Google's field data.{{.Score}}
+{{end}} + +

Issues{{with $d.Severity}}: {{.}}s{{end}}

+{{if $d.Shown}} + + + {{range $d.Shown}} + + + + + + {{end}} +
IssuePageClicksImpressions
{{.Severity}}{{.Title}}{{with .Detail}}
{{truncate 400 .}}{{end}}
{{pagePath .Page}}{{if .Traffic.Impressions}}{{num .Traffic.Clicks}}{{else}}·{{end}}{{if .Traffic.Impressions}}{{num .Traffic.Impressions}}{{else}}·{{end}}
+{{with $d.More}}

And {{.}} more.

{{end}} +{{else}}

No issues{{with $d.Severity}} of this kind{{end}}.

{{end}} +{{end}} +{{else}} +

Not audited yet. Audit now reads the site; it takes a few minutes.

+{{end}} +{{end}} +{{end}}{{end}}