Files
supermarket/cmd/supermarket/main.go
T
davidandClaude Opus 5.5 c36f786ae9 Fixes from the first round of TEST.md
SEO: a domain property (sc-domain:) covers every subdomain, so the shop,
Gitea and forum were counted as the website. What ranks, the morning
check, the Monday report, keywords, change candidates and the audit's
traffic now read only the website's own host (with or without www).
The report keeps pages worth a proposal apart from "Waiting for your
yes", explains only moves past the thresholds, and says "places up/down".

Also:
- Feed summaries drop the posts' scripts and styles.
- Spend you log can't be negative.
- Test and check buttons can't be clicked twice while they run.
- Previews show the site's web fonts and icon sprites.
- Backups are read without leaving -wal/-shm files; deleting one removes
  them, and leftovers are swept at start.
- The Overview's setup flags a CRM that Hermes can't reach.
- Import now says what came in; adding a prospect that exists says so;
  prospects can be deleted.
- Signal tags and brief addresses keep accented letters (Ü → u).
- Page errors start with a capital; clearer messages for bad uploads,
  CRM retry and cancel, keywords, and the finished audit.
- The module you're in stays unfolded in the sidebar.
- A picked keyword can be unpicked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 06:31:42 -07:00

329 lines
9.8 KiB
Go

// Supermarket serves the marketing suite's web app. It's meant to run in
// its Docker container (see compose.yaml), with its data folder at /data.
//
// Environment:
//
// SUPERMARKET_DATA data folder (default /data)
// SUPERMARKET_ADDR listen address (default :8080)
// SUPERMARKET_PUBLIC_URL the address the browser uses (default http://localhost:8470)
// SUPERMARKET_CORE_CONF CoreDesktop's core.conf (default <data>/core.conf)
// SUPERMARKET_MCP_SOCKET Unix socket for agents' MCP (default <data>/mcp.sock)
// SUPERMARKET_HOST_DATA the data folder's path on the host, to show in
// setup instructions (default: same as the data folder)
package main
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"supermarket/internal/ai"
"supermarket/internal/backup"
"supermarket/internal/content"
"supermarket/internal/core"
"supermarket/internal/crm"
"supermarket/internal/db"
"supermarket/internal/fileutil"
"supermarket/internal/legacy"
"supermarket/internal/mcpserver"
"supermarket/internal/secrets"
"supermarket/internal/web"
)
// version is set at build time (-ldflags "-X main.version=...").
var version = "dev"
func main() {
if len(os.Args) > 1 && (os.Args[1] == "version" || os.Args[1] == "--version") {
fmt.Println(version)
return
}
if len(os.Args) > 1 && (os.Args[1] == "backup" || os.Args[1] == "backups" || os.Args[1] == "restore") {
if err := backupCommand(os.Args[1], os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
log := slog.New(slog.NewTextHandler(os.Stdout, nil))
if err := run(log); err != nil {
log.Error("stopped", "err", err)
os.Exit(1)
}
}
func env(key, def string) string {
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
return v
}
return def
}
func run(log *slog.Logger) error {
dataDir := env("SUPERMARKET_DATA", "/data")
addr := env("SUPERMARKET_ADDR", ":8080")
publicURL := strings.TrimRight(env("SUPERMARKET_PUBLIC_URL", "http://localhost:8470"), "/")
coreConf := env("SUPERMARKET_CORE_CONF", filepath.Join(dataDir, "core.conf"))
mcpSocket := env("SUPERMARKET_MCP_SOCKET", filepath.Join(dataDir, "mcp.sock"))
hostData := env("SUPERMARKET_HOST_DATA", dataDir)
// Everything the app writes (database, secrets, clones) is for this user
// only: it will hold contacts and credentials.
syscall.Umask(0o077)
if err := os.MkdirAll(dataDir, 0700); err != nil {
return err
}
// A restore staged before the restart is swapped in before the
// database opens.
if r, err := backup.ApplyPending(dataDir, time.Now()); err != nil {
log.Error("backups: the restore wasn't applied", "err", err)
} else if r != nil {
log.Info("backups: restored", "from", r.From, "secrets", r.Secrets, "previous database", r.Backup)
}
// Old hand-made copies (app.db.pre-*) join the backups.
if n := backup.AdoptLegacy(dataDir, func(name string, err error) {
log.Warn("backups: an old copy was left where it is", "file", name, "err", err)
}); n > 0 {
log.Info("backups: moved old copies into the backups folder", "count", n)
}
if n := backup.RemoveOrphans(backup.Dir(dataDir)); n > 0 {
log.Info("backups: removed -wal and -shm files of deleted backups", "count", n)
}
db.BeforeMigrate = func(d *sql.DB, from, to int) error {
b, err := backup.Make(d, backup.Dir(dataDir), backup.Migration, fmt.Sprintf("before-schema-%d", to), time.Now())
if err == nil {
log.Info("backups: backed up before migrating", "from", from, "to", to, "file", b.Name)
}
return err
}
database, err := db.Open(filepath.Join(dataDir, "app.db"))
if err != nil {
return err
}
defer database.Close()
if n, err := content.RecoverInterrupted(database); err != nil {
return err
} else if n > 0 {
log.Warn("drafts were being published when Supermarket stopped; marked failed for review", "count", n)
}
// Hermes' Anthropic key and model, if the user chose to share them
ai.SharedFile = filepath.Join(dataDir, "hermes-ai.json")
// What Hermes' CRM job checks before it runs; see internal/crm.
crm.StateFile = filepath.Join(dataDir, "crm-state")
if err := crm.WriteState(database, time.Now()); err != nil {
log.Error("writing the CRM state file", "err", err)
}
sec, err := secrets.Open(filepath.Join(dataDir, "secrets.json"))
if err != nil {
return err
}
token, err := mcpToken(filepath.Join(dataDir, "mcp-token"))
if err != nil {
return err
}
c, err := core.Load(coreConf)
if err != nil {
log.Warn("couldn't read the Core's settings", "file", coreConf, "err", err)
}
// The import never stops the app: a bad old file is reported on the
// overview page instead.
status, importErr := legacy.Import(database, sec, filepath.Join(dataDir, "import"))
if importErr != nil {
log.Error("importing the old app's data", "err", importErr)
} else if status != nil {
log.Info("imported the old app's data", "summary", strings.Join(status.Summary, "; "))
}
if status == nil && importErr == nil {
status, _ = legacy.LoadStatus(database)
}
srv := &web.Server{
DB: database,
Secrets: sec,
Core: c,
DataDir: dataDir,
PublicURL: publicURL,
Version: version,
MCPToken: token,
MCPSocket: filepath.Join(hostData, filepath.Base(mcpSocket)),
MCP: mcpserver.Handler(database, token, version),
Log: log,
ImportStatus: status,
ImportErr: importErr,
}
handler, err := srv.Handler()
if err != nil {
return err
}
httpServer := &http.Server{
Addr: addr,
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// A restore from the browser stops the app; Docker starts it again
// (restart: unless-stopped), and the restore is applied on the way up.
srv.Restart = stop
errCh := make(chan error, 2)
go func() {
if err := mcpserver.ServeSocket(ctx, database, version, mcpSocket, log); err != nil {
errCh <- fmt.Errorf("MCP socket %s: %w", mcpSocket, err)
}
}()
go srv.RunScheduler(ctx)
go srv.RunImports(ctx)
go srv.RunDiscovery(ctx)
go srv.RunOutreach(ctx)
go srv.RunTracking(ctx)
go srv.RunSEO(ctx)
go srv.RunMetrics(ctx)
go srv.RunBackups(ctx)
// A sync falls due, and a claim times out, without anything being
// written: refresh the state file each minute.
go func() {
t := time.NewTicker(time.Minute)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case now := <-t.C:
if err := crm.WriteState(database, now); err != nil {
log.Error("writing the CRM state file", "err", err)
}
}
}
}()
go func() {
log.Info("Supermarket is running", "version", version, "listen", addr, "open", publicURL)
errCh <- httpServer.ListenAndServe()
}()
select {
case err := <-errCh:
if !errors.Is(err, http.ErrServerClosed) {
return err
}
case <-ctx.Done():
log.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
return err
}
}
return nil
}
// mcpToken reads the bearer token agents use for /mcp, creating it if there
// is none. install.sh may create it first, to give it to Hermes.
func mcpToken(path string) (string, error) {
raw, err := os.ReadFile(path)
if err == nil {
if t := strings.TrimSpace(string(raw)); len(t) >= 32 {
return t, nil
}
} else if !errors.Is(err, os.ErrNotExist) {
return "", err
}
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
t := hex.EncodeToString(b)
if err := fileutil.WriteFileAtomic(path, []byte(t+"\n"), 0600); err != nil {
return "", err
}
return t, nil
}
// backupCommand runs `supermarket backup [note]` and `supermarket backups`
// (inside the container: the host's command runs them with docker exec).
// It reads the database beside the running app, which WAL allows; it
// never migrates it.
func backupCommand(cmd string, args []string) error {
dataDir := env("SUPERMARKET_DATA", "/data")
dir := backup.Dir(dataDir)
if cmd == "backups" {
bs, err := backup.List(dir)
if err != nil {
return err
}
if len(bs) == 0 {
fmt.Println("No backups yet.")
return nil
}
for _, b := range bs {
schema := fmt.Sprintf("schema %d", b.Schema)
if b.Schema < 0 {
schema = "unreadable"
}
fmt.Printf("%-60s %8.1f MB %s\n", b.Name, float64(b.Size)/(1<<20), schema)
}
return nil
}
path := filepath.Join(dataDir, "app.db")
if _, err := os.Stat(path); err != nil {
return fmt.Errorf("no database at %s", path)
}
d, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(10000)")
if err != nil {
return err
}
defer d.Close()
if cmd == "restore" {
if len(args) != 1 {
return errors.New("usage: supermarket restore <backup name or file>")
}
src := args[0]
if !filepath.IsAbs(src) {
src = filepath.Join(dir, src)
}
r, err := backup.Stage(d, dataDir, src, db.Schema(), time.Now())
if err != nil {
return err
}
fmt.Printf("Ready to restore %s; the current database is backed up as %s.\n", r.From, r.Backup)
if r.Secrets {
fmt.Println("Its secrets.json (keys and tokens) will replace this one; the current one is kept in the backups folder.")
}
fmt.Println("It's applied when Supermarket restarts.")
return nil
}
if len(args) > 0 && args[0] == "--with-secrets" {
p, err := backup.Archive(d, dataDir, time.Now())
if err != nil {
return err
}
fmt.Printf("Backed up, with secrets, to backups/%s\n", filepath.Base(p))
fmt.Println("It holds your keys and tokens: keep it as safe as they are, and delete it once you've moved.")
return nil
}
b, err := backup.Make(d, dir, backup.Manual, strings.Join(args, " "), time.Now())
if err != nil {
return err
}
fmt.Printf("Backed up to %s (%.1f MB)\n", b.Name, float64(b.Size)/(1<<20))
return nil
}