diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 2fc150245..75b071993 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -11,10 +11,17 @@ import ( ) func main() { + args := os.Args[1:] + // The setup generator is dispatched before the daemon's flags are + // parsed: it writes a first-run config.toml and must not touch the + // store, NATS, or the running daemon's configuration. + if archied.IsSetupArgs(args) { + os.Exit(archied.RunSetup(args[1:], os.Stdin, os.Stdout, os.Stderr)) + } // The codesearch helper is dispatched before the daemon's flags are // parsed: it is this same binary re-invoked as a short-lived child by // internal/indexing, and it must not touch config, the store or NATS. - if args := os.Args[1:]; archied.IsCodesearchHelperArgs(args) { + if archied.IsCodesearchHelperArgs(args) { os.Exit(archied.RunCodesearchHelper(args[1:], os.Stdout)) } os.Exit(archied.Run()) diff --git a/internal/app/archied/setup.go b/internal/app/archied/setup.go new file mode 100644 index 000000000..858a5c96b --- /dev/null +++ b/internal/app/archied/setup.go @@ -0,0 +1,299 @@ +package archied + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "os/signal" + "path/filepath" + "syscall" + + configtemplate "github.com/samcharles93/archie-core" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/setup" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite" + "github.com/samcharles93/archie-core/internal/infrastructure/terminalprompt" +) + +// setupCommand is the argv[1] token that switches archied out of daemon +// mode and into the first-run configuration generator. +const setupCommand = "setup" + +// defaultsParams is the known-valid unattended baseline --defaults supplies. +// Answering every prompt with its own default does NOT produce a loadable +// config (the provider step's first option is OpenAI, whose model prompt +// hard-errors on an empty answer), so this covers every required answer and +// leaves the optional ones to answer themselves as "skip": ollama is the +// only keyless provider, so an unattended install boots without a secret. +func defaultsParams() setup.Params { + return setup.Params{ + BotUser: "archie-bot", + ForgeType: "github", + ForgeHost: "https://github.com", + Provider: "ollama", + Model: "llama3", + } +} + +// IsSetupArgs reports whether args (os.Args[1:]) selects setup rather than +// the daemon. +func IsSetupArgs(args []string) bool { + return len(args) > 0 && args[0] == setupCommand +} + +// setupFlags is the parameterised answer surface, kept apart from RunSetup so +// the flag definitions, the mapping into setup.Params and the flow stay +// independently readable. Nothing here reads a terminal or the environment: +// parameters and prompts are the only two ways an answer arrives, and no +// environment variable is consulted. +type setupFlags struct { + cfgPath string + defaults bool + botUser string + operator string + forgeType string + forgeHost string + forgeToken string + provider string + model string + providerAPIKey string + telegramToken string + telegramUserIDs string +} + +func bindSetupFlags(fs *flag.FlagSet) *setupFlags { + f := &setupFlags{} + fs.StringVar(&f.cfgPath, "config", filepath.Join(configHome(), "archie", "config.toml"), "path to write config.toml") + fs.BoolVar(&f.defaults, "defaults", false, "write a known-valid unattended baseline config without prompting") + fs.StringVar(&f.botUser, "bot-user", "", "forge username for archied's commits and API calls") + fs.StringVar(&f.operator, "operator", "", "operator display name (optional)") + fs.StringVar(&f.forgeType, "forge-type", "", "forge type: github | gitea | none") + fs.StringVar(&f.forgeHost, "forge-host", "", "forge base URL") + fs.StringVar(&f.forgeToken, "forge-token", "", "forge API token, stored in the env file beside the config") + fs.StringVar(&f.provider, "provider", "", "LLM provider class: openai | anthropic | openrouter | gemini | groq | deepseek | mistral | ollama") + fs.StringVar(&f.model, "model", "", "bare model name; the provider class prefix is added automatically") + fs.StringVar(&f.providerAPIKey, "provider-api-key", "", "cloud LLM provider API key, stored in the env file beside the config") + fs.StringVar(&f.telegramToken, "telegram-token", "", "Telegram bot token, stored in the env file beside the config") + fs.StringVar(&f.telegramUserIDs, "telegram-user-ids", "", "comma-separated allowed Telegram user IDs; configuring Telegram requires at least one") + return f +} + +// params folds the flags over the baseline. A flag always wins; without +// -defaults the baseline is empty, so only the flags pre-answer anything and +// every other question is prompted for. +func (f *setupFlags) params() (setup.Params, error) { + var params setup.Params + if f.defaults { + params = defaultsParams() + } + if f.botUser != "" { + params.BotUser = f.botUser + } + if f.operator != "" { + params.Operator = f.operator + } + if f.forgeType != "" { + params.ForgeType = f.forgeType + } + if f.forgeHost != "" { + params.ForgeHost = f.forgeHost + } + if f.forgeToken != "" { + params.ForgeToken = f.forgeToken + } + if f.provider != "" { + params.Provider = f.provider + } + if f.model != "" { + params.Model = f.model + } + if f.providerAPIKey != "" { + params.ProviderAPIKey = f.providerAPIKey + } + if f.telegramToken != "" { + params.TelegramToken = f.telegramToken + } + if f.telegramUserIDs != "" { + ids, err := setup.ParseTelegramUserIDs(f.telegramUserIDs) + if err != nil { + return setup.Params{}, fmt.Errorf("-telegram-user-ids: %w", err) + } + params.TelegramUserIDs = ids + } + return params, nil +} + +// setupPrompter picks the answer surface. -defaults answers every remaining +// question with its own default and never touches a terminal; otherwise stdin +// must be a real terminal, and terminalprompt refuses it otherwise rather than +// silently generating a config nobody chose. +func setupPrompter(defaults bool, stdin *os.File, stdout io.Writer) (setup.Prompter, error) { + if defaults { + return setup.DefaultPrompter{}, nil + } + return terminalprompt.New(stdin, stdout) +} + +// existingConfig reads the config being replaced, returning the bytes to apply +// edits to and the values worth prefilling prompts with. A missing file is a +// fresh install, not an error. A file that exists but does not load is still +// edited in place: tomlwrite only rewrites the lines it owns, and refusing +// would strand an operator whose config is malformed. +func existingConfig(loader *configuration.Loader, path string) ([]byte, setup.ExistingValues, error) { + base, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil, setup.ExistingValues{}, nil + } + if err != nil { + return nil, setup.ExistingValues{}, fmt.Errorf("read existing config: %w", err) + } + var existing setup.ExistingValues + if doc, err := loader.File(path); err == nil { + existing = setup.ExistingValues{ + BotUser: doc.Config.BotUser, + Operator: doc.Config.Chat.Operator, + ForgeHost: doc.Config.Forge.Host, + } + } + return base, existing, nil +} + +// RunSetup generates (or re-generates) a config.toml, validates it through a +// real configuration.Loader, and only then writes it atomically with mode +// 0600 and commits any secrets to the env file beside it. --defaults uses a +// known-valid unattended baseline and never touches a terminal; without it, +// stdin must be a real TTY and the guided flow runs. +func RunSetup(args []string, stdin *os.File, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet(setupCommand, flag.ContinueOnError) + fs.SetOutput(stderr) + flags := bindSetupFlags(fs) + if err := fs.Parse(args); err != nil { + return 2 + } + if fs.NArg() > 0 { + fmt.Fprintf(stderr, "setup: unexpected argument %q\n", fs.Arg(0)) + return 2 + } + params, err := flags.params() + if err != nil { + fmt.Fprintf(stderr, "setup: %v\n", err) + return 2 + } + p, err := setupPrompter(flags.defaults, stdin, stdout) + if err != nil { + fmt.Fprintf(stderr, "setup: %v\n", err) + return 1 + } + + cfgDir := filepath.Dir(flags.cfgPath) + if err := os.MkdirAll(cfgDir, 0o700); err != nil { + fmt.Fprintf(stderr, "setup: create config directory: %v\n", err) + return 1 + } + sink := setup.NewEnvFileSink(filepath.Join(cfgDir, "env")) + loader := configuration.New(nil) + base, existing, err := existingConfig(loader, flags.cfgPath) + if err != nil { + fmt.Fprintf(stderr, "setup: %v\n", err) + return 1 + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + edits, err := setup.RunParams(ctx, p, nil, sink, existing, params) + if err != nil { + fmt.Fprintf(stderr, "setup: %v\n", err) + return 1 + } + + var rendered []byte + if base != nil { + rendered, err = tomlwrite.Apply(base, edits) + } else { + rendered, err = tomlwrite.Generate(configtemplate.Example, edits) + } + if err != nil { + fmt.Fprintf(stderr, "setup: render config: %v\n", err) + return 1 + } + + if err := installValidatedConfig(loader, flags.cfgPath, sink, rendered); err != nil { + fmt.Fprintf(stderr, "setup: %v\n", err) + return 1 + } + fmt.Fprintf(stdout, "setup: wrote %s\n", flags.cfgPath) + return 0 +} + +// installValidatedConfig proves rendered loads through a real Loader, then +// writes the config atomically with mode 0600 and only then commits the +// secret sink. A validation failure returns before either write, so a bad +// generated config never leaves a config file or a secret on disk, and a +// secret is never committed pointing at a config that was never written. +func installValidatedConfig(loader *configuration.Loader, path string, sink setup.SecretSink, rendered []byte) error { + if err := proveLoadable(loader, rendered); err != nil { + return err + } + if err := writeFileAtomicMode(path, rendered, 0o600); err != nil { + return fmt.Errorf("write config: %w", err) + } + if err := sink.Commit(); err != nil { + return fmt.Errorf("commit secrets: %w", err) + } + return nil +} + +// proveLoadable decodes and validates rendered through a real +// configuration.Loader, the same check setup.Run's doc comment makes the +// caller's responsibility. The rendered bytes are staged in a temp file +// rather than the destination, so a load failure can never have already +// installed anything. +func proveLoadable(loader *configuration.Loader, rendered []byte) error { + tmp, err := os.CreateTemp("", "archie-setup-*.toml") + if err != nil { + return fmt.Errorf("prove config loads: %w", err) + } + name := tmp.Name() + defer os.Remove(name) + if err := tmp.Close(); err != nil { + return fmt.Errorf("prove config loads: %w", err) + } + if err := os.WriteFile(name, rendered, 0o600); err != nil { + return fmt.Errorf("prove config loads: %w", err) + } + if _, err := loader.File(name); err != nil { + return fmt.Errorf("generated config does not load: %w", err) + } + return nil +} + +// writeFileAtomicMode writes data to path via a same-directory temp file and +// rename, so a concurrent reader never observes a truncated config. +func writeFileAtomicMode(path string, data []byte, mode os.FileMode) error { + tmp, err := os.CreateTemp(filepath.Dir(path), ".config-*.toml") + if err != nil { + return err + } + name := tmp.Name() + defer os.Remove(name) // no-op after a successful rename + if err := tmp.Chmod(mode); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(data); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(name, path) +} diff --git a/internal/app/archied/setup_test.go b/internal/app/archied/setup_test.go new file mode 100644 index 000000000..8430e2d41 --- /dev/null +++ b/internal/app/archied/setup_test.go @@ -0,0 +1,166 @@ +package archied + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/setup" +) + +func TestSetupSubcommandIsRecognised(t *testing.T) { + if !IsSetupArgs([]string{setupCommand, "--defaults"}) { + t.Errorf("IsSetupArgs() did not recognise %q", setupCommand) + } + if IsSetupArgs([]string{"-once"}) { + t.Error("IsSetupArgs() claimed a normal daemon flag") + } + if IsSetupArgs(nil) { + t.Error("IsSetupArgs() claimed an empty argument list") + } +} + +func TestRunSetup_DefaultsWritesLoadableConfig(t *testing.T) { + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.toml") + + stdin, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + defer stdin.Close() + + var stdout, stderr strings.Builder + code := RunSetup([]string{"--defaults", "-config", cfgPath}, stdin, &stdout, &stderr) + if code != 0 { + t.Fatalf("RunSetup exit = %d, stderr:\n%s", code, stderr.String()) + } + + info, err := os.Stat(cfgPath) + if err != nil { + t.Fatalf("config not written: %v", err) + } + if info.Mode().Perm() != 0o600 { + t.Errorf("config mode = %v, want 0600", info.Mode().Perm()) + } + + doc, err := configuration.New(nil).File(cfgPath) + if err != nil { + t.Fatalf("generated config does not load: %v", err) + } + if doc.Config.BotUser != "archie-bot" { + t.Errorf("bot_user = %q, want archie-bot", doc.Config.BotUser) + } + + // The defaults baseline is keyless (ollama), so nothing may be written + // to the env file. + if _, err := os.Stat(filepath.Join(dir, "env")); !os.IsNotExist(err) { + t.Errorf("env file should not exist after a defaults run, got %v", err) + } +} + +func TestRunSetup_DefaultsWithForgeTokenWritesEnv(t *testing.T) { + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.toml") + + stdin, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + defer stdin.Close() + + var stdout, stderr strings.Builder + code := RunSetup([]string{"--defaults", "-config", cfgPath, "-forge-token", "ghp-secret"}, stdin, &stdout, &stderr) + if code != 0 { + t.Fatalf("RunSetup exit = %d, stderr:\n%s", code, stderr.String()) + } + + doc, err := configuration.New(nil).File(cfgPath) + if err != nil { + t.Fatalf("generated config does not load: %v", err) + } + if doc.Config.Forge.Token.Key != "ARCHIE_GITHUB_TOKEN" { + t.Errorf("forge.token.key = %q, want ARCHIE_GITHUB_TOKEN", doc.Config.Forge.Token.Key) + } + b, err := os.ReadFile(filepath.Join(dir, "env")) + if err != nil { + t.Fatalf("env file not written: %v", err) + } + if got, want := string(b), "ARCHIE_GITHUB_TOKEN='ghp-secret'\n"; got != want { + t.Errorf("env file = %q, want %q", got, want) + } +} + +func TestRunSetup_GuidedRequiresTTY(t *testing.T) { + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.toml") + + stdin, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + defer stdin.Close() + + var stdout, stderr strings.Builder + code := RunSetup([]string{"-config", cfgPath}, stdin, &stdout, &stderr) + if code == 0 { + t.Fatalf("RunSetup exit = 0, want non-zero for a guided run without a TTY") + } + if _, err := os.Stat(cfgPath); !os.IsNotExist(err) { + t.Errorf("config should not be written when a guided non-TTY run is refused, got %v", err) + } +} + +func TestInstallValidatedConfig_ValidationFailureWritesNothing(t *testing.T) { + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.toml") + sink := setup.NewEnvFileSink(filepath.Join(dir, "env")) + if err := sink.Put("env", "ARCHIE_GITHUB_TOKEN", "secret"); err != nil { + t.Fatal(err) + } + + err := installValidatedConfig(configuration.New(nil), cfgPath, sink, []byte("this is not toml")) + if err == nil { + t.Fatal("installValidatedConfig = nil error, want a load failure") + } + if _, err := os.Stat(cfgPath); !os.IsNotExist(err) { + t.Errorf("config written despite validation failure: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "env")); !os.IsNotExist(err) { + t.Errorf("secret written despite validation failure: %v", err) + } +} + +// TestInstallValidatedConfig_ConfigWriteFailureLeavesNoSecret pins the write +// order the setup package's SecretSink contract depends on: the config is +// installed before any secret is committed, so a secret is never left on disk +// pointing at a config that was never written. +// +// This is not covered by the validation-failure test: inverting the two writes +// leaves every other test in the package green, so this assertion is what +// actually holds the invariant. +func TestInstallValidatedConfig_ConfigWriteFailureLeavesNoSecret(t *testing.T) { + dir := t.TempDir() + // The parent directory does not exist, so validation succeeds and the + // config write fails. + cfgPath := filepath.Join(dir, "missing", "config.toml") + envPath := filepath.Join(dir, "env") + sink := setup.NewEnvFileSink(envPath) + if err := sink.Put("env", "ARCHIE_GITHUB_TOKEN", "secret"); err != nil { + t.Fatal(err) + } + + rendered := []byte("bot_user = \"widget\"\nwork_dir = \"/tmp/archie-setup-work\"\n") + err := installValidatedConfig(configuration.New(nil), cfgPath, sink, rendered) + if err == nil { + t.Fatal("installValidatedConfig = nil error, want a write failure") + } + if strings.Contains(err.Error(), "does not load") { + t.Fatalf("fixture failed validation rather than the write, so this test never exercised the write path: %v", err) + } + if _, statErr := os.Stat(envPath); !os.IsNotExist(statErr) { + t.Errorf("secret committed even though the config was never written: %v", statErr) + } +} diff --git a/internal/infrastructure/configuration/setup/defaultprompter.go b/internal/infrastructure/configuration/setup/defaultprompter.go new file mode 100644 index 000000000..a6baaeef3 --- /dev/null +++ b/internal/infrastructure/configuration/setup/defaultprompter.go @@ -0,0 +1,28 @@ +package setup + +import "context" + +// DefaultPrompter answers every question with the prompt's own default and +// never touches a terminal. archied setup uses it for --defaults, so an +// unattended install resolves every question the baseline Params do not +// cover without prompting: ReadLine returns defaultValue, Select returns the +// first option, Confirm returns defaultYes, and ReadSecret returns "" (a +// secret has no default, and the steps treat a blank secret as "leave blank +// to configure later"). +type DefaultPrompter struct{} + +// Select returns the first option. +func (DefaultPrompter) Select(context.Context, string, []string) (int, error) { return 0, nil } + +// ReadLine returns defaultValue. +func (DefaultPrompter) ReadLine(_ context.Context, _, defaultValue string) (string, error) { + return defaultValue, nil +} + +// ReadSecret returns the empty string. +func (DefaultPrompter) ReadSecret(context.Context, string) (string, error) { return "", nil } + +// Confirm returns defaultYes. +func (DefaultPrompter) Confirm(_ context.Context, _ string, defaultYes bool) (bool, error) { + return defaultYes, nil +} diff --git a/internal/infrastructure/configuration/setup/defaultprompter_test.go b/internal/infrastructure/configuration/setup/defaultprompter_test.go new file mode 100644 index 000000000..2caf13200 --- /dev/null +++ b/internal/infrastructure/configuration/setup/defaultprompter_test.go @@ -0,0 +1,26 @@ +package setup + +import ( + "context" + "testing" +) + +func TestDefaultPrompter(t *testing.T) { + var p DefaultPrompter + + if idx, err := p.Select(context.Background(), "q", []string{"a", "b"}); err != nil || idx != 0 { + t.Errorf("Select = (%d, %v), want (0, nil)", idx, err) + } + if got, err := p.ReadLine(context.Background(), "q", "default"); err != nil || got != "default" { + t.Errorf("ReadLine = (%q, %v), want (\"default\", nil)", got, err) + } + if got, err := p.ReadSecret(context.Background(), "q"); err != nil || got != "" { + t.Errorf("ReadSecret = (%q, %v), want (\"\", nil)", got, err) + } + if got, err := p.Confirm(context.Background(), "q", true); err != nil || !got { + t.Errorf("Confirm(defaultYes=true) = (%v, %v), want (true, nil)", got, err) + } + if got, err := p.Confirm(context.Background(), "q", false); err != nil || got { + t.Errorf("Confirm(defaultYes=false) = (%v, %v), want (false, nil)", got, err) + } +} diff --git a/internal/infrastructure/configuration/setup/envsink.go b/internal/infrastructure/configuration/setup/envsink.go new file mode 100644 index 000000000..394293c3e --- /dev/null +++ b/internal/infrastructure/configuration/setup/envsink.go @@ -0,0 +1,142 @@ +package setup + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" +) + +// EnvFileSink is a SecretSink that stores secrets in the env file beside +// config.toml (${XDG_CONFIG_HOME:-~/.config}/archie/env by default). The +// daemon reads that file through systemd's EnvironmentFile, so the line +// format must match what install.sh's set_env_key has always written -- a +// single-quoted KEY='value' line, with an embedded single quote escaped as a +// backslash between two single quotes -- rather than any other +// plausible-looking format. +// +// Put buffers; nothing is written until Commit, and Commit rewrites the file +// atomically with mode 0600. The caller must only Commit once the config +// text referencing these secrets has been proven loadable, so a validation +// failure leaves neither a config nor a secret on disk. +type EnvFileSink struct { + path string + entries map[string]string +} + +// NewEnvFileSink returns a sink that writes the env file at path. +func NewEnvFileSink(path string) *EnvFileSink { + return &EnvFileSink{path: path, entries: map[string]string{}} +} + +// Put records an env-file entry. Only the "env" engine has a representation +// in the env file; every key setup writes uses engine "env". +func (s *EnvFileSink) Put(engine, key, value string) error { + if engine != "env" { + return fmt.Errorf("setup: env file sink cannot store engine %q secrets", engine) + } + if strings.TrimSpace(key) == "" { + return fmt.Errorf("setup: env file sink: empty key") + } + s.entries[key] = value + return nil +} + +// Commit writes every Put entry, replacing any existing line for the same +// key, leaving unrelated lines byte-identical, and persists the result +// atomically. +func (s *EnvFileSink) Commit() error { + if len(s.entries) == 0 { + return nil + } + keys := make([]string, 0, len(s.entries)) + for k := range s.entries { + keys = append(keys, k) + } + sort.Strings(keys) + + var out []string + existing, err := readEnvLines(s.path) + if err != nil { + return fmt.Errorf("setup: read env file: %w", err) + } + for _, line := range existing { + keep := true + for _, key := range keys { + if strings.HasPrefix(line, key+"=") { + keep = false + break + } + } + if keep { + out = append(out, line) + } + } + for _, key := range keys { + out = append(out, key+"='"+escapeEnvValue(s.entries[key])+"'") + } + + if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil { + return fmt.Errorf("setup: create env directory: %w", err) + } + if err := writeEnvFileAtomic(s.path, []byte(strings.Join(out, "\n")+"\n")); err != nil { + return fmt.Errorf("setup: write env file: %w", err) + } + return nil +} + +// readEnvLines reads the env file's lines, without their trailing newline. +// A missing or empty file yields no lines. +func readEnvLines(path string) ([]string, error) { + b, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + text := strings.TrimSuffix(string(b), "\n") + if text == "" { + return nil, nil + } + return strings.Split(text, "\n"), nil +} + +// escapeEnvValue renders value as the contents of a single-quoted +// systemd EnvironmentFile value: a literal single quote becomes a backslash +// between two single quotes. This is byte-for-byte what install.sh's +// set_env_key produces, so the Go sink and the shell helper cannot disagree +// about the on-disk format. +func escapeEnvValue(v string) string { + return strings.ReplaceAll(v, "'", `'\''`) +} + +// writeEnvFileAtomic writes data to path via a same-directory temp file and +// rename, mirroring set_env_key's mktemp-then-mv so a reader never observes +// a half-written env file. +func writeEnvFileAtomic(path string, data []byte) error { + tmp, err := os.CreateTemp(filepath.Dir(path), ".env.XXXXXX") + if err != nil { + return err + } + name := tmp.Name() + defer os.Remove(name) // no-op after a successful rename + if err := tmp.Chmod(0o600); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(data); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(name, path) +} diff --git a/internal/infrastructure/configuration/setup/envsink_test.go b/internal/infrastructure/configuration/setup/envsink_test.go new file mode 100644 index 000000000..f53adc702 --- /dev/null +++ b/internal/infrastructure/configuration/setup/envsink_test.go @@ -0,0 +1,83 @@ +package setup + +import ( + "os" + "path/filepath" + "testing" +) + +func TestEnvFileSink_MatchSetEnvKeyFormat(t *testing.T) { + path := filepath.Join(t.TempDir(), "env") + s := NewEnvFileSink(path) + if err := s.Put("env", "ARCHIE_GITHUB_TOKEN", "abc"); err != nil { + t.Fatalf("Put: %v", err) + } + if err := s.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + b, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read env file: %v", err) + } + if got, want := string(b), "ARCHIE_GITHUB_TOKEN='abc'\n"; got != want { + t.Errorf("env file = %q, want %q", got, want) + } + if info, err := os.Stat(path); err != nil || info.Mode().Perm() != 0o600 { + t.Errorf("env file mode = %v (%v), want 0600", info.Mode().Perm(), err) + } +} + +func TestEnvFileSink_ReplacesExistingAndPreservesUnrelated(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "env") + if err := os.WriteFile(path, []byte("KEEP='keep'\nARCHIE_GITHUB_TOKEN='old'\n"), 0o600); err != nil { + t.Fatal(err) + } + + s := NewEnvFileSink(path) + if err := s.Put("env", "ARCHIE_GITHUB_TOKEN", "new"); err != nil { + t.Fatal(err) + } + if err := s.Put("env", "ARCHIE_GITEA_TOKEN", "gitea"); err != nil { + t.Fatal(err) + } + if err := s.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + // Unrelated line keeps its position; replaced keys move to the end (the + // same behaviour as set_env_key's grep -v + append), new keys sorted. + want := "KEEP='keep'\nARCHIE_GITEA_TOKEN='gitea'\nARCHIE_GITHUB_TOKEN='new'\n" + if got := string(b); got != want { + t.Errorf("env file = %q, want %q", got, want) + } +} + +func TestEnvFileSink_EscapesSingleQuotes(t *testing.T) { + path := filepath.Join(t.TempDir(), "env") + s := NewEnvFileSink(path) + if err := s.Put("env", "K", "a'b"); err != nil { + t.Fatal(err) + } + if err := s.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if got, want := string(b), "K='a'\\''b'\n"; got != want { + t.Errorf("env file = %q, want %q", got, want) + } +} + +func TestEnvFileSink_RejectsNonEnvEngine(t *testing.T) { + s := NewEnvFileSink(filepath.Join(t.TempDir(), "env")) + if err := s.Put("bws", "K", "v"); err == nil { + t.Error("Put(bws) = nil error, want a failure: the env file has no representation for non-env engines") + } +} diff --git a/internal/infrastructure/configuration/setup/params_test.go b/internal/infrastructure/configuration/setup/params_test.go new file mode 100644 index 000000000..3156d08ce --- /dev/null +++ b/internal/infrastructure/configuration/setup/params_test.go @@ -0,0 +1,217 @@ +package setup + +import ( + "context" + "testing" +) + +// rejectingPrompter fails the test if any question is asked, proving that a +// fully-populated Params never touches the prompt surface. +type rejectingPrompter struct { + t *testing.T +} + +func (r rejectingPrompter) Select(context.Context, string, []string) (int, error) { + r.t.Fatal("unexpected Select call: Params should have supplied this answer") + return 0, nil +} + +func (r rejectingPrompter) ReadLine(context.Context, string, string) (string, error) { + r.t.Fatal("unexpected ReadLine call: Params should have supplied this answer") + return "", nil +} + +func (r rejectingPrompter) ReadSecret(context.Context, string) (string, error) { + r.t.Fatal("unexpected ReadSecret call: Params should have supplied this answer") + return "", nil +} + +func (r rejectingPrompter) Confirm(context.Context, string, bool) (bool, error) { + r.t.Fatal("unexpected Confirm call: Params should have supplied this answer") + return false, nil +} + +func TestRunParams_ProviderAPIKeyNeverPrompts(t *testing.T) { + params := Params{ + BotUser: "archie-bot", + Operator: "Ada", // Run asks for the operator unconditionally; see the note below + ForgeType: "none", + Provider: "openai", + Model: "gpt-5.4", + ProviderAPIKey: "sk-parameterised", + // Telegram enablement is a yes/no question with no parameter to + // pre-answer it, so a genuinely prompt-free run supplies the channel + // outright. Everything else here is supplied, which is the point: the + // provider key must come from Params rather than ReadSecret. + TelegramToken: "tg-token", + TelegramUserIDs: []int64{111}, + } + secrets := newFakeSecrets() + // rejectingPrompter fails the test on any prompt. Before ProviderAPIKey + // existed this run had to ask for the key, which is why an unattended + // install could only ever choose the keyless self-hosted provider. + edits, err := RunParams(context.Background(), rejectingPrompter{t: t}, nil, secrets, ExistingValues{}, params) + if err != nil { + t.Fatalf("RunParams: %v", err) + } + if err := secrets.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + if got := secrets.committed["env:OPENAI_API_KEY"]; got != "sk-parameterised" { + t.Errorf("committed env:OPENAI_API_KEY = %q, want sk-parameterised", got) + } + + cfg := generateAndLoad(t, edits) + if got := cfg.Providers["openai"].Class; got != "openai" { + t.Errorf("providers.openai.class = %q, want openai", got) + } + if cfg.Providers["openai"].APIKey.Engine != "env" { + t.Errorf("providers.openai.api_key engine = %q, want env: the key belongs in the env file, not the config", cfg.Providers["openai"].APIKey.Engine) + } + if got := cfg.Models["builder"]; got != "openai/gpt-5.4" { + t.Errorf("models.builder = %q, want openai/gpt-5.4", got) + } +} + +func TestRunParams_FullParamsNeverPrompt(t *testing.T) { + params := Params{ + BotUser: "archie-bot", + Operator: "Ada", + ForgeType: "github", + ForgeHost: "https://github.acme.internal", + ForgeToken: "ghp-token", + Provider: "ollama", + Model: "llama3", + TelegramToken: "tg-token", + TelegramUserIDs: []int64{111, 222}, + } + secrets := newFakeSecrets() + edits, err := RunParams(context.Background(), rejectingPrompter{t: t}, nil, secrets, ExistingValues{}, params) + if err != nil { + t.Fatalf("RunParams: %v", err) + } + if err := secrets.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + + cfg := generateAndLoad(t, edits) + if cfg.BotUser != "archie-bot" { + t.Errorf("bot_user = %q, want archie-bot", cfg.BotUser) + } + if cfg.Chat.Operator != "Ada" { + t.Errorf("chat.operator = %q, want Ada", cfg.Chat.Operator) + } + if cfg.Forge.Type != "github" { + t.Errorf("forge.type = %q, want github", cfg.Forge.Type) + } + if cfg.Forge.Host != "https://github.acme.internal" { + t.Errorf("forge.host = %q, want https://github.acme.internal", cfg.Forge.Host) + } + if cfg.Forge.Token.Key != "ARCHIE_GITHUB_TOKEN" { + t.Errorf("forge.token.key = %q, want ARCHIE_GITHUB_TOKEN", cfg.Forge.Token.Key) + } + for _, role := range []string{"triage", "planner", "builder"} { + if cfg.Models[role] != "ollama/llama3" { + t.Errorf("models[%s] = %q, want ollama/llama3", role, cfg.Models[role]) + } + } + if got := secrets.committed["env:ARCHIE_GITHUB_TOKEN"]; got != "ghp-token" { + t.Errorf("committed github token = %q, want ghp-token", got) + } + if got := secrets.committed["env:ARCHIE_TELEGRAM_TOKEN"]; got != "tg-token" { + t.Errorf("committed telegram token = %q, want tg-token", got) + } + if len(cfg.Chat.Telegram.AllowedUserIDs) != 2 || cfg.Chat.Telegram.AllowedUserIDs[0] != 111 || cfg.Chat.Telegram.AllowedUserIDs[1] != 222 { + t.Errorf("chat.telegram.allowed_user_ids = %v, want [111 222]", cfg.Chat.Telegram.AllowedUserIDs) + } +} + +func TestRunParams_PartialParamsAskOnlyTheRest(t *testing.T) { + // Bot user, provider and model are supplied; operator, forge and + // telegram are left for the prompter. The provider API key is never in + // Params (there is no typed field for it), so it is always prompted. + p := &fakePrompter{ + lines: []string{""}, // operator left blank + selects: []int{2}, // forge: none + secrets: []string{"sk-openai-key"}, + confirms: []bool{false}, + } + secrets := newFakeSecrets() + edits, err := RunParams(context.Background(), p, nil, secrets, ExistingValues{}, Params{ + BotUser: "archie-bot", + Provider: "openai", + Model: "gpt-5.4", + }) + if err != nil { + t.Fatalf("RunParams: %v", err) + } + if err := secrets.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + + cfg := generateAndLoad(t, edits) + if cfg.BotUser != "archie-bot" { + t.Errorf("bot_user = %q, want archie-bot", cfg.BotUser) + } + if cfg.Chat.Operator != "" { + t.Errorf("chat.operator = %q, want empty (prompt left blank)", cfg.Chat.Operator) + } + if cfg.Forge.Type != "none" { + t.Errorf("forge.type = %q, want none", cfg.Forge.Type) + } + if cfg.Providers["openai"].APIKey.Key != "OPENAI_API_KEY" { + t.Errorf("providers.openai.api_key.key = %q, want OPENAI_API_KEY", cfg.Providers["openai"].APIKey.Key) + } + for _, role := range []string{"triage", "planner", "builder"} { + if cfg.Models[role] != "openai/gpt-5.4" { + t.Errorf("models[%s] = %q, want openai/gpt-5.4", role, cfg.Models[role]) + } + } + if got := secrets.committed["env:OPENAI_API_KEY"]; got != "sk-openai-key" { + t.Errorf("committed openai key = %q, want sk-openai-key", got) + } + if len(secrets.committed) != 1 { + t.Errorf("committed secrets = %v, want only the openai key", secrets.committed) + } +} + +// The --defaults baseline from the plan's Decision 2: bot user archie-bot, +// github, https://github.com, ollama, llama3, operator/telegram skipped. It +// must produce a loadable config with no secrets written, because ollama is +// the one keyless path. +func TestRun_DefaultsBaselineLoads(t *testing.T) { + params := Params{ + BotUser: "archie-bot", + ForgeType: "github", + ForgeHost: "https://github.com", + Provider: "ollama", + Model: "llama3", + } + secrets := newFakeSecrets() + edits, err := RunParams(context.Background(), DefaultPrompter{}, nil, secrets, ExistingValues{}, params) + if err != nil { + t.Fatalf("RunParams: %v", err) + } + if err := secrets.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + + cfg := generateAndLoad(t, edits) + if cfg.BotUser != "archie-bot" { + t.Errorf("bot_user = %q, want archie-bot", cfg.BotUser) + } + if cfg.Forge.Type != "github" || cfg.Forge.Host != "https://github.com" { + t.Errorf("forge = %q/%q, want github/https://github.com", cfg.Forge.Type, cfg.Forge.Host) + } + for _, role := range []string{"triage", "planner", "builder"} { + if cfg.Models[role] != "ollama/llama3" { + t.Errorf("models[%s] = %q, want ollama/llama3", role, cfg.Models[role]) + } + } + if cfg.Providers["ollama"].Class != "ollama" { + t.Errorf("providers.ollama.class = %q, want ollama", cfg.Providers["ollama"].Class) + } + if len(secrets.committed) != 0 { + t.Errorf("committed secrets = %v, want none: the defaults baseline is keyless", secrets.committed) + } +} diff --git a/internal/infrastructure/configuration/setup/setup.go b/internal/infrastructure/configuration/setup/setup.go index 345422ddf..8ca4f46b2 100644 --- a/internal/infrastructure/configuration/setup/setup.go +++ b/internal/infrastructure/configuration/setup/setup.go @@ -15,13 +15,14 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite" ) -// SecretSink is where setup sends the secret values a step collects. It is -// declared here, not implemented: 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. +// 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. @@ -51,6 +52,36 @@ type ExistingValues struct { // 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 @@ -58,6 +89,12 @@ type tableEdits = map[string]map[string]string // 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 { @@ -67,24 +104,32 @@ func Run(ctx context.Context, p Prompter, discovery ModelDiscovery, secrets Secr } } - 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) + 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, 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) + 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) + providerEdits, model, err := stepProvider(ctx, p, discovery, secrets, params) if err != nil { return nil, err } @@ -93,13 +138,13 @@ func Run(ctx context.Context, p Prompter, discovery ModelDiscovery, secrets Secr add(tableEdits{"models": {role: tomlwrite.String(model)}}) } - forgeEdits, err := stepForge(ctx, p, secrets, existing.ForgeHost) + forgeEdits, err := stepForge(ctx, p, secrets, existing.ForgeHost, params) if err != nil { return nil, err } add(forgeEdits) - chatEdits, err := stepChat(ctx, p, secrets) + chatEdits, err := stepChat(ctx, p, secrets, params) if err != nil { return nil, err } diff --git a/internal/infrastructure/configuration/setup/step_chat.go b/internal/infrastructure/configuration/setup/step_chat.go index cd6a39de5..b650d5585 100644 --- a/internal/infrastructure/configuration/setup/step_chat.go +++ b/internal/infrastructure/configuration/setup/step_chat.go @@ -15,18 +15,26 @@ import ( // {engine,key} inline table. const telegramTokenEnv = "ARCHIE_TELEGRAM_TOKEN" -func stepChat(ctx context.Context, p Prompter, secrets SecretSink) (tableEdits, error) { - wantTelegram, err := p.Confirm(ctx, "Configure a Telegram chat channel?", false) - if err != nil { - return nil, fmt.Errorf("setup: telegram: %w", err) +func stepChat(ctx context.Context, p Prompter, secrets SecretSink, params Params) (tableEdits, error) { + wantTelegram := len(params.TelegramUserIDs) > 0 + if !wantTelegram { + var err error + wantTelegram, err = p.Confirm(ctx, "Configure a Telegram chat channel?", false) + if err != nil { + return nil, fmt.Errorf("setup: telegram: %w", err) + } } if !wantTelegram { return nil, nil } - token, err := p.ReadSecret(ctx, "Telegram bot token (from @BotFather): ") - if err != nil { - return nil, fmt.Errorf("setup: telegram token: %w", err) + token := params.TelegramToken + if token == "" { + var err error + token, err = p.ReadSecret(ctx, "Telegram bot token (from @BotFather): ") + if err != nil { + return nil, fmt.Errorf("setup: telegram token: %w", err) + } } if strings.TrimSpace(token) == "" { return nil, nil @@ -36,16 +44,19 @@ func stepChat(ctx context.Context, p Prompter, secrets SecretSink) (tableEdits, // allowlist answers nobody, which reads as broken rather than as the // safe default it actually is. Require at least one ID rather than // shipping a channel that silently does nothing. - idsLine, err := p.ReadLine(ctx, "Allowed Telegram user IDs (comma-separated; required -- the bot answers nobody without this): ", "") - if err != nil { - return nil, fmt.Errorf("setup: telegram allowed user ids: %w", err) - } - ids, err := parseUserIDs(idsLine) - if err != nil { - return nil, fmt.Errorf("setup: telegram allowed user ids: %w", err) - } + ids := params.TelegramUserIDs if len(ids) == 0 { - return nil, fmt.Errorf("setup: at least one allowed Telegram user ID is required, or the bot will answer nobody") + idsLine, err := p.ReadLine(ctx, "Allowed Telegram user IDs (comma-separated; required -- the bot answers nobody without this): ", "") + if err != nil { + return nil, fmt.Errorf("setup: telegram allowed user ids: %w", err) + } + ids, err = ParseTelegramUserIDs(idsLine) + if err != nil { + return nil, fmt.Errorf("setup: telegram allowed user ids: %w", err) + } + if len(ids) == 0 { + return nil, fmt.Errorf("setup: at least one allowed Telegram user ID is required, or the bot will answer nobody") + } } if err := secrets.Put("env", telegramTokenEnv, token); err != nil { @@ -60,7 +71,11 @@ func stepChat(ctx context.Context, p Prompter, secrets SecretSink) (tableEdits, }, nil } -func parseUserIDs(line string) ([]int64, error) { +// ParseTelegramUserIDs parses a comma-separated Telegram allowlist into +// int64 IDs, skipping empty parts. It is exported so cmd/archied setup can +// parse -telegram-user-ids with exactly the same rules the interactive +// prompt uses, rather than a second copy that could drift. +func ParseTelegramUserIDs(line string) ([]int64, error) { var ids []int64 for part := range strings.SplitSeq(line, ",") { part = strings.TrimSpace(part) diff --git a/internal/infrastructure/configuration/setup/step_forge.go b/internal/infrastructure/configuration/setup/step_forge.go index fcec47ddd..5ffa8df51 100644 --- a/internal/infrastructure/configuration/setup/step_forge.go +++ b/internal/infrastructure/configuration/setup/step_forge.go @@ -18,25 +18,43 @@ var forgeToken = map[string]string{ "gitea": "ARCHIE_GITEA_TOKEN", } -func stepForge(ctx context.Context, p Prompter, secrets SecretSink, existingHost string) (tableEdits, error) { - choice, err := p.Select(ctx, "Code forge:", []string{"GitHub", "Gitea", "None (standalone mode)"}) - if err != nil { - return nil, fmt.Errorf("setup: forge: %w", err) +func stepForge(ctx context.Context, p Prompter, secrets SecretSink, existingHost string, params Params) (tableEdits, error) { + var choice int + if strings.TrimSpace(params.ForgeType) != "" { + var err error + choice, err = forgeChoice(params.ForgeType) + if err != nil { + return nil, fmt.Errorf("setup: forge: %w", err) + } + } else { + var err error + choice, err = p.Select(ctx, "Code forge:", []string{"GitHub", "Gitea", "None (standalone mode)"}) + if err != nil { + return nil, fmt.Errorf("setup: forge: %w", err) + } } switch choice { case 0: - return stepForgeWithToken(ctx, p, secrets, "github", "https://github.com", "GitHub token (leave blank to configure later): ") + host := params.ForgeHost + if strings.TrimSpace(host) == "" { + host = "https://github.com" + } + return stepForgeWithToken(ctx, p, secrets, "github", host, "GitHub token (leave blank to configure later): ", params.ForgeToken) case 1: defaultHost := existingHost if defaultHost == "" { defaultHost = "https://gitea.example.com" } - host, err := p.ReadLine(ctx, "Gitea base URL: ", defaultHost) - if err != nil { - return nil, fmt.Errorf("setup: gitea host: %w", err) + host := params.ForgeHost + if strings.TrimSpace(host) == "" { + var err error + host, err = p.ReadLine(ctx, "Gitea base URL: ", defaultHost) + if err != nil { + return nil, fmt.Errorf("setup: gitea host: %w", err) + } } - return stepForgeWithToken(ctx, p, secrets, "gitea", host, "Gitea token (leave blank to configure later): ") + return stepForgeWithToken(ctx, p, secrets, "gitea", host, "Gitea token (leave blank to configure later): ", params.ForgeToken) default: // The template's default [forge] block is active (type = "github" // with a host and token already set). Selecting "none" must @@ -52,14 +70,34 @@ func stepForge(ctx context.Context, p Prompter, secrets SecretSink, existingHost } } -func stepForgeWithToken(ctx context.Context, p Prompter, secrets SecretSink, forgeType, host, tokenPrompt string) (tableEdits, error) { +// forgeChoice maps a typed Params.ForgeType to the same select index the +// interactive prompt uses, so a supplied forge type and a prompted one land +// in exactly the same step logic. +func forgeChoice(name string) (int, error) { + switch strings.ToLower(strings.TrimSpace(name)) { + case "github": + return 0, nil + case "gitea": + return 1, nil + case "none": + return 2, nil + default: + return -1, fmt.Errorf("unknown forge type %q (want \"github\", \"gitea\", or \"none\")", name) + } +} + +func stepForgeWithToken(ctx context.Context, p Prompter, secrets SecretSink, forgeType, host, tokenPrompt, tokenParam string) (tableEdits, error) { edits := tableEdits{"forge": { "type": tomlwrite.String(forgeType), "host": tomlwrite.String(host), }} - token, err := p.ReadSecret(ctx, tokenPrompt) - if err != nil { - return nil, fmt.Errorf("setup: %s token: %w", forgeType, err) + token := tokenParam + if token == "" { + var err error + token, err = p.ReadSecret(ctx, tokenPrompt) + if err != nil { + return nil, fmt.Errorf("setup: %s token: %w", forgeType, err) + } } if strings.TrimSpace(token) == "" { return edits, nil diff --git a/internal/infrastructure/configuration/setup/step_provider.go b/internal/infrastructure/configuration/setup/step_provider.go index d8d1d4624..7cadb7bf4 100644 --- a/internal/infrastructure/configuration/setup/step_provider.go +++ b/internal/infrastructure/configuration/setup/step_provider.go @@ -44,24 +44,35 @@ var cloudProviders = []cloudProvider{ // landmine nothing in setup's own output would explain. const templateDefaultActiveProvider = "openai" -func stepProvider(ctx context.Context, p Prompter, discovery ModelDiscovery, secrets SecretSink) (tableEdits, string, error) { +func stepProvider(ctx context.Context, p Prompter, discovery ModelDiscovery, secrets SecretSink, params Params) (tableEdits, string, error) { options := make([]string, 0, len(cloudProviders)+1) for _, cp := range cloudProviders { options = append(options, cp.name) } options = append(options, "Self-hosted (Ollama)") - choice, err := p.Select(ctx, "LLM provider:", options) - if err != nil { - return nil, "", fmt.Errorf("setup: provider: %w", err) + var choice int + if strings.TrimSpace(params.Provider) != "" { + var err error + choice, err = providerChoice(params.Provider) + if err != nil { + return nil, "", fmt.Errorf("setup: provider: %w", err) + } + } else { + var err error + choice, err = p.Select(ctx, "LLM provider:", options) + if err != nil { + return nil, "", fmt.Errorf("setup: provider: %w", err) + } } var edits tableEdits var model string + var err error if choice == len(cloudProviders) { - edits, model, err = stepSelfHostedModel(ctx, p, discovery) + edits, model, err = stepSelfHostedModel(ctx, p, discovery, params.Model) } else { - edits, model, err = stepCloudProvider(ctx, p, secrets, cloudProviders[choice]) + edits, model, err = stepCloudProvider(ctx, p, secrets, cloudProviders[choice], params.ProviderAPIKey, params.Model) } if err != nil { return nil, "", err @@ -74,9 +85,27 @@ func stepProvider(ctx context.Context, p Prompter, discovery ModelDiscovery, sec return edits, model, nil } -func stepSelfHostedModel(ctx context.Context, p Prompter, discovery ModelDiscovery) (tableEdits, string, error) { +// providerChoice maps a typed Params.Provider class to the same select index +// the interactive prompt uses, so a supplied provider and a prompted one land +// in exactly the same step logic. +func providerChoice(name string) (int, error) { + name = strings.ToLower(strings.TrimSpace(name)) + if name == "ollama" { + return len(cloudProviders), nil + } + for i, cp := range cloudProviders { + if cp.class == name { + return i, nil + } + } + return -1, fmt.Errorf("unknown provider %q", name) +} + +func stepSelfHostedModel(ctx context.Context, p Prompter, discovery ModelDiscovery, modelParam string) (tableEdits, string, error) { var model string - if discovery != nil { + if strings.TrimSpace(modelParam) != "" { + model = modelParam + } else if discovery != nil { if models, err := discovery.ListOllamaModels(ctx); err == nil && len(models) > 0 { idx, err := p.Select(ctx, "Ollama model:", models) if err != nil { @@ -96,10 +125,17 @@ func stepSelfHostedModel(ctx context.Context, p Prompter, discovery ModelDiscove return edits, "ollama/" + model, nil } -func stepCloudProvider(ctx context.Context, p Prompter, secrets SecretSink, cp cloudProvider) (tableEdits, string, error) { - key, err := p.ReadSecret(ctx, fmt.Sprintf("%s API key: ", cp.name)) - if err != nil { - return nil, "", fmt.Errorf("setup: %s api key: %w", cp.name, err) +func stepCloudProvider(ctx context.Context, p Prompter, secrets SecretSink, cp cloudProvider, keyParam, modelParam string) (tableEdits, string, error) { + // A key supplied as a parameter must not prompt. Without this the only + // provider an unattended install could configure was the keyless + // self-hosted one, so every cloud setup needed a terminal. + var err error + key := keyParam + if strings.TrimSpace(key) == "" { + key, err = p.ReadSecret(ctx, fmt.Sprintf("%s API key: ", cp.name)) + if err != nil { + return nil, "", fmt.Errorf("setup: %s api key: %w", cp.name, err) + } } table := "providers." + cp.class edits := tableEdits{table: {"class": tomlwrite.String(cp.class)}} @@ -116,9 +152,12 @@ func stepCloudProvider(ctx context.Context, p Prompter, secrets SecretSink, cp c edits[table]["api_key"] = tomlwrite.Ref("", "") } - model, err := p.ReadLine(ctx, fmt.Sprintf("Model for %s (e.g. gpt-5.4): ", cp.name), "") - if err != nil { - return nil, "", fmt.Errorf("setup: model name: %w", err) + model := modelParam + if strings.TrimSpace(model) == "" { + model, err = p.ReadLine(ctx, fmt.Sprintf("Model for %s (e.g. gpt-5.4): ", cp.name), "") + if err != nil { + return nil, "", fmt.Errorf("setup: model name: %w", err) + } } if strings.TrimSpace(model) == "" { return nil, "", fmt.Errorf("setup: a model name is required for %s", cp.name)