Files
supermarket/internal/legacy/legacy.go
T
davidandClaude Opus 5.5 d039484a4a Phase 0: turn Supermarket into a Dockerized local web app
Replace the old Go TUI with a web app (port 8470) that runs in a
container as a CoreDesktop sibling:

- cmd/supermarket server with htmx web UI: dashboard, company profile,
  inventory (partners/competitors), AI and credential settings, and a
  Core & Hermes page
- SQLite storage and a secrets store under ~/.local/share/supermarket
- AI providers (Anthropic, OpenAI-compatible) behind one interface
- MCP server and a Hermes bridge to the Federated Core MCP hub
- Import of the old Coremarketing TUI's state
- install.sh / update.sh / lib.sh, Dockerfile, compose.yaml, the
  bin/supermarket launcher and hermes/setup.sh

Posting is not wired back up yet; that comes in Phase 1. See PLAN.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:38:09 -07:00

300 lines
8.2 KiB
Go

// Package legacy imports the data of the old terminal app (config.yaml,
// state.json, posts.json, dismissed.json) once, on the first start that finds
// them in the data folder's import/ directory. install.sh copies them there.
package legacy
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"gopkg.in/yaml.v3"
"supermarket/internal/ai"
"supermarket/internal/db"
"supermarket/internal/inventory"
"supermarket/internal/profile"
"supermarket/internal/secrets"
)
const doneKey = "legacy_import"
// ContentSettings are the old app's posting and fetching settings, which the
// content module reads.
type ContentSettings struct {
MaxLength int `json:"max_length"`
MaxResults int `json:"max_results"`
LookbackDays int `json:"lookback_days"`
}
const ContentSettingsKey = "content"
// Status records that the import ran, and what it did.
type Status struct {
At time.Time `json:"at"`
Summary []string `json:"summary"`
}
// LoadStatus returns the import's status, or nil if it never ran.
func LoadStatus(d *db.DB) (*Status, error) {
var s Status
ok, err := d.GetJSON(doneKey, &s)
if err != nil || !ok {
return nil, err
}
return &s, nil
}
type oldConfig struct {
Applications []inventory.Entry `yaml:"applications"`
Credentials struct {
Twitter struct {
BearerToken string `yaml:"bearer_token"`
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"`
OAuth2AccessToken string `yaml:"oauth2_access_token"`
OAuth2RefreshToken string `yaml:"oauth2_refresh_token"`
} `yaml:"twitter"`
LinkedIn struct {
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"`
AccessToken string `yaml:"access_token"`
AuthorURN string `yaml:"author_urn"`
} `yaml:"linkedin"`
YouTube struct {
APIKey string `yaml:"api_key"`
} `yaml:"youtube"`
Claude struct {
APIKey string `yaml:"api_key"`
Model string `yaml:"model"`
} `yaml:"claude"`
} `yaml:"credentials"`
Posting struct {
TwitterHandle string `yaml:"twitter_handle"`
MaxLength int `yaml:"max_length"`
} `yaml:"posting"`
Settings struct {
MaxResults int `yaml:"max_results"`
DefaultLookbackDays int `yaml:"default_lookback_days"`
} `yaml:"settings"`
}
// Import imports dir's files if it hasn't already. Nothing in dir is
// changed or deleted. It returns nil, nil when there is nothing to do.
func Import(d *db.DB, sec *secrets.Store, dir string) (*Status, error) {
if s, err := LoadStatus(d); err != nil || s != nil {
return nil, err
}
cfgPath := filepath.Join(dir, "config.yaml")
raw, err := os.ReadFile(cfgPath)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var cfg oldConfig
if err := yaml.Unmarshal(raw, &cfg); err != nil {
return nil, fmt.Errorf("%s: %w", cfgPath, err)
}
st := &Status{At: time.Now().UTC()}
note := func(format string, args ...any) { st.Summary = append(st.Summary, fmt.Sprintf(format, args...)) }
// The old list was Federated Core's apps, which Federated promotes: import
// them as partners, for the user to re-label.
for i := range cfg.Applications {
if strings.TrimSpace(cfg.Applications[i].Relationship) == "" {
cfg.Applications[i].Relationship = inventory.Partner
}
}
res := inventory.Import(d, cfg.Applications, false)
note("Inventory: %d added as partners, %d already there", res.Added, res.Skipped)
for _, e := range res.Errors {
note("Inventory error: %s", e)
}
c := cfg.Credentials
creds := map[string]string{
secrets.XBearerToken: c.Twitter.BearerToken,
secrets.XClientID: c.Twitter.ClientID,
secrets.XClientSecret: c.Twitter.ClientSecret,
secrets.XAccessToken: c.Twitter.OAuth2AccessToken,
secrets.XRefreshToken: c.Twitter.OAuth2RefreshToken,
secrets.LinkedInClientID: c.LinkedIn.ClientID,
secrets.LinkedInClientSecret: c.LinkedIn.ClientSecret,
secrets.LinkedInAccessToken: c.LinkedIn.AccessToken,
secrets.LinkedInAuthorURN: c.LinkedIn.AuthorURN,
secrets.YouTubeAPIKey: c.YouTube.APIKey,
secrets.AnthropicAPIKey: c.Claude.APIKey,
}
// Only fill in what's missing, so a re-import never replaces newer
// credentials entered in the app.
updates := map[string]string{}
for k, v := range creds {
v = strings.TrimSpace(v)
if v != "" && !sec.Has(k) {
updates[k] = v
}
}
if len(updates) > 0 {
if err := sec.Set(updates); err != nil {
return nil, fmt.Errorf("saving imported credentials: %w", err)
}
}
note("Credentials: %d imported", len(updates))
if c.Claude.APIKey != "" {
aiCfg, err := ai.LoadConfig(d)
if err != nil {
return nil, err
}
if m := strings.TrimSpace(c.Claude.Model); m != "" {
aiCfg.Provider = ai.ProviderAnthropic
aiCfg.Model = m
if err := ai.SaveConfig(d, aiCfg); err != nil {
return nil, err
}
note("AI: Anthropic, model %s (from the old config; change it in Settings)", m)
}
}
if h := strings.TrimSpace(cfg.Posting.TwitterHandle); h != "" {
p, err := profile.Load(d)
if err != nil {
return nil, err
}
if p.Accounts.X == "" {
p.Accounts.X = h
if err := profile.Save(d, p); err != nil {
return nil, err
}
note("Profile: X account @%s", strings.TrimPrefix(h, "@"))
}
}
cs := ContentSettings{MaxLength: 280, MaxResults: 20, LookbackDays: 7}
if cfg.Posting.MaxLength > 0 {
cs.MaxLength = cfg.Posting.MaxLength
}
if cfg.Settings.MaxResults > 0 {
cs.MaxResults = cfg.Settings.MaxResults
}
if cfg.Settings.DefaultLookbackDays > 0 {
cs.LookbackDays = cfg.Settings.DefaultLookbackDays
}
if err := d.PutJSON(ContentSettingsKey, cs); err != nil {
return nil, err
}
n, err := importState(d, filepath.Join(dir, "state.json"))
if err != nil {
return nil, err
}
note("Last-checked times: %d", n)
n, err = importPosts(d, filepath.Join(dir, "posts.json"))
if err != nil {
return nil, err
}
note("Queued posts: %d", n)
n, err = importDismissed(d, filepath.Join(dir, "dismissed.json"))
if err != nil {
return nil, err
}
note("Dismissed items: %d", n)
if err := d.PutJSON(doneKey, st); err != nil {
return nil, err
}
return st, nil
}
// readJSON decodes path into out, reporting false if the file doesn't exist.
func readJSON(path string, out any) (bool, error) {
raw, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
if err != nil {
return false, err
}
if err := json.Unmarshal(raw, out); err != nil {
return false, fmt.Errorf("%s: %w", path, err)
}
return true, nil
}
func importState(d *db.DB, path string) (int, error) {
var st struct {
LastChecked map[string]time.Time `json:"last_checked"`
}
if ok, err := readJSON(path, &st); !ok || err != nil {
return 0, err
}
n := 0
for name, t := range st.LastChecked {
if _, err := d.Exec(`INSERT OR IGNORE INTO fetch_state (key, last_checked) VALUES (?, ?)`,
"inventory:"+name, t.UTC().Format(time.RFC3339)); err != nil {
return n, err
}
n++
}
return n, nil
}
func importPosts(d *db.DB, path string) (int, error) {
var ps struct {
Posts []struct {
ID string `json:"id"`
AppName string `json:"app_name"`
Content string `json:"content"`
SourceURL string `json:"source_url"`
GeneratedAt time.Time `json:"generated_at"`
PostedTo []string `json:"posted_to"`
} `json:"posts"`
}
if ok, err := readJSON(path, &ps); !ok || err != nil {
return 0, err
}
n := 0
for _, p := range ps.Posts {
posted, _ := json.Marshal(p.PostedTo)
if p.PostedTo == nil {
posted = []byte("[]")
}
if _, err := d.Exec(`INSERT OR IGNORE INTO posts (id, inventory_name, content, source_url, generated_at, posted_to)
VALUES (?, ?, ?, ?, ?, ?)`, p.ID, p.AppName, p.Content, p.SourceURL,
p.GeneratedAt.UTC().Format(time.RFC3339), string(posted)); err != nil {
return n, err
}
n++
}
return n, nil
}
func importDismissed(d *db.DB, path string) (int, error) {
var ds struct {
IDs map[string]bool `json:"ids"`
}
if ok, err := readJSON(path, &ds); !ok || err != nil {
return 0, err
}
n := 0
for id, dismissed := range ds.IDs {
if !dismissed {
continue
}
if _, err := d.Exec(`INSERT OR IGNORE INTO dismissed (item_id) VALUES (?)`, id); err != nil {
return n, err
}
n++
}
return n, nil
}