From 0ddc43081e83dda51d69e8899f27a8b34f61c21f Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 5 Aug 2026 12:58:53 +1000 Subject: [PATCH] feat(setup): implement the interactive setup steps (archie-core-cbk) internal/infrastructure/configuration/setup.Run drives operator identity, LLM provider, models, forge, and Telegram chat channel prompts and returns TOML edits -- not a config.Config. Building a parallel in-memory representation to validate against was rejected during design review: it's a second source of truth about the exact thing (text vs. struct disagreeing) this whole feature exists to stop. Tests instead render the edits against the real embedded template and load the result through a real configuration.Loader, proving the actual defaults/decode/validate path accepts it. Two boot-time landmines in config.example.toml surfaced by that approach, both fixed here: - [providers.openai] ships active with api_key pointed at the bws engine. cmd/archied/provider_secrets.go resolves every entry in cfg.Providers at startup, not just the ones [models] references, and refuses to start the daemon if any fails -- so picking any other provider (or picking openai but skipping the key) left a config that wouldn't boot on a machine without the bws CLI installed (the common case). stepProvider now neutralises providers.openai.api_key to the zero-value secret ref whenever openai wasn't the actual choice. - [[repos]] shipped active with a placeholder owner/name that validates cleanly (owner/name are only checked non-empty) and would have archied silently polling a repo that doesn't exist. Commented out in the template with an explanation; setup does not write this section since tomlwrite cannot target array-of-tables. TestExampleConfigLoads updated to expect zero repos. Also: forge and provider secret env-var names are each defined in one table (forgeToken, cloudProviders) read by both the config edit and the secret sink, so the two can't name a secret differently -- the exact bug class this feature exists to close for the installer, tested directly (TestRun_ForgeTokenKeyMatchesStoredSecretKey compares the decoded key against the key the secret was actually stored under, not a hardcoded literal on both sides). Telegram writes chat.telegram. token_env, not a secret.SecretRef -- TelegramConfig has no such field. Telegram also requires at least one allowed_user_id: AllowedUserIDs is deny-by-default, so a bot token with none configured answers nobody, which reads as broken rather than as the safe default it is. SecretSink is a caller-supplied sink (Put buffers, Commit persists), not a return value: Run never hands back plaintext secrets, and the caller is expected to call Commit only after proving the generated config loads -- so a validation failure never leaves a secret written without the config that references it. Refs archie-core-cbk --- config.example.toml | 50 +- .../configuration/loader_test.go | 10 +- .../configuration/setup/setup.go | 109 ++++ .../configuration/setup/setup_test.go | 492 ++++++++++++++++++ .../configuration/setup/step_chat.go | 88 ++++ .../configuration/setup/step_forge.go | 73 +++ .../configuration/setup/step_provider.go | 127 +++++ 7 files changed, 926 insertions(+), 23 deletions(-) create mode 100644 internal/infrastructure/configuration/setup/setup.go create mode 100644 internal/infrastructure/configuration/setup/setup_test.go create mode 100644 internal/infrastructure/configuration/setup/step_chat.go create mode 100644 internal/infrastructure/configuration/setup/step_forge.go create mode 100644 internal/infrastructure/configuration/setup/step_provider.go diff --git a/config.example.toml b/config.example.toml index 104dc84d0..10ffc20d0 100644 --- a/config.example.toml +++ b/config.example.toml @@ -128,24 +128,32 @@ gate_max_failures = 5 # volume_ttl = "72h" # max age for persistent repo volumes and Git clone caches # pull_policy = "missing" # "missing" or "always" -[[repos]] -owner = "your-github-username" -name = "todo" -base = "main" -ecosystem = "go" # "go", "python", "node", "rust", or "custom" -# Override the ecosystem defaults when needed: -# preflight = [["go", "version"]] -# test_glob = "*_test.go" -protect = ["_templ.go"] -gate = [ - ["templ", "generate", "./components/"], - ["go", "vet", "./..."], - ["go", "build", "./..."], - ["golangci-lint", "run"], - ["go", "test", "./...", "-count=1"], -] -# allow_concurrent = true # let the daemon run multiple tasks for this repo at once instead of - # FIFO-serializing them; only safe when concurrent worktrees won't collide - # (e.g. different base branches or packages per task). Still bounded by - # [containers].max_concurrency globally. -# persistent_storage = true # reuse a per-repo Docker volume and Git object cache until volume_ttl +# At least one [[repos]] entry is required before archied will poll +# anything -- it is deliberately left commented rather than shipped active: +# an active example here validates as a normal, working repo (owner/name are +# only checked for non-empty), so archied would silently start polling a +# repository that doesn't exist. archied setup does not write this section +# ([[repos]] is an array of tables, which the text-patching setup uses +# cannot target) -- add at least one entry by hand. +# +# [[repos]] +# owner = "your-github-username" +# name = "todo" +# base = "main" +# ecosystem = "go" # "go", "python", "node", "rust", or "custom" +# # Override the ecosystem defaults when needed: +# # preflight = [["go", "version"]] +# # test_glob = "*_test.go" +# protect = ["_templ.go"] +# gate = [ +# ["templ", "generate", "./components/"], +# ["go", "vet", "./..."], +# ["go", "build", "./..."], +# ["golangci-lint", "run"], +# ["go", "test", "./...", "-count=1"], +# ] +# # allow_concurrent = true # let the daemon run multiple tasks for this repo at once instead of +# # FIFO-serializing them; only safe when concurrent worktrees won't collide +# # (e.g. different base branches or packages per task). Still bounded by +# # [containers].max_concurrency globally. +# # persistent_storage = true # reuse a per-repo Docker volume and Git object cache until volume_ttl diff --git a/internal/infrastructure/configuration/loader_test.go b/internal/infrastructure/configuration/loader_test.go index 1f6f896f7..a4fa856ef 100644 --- a/internal/infrastructure/configuration/loader_test.go +++ b/internal/infrastructure/configuration/loader_test.go @@ -210,8 +210,14 @@ func TestExampleConfigLoads(t *testing.T) { if cfg.Dispatch.AckReaction != "eyes" { t.Errorf("Dispatch.AckReaction: got %q", cfg.Dispatch.AckReaction) } - if len(cfg.Repos) != 1 || cfg.Repos[0].ResolvedTestGlob() != "*_test.go" { - t.Errorf("Repos: got %+v", cfg.Repos) + // [[repos]] is commented out in the template on purpose: an active + // example here would validate as a normal repo (owner/name are only + // checked for non-empty) and archied would silently poll one that + // doesn't exist. At least one entry is required before archied will + // poll anything, but the template cannot supply it -- see the comment + // above [[repos]] in config.example.toml. + if len(cfg.Repos) != 0 { + t.Errorf("Repos: got %+v, want none: config.example.toml's [[repos]] entry is documentation, not a live default", cfg.Repos) } } diff --git a/internal/infrastructure/configuration/setup/setup.go b/internal/infrastructure/configuration/setup/setup.go new file mode 100644 index 000000000..345422ddf --- /dev/null +++ b/internal/infrastructure/configuration/setup/setup.go @@ -0,0 +1,109 @@ +// 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. 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. +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 + +// 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) { + 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, 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) + } + if strings.TrimSpace(operator) != "" { + add(tableEdits{"chat": {"operator": tomlwrite.String(operator)}}) + } + + providerEdits, model, err := stepProvider(ctx, p, discovery, secrets) + 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) + if err != nil { + return nil, err + } + add(forgeEdits) + + chatEdits, err := stepChat(ctx, p, secrets) + if err != nil { + return nil, err + } + add(chatEdits) + + return edits, nil +} diff --git a/internal/infrastructure/configuration/setup/setup_test.go b/internal/infrastructure/configuration/setup/setup_test.go new file mode 100644 index 000000000..461f2b130 --- /dev/null +++ b/internal/infrastructure/configuration/setup/setup_test.go @@ -0,0 +1,492 @@ +package setup + +import ( + "context" + "fmt" + "maps" + "os" + "path/filepath" + "testing" + + configtemplate "github.com/samcharles93/archie-core" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite" + "github.com/samcharles93/archie-core/internal/secret" +) + +// fakePrompter drives Run from typed scripted answers rather than raw +// terminal bytes. It mirrors Prompter's real contract (an empty ReadLine +// answer resolves to the caller's default; Select/Confirm/ReadSecret return +// their scripted value directly) so a test reads as "what would the +// operator have typed", not as a simulation of terminal parsing -- +// terminalprompt's own tests already cover that parsing. +type fakePrompter struct { + selects []int + lines []string + secrets []string + confirms []bool +} + +func (f *fakePrompter) pop(name string, q *[]string) (string, error) { + if len(*q) == 0 { + return "", fmt.Errorf("fakePrompter: no more scripted %s answers", name) + } + v := (*q)[0] + *q = (*q)[1:] + return v, nil +} + +func (f *fakePrompter) Select(_ context.Context, _ string, options []string) (int, error) { + if len(f.selects) == 0 { + return -1, fmt.Errorf("fakePrompter: no more scripted selects") + } + n := f.selects[0] + f.selects = f.selects[1:] + if n < 0 || n >= len(options) { + return -1, fmt.Errorf("fakePrompter: scripted select %d out of range for %d options", n, len(options)) + } + return n, nil +} + +func (f *fakePrompter) ReadLine(_ context.Context, _, defaultValue string) (string, error) { + v, err := f.pop("line", &f.lines) + if err != nil { + return "", err + } + if v == "" { + return defaultValue, nil + } + return v, nil +} + +func (f *fakePrompter) ReadSecret(_ context.Context, _ string) (string, error) { + return f.pop("secret", &f.secrets) +} + +func (f *fakePrompter) Confirm(_ context.Context, _ string, defaultYes bool) (bool, error) { + if len(f.confirms) == 0 { + return false, fmt.Errorf("fakePrompter: no more scripted confirms") + } + v := f.confirms[0] + f.confirms = f.confirms[1:] + return v, nil +} + +// fakeSecrets records Put calls without committing until Commit is called, +// mirroring the real buffer-then-commit contract Run relies on. +type fakeSecrets struct { + pending map[string]string // "engine:key" -> value + committed map[string]string +} + +func newFakeSecrets() *fakeSecrets { + return &fakeSecrets{pending: map[string]string{}, committed: map[string]string{}} +} + +func (f *fakeSecrets) Put(engine, key, value string) error { + f.pending[engine+":"+key] = value + return nil +} + +func (f *fakeSecrets) Commit() error { + maps.Copy(f.committed, f.pending) + return nil +} + +// generateAndLoad renders edits against the real embedded template and +// loads the result through a real configuration.Loader -- the same check +// Run's own doc comment says the caller must perform. This is what "every +// config setup writes passes configuration.Validate, verified by a test +// that runs setup non-interactively and validates the output" means in +// practice: proving the real load path (defaults, decode, validate, in +// their real order) accepts it, not asserting against a second, +// hand-rolled representation. +func generateAndLoad(t *testing.T, edits []tomlwrite.Edit) config.Config { + t.Helper() + out, err := tomlwrite.Generate(configtemplate.Example, edits) + if err != nil { + t.Fatalf("tomlwrite.Generate: %v", err) + } + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + if err := os.WriteFile(path, out, 0o600); err != nil { + t.Fatal(err) + } + doc, err := configuration.New(nil).File(path) + if err != nil { + t.Fatalf("generated config does not load: %v\n%s", err, out) + } + return doc.Config +} + +func TestRun_GitHubCloudProvider(t *testing.T) { + p := &fakePrompter{ + lines: []string{"acme-archie", "Ada Lovelace", "gpt-5.4"}, + selects: []int{0, 0}, // OpenAI, GitHub + secrets: []string{"sk-openai-token", "ghp-github-token"}, + confirms: []bool{false}, // no telegram + } + secrets := newFakeSecrets() + edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{}) + if err != nil { + t.Fatalf("Run: %v", err) + } + if err := secrets.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + + cfg := generateAndLoad(t, edits) + if cfg.BotUser != "acme-archie" { + t.Errorf("bot_user = %q, want acme-archie", cfg.BotUser) + } + if cfg.Chat.Operator != "Ada Lovelace" { + t.Errorf("chat.operator = %q, want Ada Lovelace", cfg.Chat.Operator) + } + if cfg.Forge.Type != "github" { + t.Errorf("forge.type = %q, want github", cfg.Forge.Type) + } + if cfg.Forge.Token.Key != "ARCHIE_GITHUB_TOKEN" { + t.Errorf("forge.token.key = %q, want ARCHIE_GITHUB_TOKEN", cfg.Forge.Token.Key) + } + if got, want := secrets.committed["env:ARCHIE_GITHUB_TOKEN"], "ghp-github-token"; got != want { + t.Errorf("committed github token = %q, want %q", got, want) + } + if cfg.Providers["openai"].Class != "openai" { + t.Errorf("providers.openai.class = %q, want openai", cfg.Providers["openai"].Class) + } + 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) + } + if got, want := secrets.committed["env:OPENAI_API_KEY"], "sk-openai-token"; got != want { + t.Errorf("committed openai key = %q, want %q", got, want) + } + 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]) + } + } +} + +func TestRun_GiteaForge(t *testing.T) { + p := &fakePrompter{ + lines: []string{"acme-archie", "", "gpt-5.4", "https://git.acme.internal"}, + selects: []int{0, 1}, // OpenAI, Gitea + secrets: []string{"sk-openai-token", "gitea-token"}, + confirms: []bool{false}, + } + secrets := newFakeSecrets() + edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{}) + if err != nil { + t.Fatalf("Run: %v", err) + } + if err := secrets.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + + cfg := generateAndLoad(t, edits) + if cfg.Forge.Type != "gitea" { + t.Errorf("forge.type = %q, want gitea", cfg.Forge.Type) + } + if cfg.Forge.Host != "https://git.acme.internal" { + t.Errorf("forge.host = %q, want https://git.acme.internal", cfg.Forge.Host) + } + if cfg.Forge.Token.Key != "ARCHIE_GITEA_TOKEN" { + t.Errorf("forge.token.key = %q, want ARCHIE_GITEA_TOKEN", cfg.Forge.Token.Key) + } + if got, want := secrets.committed["env:ARCHIE_GITEA_TOKEN"], "gitea-token"; got != want { + t.Errorf("committed gitea token = %q, want %q", got, want) + } +} + +func TestRun_ForgeNone(t *testing.T) { + p := &fakePrompter{ + lines: []string{"acme-archie", "", "gpt-5.4"}, + selects: []int{0, 2}, // OpenAI, None + secrets: []string{"sk-openai-token"}, + confirms: []bool{false}, + } + secrets := newFakeSecrets() + edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{}) + if err != nil { + t.Fatalf("Run: %v", err) + } + if err := secrets.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + + cfg := generateAndLoad(t, edits) + if cfg.Forge.Type != "none" { + t.Errorf("forge.type = %q, want none", cfg.Forge.Type) + } + if cfg.Forge.Token.Key != "" { + t.Errorf("forge.token.key = %q, want empty: no token was ever collected for forge type none", cfg.Forge.Token.Key) + } + if len(secrets.committed) != 1 { // just the openai key + t.Errorf("committed secrets = %v, want only the openai key", secrets.committed) + } +} + +type fakeDiscovery struct { + models []string + err error +} + +func (f *fakeDiscovery) ListOllamaModels(context.Context) ([]string, error) { + return f.models, f.err +} + +func TestRun_SelfHostedWithDiscoveredModels(t *testing.T) { + p := &fakePrompter{ + lines: []string{"acme-archie", ""}, + selects: []int{len(cloudProviders), 0, 2}, // provider: self-hosted; ollama model list: index 0; forge: none + confirms: []bool{false}, + } + discovery := &fakeDiscovery{models: []string{"llama3", "qwen2.5:7b"}} + secrets := newFakeSecrets() + edits, err := Run(context.Background(), p, discovery, secrets, ExistingValues{}) + if err != nil { + t.Fatalf("Run: %v", err) + } + + cfg := generateAndLoad(t, edits) + 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: self-hosted needs no API key", secrets.committed) + } +} + +func TestRun_SelfHostedDiscoveryUnavailableFallsBackToFreeText(t *testing.T) { + p := &fakePrompter{ + lines: []string{"acme-archie", "", "custom-model:latest"}, + selects: []int{len(cloudProviders), 2}, // self-hosted, forge none + confirms: []bool{false}, + } + discovery := &fakeDiscovery{err: fmt.Errorf("ollama not found")} + secrets := newFakeSecrets() + edits, err := Run(context.Background(), p, discovery, secrets, ExistingValues{}) + if err != nil { + t.Fatalf("Run: %v", err) + } + cfg := generateAndLoad(t, edits) + if cfg.Models["triage"] != "ollama/custom-model:latest" { + t.Errorf("models[triage] = %q, want ollama/custom-model:latest", cfg.Models["triage"]) + } +} + +func TestRun_TelegramRequiresAllowedUserIDs(t *testing.T) { + p := &fakePrompter{ + lines: []string{"acme-archie", "", "gpt-5.4", ""}, // last "" is the empty allowed-ids answer + selects: []int{0, 2}, // openai, forge none + secrets: []string{"sk-openai-token", "tg-token"}, + confirms: []bool{true}, // yes, configure telegram + } + secrets := newFakeSecrets() + _, err := Run(context.Background(), p, nil, secrets, ExistingValues{}) + if err == nil { + t.Fatal("Run() = nil error, want a failure: telegram configured with no allowed user IDs answers nobody") + } + if secrets.committed["env:ARCHIE_TELEGRAM_TOKEN"] != "" { + t.Error("telegram token must not be committed when the flow aborts on missing allowed user IDs") + } +} + +func TestRun_TelegramWithAllowedUserIDs(t *testing.T) { + p := &fakePrompter{ + lines: []string{"acme-archie", "", "gpt-5.4", "111, 222"}, + selects: []int{0, 2}, + secrets: []string{"sk-openai-token", "tg-token"}, + confirms: []bool{true}, + } + secrets := newFakeSecrets() + edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{}) + if err != nil { + t.Fatalf("Run: %v", err) + } + if err := secrets.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + cfg := generateAndLoad(t, edits) + if cfg.Chat.Telegram.TokenEnv != "ARCHIE_TELEGRAM_TOKEN" { + t.Errorf("chat.telegram.token_env = %q, want ARCHIE_TELEGRAM_TOKEN", cfg.Chat.Telegram.TokenEnv) + } + 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) + } + if got, want := secrets.committed["env:ARCHIE_TELEGRAM_TOKEN"], "tg-token"; got != want { + t.Errorf("committed telegram token = %q, want %q", got, want) + } +} + +// config.example.toml ships [providers.openai] active by default with an +// api_key pointing at the bws engine, which errors when the bws CLI isn't +// installed. cmd/archied/provider_secrets.go resolves every entry in +// cfg.Providers at startup, not just the ones [models] references, so an +// operator who picks any other provider must not be left with that entry +// still pointing at bws -- the daemon would refuse to boot on a config +// setup itself produced. +func TestRun_NonOpenAIProviderNeutralisesTemplateDefaultOpenAIKey(t *testing.T) { + p := &fakePrompter{ + lines: []string{"acme-archie", "", "claude-opus"}, + selects: []int{1, 2}, // Anthropic, forge none + secrets: []string{"sk-anthropic-token"}, + confirms: []bool{false}, + } + secrets := newFakeSecrets() + edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{}) + if err != nil { + t.Fatalf("Run: %v", err) + } + cfg := generateAndLoad(t, edits) + if cfg.Providers["openai"].APIKey != (secret.SecretRef{}) { + t.Fatalf("providers.openai.api_key = %+v, want the zero value: it must not still point at the "+ + "template's default bws reference once a different provider is chosen, or the daemon refuses to boot", + cfg.Providers["openai"].APIKey) + } +} + +func TestRun_OpenAISkippedKeyNeutralisesTemplateDefault(t *testing.T) { + p := &fakePrompter{ + lines: []string{"acme-archie", "", "gpt-5.4"}, + selects: []int{0, 2}, // OpenAI, forge none + secrets: []string{""}, + confirms: []bool{false}, + } + secrets := newFakeSecrets() + edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{}) + if err != nil { + t.Fatalf("Run: %v", err) + } + cfg := generateAndLoad(t, edits) + if cfg.Providers["openai"].APIKey != (secret.SecretRef{}) { + t.Fatalf("providers.openai.api_key = %+v, want the zero value when the key prompt was left blank, "+ + "not the template's default bws reference", cfg.Providers["openai"].APIKey) + } +} + +// The drift-bug regression test: for every forge type that writes a token, +// the key decoded from the generated TOML must equal the key the secret was +// actually stored under -- not merely equal some hardcoded literal on the +// assertion side, which would pass even if both sides had independently +// drifted to the same wrong value. +func TestRun_ForgeTokenKeyMatchesStoredSecretKey(t *testing.T) { + tests := []struct { + name string + forgeIndex int + lines []string + secret string + }{ + {name: "github", forgeIndex: 0, lines: []string{"acme-archie", "", "gpt-5.4"}, secret: "ghp-token"}, + {name: "gitea", forgeIndex: 1, lines: []string{"acme-archie", "", "gpt-5.4", "https://gitea.acme.internal"}, secret: "gitea-token"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + p := &fakePrompter{ + lines: tc.lines, + selects: []int{0, tc.forgeIndex}, + secrets: []string{"sk-openai-token", tc.secret}, + confirms: []bool{false}, + } + secrets := newFakeSecrets() + edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{}) + if err != nil { + t.Fatalf("Run: %v", err) + } + if err := secrets.Commit(); err != nil { + t.Fatalf("Commit: %v", err) + } + cfg := generateAndLoad(t, edits) + + storedUnderKey := "" + for k, v := range secrets.committed { + if v == tc.secret { + storedUnderKey = k + } + } + if storedUnderKey == "" { + t.Fatalf("secret %q was never committed: %v", tc.secret, secrets.committed) + } + wantKey := "env:" + cfg.Forge.Token.Key + if storedUnderKey != wantKey { + t.Errorf("forge.token.key decodes to %q, but the secret was stored under %q -- these must match", cfg.Forge.Token.Key, storedUnderKey) + } + }) + } +} + +// A second run against an already-generated config, changing one answer, +// must not disturb the rest of the file -- tomlwrite's own guarantee +// (archie-core-rs9), exercised here through setup's edits specifically. +func TestRun_SecondRunAgainstOwnOutputChangesOnlyOneField(t *testing.T) { + p1 := &fakePrompter{ + lines: []string{"acme-archie", "", "gpt-5.4"}, + selects: []int{0, 2}, + secrets: []string{"sk-openai-token"}, + confirms: []bool{false}, + } + secrets := newFakeSecrets() + edits1, err := Run(context.Background(), p1, nil, secrets, ExistingValues{}) + if err != nil { + t.Fatalf("first Run: %v", err) + } + first, err := tomlwrite.Generate(configtemplate.Example, edits1) + if err != nil { + t.Fatalf("Generate: %v", err) + } + + p2 := &fakePrompter{ + lines: []string{"acme-archie-renamed", "", "gpt-5.4"}, + selects: []int{0, 2}, + secrets: []string{"sk-openai-token"}, + confirms: []bool{false}, + } + edits2, err := Run(context.Background(), p2, nil, secrets, ExistingValues{BotUser: "acme-archie"}) + if err != nil { + t.Fatalf("second Run: %v", err) + } + second, err := tomlwrite.Apply(first, edits2) + if err != nil { + t.Fatalf("Apply: %v", err) + } + + firstLines := splitLines(t, first) + secondLines := splitLines(t, second) + if len(firstLines) != len(secondLines) { + t.Fatalf("line count changed: %d -> %d", len(firstLines), len(secondLines)) + } + changed := 0 + for i := range firstLines { + if firstLines[i] != secondLines[i] { + changed++ + if firstLines[i] != `bot_user = "acme-archie"` { + t.Errorf("unexpected line changed on re-run: %q -> %q", firstLines[i], secondLines[i]) + } + } + } + if changed != 1 { + t.Errorf("expected exactly one changed line (bot_user), got %d", changed) + } +} + +func splitLines(t *testing.T, b []byte) []string { + t.Helper() + var lines []string + start := 0 + for i, c := range b { + if c == '\n' { + lines = append(lines, string(b[start:i])) + start = i + 1 + } + } + if start < len(b) { + lines = append(lines, string(b[start:])) + } + return lines +} diff --git a/internal/infrastructure/configuration/setup/step_chat.go b/internal/infrastructure/configuration/setup/step_chat.go new file mode 100644 index 000000000..cd6a39de5 --- /dev/null +++ b/internal/infrastructure/configuration/setup/step_chat.go @@ -0,0 +1,88 @@ +package setup + +import ( + "context" + "fmt" + "strconv" + "strings" + + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite" +) + +// telegramTokenEnv is the env var Telegram's bot token is stored under. +// TelegramConfig has no secret.SecretRef field -- unlike the forge and +// provider steps, the config edit is a plain token_env string, not a +// {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) + } + 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) + } + if strings.TrimSpace(token) == "" { + return nil, nil + } + + // TelegramConfig.AllowedUserIDs is deny-by-default: a bot token with no + // 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) + } + 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 { + return nil, fmt.Errorf("setup: store telegram token: %w", err) + } + + return tableEdits{ + "chat.telegram": { + "token_env": tomlwrite.String(telegramTokenEnv), + "allowed_user_ids": intArrayLiteral(ids), + }, + }, nil +} + +func parseUserIDs(line string) ([]int64, error) { + var ids []int64 + for part := range strings.SplitSeq(line, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + id, err := strconv.ParseInt(part, 10, 64) + if err != nil { + return nil, fmt.Errorf("%q is not a valid Telegram user ID: %w", part, err) + } + ids = append(ids, id) + } + return ids, nil +} + +// intArrayLiteral renders a single-line TOML integer array. tomlwrite only +// understands single-line values; a Telegram allowlist is short enough +// that this never needs to wrap. +func intArrayLiteral(ids []int64) string { + parts := make([]string, len(ids)) + for i, id := range ids { + parts[i] = strconv.FormatInt(id, 10) + } + return "[" + strings.Join(parts, ", ") + "]" +} diff --git a/internal/infrastructure/configuration/setup/step_forge.go b/internal/infrastructure/configuration/setup/step_forge.go new file mode 100644 index 000000000..fcec47ddd --- /dev/null +++ b/internal/infrastructure/configuration/setup/step_forge.go @@ -0,0 +1,73 @@ +package setup + +import ( + "context" + "fmt" + "strings" + + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite" +) + +// forgeToken names the env var a forge type's token is stored under. Used +// by both the config edit (forge.token = {engine="env", key=...}) and the +// secret sink, for the same reason cloudProviders is a single table in +// step_provider.go: the installer's original bug was these two writes +// disagreeing. +var forgeToken = map[string]string{ + "github": "ARCHIE_GITHUB_TOKEN", + "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) + } + + switch choice { + case 0: + return stepForgeWithToken(ctx, p, secrets, "github", "https://github.com", "GitHub token (leave blank to configure later): ") + 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) + } + return stepForgeWithToken(ctx, p, secrets, "gitea", host, "Gitea token (leave blank to configure later): ") + default: + // The template's default [forge] block is active (type = "github" + // with a host and token already set). Selecting "none" must + // overwrite host and token too, not just type -- otherwise a + // disabled forge still shows a token reference nobody configured + // and that resolveForge never reads, which is exactly the kind of + // stale/misleading value this feature exists to stop shipping. + return tableEdits{"forge": { + "type": tomlwrite.String("none"), + "host": tomlwrite.String(""), + "token": tomlwrite.Ref("", ""), + }}, nil + } +} + +func stepForgeWithToken(ctx context.Context, p Prompter, secrets SecretSink, forgeType, host, tokenPrompt 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) + } + if strings.TrimSpace(token) == "" { + return edits, nil + } + envKey := forgeToken[forgeType] + if err := secrets.Put("env", envKey, token); err != nil { + return nil, fmt.Errorf("setup: store %s token: %w", forgeType, err) + } + edits["forge"]["token"] = tomlwrite.Ref("env", envKey) + return edits, nil +} diff --git a/internal/infrastructure/configuration/setup/step_provider.go b/internal/infrastructure/configuration/setup/step_provider.go new file mode 100644 index 000000000..d8d1d4624 --- /dev/null +++ b/internal/infrastructure/configuration/setup/step_provider.go @@ -0,0 +1,127 @@ +package setup + +import ( + "context" + "fmt" + "strings" + + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite" +) + +// cloudProvider is one selectable cloud LLM provider: the config class it +// writes and the env var name its secret is stored under. Both the +// provider step (which writes providers..api_key = {engine, key}) +// and the secret sink (which is asked to store the value under exactly +// that key) read from this single table, so the two can never name the +// secret differently -- the exact class of bug archie-core-cbk exists to +// close for forge tokens, applied the same way to provider keys. +type cloudProvider struct { + name string + class string + apiKeyEnv string +} + +var cloudProviders = []cloudProvider{ + {name: "OpenAI", class: "openai", apiKeyEnv: "OPENAI_API_KEY"}, + {name: "Anthropic", class: "anthropic", apiKeyEnv: "ANTHROPIC_API_KEY"}, + {name: "OpenRouter", class: "openrouter", apiKeyEnv: "OPENROUTER_API_KEY"}, + {name: "Gemini", class: "gemini", apiKeyEnv: "GEMINI_API_KEY"}, + {name: "Groq", class: "groq", apiKeyEnv: "GROQ_API_KEY"}, + {name: "DeepSeek", class: "deepseek", apiKeyEnv: "DEEPSEEK_API_KEY"}, + {name: "Mistral", class: "mistral", apiKeyEnv: "MISTRAL_API_KEY"}, +} + +// templateDefaultActiveProvider is the one provider table config.example. +// toml ships active by default: [providers.openai], with +// api_key = {engine="bws", key="OPENAI_API_KEY"}. bws is compiled in but +// requires the bws CLI on PATH; on a machine without it (the common case), +// resolving that key errors, and cmd/archied/provider_secrets.go's +// resolveProviderSecrets walks every entry in cfg.Providers -- not just +// the ones [models] actually references -- and refuses to start the +// daemon at all if any of them fails to resolve. Choosing any provider +// other than OpenAI, or choosing OpenAI but leaving its key blank, must +// neutralise this table rather than leave it as a silent boot-time +// 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) { + 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 edits tableEdits + var model string + if choice == len(cloudProviders) { + edits, model, err = stepSelfHostedModel(ctx, p, discovery) + } else { + edits, model, err = stepCloudProvider(ctx, p, secrets, cloudProviders[choice]) + } + if err != nil { + return nil, "", err + } + + openaiTable := "providers." + templateDefaultActiveProvider + if _, chosenOpenAI := edits[openaiTable]; !chosenOpenAI { + edits[openaiTable] = map[string]string{"api_key": tomlwrite.Ref("", "")} + } + return edits, model, nil +} + +func stepSelfHostedModel(ctx context.Context, p Prompter, discovery ModelDiscovery) (tableEdits, string, error) { + var model string + 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 { + return nil, "", fmt.Errorf("setup: model selection: %w", err) + } + model = models[idx] + } + } + if model == "" { + var err error + model, err = p.ReadLine(ctx, "Ollama model name (e.g. llama3): ", "llama3") + if err != nil { + return nil, "", fmt.Errorf("setup: model name: %w", err) + } + } + edits := tableEdits{"providers.ollama": {"class": tomlwrite.String("ollama")}} + 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) + } + table := "providers." + cp.class + edits := tableEdits{table: {"class": tomlwrite.String(cp.class)}} + if strings.TrimSpace(key) != "" { + if err := secrets.Put("env", cp.apiKeyEnv, key); err != nil { + return nil, "", fmt.Errorf("setup: store %s api key: %w", cp.name, err) + } + edits[table]["api_key"] = tomlwrite.Ref("env", cp.apiKeyEnv) + } else if cp.class == templateDefaultActiveProvider { + // Skipping the key normally means "configure later" and leaves + // api_key untouched -- but for openai specifically that would + // leave the template's own unresolvable bws default active. See + // templateDefaultActiveProvider. + 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) + } + if strings.TrimSpace(model) == "" { + return nil, "", fmt.Errorf("setup: a model name is required for %s", cp.name) + } + return edits, cp.class + "/" + model, nil +}