Phase 7 part 5: add a section to an existing page

Sites → Sections and pages → Add a section, on any page built from
sections: choose one of the site's section types and where it goes; the
AI writes it from the page, its searches, the profile and the Inventory,
with the same rules as a new page. It's reviewed like a page (claims to
confirm, to-dos), and the pull request inserts it into the page's file as
text, so only that section is added; the build checks it. What to write
next suggests a FAQ for a section page found with questions, and a
comparison for one searched against something else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 07:25:19 -07:00
co-authored by Claude Opus 5.5
parent 5705a9b58b
commit fdfbcd3d3d
15 changed files with 873 additions and 39 deletions
+57
View File
@@ -1,12 +1,14 @@
package web
import (
"context"
"net/http"
"slices"
"strconv"
"strings"
"time"
"supermarket/internal/inventory"
"supermarket/internal/next"
"supermarket/internal/profile"
"supermarket/internal/seo"
@@ -78,6 +80,12 @@ func (s *Server) nextFor(cur seoSite, now time.Time) (list []next.Suggestion, mo
all = append(all, next.MentionSuggestions(ms, p)...)
}
}
// Sections for pages already on the site, from what they're searched for.
if cur.Property != "" {
if ideas, err := s.sectionIdeas(cur); err == nil {
all = append(all, ideas...)
}
}
stalled, err := next.Stalled(s.DB, cur.URL, cur.Index, now)
if err != nil {
return nil, 0, err
@@ -152,3 +160,52 @@ func (s *Server) seoNextDismiss(w http.ResponseWriter, r *http.Request) {
idx, _ := strconv.Atoi(r.URL.Query().Get("site"))
redirect(w, r, "/seo/next?site="+strconv.Itoa(idx), "next-dismissed")
}
// sectionIdeas suggest a FAQ or a comparison for the site's section pages,
// from the searches that bring people to them.
func (s *Server) sectionIdeas(cur seoSite) ([]next.Suggestion, error) {
var repo *siteRepo
for _, sr := range s.siteRepos() {
if sr.URL == cur.URL && sr.Repo != "" {
r := sr
repo = &r
}
}
if repo == nil {
return nil, nil
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cat, err := s.catalog(ctx, *repo, false)
if err != nil {
return nil, err
}
var pages []next.SectionPage
for _, pg := range cat.Pages {
if pg.Sections && !pg.Draft {
pages = append(pages, next.SectionPage{Path: pg.Path, Title: pg.Title, Types: pg.Types})
}
}
var types []string
for _, t := range cat.Types {
if !t.Missing {
types = append(types, t.Name)
}
}
sc := s.scope(cur)
searches, err := seo.SearchesByPath(s.DB, sc)
if err != nil {
return nil, err
}
var competitors []string
if entries, err := inventory.List(s.DB, "competitor"); err == nil {
for _, e := range entries {
competitors = append(competitors, e.Name)
}
}
if p, _ := profile.Load(s.DB); p != nil {
competitors = append(competitors, p.Targets.Technologies...)
}
rate, _ := sc.Rate("")
return next.SectionIdeas(pages, searches, types, competitors, cur.Index, rate), nil
}
+2
View File
@@ -223,6 +223,8 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /seo/audit/status", s.seoAuditStatus)
mux.HandleFunc("GET /seo/report", s.seoReportPage)
mux.HandleFunc("GET /seo/next", s.seoNextPage)
mux.HandleFunc("GET /sites/pages/add", s.sitesAddPage)
mux.HandleFunc("POST /sites/pages/add", s.sitesAdd)
mux.HandleFunc("POST /seo/next/dismiss", s.seoNextDismiss)
mux.HandleFunc("POST /seo/report", s.seoReportWrite)
mux.HandleFunc("GET /settings/search", s.searchSettingsPage)
+9 -4
View File
@@ -96,6 +96,9 @@ func (s *Server) campaignOf(p *sites.SitePage) string {
// compose has the AI write the page (again), then checks it.
func (s *Server) compose(ctx context.Context, cur siteRepo, p *sites.SitePage, previous bool) error {
if p.Kind == sites.KindSection {
return s.composeSection(ctx, cur, p)
}
client, prof, err := s.draftClient()
if err != nil {
return err
@@ -393,10 +396,12 @@ func (s *Server) sitePageAction(w http.ResponseWriter, r *http.Request) {
}
// Every action keeps the user's edits first.
if _, has := r.PostForm["sections"]; has {
p.Title = strings.TrimSpace(r.PostFormValue("title"))
p.Description = strings.TrimSpace(r.PostFormValue("description"))
if p.File == "" {
p.Path = sites.CleanPath(r.PostFormValue("path"))
if p.Kind != sites.KindSection { // a section keeps its page's title and address
p.Title = strings.TrimSpace(r.PostFormValue("title"))
p.Description = strings.TrimSpace(r.PostFormValue("description"))
if p.File == "" {
p.Path = sites.CleanPath(r.PostFormValue("path"))
}
}
p.Notes = strings.TrimSpace(r.PostFormValue("notes"))
p.Sections = strings.TrimSpace(strings.ReplaceAll(r.PostFormValue("sections"), "\r\n", "\n"))
+81
View File
@@ -611,3 +611,84 @@ func TestLeadForms(t *testing.T) {
t.Errorf("connected: %s", body)
}
}
// A section added to a page already on the site: written from the site's
// types, reviewed like a page, and pushed as a pull request that only adds
// the section to the page's file.
func TestAddASection(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
clone := hugotest.Site(t, map[string]string{
"layouts/partials/render-sections.html": `{{ range .Params.sections }}{{ partial (printf "sections/%s.html" .type) . }}{{ end }}`,
"layouts/partials/sections/hero.html": `<h2>{{ .title }}</h2>`,
"layouts/partials/sections/faq.html": "{{ $s := . }}{{ range $s.items }}<h3>{{ .q }}</h3>{{ .a }}{{ end }}",
"layouts/_default/single.html": `{{ define "main" }}<h1>{{ .Title }}</h1>{{ partial "render-sections.html" . }}{{ .Content }}{{ end }}`,
"content/freescout.md": "---\ntitle: FreeScout\nsections:\n - type: hero\n title: Help desk you own\n - type: faq\n items:\n - q: Old question?\n a: Old answer.\n---\n",
})
var pulls []map[string]string
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/Us/site":
fmt.Fprintf(w, `{"full_name":"Us/site","default_branch":"main","clone_url":%q,"permissions":{"push":true}}`, clone)
case r.URL.Path == "/api/v1/repos/Us/site/pulls" && r.Method == http.MethodPost:
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
pulls = append(pulls, body)
fmt.Fprint(w, `{"number":8,"state":"open","html_url":"https://gitea.example/Us/site/pulls/8"}`)
default:
http.NotFound(w, r)
}
}))
defer g.Close()
composed, _ := json.Marshal(map[string]any{
"sections_yaml": "- type: faq\n items:\n - q: Is FreeScout hosted for us?\n a: Yes, on infrastructure you own.\n",
"needs": []string{"Check the answer against the plans"}})
newAIClient = func(ai.Config, *secrets.Store) (ai.Client, error) { return cannedAI{string(composed)}, nil }
defer func() { newAIClient = ai.New }()
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Us", Description: "Widgets.", Websites: []profile.Website{{URL: "https://site.example/", Repo: "Us/site"}}})
postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}})
postForm(h, "/sites/sync?site=0", nil) // read the repository
body := do(h, http.MethodGet, "/sites?site=0", nil, nil).Body.String()
if !strings.Contains(body, "/sites/pages/add?site=0&amp;page=%2ffreescout%2f") {
i := strings.Index(body, "<main>")
t.Fatalf("no Add a section link: %s", body[i:min(len(body), i+3000)])
}
body = do(h, http.MethodGet, "/sites/pages/add?site=0&page=/freescout/", nil, nil).Body.String()
if !strings.Contains(body, `<option value="faq"`) || !strings.Contains(body, "Before section 2 (faq)") {
t.Fatalf("form: %s", body)
}
rec := postForm(h, "/sites/pages/add?site=0", url.Values{"page": {"/freescout/"}, "type": {"faq"}, "at": {"1"}, "notes": {"answer the searches"}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("add: %d %s", rec.Code, rec.Body.String())
}
loc := rec.Header().Get("Location")
body = do(h, http.MethodGet, loc, nil, nil).Body.String()
for _, want := range []string{"A new <strong>faq</strong> section for", "as its section 2", "Is FreeScout hosted for us?", "Check the answer against the plans"} {
if !strings.Contains(body, want) {
t.Errorf("review lacks %q", want)
}
}
if strings.Contains(body, `name="title"`) || strings.Contains(body, "Make a variant") {
t.Error("a section shows a page's title field or variants")
}
rec = postForm(h, loc+"/pr", url.Values{"sections": {"- type: faq\n items:\n - q: Is FreeScout hosted for us?\n a: Yes, on infrastructure you own.\n"}, "needs": {"Check the answer against the plans"}})
if len(pulls) != 1 {
t.Fatalf("pr: %d %v %s", rec.Code, pulls, rec.Body.String())
}
if pulls[0]["title"] != "Sites: a new section on /freescout/" || !strings.Contains(pulls[0]["body"], "Only that page's sections list changes") {
t.Errorf("pull: %+v", pulls[0])
}
// The file on the branch: the new section second, the rest untouched.
out, err := exec.Command("git", "-C", strings.TrimPrefix(clone, "file://"), "show", pulls[0]["head"]+":content/freescout.md").CombinedOutput()
if err != nil {
t.Fatal(err, string(out))
}
want := "---\ntitle: FreeScout\nsections:\n - type: hero\n title: Help desk you own\n - type: faq\n items:\n - q: Is FreeScout hosted for us?\n a: Yes, on infrastructure you own.\n - type: faq\n items:\n - q: Old question?\n"
if !strings.HasPrefix(string(out), want) {
t.Errorf("file on the branch:\n%s", out)
}
}
+133
View File
@@ -0,0 +1,133 @@
package web
import (
"context"
"errors"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"supermarket/internal/seo"
"supermarket/internal/sites"
)
// Adding a section to a page that's already on the site (Sites → Sections
// and pages → Add a section).
// pageNow reads a page's file from the site's working copy, as published.
func (s *Server) pageNow(ctx context.Context, cur siteRepo, path string) (raw []byte, title string, err error) {
ap := s.applier(seoSite{Index: cur.Index, URL: cur.URL})
wc, _, _, err := ap.WorkingCopy(ctx)
if err != nil {
return nil, "", err
}
defer wc.Release()
file, err := wc.FindContent(path)
if err != nil {
return nil, "", errors.New("the site has no page at " + path)
}
raw, err = os.ReadFile(filepath.Join(wc.Dir, filepath.FromSlash(file)))
if err != nil {
return nil, "", err
}
return raw, wc.FrontMatterValue(file, "title"), nil
}
// composeSection writes the section a site page of KindSection adds.
func (s *Server) composeSection(ctx context.Context, cur siteRepo, p *sites.SitePage) error {
client, prof, err := s.draftClient()
if err != nil {
return err
}
if prof == nil || !prof.IsSet() {
return errors.New("fill in the company profile under Settings → Profile first")
}
cat, err := s.catalog(ctx, cur, true)
if err != nil {
return err
}
raw, title, err := s.pageNow(ctx, cur, p.Path)
if err != nil {
return err
}
existing, _, err := sites.PageSections(raw)
if err != nil {
return err
}
in := sites.SectionInputs{Catalog: cat, PagePath: p.Path, PageTitle: title, Existing: existing, Type: p.Source.Type,
At: p.Source.At, Notes: p.Notes, SiteURL: cur.URL}
for _, st := range s.seoSites() {
if st.URL == cur.URL && st.Property != "" {
in.Searches, _ = seo.PageSearches(s.DB, s.scope(st), p.Path, 10)
}
}
out, err := (&sites.Composer{AI: client, Profile: prof}).ComposeSection(ctx, in)
if err != nil {
return err
}
p.Title, p.Needs, p.Sections = or(title, p.Path), out.Needs, out.Sections
return s.checkPage(cat, p, s.campaignOf(p))
}
// sitesAddPage is the form: which section, where, and what it's for.
func (s *Server) sitesAddPage(w http.ResponseWriter, r *http.Request) {
s.renderSitesAdd(w, r, "")
}
func (s *Server) renderSitesAdd(w http.ResponseWriter, r *http.Request, errMsg string) {
_, cur := s.currentSite(r)
path := sites.CleanPath(r.FormValue("page"))
data := map[string]any{"Current": cur, "Path": path, "Type": r.FormValue("type"), "Notes": r.FormValue("notes")}
if cur == nil || cur.Repo == "" {
errMsg = or(errMsg, "Set this website's Hugo repository in Settings → Profile first.")
} else {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
cat, err := s.catalog(ctx, *cur, false)
if err != nil {
errMsg = or(errMsg, err.Error())
} else {
data["Types"] = cat.Types
for _, pg := range cat.Pages {
if pg.Path == path {
data["Page"] = pg
}
}
if data["Page"] == nil {
errMsg = or(errMsg, "The site has no page built from sections at "+path+".")
}
}
}
s.render(w, r, "sites-add", page{Title: "Add a section", Nav: "sites/site", Error: errMsg, Data: data})
}
// sitesAdd writes the section and opens it for review, like a new page.
func (s *Server) sitesAdd(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, cur := s.currentSite(r)
if cur == nil || cur.Repo == "" {
s.renderSitesAdd(w, r, "")
return
}
at, _ := strconv.Atoi(r.PostFormValue("at"))
p := &sites.SitePage{Site: cur.URL, Repo: cur.Repo, Kind: sites.KindSection, Path: sites.CleanPath(r.PostFormValue("page")),
Notes: strings.TrimSpace(r.PostFormValue("notes"))}
p.Source.Type, p.Source.At = r.PostFormValue("type"), at
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
if err := s.composeSection(ctx, *cur, p); err != nil {
s.renderSitesAdd(w, r, err.Error())
return
}
if err := sites.SavePage(s.DB, p); err != nil {
s.serverError(w, err)
return
}
http.Redirect(w, r, "/sites/pages/"+strconv.FormatInt(p.ID, 10), http.StatusSeeOther)
}
+24
View File
@@ -0,0 +1,24 @@
{{define "content"}}{{with .Data}}{{$d := .}}
<p><a href="/sites{{with .Current}}?site={{.Index}}{{end}}">← Sections and pages</a></p>
<h1>Add a section</h1>
<p class="lede">One more section on a page that's already on the site, of one of the site's own types: a FAQ for the questions people search, a comparison table, more features. The AI writes it from the page, your profile and the Inventory, with the same rules as a new page: nothing invented, claims of experience to confirm, a pull request that adds only that section.</p>
{{with .Page}}
<form method="post" action="/sites/pages/add?site={{$d.Current.Index}}" class="card" data-busy="Reading the page and writing…">
<input type="hidden" name="page" value="{{.Path}}">
<p>On <a href="{{$d.Current.Base}}{{.Path}}" target="_blank" rel="noopener noreferrer">{{.Path}}</a> <strong>{{.Title}}</strong>: {{join .Types " · "}}</p>
<div class="cols">
<label>Section type
<select name="type">{{range $d.Types}}{{if not .Missing}}<option value="{{.Name}}" {{if eq .Name $d.Type}}selected{{end}}>{{.Name}}{{if .Uses}} (used on {{len .Pages}} pages){{end}}</option>{{end}}{{end}}</select>
</label>
<label>Where
<select name="at">{{range $i, $t := .Types}}<option value="{{$i}}">Before section {{inc $i}} ({{$t}})</option>{{end}}<option value="{{len .Types}}" selected>At the end</option></select>
<span class="help">Before the page's closing call to action reads best, usually.</span>
</label>
</div>
<label>What it's for <span class="muted">(optional)</span>
<textarea name="notes" rows="3" placeholder="Answer the questions people search for this page; compare us with the big help desks.">{{$d.Notes}}</textarea></label>
<div class="actions"><button type="submit">Write the section</button></div>
<p class="small muted">It reads the site's repository first. Writing takes a minute.</p>
</form>
{{end}}
{{end}}{{end}}
+7 -1
View File
@@ -24,11 +24,15 @@
{{with $p.Error}}<p class="error" role="alert">{{.}}</p>{{end}}
{{if $p.Editable}}
<form method="post" action="/sites/pages/{{$p.ID}}/save" class="card">
{{if eq $p.Kind "section"}}
<p>A new <strong>{{$p.Source.Type}}</strong> section for <a href="{{$p.Address}}" target="_blank" rel="noopener noreferrer">{{$p.Path}}</a>, going in as its section {{inc $p.Source.At}}. Only this section is added to the page's file; the rest of the page stays as it is.</p>
{{else}}
<div class="cols">
<label>Title <span class="muted">(for search results, under 60 characters)</span> <input name="title" value="{{$p.Title}}" maxlength="120"></label>
<label>Address {{if $p.File}}<span class="muted">(fixed: the file is on its branch)</span>{{end}} <input name="path" value="{{$p.Path}}" {{if $p.File}}readonly{{end}}></label>
</div>
<label>Description <span class="muted">(under 155 characters)</span> <textarea name="description" rows="2">{{$p.Description}}</textarea></label>
{{end}}
{{with $p.Warnings}}
<div class="warn card"><strong>To look at:</strong><ul>{{range .}}<li>{{.}}</li>{{end}}</ul></div>
@@ -61,12 +65,14 @@
{{end}}
<section class="card">
{{if ne $p.Kind "section"}}
<form method="post" action="/sites/pages/{{$p.ID}}/duplicate">
<label>Duplicate as a variant, to test against this one <span class="muted">(optional: what to change; empty makes an exact copy to edit)</span>
<textarea name="variant_notes" rows="2"></textarea></label>
<button type="submit" class="secondary" data-busy="Making it…">Make a variant</button>
</form>
{{if eq $p.Status "merged"}}
{{end}}
{{if and (eq $p.Status "merged") (ne $p.Kind "section")}}
<form method="post" action="/sites/pages/{{$p.ID}}/remove" data-confirm="Open a pull request that takes {{$p.Path}} off the site?">
<button type="submit" class="secondary" data-busy="Opening…">Remove from the site</button>
<span class="small muted">Opens a pull request deleting the page; merging takes it off.</span>
+1 -1
View File
@@ -80,7 +80,7 @@
{{with $d.SectionPages}}
<div class="table-wrap"><table class="compact">
<thead><tr><th>Address</th><th>Title</th><th>Sections</th>{{if $d.Conv}}<th class="num" title="Visits that began on the page, in 90 days (Plausible)">Visits</th><th class="num" title="Of those, the ones that went on to sign up or send a form">Sign-ups</th>{{end}}</tr></thead>
<tbody>{{range .}}<tr><td><a href="{{$d.Current.Base}}{{.Path}}" target="_blank" rel="noopener noreferrer">{{.Path}}</a>{{if .Draft}} <span class="badge draft">draft</span>{{end}}</td><td>{{.Title}}</td><td class="small">{{join .Types " · "}}</td>{{if $d.Conv}}{{with conv $d.Conv .Path}}<td class="num">{{num .Visitors}}</td><td class="num">{{if .Conversions}}<strong>{{num .Conversions}}</strong>{{else}}<span class="muted">0</span>{{end}}</td>{{end}}{{end}}</tr>{{end}}</tbody>
<tbody>{{range .}}<tr><td><a href="{{$d.Current.Base}}{{.Path}}" target="_blank" rel="noopener noreferrer">{{.Path}}</a>{{if .Draft}} <span class="badge draft">draft</span>{{end}}</td><td>{{.Title}}</td><td class="small">{{join .Types " · "}} <a class="small" href="/sites/pages/add?site={{$d.Current.Index}}&amp;page={{.Path}}">Add a section</a></td>{{if $d.Conv}}{{with conv $d.Conv .Path}}<td class="num">{{num .Visitors}}</td><td class="num">{{if .Conversions}}<strong>{{num .Conversions}}</strong>{{else}}<span class="muted">0</span>{{end}}</td>{{end}}{{end}}</tr>{{end}}</tbody>
</table></div>
{{else}}<p class="help">No page is built from sections yet.</p>{{end}}
{{with $d.OtherPages}}