diff --git a/CHANGELOG.archied.md b/CHANGELOG.archied.md index c43ca2cba..6389878e4 100644 --- a/CHANGELOG.archied.md +++ b/CHANGELOG.archied.md @@ -1,5 +1,9 @@ # archied changelog +## [Unreleased] + +- feat(config): SIGHUP-triggered config reload with `--no-config-overlay` recovery flag + ## [1.6.0] - 2026-08-09 - feat(gateway): tool-approval gate, session tools for chat, and /delete command diff --git a/CLAUDE.md b/CLAUDE.md index 3cee303c4..d56ec54bc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,14 +58,22 @@ whether the jail is lifted together determine which filesystem those tools can reach; neither is something the code should assume. NATS and the per-task archie-agent containers are Docker regardless. -**The daemon hands agent containers its own `nats.url` verbatim** — see +**The daemon hands agent containers the NATS endpoint its own client connected with at startup** — see `containerEnv` in `internal/daemon/daemon.go`, which appends `NATS_URL=` from -`d.Cfg.NATS.URL`. That URL must therefore be reachable from wherever the daemon +`d.ConnectedNATS.URL`, captured at construction. That endpoint must therefore be reachable from wherever the daemon runs *and* from inside the containers. When the daemon is on the host, that means the compose network's gateway address, not the service name and not localhost. `docker-compose.yml` pins the subnet to `172.19.0.0/16` so the gateway address cannot drift when the network is recreated. +The two URLs are the same today and deliberately *not* the same after a +SIGHUP reload of `nats.url`: the daemon's own client is startup-built, so a +reload that pointed new containers at the new URL would launch them on a +server the daemon is not publishing on, and every task would park with +`ErrNoResponders`. Freezing the connected endpoint makes that divergence +impossible regardless of what the config says or who reloads it; a reloaded +`nats.url` is logged as a change that requires a restart. + **`containers.pull_policy` can only be `"missing"`** (the default) or `"always"`. `"always"` against a private registry answers 401, because the daemon sends no credentials to the Docker API. Refresh the agent image diff --git a/cmd/archied/main.go b/cmd/archied/main.go index b4f10bb00..a8e1ad231 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -313,6 +313,7 @@ func run() int { defaultCfg := filepath.Join(configHome(), "archie", "config.toml") cfgPath := flag.String("config", defaultCfg, "path to a TOML/YAML config file or configuration directory") overlayPath := flag.String("config-overlay", "", "path to a TOML/YAML overlay file or configuration directory applied on top of -config") + noConfigOverlay := flag.Bool("no-config-overlay", false, "ignore the runtime config overlay (recovery hatch: boots on file config alone)") once := flag.Bool("once", false, "run a single poll+process cycle and exit (systemd timer / testing)") requeue := flag.Int64("requeue", 0, "requeue a parked/waiting task by id (keeps its workflow), then exit unless -once is also set") flag.Parse() @@ -321,7 +322,11 @@ func run() int { log := slog.New(slog.NewJSONHandler(os.Stderr, nil)) - doc, err := configuration.New(log).Resolve(*cfgPath, *overlayPath) + loader := configuration.New(log) + if *noConfigOverlay || configuration.SkipOverlay() { + log.Info("runtime config overlay disabled (recovery hatch); booting on file config alone") + } + doc, err := loader.Resolve(*cfgPath, *overlayPath) if err != nil { fmt.Fprintln(os.Stderr, err) return 1 @@ -427,7 +432,8 @@ func run() int { Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature), }) } - web := &webui.Server{Store: st, Log: log, LogFeed: logFeed, TaskLogs: taskLogs, Cfg: config.NewHolder(cfg), ConfigProvenance: configProvenance, Channels: channelManager, Events: bus} + web := &webui.Server{Store: st, Log: log, LogFeed: logFeed, TaskLogs: taskLogs, Cfg: config.NewHolder(cfg), Channels: channelManager, Events: bus} + web.SetProvenance(configProvenance) web.ReloadChannel = func(ctx context.Context, id string) error { if id != "telegram" || restartTelegram == nil { return fmt.Errorf("channel reload unavailable") @@ -951,6 +957,7 @@ func run() int { d := &daemon.Daemon{ Cfg: config.NewHolder(cfg), + ConnectedNATS: cfg.NATS, Store: st, Bus: bus, Forge: forgeClient, @@ -973,6 +980,35 @@ func run() int { } web.TaskStopper = d + // SIGHUP re-loads the config from disk and republishes it. The apply + // closure swaps the daemon's Holder and the dashboard's provenance; + // the reload log warns about changed fields that require a restart, so + // an operator never has to read the source to find out whether their + // edit took effect. web.LastReload exposes the outcome to /api/config. + reloadController := newReloadController(loader, *cfgPath, *overlayPath, func(doc *configuration.Document) { + old := d.Cfg.Get() + d.Cfg.Set(doc.Config) + provenance := make([]webui.ConfigOrigin, 0, len(doc.Provenance.Origins)) + for _, origin := range doc.Provenance.Origins { + provenance = append(provenance, webui.ConfigOrigin{ + Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature), + }) + } + web.SetProvenance(provenance) + if fields := changedNonReloadableFields(old, doc.Config); len(fields) > 0 { + log.Warn("config reloaded; some changes require a restart", + "fields", fields, "paths", doc.Provenance.Paths()) + } else { + log.Info("config reloaded", "paths", doc.Provenance.Paths()) + } + }) + web.LastReload = reloadController.Status + + reloadCh := make(chan os.Signal, 1) + signal.Notify(reloadCh, syscall.SIGHUP) + defer signal.Stop(reloadCh) + go reloadLoop(ctx, reloadCh, reloadController, log) + // Give /cancel and /stop a handle on work already in flight. The // controller is built before the daemon exists, so the runtime is // attached here; gateways start further down, after d.Startup, so no diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go new file mode 100644 index 000000000..df6453f28 --- /dev/null +++ b/cmd/archied/reload.go @@ -0,0 +1,145 @@ +package main + +import ( + "context" + "log/slog" + "os" + "reflect" + "sync/atomic" + "time" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" +) + +// ReloadController re-runs the configuration load on demand and +// publishes the result through apply. A failed reload never publishes: +// apply is called only with a Document that passed validation, and the +// running config is left untouched on error. That "Set is not called on +// the error path" property is the safety core of the reload feature -- +// a bad file must leave the daemon running on the previous config. +type ReloadController struct { + loader *configuration.Loader + base string + overlay string + + // apply receives a freshly loaded, validated Document. It is the + // composition root's job to wire this to whatever owns the running + // config (the daemon's Holder, the dashboard's provenance). + apply func(*configuration.Document) + + status atomic.Pointer[config.ReloadStatus] +} + +func newReloadController(loader *configuration.Loader, base, overlay string, apply func(*configuration.Document)) *ReloadController { + c := &ReloadController{loader: loader, base: base, overlay: overlay, apply: apply} + c.status.Store(&config.ReloadStatus{}) + return c +} + +// Reload re-runs the configuration load. On validation failure it +// records the error in Status and returns it; apply is not called and +// the running configuration is unchanged. On success it calls apply +// with the fresh Document and records the reload time. +func (c *ReloadController) Reload() error { + doc, err := c.loader.Resolve(c.base, c.overlay) + if err != nil { + c.status.Store(&config.ReloadStatus{ + LastError: err.Error(), + LastErrorAt: time.Now().UTC().Format(time.RFC3339), + }) + return err + } + c.apply(doc) + c.status.Store(&config.ReloadStatus{ + LastReloadAt: time.Now().UTC().Format(time.RFC3339), + }) + return nil +} + +// Status returns the most recent reload outcome. +func (c *ReloadController) Status() config.ReloadStatus { + if p := c.status.Load(); p != nil { + return *p + } + return config.ReloadStatus{} +} + +// reloadLoop waits for a reload signal on ch and re-loads the config +// each time, until ctx is cancelled. A failed reload is logged and the +// running config is left untouched (see ReloadController.Reload). +func reloadLoop(ctx context.Context, ch <-chan os.Signal, c *ReloadController, log *slog.Logger) { + for { + select { + case <-ctx.Done(): + return + case <-ch: + if err := c.Reload(); err != nil { + log.Error("config reload failed; keeping running config", "err", err) + } + } + } +} + +// reloadableFields are the Config fields the daemon re-reads per cycle +// or per dispatched task, so a reload takes effect without a restart. +// This is deliberately an allowlist: a field added to Config later +// defaults to requires-restart, which is the safe direction and forces +// whoever adds it to decide deliberately. +var reloadableFields = map[string]bool{ + // Tickers reset on change (daemon.go Run / runIdentities). + "PollInterval": true, + // Poll loops re-read per cycle (daemon.go poll / pollForIdentity). + "Repos": true, + // Per-task snapshot: configFor -> executionFor -> d.Cfg.Get() at + // dispatch, carried by TaskConfig (config.go ForTask). + "DiffCapLines": true, + "Budgets": true, + // Dispatch is read per poll (daemon.go pollIssuesWithConfig switch) + // and carried per task like DiffCapLines. + "Dispatch": true, +} + +// reloadableSubFields are sub-fields of structs that are otherwise +// startup-built. VolumeTTL and MaxConcurrency are re-read per cycle +// (cleanupExpiredStorage, drainSQLite/drainNATS); everything else in +// Containers (Image, Enabled, MaxUptime, PullPolicy, Network) is frozen +// in the startup-built container pool. +var reloadableSubFields = map[string]map[string]bool{ + "Containers": {"VolumeTTL": true, "MaxConcurrency": true}, +} + +// changedNonReloadableFields compares old and new and returns the +// dotted names of top-level Config fields whose values differ and are +// not re-read per cycle. The reload log warns about these so the +// operator knows their edit did not take effect until a restart -- +// the alternative is an operator who believes a reloaded poll interval +// changed the forge token, and burns an hour discovering it did not. +func changedNonReloadableFields(old, new config.Config) []string { + var changed []string + ov, nv := reflect.ValueOf(old), reflect.ValueOf(new) + ot := reflect.TypeFor[config.Config]() + for i := 0; i < ot.NumField(); i++ { + f := ot.Field(i) + name := f.Name + if reloadableFields[name] { + continue + } + if subs, ok := reloadableSubFields[name]; ok && f.Type.Kind() == reflect.Struct { + for j := 0; j < f.Type.NumField(); j++ { + sub := f.Type.Field(j).Name + if subs[sub] { + continue + } + if !reflect.DeepEqual(ov.Field(i).Field(j).Interface(), nv.Field(i).Field(j).Interface()) { + changed = append(changed, name+"."+sub) + } + } + continue + } + if !reflect.DeepEqual(ov.Field(i).Interface(), nv.Field(i).Interface()) { + changed = append(changed, name) + } + } + return changed +} diff --git a/cmd/archied/reload_test.go b/cmd/archied/reload_test.go new file mode 100644 index 000000000..b864e69d1 --- /dev/null +++ b/cmd/archied/reload_test.go @@ -0,0 +1,195 @@ +package main + +import ( + "context" + "log/slog" + "os" + "path/filepath" + "sync" + "syscall" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" +) + +// writeConfig writes a TOML config file. The minimal shape (bot_user + +// one repo) is the same fixture loader_test.go uses to satisfy +// validation. +func writeConfig(t *testing.T, path, body string) { + t.Helper() + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } +} + +func minimalConfigTOML(botUser string) string { + return "bot_user = \"" + botUser + "\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n" +} + +func invalidConfigTOML() string { + return "bot_user = \"widget\"\nagent = { mode = \"bogus-mode\" }\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n" +} + +func TestReloadAppliesAndPublishes(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + writeConfig(t, path, minimalConfigTOML("first")) + + loader := configuration.New(slog.New(slog.DiscardHandler)) + var published config.Config + controller := newReloadController(loader, path, "", func(doc *configuration.Document) { + published = doc.Config + }) + + if err := controller.Reload(); err != nil { + t.Fatalf("first reload: %v", err) + } + if published.BotUser != "first" { + t.Fatalf("published BotUser = %q, want first", published.BotUser) + } + + writeConfig(t, path, minimalConfigTOML("second")) + if err := controller.Reload(); err != nil { + t.Fatalf("second reload: %v", err) + } + if published.BotUser != "second" { + t.Fatalf("published BotUser = %q, want second", published.BotUser) + } + if st := controller.Status(); st.LastReloadAt == "" || st.LastError != "" { + t.Fatalf("Status after success = %+v, want LastReloadAt set and no error", st) + } +} + +// TestReloadValidationFailureDoesNotApply pins the safety property of +// the whole reload feature: a reload that fails validation must not +// publish. If apply were called on the error path, a bad file would +// half-apply or corrupt the running config. +func TestReloadValidationFailureDoesNotApply(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + writeConfig(t, path, minimalConfigTOML("widget")) + + loader := configuration.New(slog.New(slog.DiscardHandler)) + applied := 0 + controller := newReloadController(loader, path, "", func(*configuration.Document) { applied++ }) + + if err := controller.Reload(); err != nil { + t.Fatalf("first reload: %v", err) + } + if applied != 1 { + t.Fatalf("apply called %d times after successful reload, want 1", applied) + } + + writeConfig(t, path, invalidConfigTOML()) + err := controller.Reload() + if err == nil { + t.Fatal("reload with invalid config: expected an error") + } + if applied != 1 { + t.Fatalf("apply called %d times after failed reload, want still 1", applied) + } + if st := controller.Status(); st.LastError == "" || st.LastErrorAt == "" { + t.Fatalf("Status after failed reload = %+v, want LastError and LastErrorAt set", st) + } + + // A subsequent valid reload clears the error. + writeConfig(t, path, minimalConfigTOML("widget")) + if err := controller.Reload(); err != nil { + t.Fatalf("recovery reload: %v", err) + } + if st := controller.Status(); st.LastError != "" || st.LastReloadAt == "" { + t.Fatalf("Status after recovery = %+v, want no error and a reload time", st) + } +} + +func TestReloadLoopAppliesOnSignalAndStopsOnCancel(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + writeConfig(t, path, minimalConfigTOML("widget")) + + loader := configuration.New(slog.New(slog.DiscardHandler)) + applied := make(chan struct{}, 1) + controller := newReloadController(loader, path, "", func(*configuration.Document) { + applied <- struct{}{} + }) + + ctx, cancel := context.WithCancel(context.Background()) + ch := make(chan os.Signal, 1) + var wg sync.WaitGroup + wg.Go(func() { + reloadLoop(ctx, ch, controller, slog.New(slog.DiscardHandler)) + }) + + ch <- syscall.SIGHUP + select { + case <-applied: + case <-time.After(5 * time.Second): + t.Fatal("reload not applied after signal") + } + + cancel() + wg.Wait() +} + +func TestChangedNonReloadableFields(t *testing.T) { + base := config.Config{ + BotUser: "a", + MaxRetries: 3, + PollInterval: config.Duration(30 * time.Second), + Repos: []config.Repo{{Owner: "x", Name: "y"}}, + } + + // Unchanged -> empty. + if got := changedNonReloadableFields(base, base); len(got) != 0 { + t.Fatalf("unchanged: got %v, want []", got) + } + + // Reloadable-only changes (PollInterval, Repos, Budgets, Dispatch, + // DiffCapLines) -> empty. + reloadableOnly := base + reloadableOnly.PollInterval = config.Duration(60 * time.Second) + reloadableOnly.Repos = []config.Repo{{Owner: "x", Name: "z"}} + reloadableOnly.Budgets = config.Budgets{MaxSteps: 99} + reloadableOnly.Dispatch = config.Dispatch{Trigger: "label"} + reloadableOnly.DiffCapLines = 1234 + if got := changedNonReloadableFields(base, reloadableOnly); len(got) != 0 { + t.Fatalf("reloadable-only: got %v, want []", got) + } + + // A non-reloadable change is named. + nonReloadable := base + nonReloadable.BotUser = "b" + if got := changedNonReloadableFields(base, nonReloadable); len(got) != 1 || got[0] != "BotUser" { + t.Fatalf("BotUser change: got %v, want [BotUser]", got) + } + + // Containers sub-field granularity: Image change warns, MaxConcurrency + // and VolumeTTL changes do not. + c1 := base + c1.Containers = config.ContainerConfig{Image: "img1", MaxConcurrency: 2, VolumeTTL: config.Duration(24 * time.Hour)} + c2 := c1 + c2.Containers.Image = "img2" + if got := changedNonReloadableFields(c1, c2); len(got) != 1 || got[0] != "Containers.Image" { + t.Fatalf("Image change: got %v, want [Containers.Image]", got) + } + c3 := c1 + c3.Containers.MaxConcurrency = 4 + if got := changedNonReloadableFields(c1, c3); len(got) != 0 { + t.Fatalf("MaxConcurrency change: got %v, want []", got) + } + c4 := c1 + c4.Containers.VolumeTTL = config.Duration(48 * time.Hour) + if got := changedNonReloadableFields(c1, c4); len(got) != 0 { + t.Fatalf("VolumeTTL change: got %v, want []", got) + } + + // NATS is not reloadable: a URL change warns (the daemon's client is + // startup-built; containers get the frozen ConnectedNATS). + natsChanged := base + natsChanged.NATS = config.NATSConfig{URL: "nats://new:4222"} + if got := changedNonReloadableFields(base, natsChanged); len(got) != 1 || got[0] != "NATS" { + t.Fatalf("NATS change: got %v, want [NATS]", got) + } +} diff --git a/internal/config/holder.go b/internal/config/holder.go index 3c0535aed..1e2210d7e 100644 --- a/internal/config/holder.go +++ b/internal/config/holder.go @@ -22,17 +22,29 @@ import "sync" // is called; the existing decode.go:80 cfg.Extra[name] = value is fine // because it runs pre-publish. // -// # Convention +// # Torn reads across a field group // -// Call Get once per logical operation and bind the result to a local: +// A single field read inline (d.Cfg.Get().PollInterval) is fine: the +// value is a primitive, and any other reader sees a whole Config +// snapshot too. The risk is reading two or more fields of the same +// snapshot when a Set could land in between, so each field would +// derive from a different published version. When a logical operation +// needs multiple fields, bind the snapshot to a local first: // // cfg := d.Cfg.Get() -// interval := cfg.PollInterval.Std() +// if cfg.PollInterval > 0 { ... } +// for _, r := range cfg.Repos { ... } // -// Inline accessors like d.Cfg.Get().Foo are a code smell: they may -// torn-read across a Set if a reload lands between two consecutive -// calls. With a single Get, every value in the local cfg came from -// the same published snapshot. +// A single Get per logical operation is the contract; inline single- +// field access is not a smell. +// +// # Loud failures, not silent degradation +// +// Get panics on a nil receiver. A forgotten NewHolder that publishes +// the zero Holder is a programming error and should crash at the first +// consumer, not boot a daemon that runs forever with PollInterval 0 +// and empty Repos. Set has always panicked on nil for the same reason; +// the asymmetry was wrong. // // # Why a pointer // @@ -52,11 +64,10 @@ func NewHolder(c Config) *Holder { // Get returns the currently published Config. The returned value is a // shallow copy; the reference-type fields inside it are shared with the -// published snapshot and must not be mutated. See the type doc comment. +// published snapshot and must not be mutated. Get panics on a nil +// receiver; a forgotten NewHolder is a programming error. See the type +// doc comment. func (h *Holder) Get() Config { - if h == nil { - return Config{} - } h.mu.RLock() defer h.mu.RUnlock() return h.cfg @@ -64,7 +75,8 @@ func (h *Holder) Get() Config { // Set replaces the published Config with c. The previous snapshot is // dropped; c becomes the new published value and its reference-type -// fields become shared with all subsequent Get callers. +// fields become shared with all subsequent Get callers. Set panics on +// a nil receiver. func (h *Holder) Set(c Config) { h.mu.Lock() defer h.mu.Unlock() diff --git a/internal/config/holder_test.go b/internal/config/holder_test.go index 943769c16..4977df12e 100644 --- a/internal/config/holder_test.go +++ b/internal/config/holder_test.go @@ -34,17 +34,17 @@ func TestHolderConcurrentGetSetIsRaceFree(t *testing.T) { const iters = 1000 var wg sync.WaitGroup - for i := 0; i < writers; i++ { + for range writers { wg.Add(2) go func() { defer wg.Done() - for j := 0; j < iters; j++ { + for range iters { h.Set(Config{BotUser: "w"}) } }() go func() { defer wg.Done() - for j := 0; j < iters; j++ { + for range iters { _ = h.Get() } }() @@ -52,11 +52,14 @@ func TestHolderConcurrentGetSetIsRaceFree(t *testing.T) { wg.Wait() } -func TestHolderGetIsNilSafe(t *testing.T) { +func TestHolderGetPanicsOnNil(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Fatalf("Get on nil Holder did not panic") + } + }() var h *Holder - if got := h.Get(); got.BotUser != "" { - t.Fatalf("nil Holder returned non-zero Config: %+v", got) - } + _ = h.Get() } func TestHolderSharedReferenceField(t *testing.T) { diff --git a/internal/config/reload.go b/internal/config/reload.go new file mode 100644 index 000000000..6e2c770c3 --- /dev/null +++ b/internal/config/reload.go @@ -0,0 +1,17 @@ +package config + +// ReloadStatus is the outcome of the most recent config reload attempt, +// surfaced so the dashboard can tell the operator when the running +// config is stale: a reload that failed validation leaves the daemon +// running on the previous config, and that failure must be visible in +// the UI, not buried in logs. +type ReloadStatus struct { + // LastError is the validation error from the most recent failed + // reload attempt. Empty when the most recent attempt succeeded. + LastError string `json:"last_error,omitempty"` + // LastErrorAt is the RFC3339 UTC timestamp of the failed attempt. + LastErrorAt string `json:"last_error_at,omitempty"` + // LastReloadAt is the RFC3339 UTC timestamp of the most recent + // successful reload. Empty until the first reload. + LastReloadAt string `json:"last_reload_at,omitempty"` +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 010e41948..e4001e3a1 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -49,14 +49,21 @@ type TaskBus interface { type Daemon struct { // Cfg publishes the running configuration. Read through Cfg() so a // reload swaps the published snapshot atomically. See config.Holder. - Cfg *config.Holder - Store store.TaskStore - Forge forge.Forge - Trees *worktree.Manager - Agent agentexec.Runner - Bus *events.Bus - Workflows workflow.Registry - Log *slog.Logger + Cfg *config.Holder + // ConnectedNATS is the [nats] configuration the daemon's own client + // connected with at startup (the endpoint it publishes on). Container + // env is built from this, not from the live config, so a reload of + // nats.url/token_env cannot point new containers at a server the + // daemon is not publishing on. Zero value means NATS is not + // configured. + ConnectedNATS config.NATSConfig + Store store.TaskStore + Forge forge.Forge + Trees *worktree.Manager + Agent agentexec.Runner + Bus *events.Bus + Workflows workflow.Registry + Log *slog.Logger // Tasks is the optional message bus for task distribution. Nil means no // bus is configured; the existing SQLite ClaimNext flow is used. Tasks TaskBus @@ -215,7 +222,8 @@ func (d *Daemon) Run(ctx context.Context) error { if len(d.Identities) > 0 { return d.runIdentities(ctx) } - ticker := time.NewTicker(d.Cfg.Get().PollInterval.Std()) + interval := d.Cfg.Get().PollInterval.Std() + ticker := time.NewTicker(interval) defer ticker.Stop() for { d.Cycle(ctx) @@ -223,6 +231,12 @@ func (d *Daemon) Run(ctx context.Context) error { case <-ctx.Done(): return ctx.Err() case <-ticker.C: + // PollInterval may have been reloaded; reset the ticker so a + // change takes effect on the next cycle. + if iv := d.Cfg.Get().PollInterval.Std(); iv != interval { + interval = iv + ticker.Reset(iv) + } } } } @@ -262,6 +276,16 @@ func (d *Daemon) runIdentities(ctx context.Context) error { case <-ctx.Done(): return case <-ticker.C: + // The identity's own override is frozen (identity config is + // startup-built); the root fallback may have been reloaded. + iv := d.Cfg.Get().PollInterval.Std() + if id.Cfg.PollInterval > 0 { + iv = id.Cfg.PollInterval.Std() + } + if iv != interval { + interval = iv + ticker.Reset(iv) + } } } }(id) @@ -269,7 +293,8 @@ func (d *Daemon) runIdentities(ctx context.Context) error { // One shared maintenance-and-drain loop. wg.Go(func() { - ticker := time.NewTicker(d.Cfg.Get().PollInterval.Std()) + interval := d.Cfg.Get().PollInterval.Std() + ticker := time.NewTicker(interval) defer ticker.Stop() for { d.maintainAndDrain(ctx) @@ -277,6 +302,12 @@ func (d *Daemon) runIdentities(ctx context.Context) error { case <-ctx.Done(): return case <-ticker.C: + // PollInterval may have been reloaded; reset the ticker so a + // change takes effect on the next cycle. + if iv := d.Cfg.Get().PollInterval.Std(); iv != interval { + interval = iv + ticker.Reset(iv) + } } } }) @@ -1073,10 +1104,12 @@ func (d *Daemon) requestTaskRun(ctx context.Context, taskID int64, data []byte) } func (d *Daemon) containerEnv(task *store.Task) []string { - cfg := d.Cfg.Get() var env []string - env = append(env, "NATS_URL="+cfg.NATS.URL) - if tokenEnv := cfg.NATS.TokenEnv; tokenEnv != "" { + // The endpoint the daemon's own client connected with at startup, not + // the live config: a reloaded [nats] section must not point new + // containers at a server the daemon is not publishing on. + env = append(env, "NATS_URL="+d.ConnectedNATS.URL) + if tokenEnv := d.ConnectedNATS.TokenEnv; tokenEnv != "" { if token := os.Getenv(tokenEnv); token != "" { env = append(env, "NATS_TOKEN="+token) } diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index 5948cb8bc..9cf7f5dfb 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -305,12 +305,18 @@ func TestAllowConcurrentForTaskPrefersOwningIdentityRepo(t *testing.T) { func TestContainerEnvIncludesConfiguredNATSCredentials(t *testing.T) { t.Setenv("ARCHIE_NATS_SECRET", "test-nats-token") - d := &Daemon{Cfg: config.NewHolder(config.Config{ - NATS: config.NATSConfig{ - URL: "nats://nats.example:4222", - TokenEnv: "ARCHIE_NATS_SECRET", - }, - })} + // ConnectedNATS is the endpoint the daemon's own client connected with + // at startup; containerEnv deliberately reads this, not the live Cfg, + // so a reload of nats.url cannot point new containers at a server the + // daemon is not publishing on. + natsCfg := config.NATSConfig{ + URL: "nats://nats.example:4222", + TokenEnv: "ARCHIE_NATS_SECRET", + } + d := &Daemon{ + Cfg: config.NewHolder(config.Config{}), + ConnectedNATS: natsCfg, + } got := d.containerEnv(nil) for _, want := range []string{ @@ -595,6 +601,54 @@ type testForge struct { prStates map[int]string } +// pollingForge records every repo the daemon asks about, so a test can +// observe which repos are being polled -- including that a repo removed +// by a reload stops new intake. +type pollingForge struct { + testForge + asked []string +} + +func (f *pollingForge) AssignedIssues(_ context.Context, owner, repo, _ string) ([]forge.Issue, error) { + f.asked = append(f.asked, owner+"/"+repo) + return nil, nil +} + +// TestRemovingRepoStopsNewIntake pins the reload behaviour: when a repo +// vanishes from the config, the next poll cycle no longer asks the forge +// about it. In-flight tasks are unaffected because their TaskContext.Cfg +// is a value snapshot taken at dispatch -- the type system guarantees +// that half; this test covers the intake half. +func TestRemovingRepoStopsNewIntake(t *testing.T) { + fg := &pollingForge{} + d := &Daemon{ + Cfg: config.NewHolder(config.Config{ + BotUser: "archie", + Repos: []config.Repo{{Owner: "acme", Name: "widget"}}, + Dispatch: config.Dispatch{Trigger: "assignee"}, + }), + Forge: fg, + Log: slog.New(slog.DiscardHandler), + } + + ctx := context.Background() + d.poll(ctx) + if len(fg.asked) != 1 || fg.asked[0] != "acme/widget" { + t.Fatalf("after first poll, asked = %v, want [acme/widget]", fg.asked) + } + + // Simulate a reload that drops the repo: the polling loop re-reads + // d.Cfg.Get().Repos fresh, so the next poll asks about nothing. + d.Cfg.Set(config.Config{ + BotUser: "archie", + Dispatch: config.Dispatch{Trigger: "assignee"}, + }) + d.poll(ctx) + if len(fg.asked) != 1 { + t.Fatalf("after reload, asked = %v, want unchanged [acme/widget] (no new intake)", fg.asked) + } +} + type closeIssueCall struct { owner, repo string number int diff --git a/internal/infrastructure/configuration/flags.go b/internal/infrastructure/configuration/flags.go new file mode 100644 index 000000000..e91149e93 --- /dev/null +++ b/internal/infrastructure/configuration/flags.go @@ -0,0 +1,18 @@ +package configuration + +import "os" + +// envSkipOverlay names the environment variable that disables runtime +// config overlays. It is the recovery hatch for an overlay write that +// leaves the daemon unable to boot: set ARCHIE_SKIP_CONFIG_OVERLAY=1 +// and the daemon boots from file config alone. The same switch exists +// as the --no-config-overlay flag on archied. +const envSkipOverlay = "ARCHIE_SKIP_CONFIG_OVERLAY" + +// SkipOverlay reports whether runtime config overlays are disabled via +// ARCHIE_SKIP_CONFIG_OVERLAY=1. The overlay source (a later step of the +// config-editing work) consults this before loading; cmd/archied +// OR-s its --no-config-overlay flag with this at startup. +func SkipOverlay() bool { + return os.Getenv(envSkipOverlay) == "1" +} diff --git a/internal/infrastructure/configuration/flags_test.go b/internal/infrastructure/configuration/flags_test.go new file mode 100644 index 000000000..06aa4dc28 --- /dev/null +++ b/internal/infrastructure/configuration/flags_test.go @@ -0,0 +1,17 @@ +package configuration + +import "testing" + +func TestSkipOverlayEnvSet(t *testing.T) { + t.Setenv(envSkipOverlay, "1") + if !SkipOverlay() { + t.Fatal("SkipOverlay() = false with env set to 1") + } +} + +func TestSkipOverlayEnvUnset(t *testing.T) { + t.Setenv(envSkipOverlay, "") + if SkipOverlay() { + t.Fatal("SkipOverlay() = true with env empty") + } +} diff --git a/internal/infrastructure/configuration/validate.go b/internal/infrastructure/configuration/validate.go index 75e63bb98..86d99d6de 100644 --- a/internal/infrastructure/configuration/validate.go +++ b/internal/infrastructure/configuration/validate.go @@ -72,9 +72,25 @@ func validate(cfg *config.Config) error { } else if err := validateSingleIdentity(cfg); err != nil { return err } + if err := validatePollInterval(cfg); err != nil { + return err + } return validateContainers(cfg) } +// validatePollInterval rejects a non-positive poll interval. +// applyDefaults fills PollInterval == 0 with the default, so this only +// fires on an explicit negative value -- which would panic +// time.NewTicker/Reset in the daemon's poll loops, at boot and (worse) +// on a SIGHUP reload mid-run, when the edit that broke it is no longer +// fresh in the operator's mind. +func validatePollInterval(cfg *config.Config) error { + if cfg.PollInterval <= 0 { + return fmt.Errorf("%w: poll_interval must be positive", ErrInvalidInput) + } + return nil +} + 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)) diff --git a/internal/infrastructure/configuration/validate_test.go b/internal/infrastructure/configuration/validate_test.go index 5bc26bd5e..ac3013158 100644 --- a/internal/infrastructure/configuration/validate_test.go +++ b/internal/infrastructure/configuration/validate_test.go @@ -4,6 +4,7 @@ import ( "errors" "os" "testing" + "time" "github.com/samcharles93/archie-core/internal/config" ) @@ -14,8 +15,9 @@ import ( // have supplied. func minimalValidConfig() config.Config { return config.Config{ - BotUser: "archie-bot", - Agent: config.Agent{Mode: "inprocess"}, + BotUser: "archie-bot", + PollInterval: config.Duration(60 * time.Second), + Agent: config.Agent{Mode: "inprocess"}, Dispatch: config.Dispatch{ Trigger: "assignee", }, @@ -61,6 +63,16 @@ func TestValidate_RejectsTheSameProblemsAsLoaderLoad(t *testing.T) { mutate: func(cfg *config.Config) { cfg.Forge.Type = "not-a-real-forge" }, wantErr: true, }, + { + name: "negative poll_interval", + mutate: func(cfg *config.Config) { cfg.PollInterval = config.Duration(-5 * time.Second) }, + wantErr: true, + }, + { + name: "zero poll_interval", + mutate: func(cfg *config.Config) { cfg.PollInterval = 0 }, + wantErr: true, + }, { name: "provider base_url carries userinfo", mutate: func(cfg *config.Config) { diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index 88314cb4d..6fb16cb23 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -195,6 +195,9 @@ type ConfigView struct { Containers ContainersView `json:"containers"` Web WebView `json:"web"` Provenance []ConfigOrigin `json:"provenance"` + // Reload reports the most recent config reload outcome. Omitted when + // the reload status is unavailable. + Reload *config.ReloadStatus `json:"reload,omitempty"` } // IdentityView is who Archie is on the forge -- never the token that @@ -298,6 +301,11 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { // is read from this local. cfg := s.Cfg.Get() + var provenance []ConfigOrigin + if p := s.ConfigProvenance.Load(); p != nil { + provenance = append([]ConfigOrigin(nil), (*p)...) + } + view := ConfigView{ Identity: IdentityView{ BotUser: cfg.BotUser, @@ -338,7 +346,11 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { Network: cfg.Containers.Network, }, Web: WebView{Listen: cfg.Web.Listen}, - Provenance: append([]ConfigOrigin(nil), s.ConfigProvenance...), + Provenance: provenance, + } + if s.LastReload != nil { + rs := s.LastReload() + view.Reload = &rs } writeJSON(w, view) diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index 3b54ca4dd..918f043aa 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -146,6 +146,83 @@ func TestHandleConfigSafeFieldsPresent(t *testing.T) { } } +// TestHandleConfigIncludesReloadStatus proves a failed reload is surfaced +// in /api/config so the operator can see the running config is stale +// without reading logs. +func TestHandleConfigIncludesReloadStatus(t *testing.T) { + srv := newTestServer(t) + srv.Cfg = configWithFakeSecrets() + srv.LastReload = func() config.ReloadStatus { + return config.ReloadStatus{ + LastError: "poll_interval must be positive", + LastErrorAt: "2026-08-09T12:00:00Z", + } + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + var got ConfigView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if got.Reload == nil { + t.Fatal("Reload = nil, want the failed-reload status") + } + if got.Reload.LastError != "poll_interval must be positive" { + t.Errorf("Reload.LastError = %q", got.Reload.LastError) + } + if got.Reload.LastErrorAt != "2026-08-09T12:00:00Z" { + t.Errorf("Reload.LastErrorAt = %q", got.Reload.LastErrorAt) + } +} + +// TestHandleConfigOmitsReloadStatusWhenUnavailable pins that the reload +// field is absent (not empty) when the server has no reload seam wired. +func TestHandleConfigOmitsReloadStatusWhenUnavailable(t *testing.T) { + srv := newTestServer(t) + srv.Cfg = configWithFakeSecrets() + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + var got ConfigView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if got.Reload != nil { + t.Errorf("Reload = %+v, want nil (no reload seam)", got.Reload) + } +} + +// TestSetProvenancePublishesForConfigView proves a reloaded provenance +// list reaches /api/config. +func TestSetProvenancePublishesForConfigView(t *testing.T) { + srv := newTestServer(t) + srv.Cfg = configWithFakeSecrets() + srv.SetProvenance([]ConfigOrigin{ + {Path: "/etc/archie/config.toml", Role: "main", Layer: "base"}, + {Path: "/etc/archie/conf.d/docker.yaml", Role: "extra", Layer: "overlay", Feature: "docker"}, + }) + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + var got ConfigView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if len(got.Provenance) != 2 { + t.Fatalf("Provenance = %+v, want 2 origins", got.Provenance) + } + if got.Provenance[0].Path != "/etc/archie/config.toml" { + t.Errorf("Provenance[0].Path = %q", got.Provenance[0].Path) + } +} + func TestHandleChannelsReportsConfiguredState(t *testing.T) { srv := newTestServer(t) srv.Cfg = configWithFakeSecrets() diff --git a/internal/webui/server.go b/internal/webui/server.go index be67998fa..fad7033b0 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -14,6 +14,7 @@ import ( "log/slog" "net/http" "sync" + "sync/atomic" "time" "github.com/samcharles93/archie-core/internal/channels" @@ -50,9 +51,19 @@ type Server struct { // logging not configured) makes that a no-op. TaskLogs *logging.TaskRegistry - // ConfigProvenance is supplied by composition from the production loader. - // It is safe to expose: it contains paths and precedence only, never values. - ConfigProvenance []ConfigOrigin + // ConfigProvenance lists the files that produced the running config, + // in precedence order. Held through atomic.Pointer so a reload can + // swap it independently of Cfg. A reader may therefore observe the + // new config alongside the old provenance (or vice versa); this is + // display-only, and the skew is accepted rather than serialised. + ConfigProvenance atomic.Pointer[[]ConfigOrigin] + + // LastReload reports the most recent config reload outcome, so the + // dashboard can tell the operator when the running config is stale + // (a reload failed validation and the daemon kept the previous + // config). Optional: when nil, the /api/config response omits the + // reload status. + LastReload func() config.ReloadStatus // Channels reports actual adapter lifecycle, independently of configuration // presence. Nil preserves the configuration-only fallback for tests and @@ -105,6 +116,11 @@ type ConfigOrigin struct { Feature string `json:"feature,omitempty"` } +// SetProvenance publishes a fresh provenance list after a config reload. +func (s *Server) SetProvenance(origins []ConfigOrigin) { + s.ConfigProvenance.Store(&origins) +} + // IssueCloser closes the forge issue behind a task. type IssueCloser interface { CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error