refactor(config): move loading into infrastructure/configuration
internal/config both defined the types every package imports and performed
the file I/O to produce them. Importing a settings struct therefore pulled
in a TOML decoder and a YAML decoder, and the shared model owned discovery,
decoding, overlays, defaulting and validation all at once. See
docs/architecture/configuration.md, which requires loading to move out and
internal/config to be dissolved.
internal/config is now types only -- no os, no filepath, no toml. The new
package owns loading, one concern per file:
features.go the closed set of recognised feature files
discovery.go directory scan and classification
decode.go TOML/YAML decoding, format dispatch
defaults.go filling absent values, no errors
validate.go judging supplied values, no mutation
provenance.go which file contributed what
loader.go Loader wiring the above; File/Overlay/Dir
Beyond relocating, this fixes what the old code conflated:
- Defaulting and validation were interleaved. applyAgentDefaults and
applyDispatchDefaults returned validation errors; validateContainers and
validateSingleIdentity quietly mutated the config. There was no point at
which you could see what the operator actually supplied. They are now
separate passes: applyDefaults never fails, validate never writes.
- Errors were fmt.Errorf strings prefixed "config: ", so a caller could not
distinguish operator-fixable input from an unreadable file without
matching message text. Five sentinels now carry that distinction.
- dataHome() read XDG_DATA_HOME directly and discarded the error from
os.UserHomeDir, so defaulting could not be tested without the
environment. It is injectable on Loader and no longer swallows the error.
- Nothing recorded where a value came from. With overlays, feature files
and conf.d/ all able to set the same field, "which file set this?" was
answerable only by re-deriving precedence by hand. Provenance records it.
- Feature files were applied in map iteration order, making load order and
any resulting error arbitrary. Discovery now returns them sorted.
- loadMainConfig reported "no config.yaml or config.toml found in %s" with
an empty string: the directory was lost when it was extracted from
loadDirInto, so the error named no directory.
- Unreadable or malformed conf.d/ extras were skipped silently, which
presents as a setting the operator wrote simply not taking effect.
- Decode errors from the main config were returned bare, without naming
the file that failed to parse.
The 40 loader tests moved with the code and their assertions are unchanged,
so the defaulting and validation rewrite is behaviour-preserving.
Document.Config is the temporary seam: still internal/config.Config, named
as a field so the compromise is visible at each use site, with its deletion
condition recorded in doc.go. Building typed per-domain sections now, while
every consumer still reads config.Config, would mean two shapes kept in sync
by hand with no consumer for the new one; that belongs with the dissolution
work, not ahead of it.
No consumer outside cmd/archied changed.
Verified: go build, go vet, gofmt clean; go test ./internal/config/... and
./internal/infrastructure/configuration/... pass. Pre-existing gateway and
telegram failures are unchanged.
This commit is contained in:
1 parent
18d1af1eeb
commit
c66c0a2a38
19 files changed
+1508
-1027
No files matched your search
@@ -53,6 +53,7 @@
|
||||
{"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"closed","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-28T17:04:41Z","closed_at":"2026-07-28T17:04:41Z","close_reason":"Superseded by merged work: all 32 children complete (32/32, bd flags it 'eligible for close'). MemoryProvider interface, built-in file-backed memory, MemoryManager, scrubber, drain and threat scanning all landed in internal/memory. Nothing left in scope.","dependencies":[{"issue_id":"archie-core-abg.18","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16","title":"[EPIC] Gateway: rich message model, adapter lifecycle, session management","description":"Foundational gateway infrastructure to match Hermes parity. Three interdependent pieces:\\n\\n1. **Message model**: Replace the 3-field Message struct with a rich MessageEvent (MessageType enum: text/photo/video/audio/voice/document/sticker/command, media_urls, reply_to context, metadata dict, source). This is the wire type every adapter produces.\\n\\n2. **Adapter lifecycle**: Replace the 3-method Gateway interface with a BasePlatformAdapter interface: connect()/disconnect()/send() as required methods, plus optional overrides for typing indicators, edit/delete, image/voice/video/document send, interactive UX (clarify buttons, approval dialogs). Capability flags (supports_code_blocks, splits_long_messages, supports_async_delivery).\\n\\n3. **Session management**: SessionSource struct (platform, chat_id, chat_type, user_id, thread_id, guild_id, profile), AsyncSessionStore for persistent session storage, SessionContext for system prompt injection.\\n\\nAll three blocks together enable adding new platforms as plugins without touching core gateway code.\\n\\nRef: docs/prds/hermes-gap-analysis.md sections 1-2","acceptance_criteria":"New adapters can be added by implementing a Go interface with connect/disconnect/send + optional media methods. Messages carry full metadata through the pipeline. Sessions persist across gateway restarts.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:21Z","dependencies":[{"issue_id":"archie-core-abg.16","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-jfg","title":"Spawned archie-agent containers not on daemon's docker network — can't reach NATS","description":"Root cause of 'agent still failing on the server': archied's container.Pool.Acquire creates archie-agent containers via the Docker SDK with no NetworkMode set, so Docker attaches them to the default bridge network. archied and nats run on the compose-created 'archie-core_default' network instead, so the spawned container's hostname resolution for 'nats' (from NATS_URL=nats://nats:4222) fails and archie-agent can't connect. Confirmed on carina host logs: archied logs show repeating 'taskrun request failed err=\"nats: no responders available for request\"' for every task, containers created and destroyed within ~1.5s (consistent with archie-agent's NATS client failing fast). Fixed by detecting the daemon's own container's network in NewPool (selfNetwork, via ContainerInspect on os.Hostname()) and setting HostConfig.NetworkMode on spawned containers to match.","status":"closed","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:10:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:04:34Z","closed_at":"2026-07-25T13:04:34Z","close_reason":"Fix already implemented and verified: selfNetwork() in internal/container/pool.go detects the daemon's own container network via ContainerInspect(os.Hostname()) and Acquire() sets HostConfig.NetworkMode to match, so spawned archie-agent containers join the same compose network as nats. Build and internal/container tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-uxk","title":"gateway: restore /whoami /profile /sessions /resume /agents handlers","description":"These five command handlers were lost during parallel merges of the Telegram\nworkers. The Router fields they need (Identity, Models, Sessions, Agents)\nalready exist; the handlers and their Route cases do not.\n\n18 tests in internal/gateway/gateway_test.go already specify the exact\nbehaviour. They are currently failing. Run them and make them pass:\n\n go test ./internal/gateway/...\n\nFailing: TestRouteWhoami, TestRouteWhoamiNoIdentity, TestRouteWhoamiWithModel,\nTestRouteProfile, TestRouteProfileNoIdentity, TestRouteSessionsEmpty,\nTestRouteSessionsNotConfigured, TestRouteSessionsError, TestRouteResumeNoArg,\nTestRouteResumeNotConfigured, TestRouteResumeNoMatch, TestRouteResumeAmbiguous,\nTestRouteResumeExactMatch, TestRouteAgentsEmpty, TestRouteAgentsNotConfigured,\nTestRouteAgentsWithTasks, TestRouteAgentsError, TestLocalCommandsIncludesNewCommands\n\nScope:\n- ONLY internal/gateway/. Do not touch any other package.\n- Read the tests first; they define the exact reply text fragments expected\n (\"not configured\", \"No sessions\", \"Usage\", etc). Do not invent wording.\n- Follow the shape of the existing handlers in gateway.go and\n session_commands.go: handleX methods on *Router returning (string, error).\n- A nil dependency means \"not configured\" and returns a reply, not an error.\n A dependency that returns an error must propagate it (see TestRouteSessionsError).\n- Add the new commands to the Route switch and to LocalCommands.\n\nConstraints:\n- Do NOT add //nolint or otherwise suppress lint findings. Fix issues properly.\n- Do NOT write architecture docs, ledgers, plans or new beads. Just the code.\n- Do NOT modify the tests to make them pass. The tests are correct.\n\nDone when: go build ./... , go vet ./... , gofmt -l . clean, and\ngo test ./internal/gateway/... passes with zero failures.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-29T00:58:16Z","created_by":"Sam Catlow","updated_at":"2026-07-29T00:58:16Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-o3l","title":"infrastructure/eventbus/nats: relocate NATS transport","description":"Create internal/infrastructure/eventbus/nats as a properly structured replacement for internal/nats. This is NOT a mechanical move: the existing code has no interfaces, leaks vendor types (Conn() *nats.Conn, PublishMsg(*nats.Msg), Fetch() jetstream.Msg) into all four consumers, uses a 7-positional-parameter publish with stringly-typed comma-separated labels, stores an unused logger, returns (nil, nil) for 'no message', and hardcodes stream/consumer/timeout config. Rebuild it with: separate files per concern; a Message wrapper so jetstream types stop crossing the boundary; Publisher/Consumer interfaces; a Config struct; sentinel errors; consistent %w wrapping; real logging. Then update cmd/archied, cmd/archie-agent, internal/daemon and internal/agentexec to the new API.","acceptance_criteria":"internal/nats no longer exists; internal/infrastructure/eventbus/nats has its contents. All imports updated. task check clean. Container and NATS behaviour unchanged.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T00:02:50Z","created_by":"Sam Catlow","updated_at":"2026-07-29T00:14:19Z","started_at":"2026-07-29T00:04:35Z","closed_at":"2026-07-29T00:06:37Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-vq4","title":"infrastructure/configuration: external input boundary","description":"Read docs/architecture/configuration.md. Create internal/infrastructure/configuration as the external config input boundary. It owns TOML/YAML decoding, env and secret references, base/overlay precedence, compatibility aliases, input validation, and provenance. It must NOT own domain behaviour. Preserve current LoadOverlay behaviour exactly and keep every existing TOML field name working. Translate the decoded input into the current internal/config.Config shape at the composition boundary as an explicitly-marked temporary adapter, so runtime behaviour is unchanged. Do not migrate consumers in this bead.","acceptance_criteria":"internal/infrastructure/configuration exists and is the loader used by cmd/archied. Old config files still load with identical effective values. task check clean. No consumer outside cmd/archied changed. The temporary adapter carries a comment naming its deletion condition.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T00:02:49Z","created_by":"Sam Catlow","updated_at":"2026-07-29T00:13:04Z","started_at":"2026-07-29T00:04:30Z","closed_at":"2026-07-29T00:13:04Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-24g","title":"Trim the remaining agent skills to factual reference","description":"The .agents/skills/ library is 4283 lines across 12 skills. An audit found most carry useful facts buried in process ceremony. Five worst offenders were already parked at /work/apps/archie-skills-parked. Trim what remains to roughly 2200 lines total. KEEP: concrete commands, package anchors, config wiring tables, NellDB shapes, symptom-to-diagnostic indexes, known regressions, domain glossary, operational hazards, false-confidence warnings. CUT: mandated N-step procedures, handoff templates, evidence packets, acceptance checklists, ownership/deletion/rollback field lists, sibling-skill routing prose, repeated 'reject unless' instructions, dated tool snapshots. Preserve every skill's YAML frontmatter name and description. Do not delete any skill file outright.","acceptance_criteria":"Total line count of .agents/skills/*/*.md is between 1900 and 2500. All 12 skills still exist with valid frontmatter. No factual command, path, or table was lost - only procedure and ceremony. go build ./... still clean.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-28T17:18:09Z","created_by":"Sam Catlow","updated_at":"2026-07-29T00:14:32Z","started_at":"2026-07-28T17:18:44Z","closed_at":"2026-07-29T00:14:32Z","close_reason":"Completed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
|
||||
+3
-1
@@ -34,6 +34,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/memory"
|
||||
"github.com/samcharles93/archie-core/internal/memory/builtin"
|
||||
@@ -130,11 +131,12 @@ func run() int {
|
||||
|
||||
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
|
||||
|
||||
cfg, err := config.LoadOverlay(*cfgPath, *overlayPath)
|
||||
doc, err := configuration.New(log).Overlay(*cfgPath, *overlayPath)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
cfg := doc.Config
|
||||
|
||||
secrets := secret.NewRegistry()
|
||||
token, err := cfg.Forge.Token.Resolve(secrets)
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/channels/telegram"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/nell"
|
||||
"github.com/samcharles93/archie-core/internal/releaseannounce"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
@@ -99,10 +100,11 @@ func configureTelegramUpdates(tg *telegram.Gateway, s telegramSetup) {
|
||||
|
||||
func makeTelegramReload(s telegramSetup) func(*telegram.Gateway) error {
|
||||
return func(g *telegram.Gateway) error {
|
||||
newCfg, err := config.LoadOverlay(s.CfgPath, s.OverlayPath)
|
||||
doc, err := configuration.New(s.Log).Overlay(s.CfgPath, s.OverlayPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reload config: %w", err)
|
||||
}
|
||||
newCfg := doc.Config
|
||||
tokenEnv := newCfg.Chat.Telegram.TokenEnv
|
||||
if tokenEnv == "" {
|
||||
return fmt.Errorf("reload config: chat.telegram.token_env is unset")
|
||||
|
||||
+21
-264
@@ -1,22 +1,26 @@
|
||||
// Package config loads archied's TOML and YAML configuration. The forge API
|
||||
// token is deliberately not part of the file: it comes from a configurable env
|
||||
// var.
|
||||
|
||||
// Package config holds archied's configuration types.
|
||||
//
|
||||
// Loading them -- locating files, decoding TOML and YAML, applying overlays,
|
||||
// defaulting and validating -- belongs to
|
||||
// internal/infrastructure/configuration. This package no longer performs any
|
||||
// I/O, so importing a settings type no longer drags in a file decoder.
|
||||
//
|
||||
// The forge API token is deliberately not part of the file: it comes from a
|
||||
// configurable env var.
|
||||
//
|
||||
// Per docs/architecture/configuration.md this package is scheduled for
|
||||
// dissolution: its types and methods are to be reassigned to the domains
|
||||
// whose behaviour they describe. Do not add new fields here that a single
|
||||
// domain could own.
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
@@ -208,6 +212,13 @@ type Dispatch struct {
|
||||
Labels map[string]string `toml:"labels" json:"labels" yaml:"labels"`
|
||||
}
|
||||
|
||||
// DispatchLabelDefaults returns a copy of the fallback label set, for the
|
||||
// configuration loader to fill absent entries with. A copy is returned so a
|
||||
// caller filling gaps cannot mutate the defaults for everyone else.
|
||||
func DispatchLabelDefaults() map[string]string {
|
||||
return cloneStringMap(dispatchLabelDefaults)
|
||||
}
|
||||
|
||||
// dispatchLabelDefaults is the fallback label set used when the user
|
||||
// hasn't configured explicit [dispatch.labels] entries.
|
||||
var dispatchLabelDefaults = map[string]string{
|
||||
@@ -522,257 +533,3 @@ type Web struct {
|
||||
// Bind localhost (or a LAN/tailnet address) -- there is no auth.
|
||||
Listen string `toml:"listen" yaml:"listen"`
|
||||
}
|
||||
|
||||
// Load reads, parses, and defaults the configuration.
|
||||
func Load(path string) (Config, error) {
|
||||
var cfg Config
|
||||
if _, err := toml.DecodeFile(path, &cfg); err != nil {
|
||||
return cfg, fmt.Errorf("config %s: %w", path, err)
|
||||
}
|
||||
return finalize(cfg)
|
||||
}
|
||||
|
||||
// LoadOverlay reads basePath, then re-decodes overlayPath into the same
|
||||
// struct so only the fields overlayPath sets are overridden -- every field
|
||||
// it omits keeps the value from basePath. This lets a deployment-specific
|
||||
// file (e.g. config.docker.toml) declare only what differs from the base
|
||||
// config instead of duplicating the whole schema. overlayPath == "" is
|
||||
// equivalent to Load(basePath).
|
||||
func LoadOverlay(basePath, overlayPath string) (Config, error) {
|
||||
var cfg Config
|
||||
if _, err := toml.DecodeFile(basePath, &cfg); err != nil {
|
||||
return cfg, fmt.Errorf("config %s: %w", basePath, err)
|
||||
}
|
||||
if overlayPath != "" {
|
||||
if _, err := toml.DecodeFile(overlayPath, &cfg); err != nil {
|
||||
return cfg, fmt.Errorf("config %s: %w", overlayPath, err)
|
||||
}
|
||||
}
|
||||
return finalize(cfg)
|
||||
}
|
||||
|
||||
// finalize applies defaults and validates a decoded configuration.
|
||||
func finalize(cfg Config) (Config, error) {
|
||||
applyGeneralDefaults(&cfg)
|
||||
applyForgeDefaults(&cfg)
|
||||
if err := applyAgentDefaults(&cfg); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if err := applyDispatchDefaults(&cfg); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if err := validateProviders(cfg.Providers); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if len(cfg.Identities) > 0 {
|
||||
if err := validateIdentities(cfg.Identities); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
} else {
|
||||
if err := validateSingleIdentity(&cfg); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
}
|
||||
if err := validateContainers(&cfg); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func applyGeneralDefaults(cfg *Config) {
|
||||
if cfg.WorkDir == "" {
|
||||
cfg.WorkDir = filepath.Join(dataHome(), "archie", "work")
|
||||
}
|
||||
if cfg.DBPath == "" {
|
||||
cfg.DBPath = filepath.Join(dataHome(), "archie", "archie.db")
|
||||
}
|
||||
cfg.Indexing = cfg.Indexing.withDefaults(cfg.WorkDir)
|
||||
if cfg.PollInterval == 0 {
|
||||
cfg.PollInterval = Duration(60 * time.Second)
|
||||
}
|
||||
if cfg.DiffCapLines == 0 {
|
||||
cfg.DiffCapLines = 400
|
||||
}
|
||||
if cfg.Web.Listen == "" {
|
||||
cfg.Web.Listen = "127.0.0.1:8484"
|
||||
}
|
||||
if cfg.MaxRetries == 0 {
|
||||
cfg.MaxRetries = 3
|
||||
}
|
||||
}
|
||||
|
||||
func applyForgeDefaults(cfg *Config) {
|
||||
if cfg.Forge.Type == "" {
|
||||
cfg.Forge.Type = "github"
|
||||
}
|
||||
if cfg.Forge.Host == "" {
|
||||
cfg.Forge.Host = "https://github.com"
|
||||
}
|
||||
if cfg.Forge.Token.Engine == "" && cfg.Forge.Token.Key == "" && cfg.Forge.TokenEnv != "" {
|
||||
cfg.Forge.Token = secret.SecretRef{Engine: "env", Key: cfg.Forge.TokenEnv}
|
||||
}
|
||||
}
|
||||
|
||||
func applyAgentDefaults(cfg *Config) error {
|
||||
if cfg.Agent.Mode == "" {
|
||||
if cfg.Containers.Enabled {
|
||||
cfg.Agent.Mode = "nats"
|
||||
} else {
|
||||
cfg.Agent.Mode = "inprocess"
|
||||
}
|
||||
}
|
||||
if cfg.Agent.Command == "" {
|
||||
cfg.Agent.Command = "archie-agent"
|
||||
}
|
||||
if !isValidAgentMode(cfg.Agent.Mode) {
|
||||
return fmt.Errorf("config: agent.mode %q is invalid (want inprocess, subprocess, or nats)", cfg.Agent.Mode)
|
||||
}
|
||||
if cfg.Agent.Mode == "subprocess" && strings.TrimSpace(cfg.Agent.Command) == "" {
|
||||
return fmt.Errorf("config: agent.command is required in subprocess mode")
|
||||
}
|
||||
for i, name := range cfg.Agent.Env {
|
||||
if strings.TrimSpace(name) == "" || strings.Contains(name, "=") {
|
||||
return fmt.Errorf("config: agent.env[%d] %q is not an environment variable name", i, name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isValidAgentMode(m string) bool { return m == "inprocess" || m == "subprocess" || m == "nats" }
|
||||
|
||||
func validateProviders(providers map[string]Provider) error {
|
||||
for name, provider := range providers {
|
||||
if provider.BaseURL == "" {
|
||||
continue
|
||||
}
|
||||
u, err := url.Parse(provider.BaseURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("config: providers.%s.base_url is invalid: %w", name, err)
|
||||
}
|
||||
if u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return fmt.Errorf("config: providers.%s.base_url must not contain userinfo, query parameters, or a fragment", name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyDispatchDefaults(cfg *Config) error {
|
||||
if cfg.Dispatch.Trigger == "" {
|
||||
cfg.Dispatch.Trigger = "assignee"
|
||||
}
|
||||
if !isValidDispatchTrigger(cfg.Dispatch.Trigger) {
|
||||
return fmt.Errorf("config: dispatch.trigger %q is invalid (want assignee, label, or either)", cfg.Dispatch.Trigger)
|
||||
}
|
||||
if cfg.Dispatch.AckReaction == "" {
|
||||
cfg.Dispatch.AckReaction = "eyes"
|
||||
} else if strings.EqualFold(cfg.Dispatch.AckReaction, "off") {
|
||||
cfg.Dispatch.AckReaction = ""
|
||||
}
|
||||
if cfg.Dispatch.Labels == nil {
|
||||
cfg.Dispatch.Labels = map[string]string{}
|
||||
}
|
||||
for k, v := range dispatchLabelDefaults {
|
||||
if cfg.Dispatch.Labels[k] == "" {
|
||||
cfg.Dispatch.Labels[k] = v
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isValidDispatchTrigger(t string) bool { return t == "assignee" || t == "label" || t == "either" }
|
||||
|
||||
func validateIdentities(identities []IdentityConfig) error {
|
||||
for i, id := range identities {
|
||||
if id.Name == "" {
|
||||
return fmt.Errorf("config: identities[%d].name is required", i)
|
||||
}
|
||||
if id.BotUser == "" {
|
||||
return fmt.Errorf("config: identities[%d].bot_user is required", i)
|
||||
}
|
||||
if len(id.Repos) == 0 {
|
||||
return fmt.Errorf("config: identities[%d] has no [[identities.repos]] entries -- at least one is required", i)
|
||||
}
|
||||
if !validForgeType(id.Forge.Type) {
|
||||
return fmt.Errorf("config: identities[%d].forge.type %q is not supported (want github or gitea)", i, id.Forge.Type)
|
||||
}
|
||||
if id.Forge.Token == (secret.SecretRef{}) {
|
||||
return fmt.Errorf("config: identities[%d].forge.token is required (each identity needs its own secret reference; unlike the top-level [forge], there is no default)", i)
|
||||
}
|
||||
if err := validateRepos(id.Repos); err != nil {
|
||||
return fmt.Errorf("config: identities[%d]: %w", i, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSingleIdentity(cfg *Config) error {
|
||||
if cfg.BotUser == "" {
|
||||
return errors.New("config: bot_user is required (or define [[identities]])")
|
||||
}
|
||||
if cfg.BotEmail == "" {
|
||||
switch cfg.Forge.Type {
|
||||
case "github":
|
||||
cfg.BotEmail = cfg.BotUser + "@users.noreply.github.com"
|
||||
case "gitea":
|
||||
cfg.BotEmail = cfg.BotUser + "@gitea.local"
|
||||
}
|
||||
}
|
||||
if !validForgeType(cfg.Forge.Type) {
|
||||
return fmt.Errorf("config: forge.type %q is not supported (want github or gitea)", cfg.Forge.Type)
|
||||
}
|
||||
return validateRepos(cfg.Repos)
|
||||
}
|
||||
|
||||
func validForgeType(t string) bool {
|
||||
return t == "github" || t == "gitea"
|
||||
}
|
||||
|
||||
func validateRepos(repos []Repo) error {
|
||||
for i, r := range repos {
|
||||
if r.Owner == "" || r.Name == "" {
|
||||
return fmt.Errorf("repos[%d] needs owner and name", i)
|
||||
}
|
||||
if glob := r.ResolvedTestGlob(); glob != "" {
|
||||
if _, err := filepath.Match(glob, ""); err != nil {
|
||||
return fmt.Errorf("repos[%d] test_glob %q is invalid: %w", i, glob, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateContainers(cfg *Config) error {
|
||||
if !cfg.Containers.Enabled {
|
||||
return nil
|
||||
}
|
||||
if cfg.Containers.Image == "" {
|
||||
return errors.New("config: containers.image is required when containers.enabled is true")
|
||||
}
|
||||
if cfg.Agent.Mode != "nats" {
|
||||
return errors.New("config: agent.mode must be \"nats\" when containers.enabled is true")
|
||||
}
|
||||
if cfg.NATS.URL == "" {
|
||||
return errors.New("config: [nats] url is required when containers.enabled is true")
|
||||
}
|
||||
if cfg.Containers.MaxUptime == 0 {
|
||||
cfg.Containers.MaxUptime = Duration(60 * time.Minute)
|
||||
}
|
||||
if cfg.Containers.VolumeTTL < 0 {
|
||||
return errors.New("config: containers.volume_ttl must not be negative")
|
||||
}
|
||||
if cfg.Containers.VolumeTTL == 0 {
|
||||
cfg.Containers.VolumeTTL = Duration(72 * time.Hour)
|
||||
}
|
||||
if cfg.Containers.PullPolicy == "" {
|
||||
cfg.Containers.PullPolicy = "missing"
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func dataHome() string {
|
||||
if x := os.Getenv("XDG_DATA_HOME"); x != "" {
|
||||
return x
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, ".local", "share")
|
||||
}
|
||||
@@ -2,8 +2,6 @@ package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -368,282 +366,6 @@ func TestDispatchLabelValuesDedup(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadDispatchAckReaction(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dispatch string
|
||||
wantAck string
|
||||
}{
|
||||
{name: "default", wantAck: "eyes"},
|
||||
{name: "disabled", dispatch: "\n[dispatch]\nack_reaction = \"off\"\n", wantAck: ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.dispatch + "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Dispatch.AckReaction != tt.wantAck {
|
||||
t.Errorf("AckReaction: got %q, want %q", cfg.Dispatch.AckReaction, tt.wantAck)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadForgeTokenEnvBackwardCompat guards against a real production
|
||||
// incident: the secrets-engine migration replaced [forge]'s flat
|
||||
// token_env string with a {engine, key} struct, but TOML silently ignores
|
||||
// unknown fields — so deployed configs still using the old token_env key
|
||||
// had their token config dropped entirely and finalize() defaulted to
|
||||
// demanding ARCHIE_GITHUB_TOKEN, crash-looping a gitea-backed daemon.
|
||||
func TestLoadForgeTokenEnvBackwardCompat(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\ntoken_env = \"MY_GITEA_TOKEN\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Forge.Token != (secret.SecretRef{Engine: "env", Key: "MY_GITEA_TOKEN"}) {
|
||||
t.Errorf("Forge.Token = %#v, want {env MY_GITEA_TOKEN} (from legacy token_env)", cfg.Forge.Token)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadForgeTokenTakesPrecedenceOverTokenEnv verifies the new-style
|
||||
// [forge.token] wins when both the legacy token_env and the new token
|
||||
// struct are present (e.g. mid-migration configs).
|
||||
func TestLoadForgeTokenTakesPrecedenceOverTokenEnv(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[forge]\ntype = \"gitea\"\ntoken_env = \"OLD_TOKEN\"\n" +
|
||||
"[forge.token]\nengine = \"env\"\nkey = \"NEW_TOKEN\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Forge.Token != (secret.SecretRef{Engine: "env", Key: "NEW_TOKEN"}) {
|
||||
t.Errorf("Forge.Token = %#v, want {env NEW_TOKEN} (new-style token wins)", cfg.Forge.Token)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidConfigEnumsAndGlobs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
extra string
|
||||
}{
|
||||
{name: "dispatch trigger", extra: "\n[dispatch]\ntrigger = \"labels\"\n"},
|
||||
{name: "agent mode", extra: "\n[agent]\nmode = \"remote\"\n"},
|
||||
{name: "agent command", extra: "\n[agent]\nmode = \"subprocess\"\ncommand = \" \"\n"},
|
||||
{name: "agent env", extra: "\n[agent]\nenv = [\"TOKEN=value\"]\n"},
|
||||
{name: "provider userinfo", extra: "\n[providers.openai]\nclass = \"openai\"\nbase_url = \"https://token@example.com/v1\"\n"},
|
||||
{name: "provider query secret", extra: "\n[providers.openai]\nclass = \"openai\"\nbase_url = \"https://example.com/v1?api_key=secret\"\n"},
|
||||
{name: "test glob", extra: "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\ntest_glob = \"[\"\n"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n"
|
||||
if tt.name != "test glob" {
|
||||
contents += "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
}
|
||||
contents += tt.extra
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := Load(path); err == nil {
|
||||
t.Fatal("Load() succeeded, want validation error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadAgentDefaultsAndOverrides(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
agent string
|
||||
wantMode string
|
||||
wantCommand string
|
||||
wantEnv []string
|
||||
}{
|
||||
{name: "defaults", wantMode: "inprocess", wantCommand: "archie-agent"},
|
||||
{
|
||||
name: "subprocess", agent: "\n[agent]\nmode = \"subprocess\"\ncommand = \"/opt/archie-agent\"\nenv = [\"GOCACHE\"]\n",
|
||||
wantMode: "subprocess", wantCommand: "/opt/archie-agent", wantEnv: []string{"GOCACHE"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.agent + "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Agent.Mode != tt.wantMode || cfg.Agent.Command != tt.wantCommand || strings.Join(cfg.Agent.Env, ",") != strings.Join(tt.wantEnv, ",") {
|
||||
t.Fatalf("agent config = %#v", cfg.Agent)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadContainerVolumeTTL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ttl string
|
||||
wantTTL time.Duration
|
||||
}{
|
||||
{name: "default", wantTTL: 72 * time.Hour},
|
||||
{name: "explicit", ttl: "volume_ttl = \"6h\"\n", wantTTL: 6 * time.Hour},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[agent]\nmode = \"nats\"\n" +
|
||||
"[nats]\nurl = \"nats://localhost:4222\"\n" +
|
||||
"[containers]\nenabled = true\nimage = \"archie-agent:test\"\n" + tt.ttl +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\npersistent_storage = true\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := cfg.Containers.VolumeTTL.Std(); got != tt.wantTTL {
|
||||
t.Fatalf("Containers.VolumeTTL = %s, want %s", got, tt.wantTTL)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsNegativeContainerVolumeTTL(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[agent]\nmode = \"nats\"\n" +
|
||||
"[nats]\nurl = \"nats://localhost:4222\"\n" +
|
||||
"[containers]\nenabled = true\nimage = \"archie-agent:test\"\nvolume_ttl = \"-1h\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\npersistent_storage = true\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := Load(path); err == nil {
|
||||
t.Fatal("Load() accepted a negative containers.volume_ttl")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExampleConfigLoads(t *testing.T) {
|
||||
cfg, err := Load(filepath.Join("..", "..", "config.example.toml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Forge.Host != "https://github.com" {
|
||||
t.Errorf("Forge.Host: got %q", cfg.Forge.Host)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOverlay(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
basePath := filepath.Join(dir, "config.toml")
|
||||
base := "bot_user = \"widget\"\nwork_dir = \"/base/work\"\n" +
|
||||
"[agent]\nmode = \"inprocess\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(basePath, []byte(base), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
overlayPath := filepath.Join(dir, "config.docker.toml")
|
||||
overlay := "work_dir = \"/var/lib/archie/work\"\n[agent]\nmode = \"nats\"\n" +
|
||||
"[nats]\nurl = \"nats://nats:4222\"\n" +
|
||||
"[containers]\nenabled = true\nimage = \"archie-agent:latest\"\n"
|
||||
if err := os.WriteFile(overlayPath, []byte(overlay), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := LoadOverlay(basePath, overlayPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Overlay-set fields win.
|
||||
if cfg.WorkDir != "/var/lib/archie/work" {
|
||||
t.Errorf("WorkDir: got %q, want overlay value", cfg.WorkDir)
|
||||
}
|
||||
if cfg.Agent.Mode != "nats" {
|
||||
t.Errorf("Agent.Mode: got %q, want %q", cfg.Agent.Mode, "nats")
|
||||
}
|
||||
// Fields the overlay omits keep the base value.
|
||||
if cfg.BotUser != "widget" {
|
||||
t.Errorf("BotUser: got %q, want base value", cfg.BotUser)
|
||||
}
|
||||
if len(cfg.Repos) != 1 || cfg.Repos[0].Owner != "acme" {
|
||||
t.Errorf("Repos: got %+v, want base repos", cfg.Repos)
|
||||
}
|
||||
|
||||
// No overlay path behaves like Load(basePath).
|
||||
baseOnly, err := LoadOverlay(basePath, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if baseOnly.Agent.Mode != "inprocess" {
|
||||
t.Errorf("Agent.Mode with empty overlay: got %q, want %q", baseOnly.Agent.Mode, "inprocess")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDockerConfigOverlaysExampleConfig(t *testing.T) {
|
||||
cfg, err := LoadOverlay(
|
||||
filepath.Join("..", "..", "config.example.toml"),
|
||||
filepath.Join("..", "..", "config.docker.toml"),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Agent.Mode != "nats" {
|
||||
t.Errorf("Agent.Mode: got %q, want %q", cfg.Agent.Mode, "nats")
|
||||
}
|
||||
if cfg.Containers.Image == "" {
|
||||
t.Error("Containers.Image: want docker overlay image, got empty")
|
||||
}
|
||||
// bot_user and repos are not set by the docker overlay -- they must
|
||||
// come from the base config, proving the overlay isn't a standalone
|
||||
// config that silently drops required fields.
|
||||
if cfg.BotUser == "" {
|
||||
t.Error("BotUser: want value from base config.example.toml, got empty")
|
||||
}
|
||||
if len(cfg.Repos) == 0 {
|
||||
t.Error("Repos: want repos from base config.example.toml, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEcosystemDefaults(t *testing.T) {
|
||||
// Empty ecosystem → "go" (backward compat).
|
||||
r := Repo{}
|
||||
@@ -695,190 +417,3 @@ func TestEcosystemCustom(t *testing.T) {
|
||||
t.Errorf("ResolvedPreflight custom: got %v, want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigParsesTwoIdentities(t *testing.T) {
|
||||
cfg, err := LoadBytes([]byte(`
|
||||
bot_user = "default-legacy"
|
||||
|
||||
[[identities]]
|
||||
name = "archie"
|
||||
bot_user = "archie"
|
||||
forge = { type = "gitea", host = "https://git.example.test", token = { engine = "env", key = "ARCHIE_TOKEN" } }
|
||||
|
||||
[[identities.repos]]
|
||||
owner = "sam"
|
||||
name = "archie-core"
|
||||
base = "main"
|
||||
ecosystem = "go"
|
||||
|
||||
[[identities]]
|
||||
name = "winter"
|
||||
bot_user = "winter"
|
||||
forge = { type = "gitea", host = "https://git.example.test", token = { engine = "env", key = "WINTER_TOKEN" } }
|
||||
|
||||
[[identities.repos]]
|
||||
owner = "sam"
|
||||
name = "example-service"
|
||||
base = "main"
|
||||
ecosystem = "go"
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadBytes: %v", err)
|
||||
}
|
||||
if len(cfg.Identities) != 2 {
|
||||
t.Fatalf("len(Identities) = %d, want 2", len(cfg.Identities))
|
||||
}
|
||||
if cfg.Identities[0].Name != "archie" {
|
||||
t.Errorf("Identities[0].Name = %q", cfg.Identities[0].Name)
|
||||
}
|
||||
if cfg.Identities[0].BotUser != "archie" {
|
||||
t.Errorf("Identities[0].BotUser = %q", cfg.Identities[0].BotUser)
|
||||
}
|
||||
if cfg.Identities[0].Forge.Token != (secret.SecretRef{Engine: "env", Key: "ARCHIE_TOKEN"}) {
|
||||
t.Errorf("Identities[0].Forge.Token = %#v", cfg.Identities[0].Forge.Token)
|
||||
}
|
||||
if len(cfg.Identities[0].Repos) != 1 || cfg.Identities[0].Repos[0].Name != "archie-core" {
|
||||
t.Errorf("Identities[0].Repos = %+v", cfg.Identities[0].Repos)
|
||||
}
|
||||
if cfg.Identities[1].Name != "winter" {
|
||||
t.Errorf("Identities[1].Name = %q", cfg.Identities[1].Name)
|
||||
}
|
||||
if cfg.Identities[1].BotUser != "winter" {
|
||||
t.Errorf("Identities[1].BotUser = %q", cfg.Identities[1].BotUser)
|
||||
}
|
||||
if cfg.Identities[1].Forge.Token != (secret.SecretRef{Engine: "env", Key: "WINTER_TOKEN"}) {
|
||||
t.Errorf("Identities[1].Forge.Token = %#v", cfg.Identities[1].Forge.Token)
|
||||
}
|
||||
if len(cfg.Identities[1].Repos) != 1 || cfg.Identities[1].Repos[0].Name != "example-service" {
|
||||
t.Errorf("Identities[1].Repos = %+v", cfg.Identities[1].Repos)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigFallsBackToLegacyWhenEmpty(t *testing.T) {
|
||||
cfg, err := LoadBytes([]byte(`
|
||||
bot_user = "solo"
|
||||
forge = { type = "github", host = "https://github.test", token_env = "GH_TOKEN" }
|
||||
|
||||
[[repos]]
|
||||
owner = "sam"
|
||||
name = "my-repo"
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadBytes: %v", err)
|
||||
}
|
||||
if len(cfg.Identities) != 0 {
|
||||
t.Errorf("len(Identities) = %d, want 0 (empty = legacy mode)", len(cfg.Identities))
|
||||
}
|
||||
if cfg.BotUser != "solo" {
|
||||
t.Errorf("BotUser = %q, want solo (legacy field active)", cfg.BotUser)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigRejectsEmptyName(t *testing.T) {
|
||||
_, err := LoadBytes([]byte(`
|
||||
[[identities]]
|
||||
bot_user = "no-name"
|
||||
forge = { type = "github", token_env = "X" }
|
||||
`))
|
||||
if err == nil {
|
||||
t.Error("expected error for identity with empty name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigRejectsMissingForgeToken(t *testing.T) {
|
||||
// Unlike the top-level [forge], a per-identity forge has no default
|
||||
// token -- each identity needs its own secret reference (e.g.
|
||||
// distinct bot accounts each with their own token). Omitting it must
|
||||
// be a startup error, not a silent empty-string token.
|
||||
_, err := LoadBytes([]byte(`
|
||||
[[identities]]
|
||||
name = "archie"
|
||||
bot_user = "archie"
|
||||
forge = { type = "github" }
|
||||
|
||||
[[identities.repos]]
|
||||
owner = "sam"
|
||||
name = "archie-core"
|
||||
`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for identity with no forge.token")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "forge.token") {
|
||||
t.Errorf("error = %q, want mention of forge.token", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadBytesDoesNotExist(t *testing.T) {
|
||||
_, err := LoadBytes(nil)
|
||||
if err == nil {
|
||||
t.Error("expected error from nil LoadBytes")
|
||||
}
|
||||
}
|
||||
|
||||
func LoadBytes(data []byte) (Config, error) {
|
||||
if data == nil {
|
||||
return Config{}, os.ErrNotExist
|
||||
}
|
||||
tmp, err := os.CreateTemp("", "archie-config-*.toml")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
defer func() {
|
||||
_ = os.Remove(tmp.Name())
|
||||
}()
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return Config{}, err
|
||||
}
|
||||
_ = tmp.Close()
|
||||
return Load(tmp.Name())
|
||||
}
|
||||
|
||||
func TestFinalizeIndexingDefaults(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
extra string
|
||||
wantIndex string
|
||||
wantDBIsSet bool
|
||||
}{
|
||||
{
|
||||
name: "defaults derive from work_dir",
|
||||
// Both paths must land under the daemon's own work_dir so two
|
||||
// archied instances on one host cannot share an index.
|
||||
extra: "\nwork_dir = \"/srv/archie/work\"\n",
|
||||
wantIndex: filepath.Join("/srv/archie/work", "indexes"),
|
||||
wantDBIsSet: true,
|
||||
},
|
||||
{
|
||||
name: "explicit index_dir is preserved",
|
||||
extra: "\nwork_dir = \"/srv/archie/work\"\n" +
|
||||
"[indexing]\nindex_dir = \"/mnt/fast/idx\"\n",
|
||||
wantIndex: "/mnt/fast/idx",
|
||||
wantDBIsSet: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
// tc.extra precedes the table sections: a top-level key written
|
||||
// after [[repos]] would be parsed as a member of that table.
|
||||
contents := "bot_user = \"widget\"\n" + tc.extra +
|
||||
"[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\ntoken_env = \"T\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Indexing.IndexDir != tc.wantIndex {
|
||||
t.Errorf("Indexing.IndexDir = %q, want %q", cfg.Indexing.IndexDir, tc.wantIndex)
|
||||
}
|
||||
if tc.wantDBIsSet && cfg.Indexing.DBPath == "" {
|
||||
t.Error("Indexing.DBPath is empty; want a default derived from work_dir")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// knownFeatureNames is the set of recognised config.<name>.yaml feature files.
|
||||
// Any config.<name>.yaml file whose <name> is not in this set is rejected --
|
||||
// silent ignores would hide typos.
|
||||
var knownFeatureNames = map[string]bool{
|
||||
"gateway": true,
|
||||
"tools": true,
|
||||
"memory": true,
|
||||
"models": true,
|
||||
"identities": true,
|
||||
}
|
||||
|
||||
// knownFeatureList renders the recognised feature names for error messages.
|
||||
// Derived from knownFeatureNames so the two cannot drift when a feature is
|
||||
// added.
|
||||
func knownFeatureList() string {
|
||||
names := make([]string, 0, len(knownFeatureNames))
|
||||
for name := range knownFeatureNames {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return strings.Join(names, ", ")
|
||||
}
|
||||
|
||||
// LoadDir loads configuration from a directory tree.
|
||||
//
|
||||
// ~/.config/archie/config.yaml -- daemon-level fields
|
||||
// ~/.config/archie/config.gateway.yaml -- chat channels, platforms
|
||||
// ~/.config/archie/config.tools.yaml -- MCP servers, tool policy
|
||||
// ~/.config/archie/config.memory.yaml -- memory provider config
|
||||
// ~/.config/archie/config.models.yaml -- LLM providers and models
|
||||
// ~/.config/archie/config.identities.yaml -- identity configs
|
||||
// ~/.config/archie/conf.d/*.yaml -- additional feature files
|
||||
//
|
||||
// Missing feature files mean "feature disabled" -- no error, just zero values.
|
||||
// Legacy config.toml is used as a fallback when config.yaml is absent.
|
||||
// YAML takes precedence over TOML when both exist.
|
||||
//
|
||||
// When overlayDir is non-empty, files from overlayDir are decoded on top of
|
||||
// baseDir -- only the fields an overlay file declares are overridden; everything
|
||||
// else is inherited from the base.
|
||||
func LoadDir(baseDir, overlayDir string) (Config, error) {
|
||||
var cfg Config
|
||||
if err := loadDirInto(&cfg, baseDir, true); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if overlayDir != "" {
|
||||
if err := loadDirInto(&cfg, overlayDir, false); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
}
|
||||
return finalize(cfg)
|
||||
}
|
||||
|
||||
// loadDirInto scans dir for config files and decodes them into cfg.
|
||||
// When requireMain is true the directory must contain config.yaml or
|
||||
// config.toml; when false (overlay mode) a missing main config is
|
||||
// fine -- only feature and conf.d/ files are applied.
|
||||
func loadDirInto(cfg *Config, dir string, requireMain bool) error {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("config dir %s: %w", dir, err)
|
||||
}
|
||||
|
||||
mainYAML, mainTOML, featurePaths, extraPaths, err := scanConfigEntries(dir, entries)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := loadMainConfig(cfg, mainYAML, mainTOML, requireMain); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := loadFeatureConfigs(cfg, featurePaths); err != nil {
|
||||
return err
|
||||
}
|
||||
loadExtraConfigs(cfg, extraPaths)
|
||||
return nil
|
||||
}
|
||||
|
||||
// scanConfigEntries walks dir entries and classifies them into main config,
|
||||
// feature, and extra paths.
|
||||
func scanConfigEntries(dir string, entries []os.DirEntry) (mainYAML, mainTOML string, featurePaths, extraPaths map[string]string, err error) {
|
||||
featurePaths = map[string]string{}
|
||||
extraPaths = map[string]string{}
|
||||
var unknownConfigFiles []string
|
||||
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
if e.Name() == "conf.d" {
|
||||
if err := scanConfDir(dir, featurePaths, extraPaths); err != nil {
|
||||
return "", "", nil, nil, err
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
name := e.Name()
|
||||
if !strings.HasSuffix(name, ".yaml") && !strings.HasSuffix(name, ".yml") && !strings.HasSuffix(name, ".toml") {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case name == "config.yaml" || name == "config.yml":
|
||||
mainYAML = filepath.Join(dir, name)
|
||||
case name == "config.toml":
|
||||
mainTOML = filepath.Join(dir, name)
|
||||
default:
|
||||
unknown, classifyErr := classifyFeatureFile(dir, name, featurePaths)
|
||||
if classifyErr != nil {
|
||||
return "", "", nil, nil, classifyErr
|
||||
}
|
||||
if unknown != "" {
|
||||
unknownConfigFiles = append(unknownConfigFiles, unknown)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(unknownConfigFiles) > 0 {
|
||||
return "", "", nil, nil, fmt.Errorf("unrecognized config file %q (known features: %s)", unknownConfigFiles[0], knownFeatureList())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// classifyFeatureFile registers a feature file in featurePaths.
|
||||
//
|
||||
// It returns the filename when the feature is unrecognised, so the caller can
|
||||
// report all such files together, and an error when two files claim the same
|
||||
// feature: silently preferring one would apply settings the operator cannot
|
||||
// see from the filenames alone.
|
||||
func classifyFeatureFile(dir, name string, featurePaths map[string]string) (string, error) {
|
||||
if !strings.HasPrefix(name, "config.") || (!strings.HasSuffix(name, ".yaml") && !strings.HasSuffix(name, ".yml")) {
|
||||
return "", nil
|
||||
}
|
||||
feature := configFeatureName(name)
|
||||
if !knownFeatureNames[feature] {
|
||||
return name, nil
|
||||
}
|
||||
path := filepath.Join(dir, name)
|
||||
if existing, ok := featurePaths[feature]; ok {
|
||||
return "", fmt.Errorf("duplicate feature %q: both %s and %s define it", feature, existing, path)
|
||||
}
|
||||
featurePaths[feature] = path
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func configFeatureName(filename string) string {
|
||||
rest := strings.TrimPrefix(filename, "config.")
|
||||
return strings.TrimSuffix(strings.TrimSuffix(rest, ".yaml"), ".yml")
|
||||
}
|
||||
|
||||
func loadMainConfig(cfg *Config, mainYAML, mainTOML string, requireMain bool) error {
|
||||
if mainYAML != "" {
|
||||
data, err := os.ReadFile(mainYAML)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading %s: %w", mainYAML, err)
|
||||
}
|
||||
return yaml.Unmarshal(data, cfg)
|
||||
}
|
||||
if mainTOML != "" {
|
||||
_, err := toml.DecodeFile(mainTOML, cfg)
|
||||
return err
|
||||
}
|
||||
if requireMain {
|
||||
return fmt.Errorf("no config.yaml or config.toml found in %s", "")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadFeatureConfigs(cfg *Config, featurePaths map[string]string) error {
|
||||
for feature, path := range featurePaths {
|
||||
if err := loadFeatureFile(cfg, feature, path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadExtraConfigs(cfg *Config, extraPaths map[string]string) {
|
||||
for name, path := range extraPaths {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil { // skip unreadable extras silently
|
||||
continue
|
||||
}
|
||||
var val any
|
||||
if err := yaml.Unmarshal(data, &val); err != nil {
|
||||
continue
|
||||
}
|
||||
if cfg.Extra == nil {
|
||||
cfg.Extra = make(map[string]any)
|
||||
}
|
||||
cfg.Extra[name] = val
|
||||
}
|
||||
}
|
||||
|
||||
// scanConfDir reads YAML files from dir/conf.d/ and distributes them into
|
||||
// featurePaths (known features) or extraPaths (unknown).
|
||||
func scanConfDir(dir string, featurePaths, extraPaths map[string]string) error {
|
||||
confEntries, err := os.ReadDir(filepath.Join(dir, "conf.d"))
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("reading conf.d: %w", err)
|
||||
}
|
||||
for _, ce := range confEntries {
|
||||
cn := ce.Name()
|
||||
if ce.IsDir() || (!strings.HasSuffix(cn, ".yaml") && !strings.HasSuffix(cn, ".yml")) {
|
||||
continue
|
||||
}
|
||||
feature := strings.TrimSuffix(strings.TrimSuffix(cn, ".yaml"), ".yml")
|
||||
fullPath := filepath.Join(dir, "conf.d", cn)
|
||||
if knownFeatureNames[feature] {
|
||||
if _, exists := featurePaths[feature]; exists {
|
||||
return fmt.Errorf("duplicate feature %q: both config.%s.yaml and conf.d/%s.yaml exist", feature, feature, feature)
|
||||
}
|
||||
featurePaths[feature] = fullPath
|
||||
} else {
|
||||
extraPaths[feature] = fullPath
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadFeatureFile decodes a feature file's YAML into the correct part of
|
||||
// Config. Most feature files map to top-level Config fields and can be
|
||||
// decoded with yaml.Unmarshal(data, cfg) directly. Memory and tools are
|
||||
// sub-structs whose YAML keys live at the top level of the file, not nested
|
||||
// under a "memory:" or "tools:" key -- decode those into their target
|
||||
// sub-struct directly.
|
||||
func loadFeatureFile(cfg *Config, feature, path string) error {
|
||||
if cfg == nil {
|
||||
return fmt.Errorf("config must not be nil")
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading %s: %w", path, err)
|
||||
}
|
||||
switch feature {
|
||||
case "memory":
|
||||
if err := yaml.Unmarshal(data, &cfg.Memory); err != nil {
|
||||
return fmt.Errorf("parsing %s: %w", path, err)
|
||||
}
|
||||
case "tools":
|
||||
if err := yaml.Unmarshal(data, &cfg.Tools); err != nil {
|
||||
return fmt.Errorf("parsing %s: %w", path, err)
|
||||
}
|
||||
default:
|
||||
// models, gateway, identities -- these have top-level keys that
|
||||
// match Config fields directly.
|
||||
if err := yaml.Unmarshal(data, cfg); err != nil {
|
||||
return fmt.Errorf("parsing %s: %w", path, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -13,12 +13,12 @@ type IndexingConfig struct {
|
||||
DBPath string `toml:"db_path" yaml:"db_path" json:"db_path,omitempty"`
|
||||
}
|
||||
|
||||
// withDefaults fills unset paths from the daemon's work directory.
|
||||
// WithDefaults fills unset paths from the daemon's work directory.
|
||||
//
|
||||
// Deriving from workDir rather than a shared data home is deliberate: two
|
||||
// archied instances run on one host, each with its own work_dir, so this
|
||||
// keeps their indexes separate without either having to configure anything.
|
||||
func (c IndexingConfig) withDefaults(workDir string) IndexingConfig {
|
||||
func (c IndexingConfig) WithDefaults(workDir string) IndexingConfig {
|
||||
if c.IndexDir == "" {
|
||||
c.IndexDir = filepath.Join(workDir, "indexes")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// decodeTOML decodes a TOML file into target.
|
||||
func decodeTOML(path string, target any) error {
|
||||
if _, err := toml.DecodeFile(path, target); err != nil {
|
||||
return fmt.Errorf("%w: parsing %s: %w", ErrUnreadable, path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeYAML decodes a YAML file into target.
|
||||
//
|
||||
// Every decode error names its file. The previous loadMainConfig returned
|
||||
// bare yaml.Unmarshal and toml.DecodeFile errors, so a syntax error in one
|
||||
// of several files gave no clue which one to open.
|
||||
func decodeYAML(path string, target any) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: reading %s: %w", ErrUnreadable, path, err)
|
||||
}
|
||||
if err := yaml.Unmarshal(data, target); err != nil {
|
||||
return fmt.Errorf("%w: parsing %s: %w", ErrUnreadable, path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeFeature decodes a feature file into the part of cfg it describes.
|
||||
//
|
||||
// Most feature files carry top-level keys matching Config fields and decode
|
||||
// into cfg directly. Memory and tools are sub-structs whose keys sit at the
|
||||
// top level of their own file rather than nested under a "memory:" or
|
||||
// "tools:" key, so they decode into the sub-struct.
|
||||
func decodeFeature(cfg *config.Config, feature Feature, path string) error {
|
||||
switch feature {
|
||||
case FeatureMemory:
|
||||
return decodeYAML(path, &cfg.Memory)
|
||||
case FeatureTools:
|
||||
return decodeYAML(path, &cfg.Tools)
|
||||
default:
|
||||
return decodeYAML(path, cfg)
|
||||
}
|
||||
}
|
||||
|
||||
// decodeExtra decodes an unrecognised conf.d/ file into cfg.Extra under name.
|
||||
//
|
||||
// Unlike the previous implementation this reports failures instead of
|
||||
// skipping them: silently dropping a file the operator wrote, because it
|
||||
// happened to be unreadable or malformed, presents as the setting simply not
|
||||
// taking effect.
|
||||
func decodeExtra(cfg *config.Config, name, path string) error {
|
||||
var value any
|
||||
if err := decodeYAML(path, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.Extra == nil {
|
||||
cfg.Extra = make(map[string]any)
|
||||
}
|
||||
cfg.Extra[name] = value
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// Defaults applied to absent input. Named so a reader can find the value
|
||||
// without reading the code that applies it.
|
||||
const (
|
||||
defaultPollInterval = 60 * time.Second
|
||||
defaultDiffCapLines = 400
|
||||
defaultWebListen = "127.0.0.1:8484" // "off" disables
|
||||
defaultMaxRetries = 3
|
||||
defaultForgeType = "github"
|
||||
defaultForgeHost = "https://github.com"
|
||||
defaultAgentCommand = "archie-agent"
|
||||
defaultDispatchTrigger = "assignee"
|
||||
defaultAckReaction = "eyes"
|
||||
defaultContainerUptime = 60 * time.Minute
|
||||
defaultVolumeTTL = 72 * time.Hour
|
||||
defaultPullPolicy = "missing"
|
||||
)
|
||||
|
||||
// applyDefaults fills in every absent value. It never reports an error and
|
||||
// never rejects input.
|
||||
//
|
||||
// Defaulting and validation were previously interleaved: functions named
|
||||
// applyXDefaults also returned validation errors, and functions named
|
||||
// validateX quietly mutated the config. That made it impossible to answer
|
||||
// "what did the operator actually set?" -- the only way to see the supplied
|
||||
// input was to not call them. Splitting them means defaults can be applied,
|
||||
// inspected, and reasoned about independently of whether the result is valid.
|
||||
func (l *Loader) applyDefaults(cfg *config.Config) {
|
||||
l.applyGeneralDefaults(cfg)
|
||||
applyForgeDefaults(cfg)
|
||||
applyAgentDefaults(cfg)
|
||||
applyDispatchDefaults(cfg)
|
||||
applyIdentityDefaults(cfg)
|
||||
applyContainerDefaults(cfg)
|
||||
}
|
||||
|
||||
// applyGeneralDefaults derives the paths and limits that have no owning
|
||||
// section.
|
||||
func (l *Loader) applyGeneralDefaults(cfg *config.Config) {
|
||||
if cfg.WorkDir == "" {
|
||||
cfg.WorkDir = filepath.Join(l.dataHome(), "archie", "work")
|
||||
}
|
||||
if cfg.DBPath == "" {
|
||||
cfg.DBPath = filepath.Join(l.dataHome(), "archie", "archie.db")
|
||||
}
|
||||
cfg.Indexing = cfg.Indexing.WithDefaults(cfg.WorkDir)
|
||||
if cfg.PollInterval == 0 {
|
||||
cfg.PollInterval = config.Duration(defaultPollInterval)
|
||||
}
|
||||
if cfg.DiffCapLines == 0 {
|
||||
cfg.DiffCapLines = defaultDiffCapLines
|
||||
}
|
||||
if cfg.Web.Listen == "" {
|
||||
cfg.Web.Listen = defaultWebListen
|
||||
}
|
||||
if cfg.MaxRetries == 0 {
|
||||
cfg.MaxRetries = defaultMaxRetries
|
||||
}
|
||||
}
|
||||
|
||||
// applyForgeDefaults fills the forge section, promoting the legacy
|
||||
// token_env field to a secret reference when no explicit one was given.
|
||||
func applyForgeDefaults(cfg *config.Config) {
|
||||
if cfg.Forge.Type == "" {
|
||||
cfg.Forge.Type = defaultForgeType
|
||||
}
|
||||
if cfg.Forge.Host == "" {
|
||||
cfg.Forge.Host = defaultForgeHost
|
||||
}
|
||||
if cfg.Forge.Token.Engine == "" && cfg.Forge.Token.Key == "" && cfg.Forge.TokenEnv != "" {
|
||||
cfg.Forge.Token = secret.SecretRef{Engine: "env", Key: cfg.Forge.TokenEnv}
|
||||
}
|
||||
}
|
||||
|
||||
// applyAgentDefaults picks the execution mode. Containers require the NATS
|
||||
// transport, so enabling them selects it unless the operator said otherwise.
|
||||
func applyAgentDefaults(cfg *config.Config) {
|
||||
if cfg.Agent.Mode == "" {
|
||||
if cfg.Containers.Enabled {
|
||||
cfg.Agent.Mode = agentModeNATS
|
||||
} else {
|
||||
cfg.Agent.Mode = agentModeInProcess
|
||||
}
|
||||
}
|
||||
if cfg.Agent.Command == "" {
|
||||
cfg.Agent.Command = defaultAgentCommand
|
||||
}
|
||||
}
|
||||
|
||||
// applyDispatchDefaults fills the dispatch section. "off" is the documented
|
||||
// way to disable the acknowledgement reaction, and normalises to empty.
|
||||
func applyDispatchDefaults(cfg *config.Config) {
|
||||
if cfg.Dispatch.Trigger == "" {
|
||||
cfg.Dispatch.Trigger = defaultDispatchTrigger
|
||||
}
|
||||
switch {
|
||||
case cfg.Dispatch.AckReaction == "":
|
||||
cfg.Dispatch.AckReaction = defaultAckReaction
|
||||
case isOff(cfg.Dispatch.AckReaction):
|
||||
cfg.Dispatch.AckReaction = ""
|
||||
}
|
||||
if cfg.Dispatch.Labels == nil {
|
||||
cfg.Dispatch.Labels = map[string]string{}
|
||||
}
|
||||
for k, v := range config.DispatchLabelDefaults() {
|
||||
if cfg.Dispatch.Labels[k] == "" {
|
||||
cfg.Dispatch.Labels[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// applyIdentityDefaults derives the commit email for a single-identity
|
||||
// deployment. Multi-identity deployments configure each identity explicitly.
|
||||
func applyIdentityDefaults(cfg *config.Config) {
|
||||
if len(cfg.Identities) > 0 || cfg.BotUser == "" || cfg.BotEmail != "" {
|
||||
return
|
||||
}
|
||||
switch cfg.Forge.Type {
|
||||
case forgeTypeGitHub:
|
||||
cfg.BotEmail = cfg.BotUser + "@users.noreply.github.com"
|
||||
case forgeTypeGitea:
|
||||
cfg.BotEmail = cfg.BotUser + "@gitea.local"
|
||||
}
|
||||
}
|
||||
|
||||
// applyContainerDefaults fills the container lifetimes. A negative VolumeTTL
|
||||
// is left alone for validation to reject rather than silently corrected.
|
||||
func applyContainerDefaults(cfg *config.Config) {
|
||||
if !cfg.Containers.Enabled {
|
||||
return
|
||||
}
|
||||
if cfg.Containers.MaxUptime == 0 {
|
||||
cfg.Containers.MaxUptime = config.Duration(defaultContainerUptime)
|
||||
}
|
||||
if cfg.Containers.VolumeTTL == 0 {
|
||||
cfg.Containers.VolumeTTL = config.Duration(defaultVolumeTTL)
|
||||
}
|
||||
if cfg.Containers.PullPolicy == "" {
|
||||
cfg.Containers.PullPolicy = defaultPullPolicy
|
||||
}
|
||||
}
|
||||
+30
-30
@@ -17,7 +17,7 @@
|
||||
// Legacy config.toml is still supported as a fallback.
|
||||
// Overlay support: --config-overlay <dir> applies files from <dir>
|
||||
// on top of the base config directory.
|
||||
package config
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
@@ -62,7 +62,7 @@ max_retries: 5
|
||||
bot_user: archie
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -87,7 +87,7 @@ func TestLoadDirAppliesDefaultsForMissingDaemonFields(t *testing.T) {
|
||||
dir := tmpConfigDir(t)
|
||||
writeFile(t, dir, "config.yaml", `bot_user: solo`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -103,7 +103,7 @@ func TestLoadDirAppliesDefaultsForMissingDaemonFields(t *testing.T) {
|
||||
func TestLoadDirRequiresBotUser(t *testing.T) {
|
||||
dir := tmpConfigDir(t)
|
||||
writeFile(t, dir, "config.yaml", `db_path: /tmp/db`)
|
||||
_, err := LoadDir(dir, "")
|
||||
_, err := loadDir(dir, "")
|
||||
if err == nil || !strings.Contains(err.Error(), "bot_user") {
|
||||
t.Errorf("expected bot_user error, got: %v", err)
|
||||
}
|
||||
@@ -116,7 +116,7 @@ func TestLoadDirMissingFeatureFilesSucceeds(t *testing.T) {
|
||||
// Only config.yaml exists -- no gateway, tools, memory, models, identities files.
|
||||
writeFile(t, dir, "config.yaml", `bot_user: minimal`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -143,7 +143,7 @@ web:
|
||||
listen: "0.0.0.0:9090"
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -174,7 +174,7 @@ providers:
|
||||
api_key_env: ANTHROPIC_KEY
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -206,7 +206,7 @@ provider_config:
|
||||
session_ttl: 72h
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -241,7 +241,7 @@ tool_policy:
|
||||
parallel_execution: true
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -298,7 +298,7 @@ identities:
|
||||
ecosystem: go
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -328,7 +328,7 @@ custom_tools:
|
||||
command: /usr/local/bin/analyzer
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -369,7 +369,7 @@ owner = "sam"
|
||||
name = "legacy-repo"
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -390,7 +390,7 @@ func TestLoadDirYamlTakesPrecedenceOverToml(t *testing.T) {
|
||||
writeFile(t, dir, "config.yaml", `bot_user: yaml-wins`)
|
||||
writeFile(t, dir, "config.toml", `bot_user = "toml-loses"`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -424,7 +424,7 @@ models:
|
||||
planner: overlay/planner
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(baseDir, overlayDir)
|
||||
cfg, err := loadDir(baseDir, overlayDir)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -461,7 +461,7 @@ chat:
|
||||
token_env: OVERLAY_TG_TOKEN
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(baseDir, overlayDir)
|
||||
cfg, err := loadDir(baseDir, overlayDir)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -475,9 +475,9 @@ func TestLoadDirOverlayEmptyDirIsNoop(t *testing.T) {
|
||||
writeFile(t, baseDir, "config.yaml", `bot_user: base-only`)
|
||||
|
||||
overlayDir := tmpConfigDir(t)
|
||||
// Empty overlay directory -- same as calling LoadDir(baseDir, "").
|
||||
// Empty overlay directory -- same as calling loadDir(baseDir, "").
|
||||
|
||||
cfg, err := LoadDir(baseDir, overlayDir)
|
||||
cfg, err := loadDir(baseDir, overlayDir)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -493,7 +493,7 @@ func TestLoadDirRejectsInvalidFeatureFile(t *testing.T) {
|
||||
writeFile(t, dir, "config.yaml", `bot_user: valid`)
|
||||
writeFile(t, dir, "config.models.yaml", `this: [is: not: valid: yaml: }}`)
|
||||
|
||||
_, err := LoadDir(dir, "")
|
||||
_, err := loadDir(dir, "")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for malformed feature file")
|
||||
}
|
||||
@@ -505,7 +505,7 @@ func TestLoadDirRejectsUnknownFeatureFile(t *testing.T) {
|
||||
// config.unknown.yaml is not a known feature -- should error, not silently ignore.
|
||||
writeFile(t, dir, "config.unknown.yaml", `foo: bar`)
|
||||
|
||||
_, err := LoadDir(dir, "")
|
||||
_, err := loadDir(dir, "")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for unknown feature file (silent ignore would hide typos)")
|
||||
}
|
||||
@@ -521,7 +521,7 @@ func TestLoadDirRejectsDuplicateFeatureFiles(t *testing.T) {
|
||||
writeFile(t, dir, "config.gateway.yaml", `chat: {telegram: {token_env: FIRST}}`)
|
||||
writeFile(t, dir, "conf.d/gateway.yaml", `chat: {telegram: {token_env: SECOND}}`)
|
||||
|
||||
_, err := LoadDir(dir, "")
|
||||
_, err := loadDir(dir, "")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for duplicate feature files")
|
||||
}
|
||||
@@ -533,7 +533,7 @@ func TestLoadDirRejectsDuplicateFeatureFiles(t *testing.T) {
|
||||
func TestLoadDirRequiresConfigYamlOrConfigToml(t *testing.T) {
|
||||
dir := tmpConfigDir(t)
|
||||
// Neither config.yaml nor config.toml exists.
|
||||
_, err := LoadDir(dir, "")
|
||||
_, err := loadDir(dir, "")
|
||||
if err == nil || !strings.Contains(err.Error(), "config.yaml") && !strings.Contains(err.Error(), "config.toml") {
|
||||
t.Errorf("expected error about missing config.yaml or config.toml, got: %v", err)
|
||||
}
|
||||
@@ -557,7 +557,7 @@ budgets:
|
||||
wall_clock: 30m
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -588,7 +588,7 @@ containers:
|
||||
pull_policy: always
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -618,7 +618,7 @@ dispatch:
|
||||
pr: bot:pr
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -643,7 +643,7 @@ notify:
|
||||
webhook: https://hooks.example.test/archie
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -661,7 +661,7 @@ bot_user: difftest
|
||||
diff_cap_lines: 200
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -680,7 +680,7 @@ skills_dir: /opt/archie/skills
|
||||
plugin_dir: /opt/archie/plugins
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -706,7 +706,7 @@ models:
|
||||
planner: openai/gpt
|
||||
`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
cfg, err := loadDir(dir, "")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadDir: %v", err)
|
||||
}
|
||||
@@ -746,7 +746,7 @@ owner = "sam"
|
||||
name = "old-repo"
|
||||
`)
|
||||
|
||||
cfg, err := Load(filepath.Join(dir, "config.toml"))
|
||||
cfg, err := loadFile(filepath.Join(dir, "config.toml"))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -773,7 +773,7 @@ bot_user = "overlaid"
|
||||
max_retries = 5
|
||||
`)
|
||||
|
||||
cfg, err := LoadOverlay(
|
||||
cfg, err := loadOverlay(
|
||||
filepath.Join(baseDir, "config.toml"),
|
||||
filepath.Join(overlayDir, "config.toml"),
|
||||
)
|
||||
@@ -0,0 +1,156 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// confDirName is the subdirectory holding additional feature files.
|
||||
const confDirName = "conf.d"
|
||||
|
||||
// fileSet is the outcome of scanning one configuration directory: which file
|
||||
// carries the daemon-level settings, which files carry recognised features,
|
||||
// and which carry opaque extras.
|
||||
//
|
||||
// Scanning previously returned four bare values (two paths and two maps),
|
||||
// which left the caller to remember that YAML wins over TOML and that extras
|
||||
// are keyed by feature name.
|
||||
type fileSet struct {
|
||||
mainYAML string
|
||||
mainTOML string
|
||||
features map[Feature]string
|
||||
extras map[string]string
|
||||
}
|
||||
|
||||
// main returns the daemon-level config file and its format. YAML wins when
|
||||
// both are present; legacy config.toml is the fallback.
|
||||
func (fs fileSet) main() (path string, yaml bool, ok bool) {
|
||||
if fs.mainYAML != "" {
|
||||
return fs.mainYAML, true, true
|
||||
}
|
||||
if fs.mainTOML != "" {
|
||||
return fs.mainTOML, false, true
|
||||
}
|
||||
return "", false, false
|
||||
}
|
||||
|
||||
// sortedFeatures returns recognised features in a stable order, so loading
|
||||
// is deterministic and provenance reads the same across runs. Map iteration
|
||||
// order previously made the applied order arbitrary.
|
||||
func (fs fileSet) sortedFeatures() []Feature {
|
||||
names := make([]Feature, 0, len(fs.features))
|
||||
for f := range fs.features {
|
||||
names = append(names, f)
|
||||
}
|
||||
sort.Slice(names, func(i, j int) bool { return names[i] < names[j] })
|
||||
return names
|
||||
}
|
||||
|
||||
// sortedExtras returns extra names in a stable order.
|
||||
func (fs fileSet) sortedExtras() []string {
|
||||
names := make([]string, 0, len(fs.extras))
|
||||
for n := range fs.extras {
|
||||
names = append(names, n)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
|
||||
// discover scans dir and classifies its entries.
|
||||
func discover(dir string) (fileSet, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return fileSet{}, fmt.Errorf("%w: config dir %s: %w", ErrUnreadable, dir, err)
|
||||
}
|
||||
|
||||
fs := fileSet{
|
||||
features: map[Feature]string{},
|
||||
extras: map[string]string{},
|
||||
}
|
||||
var unknown []string
|
||||
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
if e.IsDir() {
|
||||
if name == confDirName {
|
||||
if err := fs.scanConfDir(dir); err != nil {
|
||||
return fileSet{}, err
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case name == "config.yaml" || name == "config.yml":
|
||||
fs.mainYAML = filepath.Join(dir, name)
|
||||
case name == "config.toml":
|
||||
fs.mainTOML = filepath.Join(dir, name)
|
||||
case isYAML(name) || isTOML(name):
|
||||
if err := fs.classify(dir, name, &unknown); err != nil {
|
||||
return fileSet{}, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(unknown) > 0 {
|
||||
sort.Strings(unknown)
|
||||
return fileSet{}, fmt.Errorf("%w: %q (known features: %s)", ErrUnknownFeature, unknown[0], featureList())
|
||||
}
|
||||
return fs, nil
|
||||
}
|
||||
|
||||
// classify records a config.<feature>.yaml file, collecting unrecognised
|
||||
// names into unknown so every one can be reported rather than just the first
|
||||
// encountered.
|
||||
func (fs fileSet) classify(dir, name string, unknown *[]string) error {
|
||||
feature := featureFromFilename(name)
|
||||
if feature == "" {
|
||||
return nil
|
||||
}
|
||||
if !feature.known() {
|
||||
*unknown = append(*unknown, name)
|
||||
return nil
|
||||
}
|
||||
return fs.addFeature(feature, filepath.Join(dir, name))
|
||||
}
|
||||
|
||||
// scanConfDir reads dir/conf.d/, routing recognised names to features and
|
||||
// the rest to extras.
|
||||
func (fs fileSet) scanConfDir(dir string) error {
|
||||
confDir := filepath.Join(dir, confDirName)
|
||||
entries, err := os.ReadDir(confDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%w: %s: %w", ErrUnreadable, confDir, err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
if e.IsDir() || !isYAML(name) {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(confDir, name)
|
||||
feature := Feature(trimYAMLSuffix(name))
|
||||
if !feature.known() {
|
||||
fs.extras[string(feature)] = path
|
||||
continue
|
||||
}
|
||||
if err := fs.addFeature(feature, path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// addFeature records a feature file, rejecting a second file claiming the
|
||||
// same feature. Preferring either silently would apply settings the operator
|
||||
// cannot predict from the filenames.
|
||||
func (fs fileSet) addFeature(feature Feature, path string) error {
|
||||
if existing, ok := fs.features[feature]; ok {
|
||||
return fmt.Errorf("%w: %q defined by both %s and %s", ErrDuplicateFeature, feature, existing, path)
|
||||
}
|
||||
fs.features[feature] = path
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Package configuration is the external configuration input boundary.
|
||||
//
|
||||
// It owns everything about how configuration arrives: locating files,
|
||||
// decoding TOML and YAML, applying base/overlay precedence, resolving
|
||||
// environment and secret references, defaulting absent input, validating
|
||||
// what was supplied, and recording where each value came from.
|
||||
//
|
||||
// It owns none of the behaviour those values describe. Deciding what a
|
||||
// dispatch trigger or a retry budget *means* belongs to the domain that
|
||||
// acts on it; this package only decides whether the operator supplied
|
||||
// something usable, and says so clearly when they did not.
|
||||
//
|
||||
// # Why this package exists
|
||||
//
|
||||
// Loading used to live inside internal/config, alongside the runtime types
|
||||
// every package imports. That made the shared model responsible for file
|
||||
// I/O, so a package that merely wanted a settings struct also pulled in a
|
||||
// TOML decoder, and defaulting, validation and decoding were interleaved in
|
||||
// one function. See docs/architecture/configuration.md.
|
||||
//
|
||||
// # The temporary seam
|
||||
//
|
||||
// docs/architecture/configuration.md requires a private input document that
|
||||
// is translated into per-domain settings and never returned as the
|
||||
// application's runtime model. [Document.Config] is not that yet: it is the
|
||||
// existing internal/config.Config, exposed here so this package can take
|
||||
// over loading without every consumer changing at once.
|
||||
//
|
||||
// It is deliberately a named field rather than a bare return value so the
|
||||
// compromise is visible at each use site. It should be replaced by typed
|
||||
// per-domain sections once those domains own their settings; the condition
|
||||
// for deleting it is that internal/config no longer exists. Until then, do
|
||||
// not add behaviour to it, and do not treat its presence as licence to pass
|
||||
// whole-application configuration into a domain.
|
||||
package configuration
|
||||
@@ -0,0 +1,36 @@
|
||||
package configuration
|
||||
|
||||
import "errors"
|
||||
|
||||
// Sentinel errors callers can match with errors.Is. Everything else this
|
||||
// package returns is wrapped with the offending path via %w.
|
||||
//
|
||||
// The distinction that matters to a caller is whether the operator can fix
|
||||
// the problem by editing a file (ErrInvalidInput) or whether the
|
||||
// configuration could not be read at all (ErrNoConfigFile, ErrUnreadable).
|
||||
// The previous code signalled all of these with fmt.Errorf strings prefixed
|
||||
// "config: ", so a caller had to match on message text to tell them apart.
|
||||
var (
|
||||
// ErrInvalidInput reports configuration that decoded successfully but
|
||||
// describes something unusable -- an unknown enum value, a missing
|
||||
// required field, a malformed URL.
|
||||
ErrInvalidInput = errors.New("configuration: invalid input")
|
||||
|
||||
// ErrNoConfigFile reports a directory containing neither config.yaml
|
||||
// nor config.toml where one was required.
|
||||
ErrNoConfigFile = errors.New("configuration: no config file")
|
||||
|
||||
// ErrUnknownFeature reports a config.<name>.yaml whose <name> is not a
|
||||
// recognised feature. Ignoring these silently would hide a typo as a
|
||||
// disabled feature.
|
||||
ErrUnknownFeature = errors.New("configuration: unrecognized feature file")
|
||||
|
||||
// ErrDuplicateFeature reports two files claiming the same feature, where
|
||||
// choosing either would apply settings the operator cannot predict from
|
||||
// the filenames.
|
||||
ErrDuplicateFeature = errors.New("configuration: duplicate feature file")
|
||||
|
||||
// ErrUnreadable reports a file or directory that could not be read or
|
||||
// decoded.
|
||||
ErrUnreadable = errors.New("configuration: unreadable")
|
||||
)
|
||||
@@ -0,0 +1,65 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Feature names a recognised config.<feature>.yaml section.
|
||||
type Feature string
|
||||
|
||||
const (
|
||||
FeatureGateway Feature = "gateway"
|
||||
FeatureTools Feature = "tools"
|
||||
FeatureMemory Feature = "memory"
|
||||
FeatureModels Feature = "models"
|
||||
FeatureIdentities Feature = "identities"
|
||||
)
|
||||
|
||||
// knownFeatures is the closed set of recognised feature files. A
|
||||
// config.<name>.yaml outside this set is an error rather than a silent
|
||||
// no-op, so a misspelled filename does not look like a disabled feature.
|
||||
var knownFeatures = map[Feature]bool{
|
||||
FeatureGateway: true,
|
||||
FeatureTools: true,
|
||||
FeatureMemory: true,
|
||||
FeatureModels: true,
|
||||
FeatureIdentities: true,
|
||||
}
|
||||
|
||||
// known reports whether f is a recognised feature.
|
||||
func (f Feature) known() bool { return knownFeatures[f] }
|
||||
|
||||
// featureList renders the recognised names for error messages. Derived from
|
||||
// knownFeatures so the message cannot drift from the set it describes -- it
|
||||
// was previously spelled out as a literal beside the map.
|
||||
func featureList() string {
|
||||
names := make([]string, 0, len(knownFeatures))
|
||||
for name := range knownFeatures {
|
||||
names = append(names, string(name))
|
||||
}
|
||||
sort.Strings(names)
|
||||
return strings.Join(names, ", ")
|
||||
}
|
||||
|
||||
// featureFromFilename extracts the feature from a "config.<feature>.yaml"
|
||||
// filename, or "" if the name does not have that shape.
|
||||
func featureFromFilename(name string) Feature {
|
||||
if !strings.HasPrefix(name, "config.") || !isYAML(name) {
|
||||
return ""
|
||||
}
|
||||
return Feature(trimYAMLSuffix(strings.TrimPrefix(name, "config.")))
|
||||
}
|
||||
|
||||
// isYAML reports whether name has a YAML extension.
|
||||
func isYAML(name string) bool {
|
||||
return strings.HasSuffix(name, ".yaml") || strings.HasSuffix(name, ".yml")
|
||||
}
|
||||
|
||||
// isTOML reports whether name has a TOML extension.
|
||||
func isTOML(name string) bool { return strings.HasSuffix(name, ".toml") }
|
||||
|
||||
// trimYAMLSuffix removes a .yaml or .yml extension.
|
||||
func trimYAMLSuffix(name string) string {
|
||||
return strings.TrimSuffix(strings.TrimSuffix(name, ".yaml"), ".yml")
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package configuration
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/config"
|
||||
|
||||
// These helpers unwrap Document for tests that only assert on the resulting
|
||||
// settings. Tests covering provenance use the Loader methods directly.
|
||||
|
||||
func loadFile(path string) (config.Config, error) {
|
||||
return unwrap(New(nil).File(path))
|
||||
}
|
||||
|
||||
func loadOverlay(basePath, overlayPath string) (config.Config, error) {
|
||||
return unwrap(New(nil).Overlay(basePath, overlayPath))
|
||||
}
|
||||
|
||||
func loadDir(baseDir, overlayDir string) (config.Config, error) {
|
||||
return unwrap(New(nil).Dir(baseDir, overlayDir))
|
||||
}
|
||||
|
||||
func unwrap(doc *Document, err error) (config.Config, error) {
|
||||
if err != nil {
|
||||
return config.Config{}, err
|
||||
}
|
||||
return doc.Config, nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// Document is the decoded external configuration together with a record of
|
||||
// where it came from.
|
||||
type Document struct {
|
||||
// Config is the translated settings.
|
||||
//
|
||||
// TEMPORARY. docs/architecture/configuration.md requires this to become
|
||||
// typed per-domain sections that never expose a whole-application model.
|
||||
// It stays for now so this package can own loading without every
|
||||
// consumer changing at once. Delete when internal/config is dissolved.
|
||||
Config config.Config
|
||||
|
||||
// Provenance lists the files that produced Config, in precedence order.
|
||||
Provenance Provenance
|
||||
}
|
||||
|
||||
// Loader reads configuration from files. The zero value is not usable; call
|
||||
// [New].
|
||||
type Loader struct {
|
||||
log *slog.Logger
|
||||
|
||||
// dataHomeFn resolves the base directory for derived paths. Injected so
|
||||
// tests can exercise defaulting without depending on the environment --
|
||||
// the previous package-level dataHome() read XDG_DATA_HOME directly and
|
||||
// discarded the error from os.UserHomeDir.
|
||||
dataHomeFn func() string
|
||||
}
|
||||
|
||||
// New returns a Loader. A nil logger discards output.
|
||||
func New(log *slog.Logger) *Loader {
|
||||
if log == nil {
|
||||
log = slog.New(slog.DiscardHandler)
|
||||
}
|
||||
return &Loader{log: log, dataHomeFn: xdgDataHome}
|
||||
}
|
||||
|
||||
// dataHome resolves the base directory for derived paths.
|
||||
func (l *Loader) dataHome() string {
|
||||
if l.dataHomeFn == nil {
|
||||
return xdgDataHome()
|
||||
}
|
||||
return l.dataHomeFn()
|
||||
}
|
||||
|
||||
// xdgDataHome returns $XDG_DATA_HOME, falling back to ~/.local/share, and
|
||||
// finally to a relative path when the home directory is unknowable.
|
||||
func xdgDataHome() string {
|
||||
if dir := os.Getenv("XDG_DATA_HOME"); dir != "" {
|
||||
return dir
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return filepath.Join(".local", "share")
|
||||
}
|
||||
return filepath.Join(home, ".local", "share")
|
||||
}
|
||||
|
||||
// File loads a single TOML configuration file.
|
||||
func (l *Loader) File(path string) (*Document, error) {
|
||||
return l.Overlay(path, "")
|
||||
}
|
||||
|
||||
// Overlay loads basePath, then decodes overlayPath into the same value so
|
||||
// only the fields the overlay sets are replaced -- every field it omits keeps
|
||||
// the base value. This lets a deployment-specific file (config.docker.toml)
|
||||
// declare only what differs instead of restating the whole schema. An empty
|
||||
// overlayPath is equivalent to [Loader.File].
|
||||
func (l *Loader) Overlay(basePath, overlayPath string) (*Document, error) {
|
||||
doc := &Document{}
|
||||
|
||||
if err := decodeTOML(basePath, &doc.Config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc.Provenance.record(Origin{Path: basePath, Role: RoleMain, Layer: LayerBase})
|
||||
|
||||
if overlayPath != "" {
|
||||
if err := decodeTOML(overlayPath, &doc.Config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc.Provenance.record(Origin{Path: overlayPath, Role: RoleMain, Layer: LayerOverlay})
|
||||
}
|
||||
|
||||
return l.finalize(doc)
|
||||
}
|
||||
|
||||
// Dir loads configuration from a directory tree:
|
||||
//
|
||||
// config.yaml daemon-level settings
|
||||
// config.gateway.yaml chat channels and platforms
|
||||
// config.tools.yaml MCP servers and tool policy
|
||||
// config.memory.yaml memory provider settings
|
||||
// config.models.yaml LLM providers and models
|
||||
// config.identities.yaml identity settings
|
||||
// conf.d/*.yaml additional feature files
|
||||
//
|
||||
// A missing feature file means the feature is absent, not an error. Legacy
|
||||
// config.toml is the fallback when config.yaml is absent; YAML wins when
|
||||
// both exist.
|
||||
//
|
||||
// When overlayDir is non-empty its files are applied on top of baseDir, with
|
||||
// the same field-level precedence as [Loader.Overlay]. The overlay directory
|
||||
// need not contain a main config.
|
||||
func (l *Loader) Dir(baseDir, overlayDir string) (*Document, error) {
|
||||
doc := &Document{}
|
||||
|
||||
if err := l.loadDir(doc, baseDir, LayerBase); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if overlayDir != "" {
|
||||
if err := l.loadDir(doc, overlayDir, LayerOverlay); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return l.finalize(doc)
|
||||
}
|
||||
|
||||
// loadDir discovers and decodes one directory into doc. The base layer must
|
||||
// supply a main config; an overlay may contribute feature files alone.
|
||||
func (l *Loader) loadDir(doc *Document, dir string, layer Layer) error {
|
||||
files, err := discover(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch path, isYAMLFile, ok := files.main(); {
|
||||
case ok:
|
||||
if err := l.decodeMain(&doc.Config, path, isYAMLFile); err != nil {
|
||||
return err
|
||||
}
|
||||
doc.Provenance.record(Origin{Path: path, Role: RoleMain, Layer: layer})
|
||||
case layer == LayerBase:
|
||||
return fmt.Errorf("%w: no config.yaml or config.toml in %s", ErrNoConfigFile, dir)
|
||||
}
|
||||
|
||||
for _, feature := range files.sortedFeatures() {
|
||||
path := files.features[feature]
|
||||
if err := decodeFeature(&doc.Config, feature, path); err != nil {
|
||||
return err
|
||||
}
|
||||
doc.Provenance.record(Origin{Path: path, Role: RoleFeature, Layer: layer, Feature: feature})
|
||||
}
|
||||
|
||||
for _, name := range files.sortedExtras() {
|
||||
path := files.extras[name]
|
||||
if err := decodeExtra(&doc.Config, name, path); err != nil {
|
||||
return err
|
||||
}
|
||||
doc.Provenance.record(Origin{Path: path, Role: RoleExtra, Layer: layer, Feature: Feature(name)})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeMain decodes the daemon-level file in whichever format it uses.
|
||||
func (l *Loader) decodeMain(cfg *config.Config, path string, isYAMLFile bool) error {
|
||||
if isYAMLFile {
|
||||
return decodeYAML(path, cfg)
|
||||
}
|
||||
return decodeTOML(path, cfg)
|
||||
}
|
||||
|
||||
// finalize applies defaults, then validates. The order matters: validation
|
||||
// judges the effective configuration, including values the operator never
|
||||
// wrote.
|
||||
func (l *Loader) finalize(doc *Document) (*Document, error) {
|
||||
l.applyDefaults(&doc.Config)
|
||||
if err := validate(&doc.Config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.log.Debug("configuration loaded", "sources", doc.Provenance.String())
|
||||
return doc, nil
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
func TestLoadDispatchAckReaction(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dispatch string
|
||||
wantAck string
|
||||
}{
|
||||
{name: "default", wantAck: "eyes"},
|
||||
{name: "disabled", dispatch: "\n[dispatch]\nack_reaction = \"off\"\n", wantAck: ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.dispatch + "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Dispatch.AckReaction != tt.wantAck {
|
||||
t.Errorf("AckReaction: got %q, want %q", cfg.Dispatch.AckReaction, tt.wantAck)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadForgeTokenEnvBackwardCompat guards against a real production
|
||||
// incident: the secrets-engine migration replaced [forge]'s flat
|
||||
// token_env string with a {engine, key} struct, but TOML silently ignores
|
||||
// unknown fields — so deployed configs still using the old token_env key
|
||||
// had their token config dropped entirely and finalize() defaulted to
|
||||
// demanding ARCHIE_GITHUB_TOKEN, crash-looping a gitea-backed daemon.
|
||||
func TestLoadForgeTokenEnvBackwardCompat(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\ntoken_env = \"MY_GITEA_TOKEN\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Forge.Token != (secret.SecretRef{Engine: "env", Key: "MY_GITEA_TOKEN"}) {
|
||||
t.Errorf("Forge.Token = %#v, want {env MY_GITEA_TOKEN} (from legacy token_env)", cfg.Forge.Token)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadForgeTokenTakesPrecedenceOverTokenEnv verifies the new-style
|
||||
// [forge.token] wins when both the legacy token_env and the new token
|
||||
// struct are present (e.g. mid-migration configs).
|
||||
func TestLoadForgeTokenTakesPrecedenceOverTokenEnv(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[forge]\ntype = \"gitea\"\ntoken_env = \"OLD_TOKEN\"\n" +
|
||||
"[forge.token]\nengine = \"env\"\nkey = \"NEW_TOKEN\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Forge.Token != (secret.SecretRef{Engine: "env", Key: "NEW_TOKEN"}) {
|
||||
t.Errorf("Forge.Token = %#v, want {env NEW_TOKEN} (new-style token wins)", cfg.Forge.Token)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidConfigEnumsAndGlobs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
extra string
|
||||
}{
|
||||
{name: "dispatch trigger", extra: "\n[dispatch]\ntrigger = \"labels\"\n"},
|
||||
{name: "agent mode", extra: "\n[agent]\nmode = \"remote\"\n"},
|
||||
{name: "agent command", extra: "\n[agent]\nmode = \"subprocess\"\ncommand = \" \"\n"},
|
||||
{name: "agent env", extra: "\n[agent]\nenv = [\"TOKEN=value\"]\n"},
|
||||
{name: "provider userinfo", extra: "\n[providers.openai]\nclass = \"openai\"\nbase_url = \"https://token@example.com/v1\"\n"},
|
||||
{name: "provider query secret", extra: "\n[providers.openai]\nclass = \"openai\"\nbase_url = \"https://example.com/v1?api_key=secret\"\n"},
|
||||
{name: "test glob", extra: "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\ntest_glob = \"[\"\n"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n"
|
||||
if tt.name != "test glob" {
|
||||
contents += "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
}
|
||||
contents += tt.extra
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := loadFile(path); err == nil {
|
||||
t.Fatal("loadFile() succeeded, want validation error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadAgentDefaultsAndOverrides(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
agent string
|
||||
wantMode string
|
||||
wantCommand string
|
||||
wantEnv []string
|
||||
}{
|
||||
{name: "defaults", wantMode: "inprocess", wantCommand: "archie-agent"},
|
||||
{
|
||||
name: "subprocess", agent: "\n[agent]\nmode = \"subprocess\"\ncommand = \"/opt/archie-agent\"\nenv = [\"GOCACHE\"]\n",
|
||||
wantMode: "subprocess", wantCommand: "/opt/archie-agent", wantEnv: []string{"GOCACHE"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.agent + "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Agent.Mode != tt.wantMode || cfg.Agent.Command != tt.wantCommand || strings.Join(cfg.Agent.Env, ",") != strings.Join(tt.wantEnv, ",") {
|
||||
t.Fatalf("agent config = %#v", cfg.Agent)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadContainerVolumeTTL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ttl string
|
||||
wantTTL time.Duration
|
||||
}{
|
||||
{name: "default", wantTTL: 72 * time.Hour},
|
||||
{name: "explicit", ttl: "volume_ttl = \"6h\"\n", wantTTL: 6 * time.Hour},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[agent]\nmode = \"nats\"\n" +
|
||||
"[nats]\nurl = \"nats://localhost:4222\"\n" +
|
||||
"[containers]\nenabled = true\nimage = \"archie-agent:test\"\n" + tt.ttl +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\npersistent_storage = true\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := cfg.Containers.VolumeTTL.Std(); got != tt.wantTTL {
|
||||
t.Fatalf("Containers.VolumeTTL = %s, want %s", got, tt.wantTTL)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsNegativeContainerVolumeTTL(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[agent]\nmode = \"nats\"\n" +
|
||||
"[nats]\nurl = \"nats://localhost:4222\"\n" +
|
||||
"[containers]\nenabled = true\nimage = \"archie-agent:test\"\nvolume_ttl = \"-1h\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\npersistent_storage = true\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := loadFile(path); err == nil {
|
||||
t.Fatal("loadFile() accepted a negative containers.volume_ttl")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExampleConfigLoads(t *testing.T) {
|
||||
cfg, err := loadFile(filepath.Join("..", "..", "..", "config.example.toml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Forge.Host != "https://github.com" {
|
||||
t.Errorf("Forge.Host: got %q", cfg.Forge.Host)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverlay(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
basePath := filepath.Join(dir, "config.toml")
|
||||
base := "bot_user = \"widget\"\nwork_dir = \"/base/work\"\n" +
|
||||
"[agent]\nmode = \"inprocess\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(basePath, []byte(base), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
overlayPath := filepath.Join(dir, "config.docker.toml")
|
||||
overlay := "work_dir = \"/var/lib/archie/work\"\n[agent]\nmode = \"nats\"\n" +
|
||||
"[nats]\nurl = \"nats://nats:4222\"\n" +
|
||||
"[containers]\nenabled = true\nimage = \"archie-agent:latest\"\n"
|
||||
if err := os.WriteFile(overlayPath, []byte(overlay), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadOverlay(basePath, overlayPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Overlay-set fields win.
|
||||
if cfg.WorkDir != "/var/lib/archie/work" {
|
||||
t.Errorf("WorkDir: got %q, want overlay value", cfg.WorkDir)
|
||||
}
|
||||
if cfg.Agent.Mode != "nats" {
|
||||
t.Errorf("Agent.Mode: got %q, want %q", cfg.Agent.Mode, "nats")
|
||||
}
|
||||
// Fields the overlay omits keep the base value.
|
||||
if cfg.BotUser != "widget" {
|
||||
t.Errorf("BotUser: got %q, want base value", cfg.BotUser)
|
||||
}
|
||||
if len(cfg.Repos) != 1 || cfg.Repos[0].Owner != "acme" {
|
||||
t.Errorf("Repos: got %+v, want base repos", cfg.Repos)
|
||||
}
|
||||
|
||||
// No overlay path behaves like loadFile(basePath).
|
||||
baseOnly, err := loadOverlay(basePath, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if baseOnly.Agent.Mode != "inprocess" {
|
||||
t.Errorf("Agent.Mode with empty overlay: got %q, want %q", baseOnly.Agent.Mode, "inprocess")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDockerConfigOverlaysExampleConfig(t *testing.T) {
|
||||
cfg, err := loadOverlay(
|
||||
filepath.Join("..", "..", "..", "config.example.toml"),
|
||||
filepath.Join("..", "..", "..", "config.docker.toml"),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Agent.Mode != "nats" {
|
||||
t.Errorf("Agent.Mode: got %q, want %q", cfg.Agent.Mode, "nats")
|
||||
}
|
||||
if cfg.Containers.Image == "" {
|
||||
t.Error("Containers.Image: want docker overlay image, got empty")
|
||||
}
|
||||
// bot_user and repos are not set by the docker overlay -- they must
|
||||
// come from the base config, proving the overlay isn't a standalone
|
||||
// config that silently drops required fields.
|
||||
if cfg.BotUser == "" {
|
||||
t.Error("BotUser: want value from base config.example.toml, got empty")
|
||||
}
|
||||
if len(cfg.Repos) == 0 {
|
||||
t.Error("Repos: want repos from base config.example.toml, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadBytesDoesNotExist(t *testing.T) {
|
||||
_, err := loadBytes(nil)
|
||||
if err == nil {
|
||||
t.Error("expected error from nil LoadBytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeIndexingDefaults(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
extra string
|
||||
wantIndex string
|
||||
wantDBIsSet bool
|
||||
}{
|
||||
{
|
||||
name: "defaults derive from work_dir",
|
||||
// Both paths must land under the daemon's own work_dir so two
|
||||
// archied instances on one host cannot share an index.
|
||||
extra: "\nwork_dir = \"/srv/archie/work\"\n",
|
||||
wantIndex: filepath.Join("/srv/archie/work", "indexes"),
|
||||
wantDBIsSet: true,
|
||||
},
|
||||
{
|
||||
name: "explicit index_dir is preserved",
|
||||
extra: "\nwork_dir = \"/srv/archie/work\"\n" +
|
||||
"[indexing]\nindex_dir = \"/mnt/fast/idx\"\n",
|
||||
wantIndex: "/mnt/fast/idx",
|
||||
wantDBIsSet: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
// tc.extra precedes the table sections: a top-level key written
|
||||
// after [[repos]] would be parsed as a member of that table.
|
||||
contents := "bot_user = \"widget\"\n" + tc.extra +
|
||||
"[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\ntoken_env = \"T\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Indexing.IndexDir != tc.wantIndex {
|
||||
t.Errorf("Indexing.IndexDir = %q, want %q", cfg.Indexing.IndexDir, tc.wantIndex)
|
||||
}
|
||||
if tc.wantDBIsSet && cfg.Indexing.DBPath == "" {
|
||||
t.Error("Indexing.DBPath is empty; want a default derived from work_dir")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestIdentitiesConfigParsesTwoIdentities(t *testing.T) {
|
||||
cfg, err := loadBytes([]byte(`
|
||||
bot_user = "default-legacy"
|
||||
|
||||
[[identities]]
|
||||
name = "archie"
|
||||
bot_user = "archie"
|
||||
forge = { type = "gitea", host = "https://git.example.test", token = { engine = "env", key = "ARCHIE_TOKEN" } }
|
||||
|
||||
[[identities.repos]]
|
||||
owner = "sam"
|
||||
name = "archie-core"
|
||||
base = "main"
|
||||
ecosystem = "go"
|
||||
|
||||
[[identities]]
|
||||
name = "winter"
|
||||
bot_user = "winter"
|
||||
forge = { type = "gitea", host = "https://git.example.test", token = { engine = "env", key = "WINTER_TOKEN" } }
|
||||
|
||||
[[identities.repos]]
|
||||
owner = "sam"
|
||||
name = "example-service"
|
||||
base = "main"
|
||||
ecosystem = "go"
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadBytes: %v", err)
|
||||
}
|
||||
if len(cfg.Identities) != 2 {
|
||||
t.Fatalf("len(Identities) = %d, want 2", len(cfg.Identities))
|
||||
}
|
||||
if cfg.Identities[0].Name != "archie" {
|
||||
t.Errorf("Identities[0].Name = %q", cfg.Identities[0].Name)
|
||||
}
|
||||
if cfg.Identities[0].BotUser != "archie" {
|
||||
t.Errorf("Identities[0].BotUser = %q", cfg.Identities[0].BotUser)
|
||||
}
|
||||
if cfg.Identities[0].Forge.Token != (secret.SecretRef{Engine: "env", Key: "ARCHIE_TOKEN"}) {
|
||||
t.Errorf("Identities[0].Forge.Token = %#v", cfg.Identities[0].Forge.Token)
|
||||
}
|
||||
if len(cfg.Identities[0].Repos) != 1 || cfg.Identities[0].Repos[0].Name != "archie-core" {
|
||||
t.Errorf("Identities[0].Repos = %+v", cfg.Identities[0].Repos)
|
||||
}
|
||||
if cfg.Identities[1].Name != "winter" {
|
||||
t.Errorf("Identities[1].Name = %q", cfg.Identities[1].Name)
|
||||
}
|
||||
if cfg.Identities[1].BotUser != "winter" {
|
||||
t.Errorf("Identities[1].BotUser = %q", cfg.Identities[1].BotUser)
|
||||
}
|
||||
if cfg.Identities[1].Forge.Token != (secret.SecretRef{Engine: "env", Key: "WINTER_TOKEN"}) {
|
||||
t.Errorf("Identities[1].Forge.Token = %#v", cfg.Identities[1].Forge.Token)
|
||||
}
|
||||
if len(cfg.Identities[1].Repos) != 1 || cfg.Identities[1].Repos[0].Name != "example-service" {
|
||||
t.Errorf("Identities[1].Repos = %+v", cfg.Identities[1].Repos)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigFallsBackToLegacyWhenEmpty(t *testing.T) {
|
||||
cfg, err := loadBytes([]byte(`
|
||||
bot_user = "solo"
|
||||
forge = { type = "github", host = "https://github.test", token_env = "GH_TOKEN" }
|
||||
|
||||
[[repos]]
|
||||
owner = "sam"
|
||||
name = "my-repo"
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadBytes: %v", err)
|
||||
}
|
||||
if len(cfg.Identities) != 0 {
|
||||
t.Errorf("len(Identities) = %d, want 0 (empty = legacy mode)", len(cfg.Identities))
|
||||
}
|
||||
if cfg.BotUser != "solo" {
|
||||
t.Errorf("BotUser = %q, want solo (legacy field active)", cfg.BotUser)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigRejectsEmptyName(t *testing.T) {
|
||||
_, err := loadBytes([]byte(`
|
||||
[[identities]]
|
||||
bot_user = "no-name"
|
||||
forge = { type = "github", token_env = "X" }
|
||||
`))
|
||||
if err == nil {
|
||||
t.Error("expected error for identity with empty name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigRejectsMissingForgeToken(t *testing.T) {
|
||||
// Unlike the top-level [forge], a per-identity forge has no default
|
||||
// token -- each identity needs its own secret reference (e.g.
|
||||
// distinct bot accounts each with their own token). Omitting it must
|
||||
// be a startup error, not a silent empty-string token.
|
||||
_, err := loadBytes([]byte(`
|
||||
[[identities]]
|
||||
name = "archie"
|
||||
bot_user = "archie"
|
||||
forge = { type = "github" }
|
||||
|
||||
[[identities.repos]]
|
||||
owner = "sam"
|
||||
name = "archie-core"
|
||||
`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for identity with no forge.token")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "forge.token") {
|
||||
t.Errorf("error = %q, want mention of forge.token", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// loadBytes writes data to a temporary file and loads it, so tests can
|
||||
// exercise decoding without managing files themselves.
|
||||
func loadBytes(data []byte) (config.Config, error) {
|
||||
if data == nil {
|
||||
return config.Config{}, os.ErrNotExist
|
||||
}
|
||||
tmp, err := os.CreateTemp("", "archie-config-*.toml")
|
||||
if err != nil {
|
||||
return config.Config{}, err
|
||||
}
|
||||
defer func() { _ = os.Remove(tmp.Name()) }()
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return config.Config{}, err
|
||||
}
|
||||
_ = tmp.Close()
|
||||
return loadFile(tmp.Name())
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Role describes why a file was read, so provenance distinguishes a value
|
||||
// the operator set in the base config from one an overlay replaced.
|
||||
type Role string
|
||||
|
||||
const (
|
||||
RoleMain Role = "main" // config.yaml / config.toml
|
||||
RoleFeature Role = "feature" // config.<feature>.yaml or conf.d/<feature>.yaml
|
||||
RoleExtra Role = "extra" // conf.d/*.yaml for an unrecognised name
|
||||
)
|
||||
|
||||
// Layer distinguishes the base configuration from an overlay applied on top.
|
||||
type Layer string
|
||||
|
||||
const (
|
||||
LayerBase Layer = "base"
|
||||
LayerOverlay Layer = "overlay"
|
||||
)
|
||||
|
||||
// Origin records one file that contributed to a loaded configuration.
|
||||
type Origin struct {
|
||||
Path string
|
||||
Role Role
|
||||
Layer Layer
|
||||
Feature Feature // set when Role is RoleFeature or RoleExtra
|
||||
}
|
||||
|
||||
// String renders an origin for logs and error messages.
|
||||
func (o Origin) String() string {
|
||||
if o.Feature != "" {
|
||||
return fmt.Sprintf("%s (%s %s %s)", o.Path, o.Layer, o.Role, o.Feature)
|
||||
}
|
||||
return fmt.Sprintf("%s (%s %s)", o.Path, o.Layer, o.Role)
|
||||
}
|
||||
|
||||
// Provenance is the ordered list of files that produced a configuration,
|
||||
// earliest first, so a later entry overrides an earlier one.
|
||||
//
|
||||
// Nothing recorded where a value came from before. With overlays, feature
|
||||
// files and conf.d/ all able to set the same field, "which file set this?"
|
||||
// was answerable only by re-deriving the precedence rules by hand.
|
||||
type Provenance struct {
|
||||
Origins []Origin
|
||||
}
|
||||
|
||||
// record appends an origin.
|
||||
func (p *Provenance) record(o Origin) { p.Origins = append(p.Origins, o) }
|
||||
|
||||
// Paths returns the contributing file paths in precedence order.
|
||||
func (p Provenance) Paths() []string {
|
||||
paths := make([]string, 0, len(p.Origins))
|
||||
for _, o := range p.Origins {
|
||||
paths = append(paths, o.Path)
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// String renders the full chain for diagnostics.
|
||||
func (p Provenance) String() string {
|
||||
if len(p.Origins) == 0 {
|
||||
return "(no configuration files)"
|
||||
}
|
||||
parts := make([]string, 0, len(p.Origins))
|
||||
for _, o := range p.Origins {
|
||||
parts = append(parts, o.String())
|
||||
}
|
||||
return strings.Join(parts, " -> ")
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// Recognised enum values, named so validation and its error message cannot
|
||||
// disagree about what is allowed.
|
||||
const (
|
||||
agentModeInProcess = "inprocess"
|
||||
agentModeSubprocess = "subprocess"
|
||||
agentModeNATS = "nats"
|
||||
|
||||
forgeTypeGitHub = "github"
|
||||
forgeTypeGitea = "gitea"
|
||||
|
||||
dispatchTriggerAssignee = "assignee"
|
||||
dispatchTriggerLabel = "label"
|
||||
dispatchTriggerEither = "either"
|
||||
)
|
||||
|
||||
var (
|
||||
agentModes = []string{agentModeInProcess, agentModeSubprocess, agentModeNATS}
|
||||
forgeTypes = []string{forgeTypeGitHub, forgeTypeGitea}
|
||||
dispatchTriggers = []string{dispatchTriggerAssignee, dispatchTriggerLabel, dispatchTriggerEither}
|
||||
)
|
||||
|
||||
// validate reports the first problem that would stop the daemon running.
|
||||
// It does not modify cfg -- run applyDefaults first.
|
||||
func validate(cfg *config.Config) error {
|
||||
if err := validateAgent(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateDispatch(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateProviders(cfg.Providers); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(cfg.Identities) > 0 {
|
||||
if err := validateIdentities(cfg.Identities); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err := validateSingleIdentity(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateContainers(cfg)
|
||||
}
|
||||
|
||||
func validateAgent(cfg *config.Config) error {
|
||||
if !oneOf(cfg.Agent.Mode, agentModes) {
|
||||
return fmt.Errorf("%w: agent.mode %q (want %s)", ErrInvalidInput, cfg.Agent.Mode, list(agentModes))
|
||||
}
|
||||
if cfg.Agent.Mode == agentModeSubprocess && strings.TrimSpace(cfg.Agent.Command) == "" {
|
||||
return fmt.Errorf("%w: agent.command is required in subprocess mode", ErrInvalidInput)
|
||||
}
|
||||
for i, name := range cfg.Agent.Env {
|
||||
if strings.TrimSpace(name) == "" || strings.Contains(name, "=") {
|
||||
return fmt.Errorf("%w: agent.env[%d] %q is not an environment variable name", ErrInvalidInput, i, name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDispatch(cfg *config.Config) error {
|
||||
if !oneOf(cfg.Dispatch.Trigger, dispatchTriggers) {
|
||||
return fmt.Errorf("%w: dispatch.trigger %q (want %s)", ErrInvalidInput, cfg.Dispatch.Trigger, list(dispatchTriggers))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateProviders rejects base URLs carrying credentials or query state.
|
||||
// A provider URL is used to build API requests, so userinfo or a stray query
|
||||
// string would be silently attached to every call.
|
||||
func validateProviders(providers map[string]config.Provider) error {
|
||||
for name, provider := range providers {
|
||||
if provider.BaseURL == "" {
|
||||
continue
|
||||
}
|
||||
u, err := url.Parse(provider.BaseURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: providers.%s.base_url: %w", ErrInvalidInput, name, err)
|
||||
}
|
||||
if u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return fmt.Errorf("%w: providers.%s.base_url must not contain userinfo, query parameters, or a fragment", ErrInvalidInput, name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateIdentities(identities []config.IdentityConfig) error {
|
||||
for i, id := range identities {
|
||||
if id.Name == "" {
|
||||
return fmt.Errorf("%w: identities[%d].name is required", ErrInvalidInput, i)
|
||||
}
|
||||
if id.BotUser == "" {
|
||||
return fmt.Errorf("%w: identities[%d].bot_user is required", ErrInvalidInput, i)
|
||||
}
|
||||
if len(id.Repos) == 0 {
|
||||
return fmt.Errorf("%w: identities[%d] has no [[identities.repos]] entries -- at least one is required", ErrInvalidInput, i)
|
||||
}
|
||||
if !oneOf(id.Forge.Type, forgeTypes) {
|
||||
return fmt.Errorf("%w: identities[%d].forge.type %q (want %s)", ErrInvalidInput, i, id.Forge.Type, list(forgeTypes))
|
||||
}
|
||||
if id.Forge.Token == (secret.SecretRef{}) {
|
||||
return fmt.Errorf("%w: identities[%d].forge.token is required (each identity needs its own secret reference; unlike the top-level [forge], there is no default)", ErrInvalidInput, i)
|
||||
}
|
||||
if err := validateRepos(id.Repos); err != nil {
|
||||
return fmt.Errorf("identities[%d]: %w", i, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSingleIdentity(cfg *config.Config) error {
|
||||
if cfg.BotUser == "" {
|
||||
return fmt.Errorf("%w: bot_user is required (or define [[identities]])", ErrInvalidInput)
|
||||
}
|
||||
if !oneOf(cfg.Forge.Type, forgeTypes) {
|
||||
return fmt.Errorf("%w: forge.type %q (want %s)", ErrInvalidInput, cfg.Forge.Type, list(forgeTypes))
|
||||
}
|
||||
return validateRepos(cfg.Repos)
|
||||
}
|
||||
|
||||
func validateRepos(repos []config.Repo) error {
|
||||
for i, r := range repos {
|
||||
if r.Owner == "" || r.Name == "" {
|
||||
return fmt.Errorf("%w: repos[%d] needs owner and name", ErrInvalidInput, i)
|
||||
}
|
||||
if glob := r.ResolvedTestGlob(); glob != "" {
|
||||
if _, err := filepath.Match(glob, ""); err != nil {
|
||||
return fmt.Errorf("%w: repos[%d] test_glob %q: %w", ErrInvalidInput, i, glob, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateContainers checks the combination that container execution
|
||||
// requires: a NATS transport and somewhere to reach it.
|
||||
func validateContainers(cfg *config.Config) error {
|
||||
if !cfg.Containers.Enabled {
|
||||
return nil
|
||||
}
|
||||
if cfg.Containers.Image == "" {
|
||||
return fmt.Errorf("%w: containers.image is required when containers.enabled is true", ErrInvalidInput)
|
||||
}
|
||||
if cfg.Agent.Mode != agentModeNATS {
|
||||
return fmt.Errorf("%w: agent.mode must be %q when containers.enabled is true", ErrInvalidInput, agentModeNATS)
|
||||
}
|
||||
if cfg.NATS.URL == "" {
|
||||
return fmt.Errorf("%w: [nats] url is required when containers.enabled is true", ErrInvalidInput)
|
||||
}
|
||||
if cfg.Containers.VolumeTTL < 0 {
|
||||
return fmt.Errorf("%w: containers.volume_ttl must not be negative", ErrInvalidInput)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// oneOf reports whether value is in allowed.
|
||||
func oneOf(value string, allowed []string) bool {
|
||||
for _, a := range allowed {
|
||||
if value == a {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// list renders allowed values for an error message.
|
||||
func list(values []string) string { return strings.Join(values, ", ") }
|
||||
|
||||
// isOff reports the documented "disable this" spelling.
|
||||
func isOff(value string) bool { return strings.EqualFold(value, "off") }
|
||||
Reference in new issue
Block a user