Files
archie/internal/infrastructure/configuration/setup/setup.go
T
sam ebc6dd67e6 fix(setup): offer the bundled database as an explicit choice on a re-run (#1388)
With an existing database_url, setup prefilled the URL, so a blank answer
kept it and the bundled socket database was unreachable without typing its
URL. The re-run database step now presents a choice menu: keep the existing
URL (still the default), switch to the bundled database (socket URL plus a
generated PGPASSWORD written to the env file), or enter a different URL.
Fresh installs and -database-url are unchanged; a blank answer anywhere
still keeps the existing URL. Pinned at the setup API level with fake
prompter/sink: TestRunParamsDatabaseChoice.
2026-10-31 20:03:33 +11:00

199 lines
6.5 KiB
Go

// Package setup runs archied's first-run configuration flow and returns the
// TOML edits to persist it.
package setup
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite"
)
// SecretSink receives the secret values setup collects. Put buffers; the
// caller commits once the generated config is proven loadable.
type SecretSink interface {
// Put records that key (as looked up through engine) must resolve to
// value once Commit is called.
Put(engine, key, value string) error
// Commit persists everything Put has recorded so far.
Commit() error
}
// ModelDiscovery finds locally available models for the self-hosted
// provider path. A nil ModelDiscovery, or one that returns an error,
// degrades to a free-text model name -- discovery is a convenience, not a
// requirement.
type ModelDiscovery interface {
ListOllamaModels(ctx context.Context) ([]string, error)
}
// ExistingValues prefills prompts on a re-run. The zero value is correct
// for a fresh install.
type ExistingValues struct {
BotUser string
Operator string
ForgeHost string
DatabaseURL string
}
// tableEdits groups pending edits by table before Run flattens them into
// []tomlwrite.Edit, so a step can build "everything for [forge]" as one
// value and let Run decide the flattening order.
type tableEdits = map[string]map[string]string
// Params pre-answers setup questions; a step prompts only for unset fields.
// Provider is a config class; Model is the bare model name.
type Params struct {
DatabaseURL string
BotUser string
Operator string
ForgeType string // github | gitea | none
ForgeHost string
Provider string // openai | anthropic | openrouter | gemini | groq | deepseek | mistral | ollama
Model string // bare model name; the step adds the "class/" prefix
// TelegramUserIDs non-empty configures Telegram. The reference fields name
// already-stored secrets as engine:key; when set, the step writes the
// reference without prompting.
ForgeTokenRef config.SecretRef
ProviderAPIKeyRef config.SecretRef
TelegramTokenRef config.SecretRef
TelegramUserIDs []int64
// Secret values are never parameters; they come from a prompt through
// SecretSink.
}
// RunParams drives the setup flow with the question sites pre-answered from params. A zero
// Params behaves exactly like Run.
func RunParams(ctx context.Context, p Prompter, discovery ModelDiscovery, secrets SecretSink, existing ExistingValues, params Params) ([]tomlwrite.Edit, error) {
var edits []tomlwrite.Edit
add := func(all tableEdits) {
for table, kv := range all {
for k, v := range kv {
edits = append(edits, tomlwrite.Edit{Table: table, Key: k, Value: v})
}
}
}
dbURL, err := stepDatabase(ctx, p, secrets, existing.DatabaseURL, params.DatabaseURL)
if err != nil {
return nil, err
}
add(tableEdits{"": {"database_url": tomlwrite.String(dbURL)}})
botUser := params.BotUser
if strings.TrimSpace(botUser) == "" {
var err error
botUser, err = p.ReadLine(ctx, "Bot user (forge username for archied's commits and API calls): ", existing.BotUser)
if err != nil {
return nil, fmt.Errorf("setup: bot user: %w", err)
}
}
if strings.TrimSpace(botUser) == "" {
return nil, fmt.Errorf("setup: bot user is required")
}
add(tableEdits{"": {"bot_user": tomlwrite.String(botUser)}})
operator := params.Operator
if strings.TrimSpace(operator) == "" {
var err error
operator, err = p.ReadLine(ctx, "Operator display name (shown to the chat agent; blank to skip): ", existing.Operator)
if err != nil {
return nil, fmt.Errorf("setup: operator: %w", err)
}
}
if strings.TrimSpace(operator) != "" {
add(tableEdits{"chat": {"operator": tomlwrite.String(operator)}})
}
providerEdits, model, err := stepProvider(ctx, p, discovery, secrets, params)
if err != nil {
return nil, err
}
add(providerEdits)
add(tableEdits{"models": {config.DefaultModelAlias: tomlwrite.String(model)}})
forgeEdits, err := stepForge(ctx, p, secrets, existing.ForgeHost, params)
if err != nil {
return nil, err
}
add(forgeEdits)
chatEdits, err := stepChat(ctx, p, secrets, params)
if err != nil {
return nil, err
}
add(chatEdits)
return edits, nil
}
// stepDatabase returns the PostgreSQL URL. A blank answer on a fresh install
// means the bundled database. On a re-run with an existing URL the bundled
// database is an explicit choice rather than something reachable only by
// typing its socket URL; keeping the existing URL is the first option, so
// the default answer is unchanged.
func stepDatabase(ctx context.Context, p Prompter, secrets SecretSink, existing, param string) (string, error) {
if strings.TrimSpace(param) != "" {
return param, nil
}
if strings.TrimSpace(existing) != "" {
choice, err := p.Select(ctx, "Database:", []string{
"Keep the existing database URL",
"Bundled database (Unix socket, generated password in the env file)",
"Enter a different PostgreSQL 18 URL",
})
if err != nil {
return "", fmt.Errorf("setup: database choice: %w", err)
}
switch choice {
case 0:
return existing, nil
case 1:
return bundledDatabase(secrets)
default:
url, err := p.ReadLine(ctx, "PostgreSQL 18 URL: ", "")
if err != nil {
return "", fmt.Errorf("setup: database url: %w", err)
}
if strings.TrimSpace(url) == "" {
// A blank answer keeps the existing URL, as it always has.
return existing, nil
}
return url, nil
}
}
prompt := "PostgreSQL 18 URL (blank for the bundled database with a generated password): "
url, err := p.ReadLine(ctx, prompt, "")
if err != nil {
return "", fmt.Errorf("setup: database url: %w", err)
}
if strings.TrimSpace(url) != "" {
return url, nil
}
return bundledDatabase(secrets)
}
// bundledDatabase switches to the bundled database: no network, reached
// through its Unix socket, with a generated password that goes only to the
// env file as PGPASSWORD, which pgx and Compose both read, so config.toml
// holds no secret.
func bundledDatabase(secrets SecretSink) (string, error) {
pw := make([]byte, 24)
if _, err := rand.Read(pw); err != nil {
return "", fmt.Errorf("setup: generate database password: %w", err)
}
password := hex.EncodeToString(pw)
if err := secrets.Put("env", "PGPASSWORD", password); err != nil {
return "", fmt.Errorf("setup: store database password: %w", err)
}
return "postgres://archie@/archie?host=" + configuration.DefaultPostgresSocketDir(), nil
}