diff --git a/PLAN.md b/PLAN.md
index 3db9b94..a98782d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -1325,6 +1325,28 @@ signal preset). Per page:
The scorecard shows how many landing pages each signal has live. Phase 2's
part 8 is done by this.
+**Part 5 built (2026-11-22; schema 24: `live_at`, `gone_at`, `checked_at`,
+`live_note`).** The SEO loop (every 30 minutes) now also follows Sites
+pages' pull requests and checks the live site for pages waiting on it; so
+do the page, the signal's page and Sites → Publishing whenever they're
+opened (at most once a minute), and *Check the live site now*. A merged
+page is live when its address answers 200 with its own words (the first
+heading of its sections, without Markdown) and its title; words without
+the title count as live, with a note; the title without the words means
+the old version is still deployed. A removed page must answer 404 or 410,
+or lead elsewhere. Two hours after a merge without the page, it says to
+check the deploy hook. Badges read *merged, not live yet* / *live* and
+*removal merged, still on the site* / *removed*. Pages that go live or
+away are sent to IndexNow with the SEO changes (`seo.NewlyLive`). Sites →
+Publishing lists what's waiting for the live site, open pull requests,
+and the repository's latest merged pull requests (Supermarket's or
+anyone's), each linked to its page. federated-website has no merged pull
+requests: its changes are pushed straight to `main`, shown as commits
+under Sections and pages.
+
+**Phase 5 is complete** (parts 1–5). Not yet tried for real: building a
+page (a paid AI call) and pushing it to the real repository.
+
### Future enhancements
Not in any phase yet; picked up when the user asks.
diff --git a/TEST.md b/TEST.md
index e91eea9..33c0b85 100644
--- a/TEST.md
+++ b/TEST.md
@@ -567,6 +567,25 @@ Throughout, also notice:
stops counting it. Closing that pull request instead puts it back to
*merged*.
+### Publishing
+
+- [ ] Right after merging a page's pull request, its page (and Sites →
+ Publishing) shows *merged, not live yet* with what the last check
+ found (e.g. "it answers 404").
+- [ ] Once the deploy has run, the page shows *live*, "On the live site
+ since…", and its live address; *Check the live site now* gets there
+ without waiting.
+- [ ] If the title on the live site differs, it still shows live, with a
+ note giving the title the site shows.
+- [ ] If the deploy doesn't run, after two hours the page says to check
+ the deploy hook.
+- [ ] After a removal is merged and deployed, the page shows *removed* and
+ "Off the live site since…".
+- [ ] Sites → Publishing lists recent merged pull requests with who opened
+ them (Supermarket or a person); Supermarket's link to their pages.
+- [ ] A page that went live, or was removed, shows up in SEO → Search
+ engines' IndexNow log (when IndexNow is set up).
+
## 9. Search
- [ ] Searching for an inventory entry, a fetched item, a post, a prospect
diff --git a/internal/api/gitea/client.go b/internal/api/gitea/client.go
index 87bf562..596c139 100644
--- a/internal/api/gitea/client.go
+++ b/internal/api/gitea/client.go
@@ -117,6 +117,21 @@ type Pull struct {
Merged bool `json:"merged"`
MergedAt *time.Time `json:"merged_at"`
HTMLURL string `json:"html_url"`
+ Title string `json:"title"`
+ Head struct {
+ Ref string `json:"ref"`
+ } `json:"head"`
+ User struct {
+ Login string `json:"login"`
+ } `json:"user"`
+}
+
+// ClosedPulls are a repository's latest closed pull requests (merged or
+// not), most recently updated first.
+func (c *Client) ClosedPulls(ctx context.Context, full string, limit int) ([]Pull, error) {
+ var ps []Pull
+ err := c.do(ctx, http.MethodGet, fmt.Sprintf("/repos/%s/pulls?state=closed&sort=recentupdate&limit=%d", escapeFull(full), limit), nil, &ps)
+ return ps, err
}
// OpenPull opens a pull request from head into base.
diff --git a/internal/db/db.go b/internal/db/db.go
index 47080da..fa735e1 100644
--- a/internal/db/db.go
+++ b/internal/db/db.go
@@ -602,6 +602,13 @@ CREATE INDEX site_pages_by_site ON site_pages (site, created_at);
ALTER TABLE site_pages ADD COLUMN removal_branch TEXT NOT NULL DEFAULT '';
ALTER TABLE site_pages ADD COLUMN removal_pr_number INTEGER NOT NULL DEFAULT 0;
ALTER TABLE site_pages ADD COLUMN removal_pr_url TEXT NOT NULL DEFAULT '';
+`,
+ // 24: whether a merged page is on the live site (or a removed one gone).
+ `
+ALTER TABLE site_pages ADD COLUMN live_at TEXT;
+ALTER TABLE site_pages ADD COLUMN gone_at TEXT;
+ALTER TABLE site_pages ADD COLUMN checked_at TEXT;
+ALTER TABLE site_pages ADD COLUMN live_note TEXT NOT NULL DEFAULT '';
`,
}
diff --git a/internal/seo/audit.go b/internal/seo/audit.go
index 1889bcd..6d6b813 100644
--- a/internal/seo/audit.go
+++ b/internal/seo/audit.go
@@ -163,6 +163,29 @@ func (f *Fetcher) get(ctx context.Context, u string, method string, limit int64)
return nil, errors.New("too many redirects")
}
+// LivePage is a page as the live site serves it.
+type LivePage struct {
+ Status int
+ Final string // the address after redirects
+ Title string
+ Text string // its visible text
+}
+
+// Page reads one page of a live site.
+func (f *Fetcher) Page(ctx context.Context, u string) (*LivePage, error) {
+ r, err := f.get(ctx, u, http.MethodGet, 4<<20)
+ if err != nil {
+ return nil, err
+ }
+ lp := &LivePage{Status: r.status, Final: r.final}
+ if r.status == http.StatusOK {
+ p := PageReport{URL: u}
+ lp.Text = readPageText(&p, r.final, r.body)
+ lp.Title = p.Title
+ }
+ return lp, nil
+}
+
// 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.
diff --git a/internal/seo/engines.go b/internal/seo/engines.go
index cdcae24..cde33e9 100644
--- a/internal/seo/engines.go
+++ b/internal/seo/engines.go
@@ -131,7 +131,9 @@ func SubmitIndexNow(ctx context.Context, d *db.DB, site, key string, pages []str
func NewlyLive(d *db.DB, site string, now time.Time) ([]string, error) {
since := now.AddDate(0, 0, -14).UTC().Format(time.RFC3339)
rows, err := d.Query(`SELECT page FROM seo_changes WHERE site = ? AND status = 'live' AND live_at >= ?
- UNION SELECT page FROM seo_briefs WHERE site = ? AND status = 'live' AND live_at >= ? AND page != ''`, site, since, site, since)
+ UNION SELECT page FROM seo_briefs WHERE site = ? AND status = 'live' AND live_at >= ? AND page != ''
+ UNION SELECT rtrim(site, '/') || path FROM site_pages WHERE site = ? AND (live_at >= ? OR gone_at >= ?)`,
+ site, since, site, since, site, since, since)
if err != nil {
return nil, err
}
diff --git a/internal/sites/live.go b/internal/sites/live.go
new file mode 100644
index 0000000..f8529c2
--- /dev/null
+++ b/internal/sites/live.go
@@ -0,0 +1,211 @@
+package sites
+
+import (
+ "context"
+ "fmt"
+ "html"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "time"
+
+ "gopkg.in/yaml.v3"
+
+ "supermarket/internal/api/gitea"
+ "supermarket/internal/db"
+ "supermarket/internal/seo"
+)
+
+// GiveUpAfter is how long after merging a page that still isn't live is
+// called a problem (the deploy hook, most likely).
+const GiveUpAfter = 2 * time.Hour
+
+// Address is the page's address on the live site.
+func (p *SitePage) Address() string {
+ return strings.TrimRight(p.Site, "/") + p.Path
+}
+
+// Waiting says whether the live site hasn't caught up with the page yet:
+// merged but not seen live, or removed but not seen gone.
+func (p *SitePage) Waiting() bool {
+ return (p.Status == PageMerged && p.LiveAt.IsZero()) || (p.Status == PageRemoved && p.GoneAt.IsZero())
+}
+
+// Late says whether it's been waiting too long.
+func (p *SitePage) Late(now time.Time) bool {
+ return p.Waiting() && !p.MergedAt.IsZero() && now.Sub(p.MergedAt) > GiveUpAfter && p.Status == PageMerged
+}
+
+// RefreshPR follows a page's open pull request (adding or removing it): a
+// merge or a close changes its status. It says whether anything changed.
+func RefreshPR(ctx context.Context, d *db.DB, g interface {
+ GetPull(context.Context, string, int64) (*gitea.Pull, error)
+}, p *SitePage, now time.Time) (bool, error) {
+ _, full, err := gitea.ParseRepo(p.Repo)
+ if err != nil {
+ return false, nil
+ }
+ switch p.Status {
+ case PageRemoving:
+ pull, err := g.GetPull(ctx, full, p.RemovalPRNumber)
+ if err != nil {
+ return false, err
+ }
+ switch {
+ case pull.Merged:
+ p.Status, p.GoneAt, p.LiveNote = PageRemoved, time.Time{}, ""
+ p.MergedAt = now
+ if pull.MergedAt != nil {
+ p.MergedAt = *pull.MergedAt
+ }
+ case pull.State == "closed":
+ p.Status, p.RemovalPRNumber, p.RemovalPRURL = PageMerged, 0, ""
+ default:
+ return false, nil
+ }
+ case PagePR:
+ pull, err := g.GetPull(ctx, full, p.PRNumber)
+ if err != nil {
+ return false, err
+ }
+ switch {
+ case pull.Merged:
+ p.Status, p.MergedAt, p.LiveAt, p.LiveNote = PageMerged, now, time.Time{}, ""
+ if pull.MergedAt != nil {
+ p.MergedAt = *pull.MergedAt
+ }
+ case pull.State == "closed":
+ p.Status = PageClosed
+ default:
+ return false, nil
+ }
+ default:
+ return false, nil
+ }
+ return true, SavePage(d, p)
+}
+
+// CheckLive looks at the live site for a page that's waiting: a merged
+// one must answer, with its title and its own words; a removed one must
+// be gone (404 or 410, or sent elsewhere). It notes what it found.
+func CheckLive(ctx context.Context, f *seo.Fetcher, p *SitePage, now time.Time) {
+ p.CheckedAt = now
+ lp, err := f.Page(ctx, p.Address())
+ if err != nil {
+ p.LiveNote = "Couldn't reach the site: " + err.Error()
+ return
+ }
+ if p.Status == PageRemoved {
+ moved := false
+ if u, err := url.Parse(lp.Final); err == nil && strings.TrimRight(u.Path, "/") != strings.TrimRight(p.Path, "/") {
+ moved = true
+ }
+ switch {
+ case lp.Status == http.StatusNotFound || lp.Status == http.StatusGone:
+ p.GoneAt, p.LiveNote = now, fmt.Sprintf("Gone from the site (it answers %d).", lp.Status)
+ case moved:
+ p.GoneAt, p.LiveNote = now, "Gone from the site: its address now leads to "+lp.Final+"."
+ default:
+ p.LiveNote = fmt.Sprintf("Still on the site (it answers %d).", lp.Status)
+ }
+ return
+ }
+ if lp.Status != http.StatusOK {
+ p.LiveNote = fmt.Sprintf("Not on the site yet (it answers %d).", lp.Status)
+ return
+ }
+ titleOK := p.Title == "" || strings.Contains(norm(lp.Title), norm(p.Title))
+ phrase := Phrase(p.Sections)
+ textOK := phrase == "" || strings.Contains(norm(lp.Text), norm(phrase))
+ switch {
+ case titleOK && textOK:
+ p.LiveAt, p.LiveNote = now, "Live: the title and the words match."
+ case textOK:
+ p.LiveAt, p.LiveNote = now, fmt.Sprintf("Live, but its title shows as %q.", lp.Title)
+ case titleOK:
+ p.LiveNote = fmt.Sprintf("The page is there with its title, but not this version's words yet (looking for %q).", phrase)
+ default:
+ p.LiveNote = fmt.Sprintf("Something else is at this address (its title is %q).", lp.Title)
+ }
+}
+
+var (
+ mdLinkText = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
+ mdMarks = regexp.MustCompile("[*_`#>]+")
+ spaces = regexp.MustCompile(`\s+`)
+)
+
+// Phrase is words from the page that should show on the live site: the
+// first heading of its first section that has one, without Markdown.
+func Phrase(sectionsYAML string) string {
+ var doc yaml.Node
+ if yaml.Unmarshal([]byte(sectionsYAML), &doc) != nil || len(doc.Content) == 0 || doc.Content[0].Kind != yaml.SequenceNode {
+ return ""
+ }
+ for _, sec := range doc.Content[0].Content {
+ for _, key := range []string{"title", "headline", "text", "body"} {
+ if v := mapValue(sec, key); v != nil && v.Kind == yaml.ScalarNode && strings.TrimSpace(v.Value) != "" {
+ s := mdLinkText.ReplaceAllString(v.Value, "$1")
+ s = strings.TrimSpace(spaces.ReplaceAllString(mdMarks.ReplaceAllString(s, ""), " "))
+ if r := []rune(s); len(r) > 80 {
+ s = string(r[:80])
+ if i := strings.LastIndex(s, " "); i > 20 {
+ s = s[:i]
+ }
+ }
+ return s
+ }
+ }
+ }
+ return ""
+}
+
+func norm(s string) string {
+ s = html.UnescapeString(s)
+ s = strings.NewReplacer("’", "'", "‘", "'", "“", `"`, "”", `"`, "–", "-", "—", "-", " ", " ").Replace(s)
+ return strings.ToLower(strings.TrimSpace(spaces.ReplaceAllString(s, " ")))
+}
+
+// Refresh follows every page's pull request and checks the live site for
+// pages waiting on it. Pages are checked at most every few minutes.
+func Refresh(ctx context.Context, d *db.DB, g interface {
+ GetPull(context.Context, string, int64) (*gitea.Pull, error)
+}, f *seo.Fetcher, now time.Time) error {
+ ps, err := PagesIn(d, PagePR, PageRemoving, PageMerged, PageRemoved)
+ if err != nil {
+ return err
+ }
+ for i := range ps {
+ p := &ps[i]
+ if g != nil {
+ if _, err := RefreshPR(ctx, d, g, p, now); err != nil {
+ continue
+ }
+ }
+ if !p.Waiting() || now.Sub(p.CheckedAt) < 4*time.Minute {
+ continue
+ }
+ CheckLive(ctx, f, p, now)
+ if err := SavePage(d, p); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// LiveAddresses are pages that went live, or went away, since a time: for
+// telling search engines (IndexNow takes both).
+func LiveAddresses(d *db.DB, site string, since time.Time) ([]string, error) {
+ ps, err := Pages(d, site)
+ if err != nil {
+ return nil, err
+ }
+ var out []string
+ for _, p := range ps {
+ if (!p.LiveAt.IsZero() && p.LiveAt.After(since)) || (!p.GoneAt.IsZero() && p.GoneAt.After(since)) {
+ out = append(out, p.Address())
+ }
+ }
+ return out, nil
+}
diff --git a/internal/sites/live_test.go b/internal/sites/live_test.go
new file mode 100644
index 0000000..757de24
--- /dev/null
+++ b/internal/sites/live_test.go
@@ -0,0 +1,163 @@
+package sites
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "supermarket/internal/api/gitea"
+ "supermarket/internal/db"
+ "supermarket/internal/seo"
+)
+
+func openDB(t *testing.T) *db.DB {
+ d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { d.Close() })
+ return d
+}
+
+func TestPhrase(t *testing.T) {
+ for in, want := range map[string]string{
+ "- type: hero\n title: \"**One bill** for [your church](/c/)\"\n": "One bill for your church",
+ "- type: stats\n items: []\n- type: text\n headline: Why it works\n": "Why it works",
+ "- type: hero\n subhead: no title here\n": "",
+ "- type: hero\n title: " + strings.Repeat("word ", 30) + "\n": strings.TrimSpace(strings.Repeat("word ", 16)),
+ "not yaml: [": "",
+ } {
+ if got := Phrase(in); got != want {
+ t.Errorf("%q: %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestCheckLive(t *testing.T) {
+ var page string
+ status := 200
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/moved/" {
+ http.Redirect(w, r, "/elsewhere/", http.StatusMovedPermanently)
+ return
+ }
+ w.WriteHeader(status)
+ fmt.Fprint(w, page)
+ }))
+ defer srv.Close()
+ f := seo.NewFetcher("test")
+ now := time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)
+ p := &SitePage{Site: srv.URL + "/", Path: "/for-churches/", Title: "For churches", Status: PageMerged,
+ Sections: "- type: hero\n title: Run your church on one bill\n", MergedAt: now.Add(-time.Hour)}
+
+ status = 404
+ CheckLive(context.Background(), f, p, now)
+ if !p.LiveAt.IsZero() || p.LiveNote != "Not on the site yet (it answers 404)." || !p.CheckedAt.Equal(now) || !p.Waiting() || p.Late(now) {
+ t.Errorf("404: %+v", p)
+ }
+ status = 200
+ page = `
Old page · Us
Something else
`
+ CheckLive(context.Background(), f, p, now)
+ if !p.LiveAt.IsZero() || !strings.Contains(p.LiveNote, `Something else is at this address (its title is "Old page · Us")`) {
+ t.Errorf("other page: %s", p.LiveNote)
+ }
+ page = `For churches · Us
For churches
An older version.
`
+ CheckLive(context.Background(), f, p, now)
+ if !p.LiveAt.IsZero() || !strings.Contains(p.LiveNote, "not this version's words yet") {
+ t.Errorf("old version: %s", p.LiveNote)
+ }
+ if !p.Late(now.Add(2 * time.Hour)) {
+ t.Error("not late after three hours")
+ }
+ page = `Churches
Run your church on one bill
`
+ CheckLive(context.Background(), f, p, now)
+ if !p.LiveAt.Equal(now) || p.LiveNote != `Live, but its title shows as "Churches".` || p.Waiting() {
+ t.Errorf("live, other title: %+v", p)
+ }
+ p.LiveAt = time.Time{}
+ page = `For churches · Us
Run your church on one bill
`
+ CheckLive(context.Background(), f, p, now)
+ if !p.LiveAt.Equal(now) || p.LiveNote != "Live: the title and the words match." {
+ t.Errorf("live: %+v", p)
+ }
+
+ // Removed pages must be gone.
+ p.Status = PageRemoved
+ CheckLive(context.Background(), f, p, now)
+ if !p.GoneAt.IsZero() || p.LiveNote != "Still on the site (it answers 200)." {
+ t.Errorf("still there: %s", p.LiveNote)
+ }
+ status = 410
+ CheckLive(context.Background(), f, p, now)
+ if !p.GoneAt.Equal(now) || p.Waiting() {
+ t.Errorf("gone: %+v", p)
+ }
+ p.GoneAt, p.Path, status = time.Time{}, "/moved/", 200
+ CheckLive(context.Background(), f, p, now)
+ if p.GoneAt.IsZero() || !strings.Contains(p.LiveNote, "/elsewhere/") {
+ t.Errorf("redirected: %s", p.LiveNote)
+ }
+}
+
+type fakePulls map[int64]*gitea.Pull
+
+func (f fakePulls) GetPull(_ context.Context, full string, n int64) (*gitea.Pull, error) {
+ if full != "Us/site" {
+ return nil, fmt.Errorf("repo %s", full)
+ }
+ return f[n], nil
+}
+
+func TestRefresh(t *testing.T) {
+ d := openDB(t)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, `A
Hello there
`)
+ }))
+ defer srv.Close()
+ at := time.Date(2026, 11, 22, 9, 0, 0, 0, time.UTC)
+ mk := func(path, status string, pr int64) *SitePage {
+ p := &SitePage{Site: srv.URL + "/", Repo: "Us/site", Kind: "landing", Path: path, Title: "A", Status: status, PRNumber: pr,
+ Sections: "- type: hero\n title: Hello there\n"}
+ if err := SavePage(d, p); err != nil {
+ t.Fatal(err)
+ }
+ return p
+ }
+ open := mk("/open/", PagePR, 1)
+ merging := mk("/merging/", PagePR, 2)
+ closing := mk("/closing/", PagePR, 3)
+ draft := mk("/draft/", PageDraft, 0)
+ g := fakePulls{1: {State: "open"}, 2: {State: "closed", Merged: true, MergedAt: &at}, 3: {State: "closed"}}
+ now := at.Add(time.Hour)
+ if err := Refresh(context.Background(), d, g, seo.NewFetcher("test"), now); err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range []struct {
+ p *SitePage
+ status string
+ live bool
+ }{{open, PagePR, false}, {merging, PageMerged, true}, {closing, PageClosed, false}, {draft, PageDraft, false}} {
+ got, _ := GetPage(d, c.p.ID)
+ if got.Status != c.status || got.LiveAt.IsZero() == c.live {
+ t.Errorf("%s: %s live=%v", c.p.Path, got.Status, !got.LiveAt.IsZero())
+ }
+ }
+ got, _ := GetPage(d, merging.ID)
+ if !got.MergedAt.Equal(at) || got.LiveNote != "Live: the title and the words match." {
+ t.Errorf("merged: %+v", got)
+ }
+ // Live and gone addresses are for IndexNow; seo picks them up too.
+ addrs, _ := LiveAddresses(d, srv.URL+"/", at)
+ if len(addrs) != 1 || addrs[0] != srv.URL+"/merging/" {
+ t.Errorf("addresses: %v", addrs)
+ }
+ newly, err := seo.NewlyLive(d, srv.URL+"/", now)
+ if err != nil || len(newly) != 1 || newly[0] != srv.URL+"/merging/" {
+ t.Errorf("newly live: %v %v", newly, err)
+ }
+}
diff --git a/internal/sites/pages.go b/internal/sites/pages.go
index 4ff62f1..b88a688 100644
--- a/internal/sites/pages.go
+++ b/internal/sites/pages.go
@@ -93,6 +93,11 @@ type SitePage struct {
RemovalBranch string
RemovalPRNumber int64
RemovalPRURL string
+
+ LiveAt time.Time // seen on the live site after merging
+ GoneAt time.Time // seen gone after its removal was merged
+ CheckedAt time.Time // the live site was last checked
+ LiveNote string // what that check found
}
// Live says whether the page is on the published site.
@@ -114,7 +119,7 @@ func (p *SitePage) Editable() bool {
const pageCols = `id, site, repo, kind, source, notes, path, title, description, sections, needs, warnings, claims,
status, branch, file, pr_number, pr_url, note, error, created_at, updated_at, merged_at,
- removal_branch, removal_pr_number, removal_pr_url`
+ removal_branch, removal_pr_number, removal_pr_url, live_at, gone_at, checked_at, live_note`
func scanPages(rows *sql.Rows) ([]SitePage, error) {
defer rows.Close()
@@ -122,10 +127,11 @@ func scanPages(rows *sql.Rows) ([]SitePage, error) {
for rows.Next() {
var p SitePage
var src, needs, warns, claims, created, updated string
- var merged sql.NullString
+ var merged, live, gone, checked sql.NullString
if err := rows.Scan(&p.ID, &p.Site, &p.Repo, &p.Kind, &src, &p.Notes, &p.Path, &p.Title, &p.Description, &p.Sections,
&needs, &warns, &claims, &p.Status, &p.Branch, &p.File, &p.PRNumber, &p.PRURL, &p.Note, &p.Error,
- &created, &updated, &merged, &p.RemovalBranch, &p.RemovalPRNumber, &p.RemovalPRURL); err != nil {
+ &created, &updated, &merged, &p.RemovalBranch, &p.RemovalPRNumber, &p.RemovalPRURL,
+ &live, &gone, &checked, &p.LiveNote); err != nil {
return nil, err
}
_ = json.Unmarshal([]byte(src), &p.Source)
@@ -134,8 +140,13 @@ func scanPages(rows *sql.Rows) ([]SitePage, error) {
_ = json.Unmarshal([]byte(claims), &p.Claims)
p.CreatedAt, _ = time.Parse(time.RFC3339, created)
p.UpdatedAt, _ = time.Parse(time.RFC3339, updated)
- if merged.Valid {
- p.MergedAt, _ = time.Parse(time.RFC3339, merged.String)
+ for _, t := range []struct {
+ v sql.NullString
+ to *time.Time
+ }{{merged, &p.MergedAt}, {live, &p.LiveAt}, {gone, &p.GoneAt}, {checked, &p.CheckedAt}} {
+ if t.v.Valid {
+ *t.to, _ = time.Parse(time.RFC3339, t.v.String)
+ }
}
out = append(out, p)
}
@@ -226,10 +237,13 @@ func PagesIn(d *db.DB, statuses ...string) ([]SitePage, error) {
func SavePage(d *db.DB, p *SitePage) error {
now := time.Now().UTC()
p.UpdatedAt = now
- var merged any
- if !p.MergedAt.IsZero() {
- merged = p.MergedAt.UTC().Format(time.RFC3339)
+ ts := func(t time.Time) any {
+ if t.IsZero() {
+ return nil
+ }
+ return t.UTC().Format(time.RFC3339)
}
+ merged := ts(p.MergedAt)
src, _ := json.Marshal(p.Source)
if p.ID == 0 {
if p.CreatedAt.IsZero() {
@@ -240,12 +254,12 @@ func SavePage(d *db.DB, p *SitePage) error {
}
res, err := d.Exec(`INSERT INTO site_pages (site, repo, kind, source, notes, path, title, description, sections, needs, warnings,
claims, status, branch, file, pr_number, pr_url, note, error, created_at, updated_at, merged_at,
- removal_branch, removal_pr_number, removal_pr_url)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ removal_branch, removal_pr_number, removal_pr_url, live_at, gone_at, checked_at, live_note)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
p.Site, p.Repo, p.Kind, string(src), p.Notes, p.Path, p.Title, p.Description, p.Sections, jsonText(p.Needs), jsonText(p.Warnings),
jsonText(p.Claims), p.Status, p.Branch, p.File, p.PRNumber, p.PRURL, p.Note, p.Error,
p.CreatedAt.UTC().Format(time.RFC3339), now.Format(time.RFC3339), merged,
- p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL)
+ p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL, ts(p.LiveAt), ts(p.GoneAt), ts(p.CheckedAt), p.LiveNote)
if err != nil {
return err
}
@@ -254,10 +268,11 @@ func SavePage(d *db.DB, p *SitePage) error {
}
res, err := d.Exec(`UPDATE site_pages SET site = ?, repo = ?, kind = ?, source = ?, notes = ?, path = ?, title = ?, description = ?,
sections = ?, needs = ?, warnings = ?, claims = ?, status = ?, branch = ?, file = ?, pr_number = ?, pr_url = ?, note = ?, error = ?,
- updated_at = ?, merged_at = ?, removal_branch = ?, removal_pr_number = ?, removal_pr_url = ? WHERE id = ?`,
+ updated_at = ?, merged_at = ?, removal_branch = ?, removal_pr_number = ?, removal_pr_url = ?,
+ live_at = ?, gone_at = ?, checked_at = ?, live_note = ? WHERE id = ?`,
p.Site, p.Repo, p.Kind, string(src), p.Notes, p.Path, p.Title, p.Description, p.Sections, jsonText(p.Needs), jsonText(p.Warnings),
jsonText(p.Claims), p.Status, p.Branch, p.File, p.PRNumber, p.PRURL, p.Note, p.Error, now.Format(time.RFC3339), merged,
- p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL, p.ID)
+ p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL, ts(p.LiveAt), ts(p.GoneAt), ts(p.CheckedAt), p.LiveNote, p.ID)
if err != nil {
return err
}
diff --git a/internal/web/seo.go b/internal/web/seo.go
index 08f5ac3..9ad7332 100644
--- a/internal/web/seo.go
+++ b/internal/web/seo.go
@@ -274,6 +274,7 @@ func (s *Server) RunSEO(ctx context.Context) {
}
s.refreshChanges(ctx)
s.refreshBriefs(ctx)
+ s.refreshSitePages(ctx)
s.pingNewlyLive(ctx)
select {
case <-ctx.Done():
diff --git a/internal/web/server.go b/internal/web/server.go
index 12e08de..53b7435 100644
--- a/internal/web/server.go
+++ b/internal/web/server.go
@@ -183,6 +183,7 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /sites/pages", s.sitePageNew)
mux.HandleFunc("GET /sites/pages/{id}", s.sitePagePage)
mux.HandleFunc("POST /sites/pages/{id}/{action}", s.sitePageAction)
+ mux.HandleFunc("GET /sites/publishing", s.sitesPublishingPage)
mux.HandleFunc("GET /sites/previews", s.sitesPreviewsPage)
mux.HandleFunc("POST /sites/previews/build", s.sitesPreviewBuild)
mux.HandleFunc("POST /sites/previews/delete", s.sitesPreviewDelete)
diff --git a/internal/web/server_test.go b/internal/web/server_test.go
index 4b34317..b6181ab 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", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages",
+ "/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", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages", "/sites/publishing",
"/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/signals.go b/internal/web/signals.go
index 87607e3..f778110 100644
--- a/internal/web/signals.go
+++ b/internal/web/signals.go
@@ -712,6 +712,14 @@ func (s *Server) signalPages(ctx context.Context, sig *signals.Signal, d *signal
}
cancel()
}
+ lctx, lcancel := context.WithTimeout(ctx, 15*time.Second)
+ for i := range ps {
+ if ps[i].Waiting() && time.Since(ps[i].CheckedAt) > time.Minute {
+ sites.CheckLive(lctx, s.liveFetcher(), &ps[i], time.Now())
+ _ = sites.SavePage(s.DB, &ps[i])
+ }
+ }
+ lcancel()
prof, _ := profile.Load(s.DB)
bySite := map[string][]string{}
for _, p := range ps {
diff --git a/internal/web/sitepages.go b/internal/web/sitepages.go
index 016e715..0b46e64 100644
--- a/internal/web/sitepages.go
+++ b/internal/web/sitepages.go
@@ -238,7 +238,14 @@ func (s *Server) renderSitePage(w http.ResponseWriter, r *http.Request, errMsg,
s.refreshPagePR(ctx, p)
cancel()
}
- data := map[string]any{"P": p, "Kind": sites.KindLabel(p.Kind), "Gitea": s.gitea() != nil, "Site": cur, "HasSite": ok}
+ if p.Waiting() && time.Since(p.CheckedAt) > time.Minute {
+ ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
+ sites.CheckLive(ctx, s.liveFetcher(), p, time.Now())
+ cancel()
+ _ = sites.SavePage(s.DB, p)
+ }
+ data := map[string]any{"P": p, "Kind": sites.KindLabel(p.Kind), "Gitea": s.gitea() != nil, "Site": cur, "HasSite": ok,
+ "Late": p.Late(time.Now())}
if ok && p.Branch != "" {
for _, pv := range s.previews(cur.Repo) {
if pv.Branch == p.Branch && pv.Commit != "" {
@@ -270,50 +277,29 @@ func (s *Server) renderSitePage(w http.ResponseWriter, r *http.Request, errMsg,
s.render(w, r, "sites-page", page{Title: or(p.Title, "New page"), Nav: "sites/pages", Error: errMsg, Flash: flash, Data: data})
}
-// refreshPagePR notes when a page's pull request (adding or removing it)
-// is merged or closed.
+// refreshPagePR follows a page's pull request on Gitea.
func (s *Server) refreshPagePR(ctx context.Context, p *sites.SitePage) {
- _, full, err := gitea.ParseRepo(p.Repo)
- if err != nil {
- return
+ if g := s.gitea(); g != nil {
+ _, _ = sites.RefreshPR(ctx, s.DB, g, p, time.Now())
}
- if p.Status == sites.PageRemoving {
- pull, err := s.gitea().GetPull(ctx, full, p.RemovalPRNumber)
- if err != nil {
- return
- }
- switch {
- case pull.Merged:
- p.Status = sites.PageRemoved
- case pull.State == "closed":
- p.Status, p.RemovalPRNumber, p.RemovalPRURL = sites.PageMerged, 0, ""
- default:
- return
- }
- _ = sites.SavePage(s.DB, p)
- return
+}
+
+// refreshSitePages follows the pages' pull requests and checks the live
+// site for those waiting on it; the SEO loop runs it.
+func (s *Server) refreshSitePages(ctx context.Context) {
+ var g interface {
+ GetPull(context.Context, string, int64) (*gitea.Pull, error)
}
- if p.PRNumber == 0 {
- return
+ if c := s.gitea(); c != nil {
+ g = c
}
- pull, err := s.gitea().GetPull(ctx, full, p.PRNumber)
- if err != nil {
- return
+ if err := sites.Refresh(ctx, s.DB, g, s.liveFetcher(), time.Now()); err != nil {
+ s.Log.Warn("sites: checking pages", "err", err)
}
- switch {
- case pull.Merged:
- p.Status = sites.PageMerged
- if pull.MergedAt != nil {
- p.MergedAt = *pull.MergedAt
- } else {
- p.MergedAt = time.Now()
- }
- case pull.State == "closed":
- p.Status = sites.PageClosed
- default:
- return
- }
- _ = sites.SavePage(s.DB, p)
+}
+
+func (s *Server) liveFetcher() *seo.Fetcher {
+ return seo.NewFetcher("Supermarket/" + s.Version + " (Sites)")
}
func (s *Server) sitePageAction(w http.ResponseWriter, r *http.Request) {
@@ -346,6 +332,16 @@ func (s *Server) sitePageAction(w http.ResponseWriter, r *http.Request) {
back = ret
}
switch action {
+ case "check":
+ ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
+ defer cancel()
+ sites.CheckLive(ctx, s.liveFetcher(), p, time.Now())
+ if err := sites.SavePage(s.DB, p); err != nil {
+ s.serverError(w, err)
+ return
+ }
+ http.Redirect(w, r, back, http.StatusSeeOther)
+ return
case "duplicate":
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
@@ -461,3 +457,70 @@ func (s *Server) sitePageAction(w http.ResponseWriter, r *http.Request) {
}
s.renderSitePage(w, r, "", flash)
}
+
+// --- Publishing ---
+
+// mergeRow is a merged pull request on the publishing page.
+type mergeRow struct {
+ gitea.Pull
+ Ours bool // opened by Supermarket (a supermarket/ branch)
+ Page *sites.SitePage // the Sites page it added or removed, if any
+}
+
+func (s *Server) sitesPublishingPage(w http.ResponseWriter, r *http.Request) {
+ all, cur := s.currentSite(r)
+ data := map[string]any{"Sites": all, "Current": cur, "Gitea": s.gitea() != nil}
+ if cur != nil && cur.Repo != "" {
+ ps, err := sites.Pages(s.DB, cur.URL)
+ if err != nil {
+ s.serverError(w, err)
+ return
+ }
+ if g := s.gitea(); g != nil {
+ ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
+ for i := range ps {
+ if ps[i].Status == sites.PagePR || ps[i].Status == sites.PageRemoving {
+ _, _ = sites.RefreshPR(ctx, s.DB, g, &ps[i], time.Now())
+ }
+ }
+ pulls, err := g.ClosedPulls(ctx, cur.Repo, 30)
+ cancel()
+ if err != nil {
+ data["PullsErr"] = err.Error()
+ }
+ var merges []mergeRow
+ for _, pl := range pulls {
+ if !pl.Merged {
+ continue
+ }
+ m := mergeRow{Pull: pl, Ours: strings.HasPrefix(pl.Head.Ref, "supermarket/")}
+ for i := range ps {
+ if pl.Head.Ref == ps[i].Branch || pl.Head.Ref == ps[i].RemovalBranch {
+ m.Page = &ps[i]
+ }
+ }
+ merges = append(merges, m)
+ }
+ data["Merges"] = merges
+ }
+ lctx, lcancel := context.WithTimeout(r.Context(), 20*time.Second)
+ for i := range ps {
+ if ps[i].Waiting() && time.Since(ps[i].CheckedAt) > time.Minute {
+ sites.CheckLive(lctx, s.liveFetcher(), &ps[i], time.Now())
+ _ = sites.SavePage(s.DB, &ps[i])
+ }
+ }
+ lcancel()
+ var waiting, open []sites.SitePage
+ for _, p := range ps {
+ switch {
+ case p.Waiting():
+ waiting = append(waiting, p)
+ case p.Status == sites.PagePR || p.Status == sites.PageRemoving:
+ open = append(open, p)
+ }
+ }
+ data["Waiting"], data["Open"], data["Now"] = waiting, open, time.Now()
+ }
+ s.render(w, r, "sites-publishing", page{Title: "Publishing", Nav: "sites/publishing", Data: data})
+}
diff --git a/internal/web/sites_test.go b/internal/web/sites_test.go
index 3ce6090..44c5354 100644
--- a/internal/web/sites_test.go
+++ b/internal/web/sites_test.go
@@ -14,6 +14,7 @@ import (
"strconv"
"strings"
"testing"
+ "time"
"supermarket/internal/ai"
"supermarket/internal/signals"
@@ -219,8 +220,16 @@ func TestSitePageBuilder(t *testing.T) {
newAIClient = func(ai.Config, *secrets.Store) (ai.Client, error) { return cannedAI{string(composed)}, nil }
defer func() { newAIClient = ai.New }()
+ live := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/for-churches/" {
+ http.NotFound(w, r)
+ return
+ }
+ fmt.Fprint(w, `For churches · Us
For churches
Run your church on one bill
`)
+ }))
+ defer live.Close()
s, h := newTestServer(t, nil)
- profile.Save(s.DB, &profile.Profile{Name: "Us", Description: "Widgets.", Websites: []profile.Website{{URL: "https://us.example/", Repo: "Us/site"}}})
+ profile.Save(s.DB, &profile.Profile{Name: "Us", Description: "Widgets.", Websites: []profile.Website{{URL: live.URL + "/", Repo: "Us/site"}}})
sig := &signals.Signal{Name: "Churches", Slug: "churches", Status: "testing"}
if err := signals.Save(s.DB, sig); err != nil {
t.Fatal(err)
@@ -296,7 +305,8 @@ func TestSitePageBuilder(t *testing.T) {
// Gitea says it's merged: the page shows it, and can't be edited.
body = do(h, http.MethodGet, "/sites/pages/1", nil, nil).Body.String()
- if !strings.Contains(body, ">merged<") || strings.Contains(body, `name="sections"`) {
+ if !strings.Contains(body, ">live<") || !strings.Contains(body, "On the live site since") || !strings.Contains(body, "Live: the title and the words match.") ||
+ strings.Contains(body, `name="sections"`) {
t.Errorf("merged: %s", body)
}
if body := postForm(h, "/sites/pages/1/save", form(good)).Body.String(); !strings.Contains(body, "can't be changed") {
@@ -358,8 +368,17 @@ func TestSignalLandingPages(t *testing.T) {
newAIClient = func(ai.Config, *secrets.Store) (ai.Client, error) { return cannedAI{string(composed)}, nil }
defer func() { newAIClient = ai.New }()
+ gone := false
+ live := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/for-churches/" || gone {
+ http.NotFound(w, r)
+ return
+ }
+ fmt.Fprint(w, `For churches
{{end}}{{end}}
+ {{if eq $p.Status "removed"}}{{if not $p.GoneAt.IsZero}}
Off the live site since {{ago $p.GoneAt}}.
{{end}}{{end}}
+ {{with $p.LiveNote}}
{{if $d.Late}}{{.}} It's been over two hours since the merge: check that the site's deploy (the Gitea hook) ran.{{else}}{{.}}{{end}} {{if not $p.CheckedAt.IsZero}}Checked {{ago $p.CheckedAt}}.{{end}}
Merging a pull request on Gitea publishes it: your Gitea hook deploys the site. Supermarket follows its pull requests, and after a merge checks the live site until the page is there, with its title and its own words, or, for a removal, gone. It checks every 30 minutes, and whenever you open the page.
+
+{{if not .Sites}}
+
Add your website and its Hugo repository under Settings → Profile first.
SEO changes and briefs follow their own pages to the live site, under SEO → Changes and Briefs and pages.
+{{else}}
No merged pull requests yet. Changes pushed straight to the published branch aren't pull requests: they're under Sections and pages, in the latest commits.