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>
This commit is contained in:
@@ -0,0 +1,299 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package legacy
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"supermarket/internal/ai"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/secrets"
|
||||
)
|
||||
|
||||
const oldConfigYAML = `applications:
|
||||
- name: "Nextcloud"
|
||||
description: "Files"
|
||||
twitter_handle: "Nextclouders"
|
||||
youtube_channel_id: "UCx"
|
||||
instagram_handle: ""
|
||||
hashtags: ["#Nextcloud", "SelfHosted"]
|
||||
- name: "Jitsi"
|
||||
description: "Video"
|
||||
twitter_handle: "jitsinews"
|
||||
credentials:
|
||||
twitter:
|
||||
bearer_token: "bt"
|
||||
client_id: "cid"
|
||||
oauth2_access_token: "at"
|
||||
oauth2_refresh_token: "rt"
|
||||
linkedin:
|
||||
access_token: ""
|
||||
claude:
|
||||
api_key: "sk-old"
|
||||
model: "claude-sonnet-4-6"
|
||||
posting:
|
||||
twitter_handle: "federatedcomp"
|
||||
max_length: 280
|
||||
settings:
|
||||
max_results: 15
|
||||
`
|
||||
|
||||
func write(t *testing.T, dir, name, body string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImport(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
importDir := filepath.Join(dir, "import")
|
||||
os.Mkdir(importDir, 0700)
|
||||
write(t, importDir, "config.yaml", oldConfigYAML)
|
||||
write(t, importDir, "state.json", `{"last_checked":{"Nextcloud":"2026-11-01T10:00:00Z"}}`)
|
||||
write(t, importDir, "posts.json", `{"posts":[{"id":"1","app_name":"Jitsi","content":"Hi","source_url":"https://x.com/1","generated_at":"2026-11-02T10:00:00Z","posted_to":["x"]}]}`)
|
||||
write(t, importDir, "dismissed.json", `{"ids":{"a":true,"b":true,"c":false}}`)
|
||||
|
||||
d, err := db.Open(filepath.Join(dir, "app.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
sec, _ := secrets.Open(filepath.Join(dir, "secrets.json"))
|
||||
// A key entered in the new app must survive the import.
|
||||
sec.Set(map[string]string{secrets.AnthropicAPIKey: "sk-new"})
|
||||
|
||||
st, err := Import(d, sec, importDir)
|
||||
if err != nil || st == nil {
|
||||
t.Fatalf("import: %v %v", st, err)
|
||||
}
|
||||
|
||||
entries, _ := inventory.List(d, inventory.Partner)
|
||||
if len(entries) != 2 || entries[1].Name != "Nextcloud" || entries[1].Hashtags[1] != "#SelfHosted" {
|
||||
t.Errorf("inventory: %+v", entries)
|
||||
}
|
||||
if sec.Get(secrets.XAccessToken) != "at" || sec.Get(secrets.XRefreshToken) != "rt" || sec.Get(secrets.XBearerToken) != "bt" {
|
||||
t.Error("X credentials not imported")
|
||||
}
|
||||
if sec.Get(secrets.AnthropicAPIKey) != "sk-new" {
|
||||
t.Error("import overwrote a newer key")
|
||||
}
|
||||
if sec.Has(secrets.LinkedInAccessToken) {
|
||||
t.Error("empty values must not be imported")
|
||||
}
|
||||
cfg, _ := ai.LoadConfig(d)
|
||||
if cfg.Model != "claude-sonnet-4-6" {
|
||||
t.Errorf("model = %q", cfg.Model)
|
||||
}
|
||||
p, _ := profile.Load(d)
|
||||
if p.Accounts.X != "federatedcomp" {
|
||||
t.Errorf("x account = %q", p.Accounts.X)
|
||||
}
|
||||
var cs ContentSettings
|
||||
d.GetJSON(ContentSettingsKey, &cs)
|
||||
if cs.MaxLength != 280 || cs.MaxResults != 15 || cs.LookbackDays != 7 {
|
||||
t.Errorf("content settings = %+v", cs)
|
||||
}
|
||||
count := func(q string) int {
|
||||
var n int
|
||||
d.QueryRow(q).Scan(&n)
|
||||
return n
|
||||
}
|
||||
if count(`SELECT count(*) FROM posts WHERE posted_to = '["x"]'`) != 1 {
|
||||
t.Error("posts not imported")
|
||||
}
|
||||
if count(`SELECT count(*) FROM dismissed`) != 2 {
|
||||
t.Error("dismissed not imported")
|
||||
}
|
||||
if count(`SELECT count(*) FROM fetch_state WHERE key = 'inventory:Nextcloud'`) != 1 {
|
||||
t.Error("state not imported")
|
||||
}
|
||||
|
||||
// Runs once.
|
||||
if st, err := Import(d, sec, importDir); st != nil || err != nil {
|
||||
t.Errorf("second import ran: %v %v", st, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportNothingToDo(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
d, _ := db.Open(filepath.Join(dir, "app.db"))
|
||||
defer d.Close()
|
||||
sec, _ := secrets.Open(filepath.Join(dir, "secrets.json"))
|
||||
if st, err := Import(d, sec, filepath.Join(dir, "import")); st != nil || err != nil {
|
||||
t.Errorf("got %v %v", st, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportBadFileIsRetried(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write(t, dir, "config.yaml", oldConfigYAML)
|
||||
write(t, dir, "posts.json", `{not json`)
|
||||
d, _ := db.Open(filepath.Join(dir, "app.db"))
|
||||
defer d.Close()
|
||||
sec, _ := secrets.Open(filepath.Join(dir, "secrets.json"))
|
||||
if _, err := Import(d, sec, dir); err == nil {
|
||||
t.Fatal("expected an error for posts.json")
|
||||
}
|
||||
write(t, dir, "posts.json", `{"posts":[]}`)
|
||||
if st, err := Import(d, sec, dir); err != nil || st == nil {
|
||||
t.Fatalf("retry: %v %v", st, err)
|
||||
}
|
||||
entries, _ := inventory.List(d, "")
|
||||
if len(entries) != 2 {
|
||||
t.Errorf("retry duplicated or lost entries: %d", len(entries))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user