docs/architecture/configuration.md decides that "install.sh must stop generating
config.toml; archied setup owns it", and gives the reason: the installer
hand-rolling TOML already drifted from the schema once, and "the durable fix is
that the code writing the config is the code that reads it". setup.Run,
tomlwrite, configtemplate.Example and terminalprompt were all built for that and
had no production caller between them. This adds the caller.
setup.Run's own doc comment states the obligations, and they are the shape of
installValidatedConfig: render the edits, prove the result loads through a real
configuration.Loader, and only then install the file and commit the secrets. A
validation failure returns before either write, so a bad config leaves neither a
config nor a secret on disk. The rendered bytes are proven from a temp file, so
a load failure cannot have already installed anything. The config is written
0600 via same-directory temp and rename.
Parameterisation is typed, not matched against prompt text. A flag-to-prompt
mapping would have to match strings, which is the brittleness removed in
1f3f54b, so setup.Params is consulted before each question instead and the
prompts are only reached for answers nothing supplied. Run stays a wrapper
passing the zero value, so the package's existing tests keep passing untouched.
No environment variable is consulted anywhere: flags and prompts are the only
two ways an answer arrives.
--defaults is a known-valid unattended baseline, not "each prompt's own default".
That cannot work, and the test proves it: the provider step's first option is
OpenAI, whose model prompt hard-errors on an empty answer. The baseline therefore
covers every required answer and leaves optional ones to answer themselves as
"skip" -- ollama is the only keyless provider, so an unattended install boots
without needing a secret.
Two gaps closed after review rather than left as accepted work:
- A cloud provider was not configurable without a terminal, because the provider
API key had no typed parameter: unattended setup could only ever pick the
keyless self-hosted provider. Params.ProviderAPIKey and -provider-api-key fix
that. The key goes to the env file and TOML carries only the secret reference.
- The write order was unpinned. Inverting installValidatedConfig's two writes --
committing secrets before the config -- left every test green, so nothing held
the invariant the SecretSink contract states. The new
TestInstallValidatedConfig_ConfigWriteFailureLeavesNoSecret fails on that
inversion; the existing validation-failure test does not cover it.
Also fixed three lint failures in the first pass (gocyclo on RunSetup, and two
ineffectual `choice` initialisers): RunSetup's flag surface, the flag-to-Params
mapping, the prompter choice and the existing-config read are now separate
functions, which is the real fix for the complexity rather than a suppression.
The setup flow no longer hand-rolls its own answer format: -telegram-user-ids
reuses setup.ParseTelegramUserIDs, the same parser the prompt path uses, so the
allowlist cannot be parsed two ways.
Found by an adversarial package sweep (temp tracker: config-1,
repo-root-deployment-2, .local/issue-tracker/). Plan of record:
.local/issue-tracker/design-archied-setup.md. install.sh still generates its own
config; that is phase 2 and is not claimed here.
155 lines
6.1 KiB
Go
155 lines
6.1 KiB
Go
// Package setup drives archied's interactive first-run configuration flow
|
|
// and produces the TOML edits to persist it. See the [Run] doc comment for
|
|
// why it returns edits rather than a config.Config: the whole point of this
|
|
// feature is to stop the config-writing code and the config-reading code
|
|
// disagreeing about the schema, and building a second, parallel
|
|
// representation to validate against would reintroduce exactly that risk
|
|
// inside setup itself.
|
|
package setup
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite"
|
|
)
|
|
|
|
// SecretSink is where setup sends the secret values a step collects. setup
|
|
// edits config.toml keys; it does not write the env file itself. Put is
|
|
// expected to buffer rather than write immediately -- the caller commits only
|
|
// once the config text setup produced has been proven loadable, so a
|
|
// validation failure after some secrets were already prompted for never
|
|
// leaves a secret written without the config that references it, or vice
|
|
// versa. [EnvFileSink] is the concrete implementation for the env file that
|
|
// sits beside config.toml; the caller owns the path and constructs it.
|
|
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
|
|
}
|
|
|
|
// 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 supplies pre-answered values for the setup flow's question sites.
|
|
// Each step consults Params first and only asks the Prompter when the
|
|
// corresponding field is unset, so an unattended install can state what it
|
|
// wants without a terminal and without matching against prompt text -- the
|
|
// brittleness class removed in 9a4f11c (prompt text is not a stable key for
|
|
// a flag-to-answer mapping).
|
|
//
|
|
// Provider is a config class ("openai", "anthropic", "openrouter", "gemini",
|
|
// "groq", "deepseek", "mistral", or "ollama" for the self-hosted path). Model
|
|
// is the bare model name; the step adds the "class/" prefix. TelegramUserIDs
|
|
// non-empty is the signal to configure Telegram -- the step already refuses
|
|
// an empty allowlist, so an empty slice means "ask" (or "skip" when the
|
|
// prompter's default is no).
|
|
type Params struct {
|
|
BotUser string
|
|
Operator string
|
|
ForgeType string // github | gitea | none
|
|
ForgeHost string
|
|
ForgeToken string
|
|
Provider string // openai | anthropic | openrouter | gemini | groq | deepseek | mistral | ollama
|
|
Model string // bare model name; the step adds the "class/" prefix
|
|
// ProviderAPIKey is a cloud provider key. It is written to the env file and
|
|
// referenced from TOML, never stored in the config itself. Supplying it is
|
|
// what makes a cloud provider configurable without a terminal: the keyless
|
|
// self-hosted provider was previously the only unattended option.
|
|
ProviderAPIKey string
|
|
TelegramToken string
|
|
TelegramUserIDs []int64 // non-empty means "configure Telegram"
|
|
}
|
|
|
|
// Run drives the interactive setup flow and returns the TOML edits to
|
|
// apply. It does not read or write any file itself: the caller renders the
|
|
// edits (tomlwrite.Generate against a fresh template, or tomlwrite.Apply
|
|
// against an existing config's bytes for a re-run) and must prove the
|
|
// result loads through a real configuration.Loader before installing it or
|
|
// calling secrets.Commit.
|
|
func Run(ctx context.Context, p Prompter, discovery ModelDiscovery, secrets SecretSink, existing ExistingValues) ([]tomlwrite.Edit, error) {
|
|
return RunParams(ctx, p, discovery, secrets, existing, Params{})
|
|
}
|
|
|
|
// RunParams is Run 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})
|
|
}
|
|
}
|
|
}
|
|
|
|
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)
|
|
for _, role := range []string{"triage", "planner", "builder"} {
|
|
add(tableEdits{"models": {role: 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
|
|
}
|