From b6f0aea93033a6326c3667f0e49b00cfdd5888b7 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 9 Aug 2026 23:29:52 +1000 Subject: [PATCH] refactor(daemon,webui): make Daemon.Cfg and webui.Server.Cfg reload-safe Daemon.Cfg, webui.Server.Cfg, and telegramSetup.Cfg were all held by value (or as a raw shared pointer in webui's case), so a future reload path could not swap the running configuration -- the consumers held frozen snapshots made at construction. This is the prerequisite for issue #348. Add config.Holder, a small RWMutex-backed snapshot holder: - Get returns a value copy under RLock; the copy shares its reference-type fields with the published snapshot, so a doc comment pins the immutability invariant (a published Config is immutable; reload constructs a fresh one). - Set replaces the snapshot under WLock. - Get is nil-safe; Set is not. Convert every consumer to read through the accessor. The convention 'cfg := h.Get() once per logical operation' is documented on the type so the next reader knows that inline d.Cfg.Get().Foo is a code smell (a Set could land between two consecutive Gets). Special cases: - webui.Server.Cfg: was *config.Config, a raw shared pointer read from handler goroutines. Convert to *config.Holder. The pre-existing 'cfg := s.Cfg' aliasing bug at api_config.go:295 (which was *trying* to copy but only copied the pointer) now becomes 'cfg := s.Cfg.Get()', which is the value copy the read-only view always wanted. - daemon_test.go: one test mutated d.Cfg.DiffCapLines in place, which the Holder forbids. Replace with the documented read-modify-write pattern (prev := d.Cfg.Get(); prev.X = Y; d.Cfg.Set(prev)). - telegramSetup.Cfg: matches the daemon's API for consistency even though setup runs before the daemon is alive. TaskContext.Cfg in internal/domain/workflow/workflow.go is deliberately NOT converted -- a task that starts under one config should finish under it, and a config changing between TDD and gate stages is a bug, not a feature. Snapshotted at dispatch, as before. Verified: go test ./... (61 packages), go vet, -race on internal/daemon and internal/config. --- cmd/archied/main.go | 10 ++-- cmd/archied/task_actions_test.go | 2 +- cmd/archied/telegram_setup.go | 36 +++++++----- internal/config/holder.go | 72 +++++++++++++++++++++++ internal/config/holder_test.go | 75 ++++++++++++++++++++++++ internal/daemon/daemon.go | 39 ++++++------ internal/daemon/daemon_test.go | 42 ++++++------- internal/webui/api_config.go | 8 ++- internal/webui/api_config_test.go | 10 ++-- internal/webui/api_logs.go | 2 +- internal/webui/api_setup.go | 12 ++-- internal/webui/api_skills.go | 5 +- internal/webui/api_tasks.go | 7 ++- internal/webui/api_tasks_actions_test.go | 8 +-- internal/webui/server.go | 6 +- 15 files changed, 251 insertions(+), 83 deletions(-) create mode 100644 internal/config/holder.go create mode 100644 internal/config/holder_test.go diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 8b1a78cb0..b4f10bb00 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -427,7 +427,7 @@ 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: &cfg, ConfigProvenance: configProvenance, Channels: channelManager, Events: bus} + web := &webui.Server{Store: st, Log: log, LogFeed: logFeed, TaskLogs: taskLogs, Cfg: config.NewHolder(cfg), ConfigProvenance: configProvenance, Channels: channelManager, Events: bus} web.ReloadChannel = func(ctx context.Context, id string) error { if id != "telegram" || restartTelegram == nil { return fmt.Errorf("channel reload unavailable") @@ -504,7 +504,7 @@ func run() int { requeue: st.Requeue, transition: st.Transition, }) - updateService := makeUpdateService(telegramSetup{Cfg: cfg}) + updateService := makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)}) web.WorkRequests = chatTasks // The dashboard is another gateway, not a second chat implementation. It @@ -528,7 +528,7 @@ func run() int { webRouter.InitSessions(chatSessionStore) configureTaskCommands(webRouter, chatTasks, chatController, defaultChatIdentity) webSetup := telegramSetup{ - Cfg: cfg, St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg, + Cfg: config.NewHolder(cfg), St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg, Personas: personas, ChatTasks: chatTasks, ChatController: chatController, ChatTaskLister: chatTaskListerAdapter{tasks: st.Tasks}, ChatTaskLogs: chatTaskLogReaderAdapter{ @@ -553,7 +553,7 @@ func run() int { // Multi-agent collaboration PRD phase C (docs/prds/multi-agent-collaboration.md). var startGateways []func() start, ok := setupTelegramGateway(ctx, telegramSetup{ - Cfg: cfg, CfgPath: *cfgPath, OverlayPath: *overlayPath, + Cfg: config.NewHolder(cfg), CfgPath: *cfgPath, OverlayPath: *overlayPath, St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg, Personas: personas, ChatTasks: chatTasks, ChatController: chatController, ChatTaskLister: chatTaskListerAdapter{tasks: st.Tasks}, @@ -950,7 +950,7 @@ func run() int { // via Yaegi is deferred to the container/agent runtime. d := &daemon.Daemon{ - Cfg: cfg, + Cfg: config.NewHolder(cfg), Store: st, Bus: bus, Forge: forgeClient, diff --git a/cmd/archied/task_actions_test.go b/cmd/archied/task_actions_test.go index bf503ea4a..e599c70ef 100644 --- a/cmd/archied/task_actions_test.go +++ b/cmd/archied/task_actions_test.go @@ -72,7 +72,7 @@ func TestDashboardAndChatAgreeOnTerminalStates(t *testing.T) { t.Fatalf("chat %s: %v", tc.action, actErr) } } else { - srv := &webui.Server{Store: st, Cfg: &config.Config{MaxRetries: 3}} + srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{MaxRetries: 3})} req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"`+tc.action+`"}`)) diff --git a/cmd/archied/telegram_setup.go b/cmd/archied/telegram_setup.go index 38dc86ab2..454d74512 100644 --- a/cmd/archied/telegram_setup.go +++ b/cmd/archied/telegram_setup.go @@ -28,7 +28,10 @@ import ( // chat gateway. Every field is intentionally explicit so the function // signature acts as a contract of what the gateway depends on. type telegramSetup struct { - Cfg config.Config + // Cfg is read once per setup function via Get(); the daemon is not + // running yet at this point, so the reload-safe Holder is mostly a + // formality, but matching the daemon's API keeps callers honest. + Cfg *config.Holder CfgPath string OverlayPath string St store.TaskStore @@ -57,19 +60,20 @@ type telegramSetup struct { // token is configured. It returns a start function (nil when no token // is configured) and ok=false to signal the caller must exit early. func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), ok bool) { - if s.Cfg.Chat.Telegram.TokenEnv == "" { + cfg := s.Cfg.Get() + if cfg.Chat.Telegram.TokenEnv == "" { return nil, true } - tgToken := os.Getenv(s.Cfg.Chat.Telegram.TokenEnv) + tgToken := os.Getenv(cfg.Chat.Telegram.TokenEnv) if tgToken == "" { - s.Log.Error("chat.telegram configured but token env var is empty", "env", s.Cfg.Chat.Telegram.TokenEnv) + s.Log.Error("chat.telegram configured but token env var is empty", "env", cfg.Chat.Telegram.TokenEnv) return nil, false } - if len(s.Cfg.Chat.Telegram.AllowedUserIDs) == 0 { + if len(cfg.Chat.Telegram.AllowedUserIDs) == 0 { s.Log.Warn("chat.telegram has no allowed_user_ids: every sender will be rejected. " + "Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.") } - tg := telegram.New(tgToken, "", "", s.Cfg.Chat.Telegram.AllowedUserIDs, s.Log) + tg := telegram.New(tgToken, "", "", cfg.Chat.Telegram.AllowedUserIDs, s.Log) if s.RegisterRestart != nil { s.RegisterRestart(tg.RequestRestart) } @@ -83,7 +87,7 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o } tg.Dangerous = s.Dangerous tg.ReleaseAnnouncements = &releaseannounce.Announcer{ - StatePath: releaseAnnouncementStatePath(s.Cfg.WorkDir, s.Cfg.BotUser), + StatePath: releaseAnnouncementStatePath(cfg.WorkDir, cfg.BotUser), Components: []releaseannounce.Component{ {ID: "gateway", Label: "THE GATEWAY", Version: gatewayVersion, ChangelogPath: packagedGatewayChangelogPath}, {ID: "runtime", Label: "THE RUNTIME", Version: runtimeVersion, ChangelogPath: packagedRuntimeChangelogPath}, @@ -120,15 +124,16 @@ func configureTelegramUpdates(tg *telegram.Gateway, s telegramSetup) { } func makeUpdateService(s telegramSetup) *releaseupdate.Service { - if len(s.Cfg.Chat.Telegram.UpdateCheckCommand) == 0 { + cfg := s.Cfg.Get() + if len(cfg.Chat.Telegram.UpdateCheckCommand) == 0 { return nil } updates := &releaseupdate.Service{ - Catalog: releaseupdate.CommandCatalog{Command: s.Cfg.Chat.Telegram.UpdateCheckCommand}, - StatePath: filepath.Join(s.Cfg.WorkDir, "telegram-update-deferrals.json"), + Catalog: releaseupdate.CommandCatalog{Command: cfg.Chat.Telegram.UpdateCheckCommand}, + StatePath: filepath.Join(cfg.WorkDir, "telegram-update-deferrals.json"), } - if len(s.Cfg.Chat.Telegram.UpdateInstallCommand) != 0 { - updates.Installer = releaseupdate.CommandInstaller{Command: s.Cfg.Chat.Telegram.UpdateInstallCommand} + if len(cfg.Chat.Telegram.UpdateInstallCommand) != 0 { + updates.Installer = releaseupdate.CommandInstaller{Command: cfg.Chat.Telegram.UpdateInstallCommand} } return updates } @@ -204,20 +209,21 @@ func newChatTurnRunner( sessionStore gateway.SessionStore, router *gateway.Router, ) *gateway.TurnRunner { + cfg := s.Cfg.Get() runner := gateway.NewTurnRunner(gateway.TurnRunnerConfig{ Router: router, Sessions: sessionStore, Models: s.ChatModels, Personas: s.Personas, - Model: newChatTurnModel(s.LLM, s.ToolReg, s.Cfg.Chat.MaxSteps, toolLimits(s.Cfg)), + Model: newChatTurnModel(s.LLM, s.ToolReg, cfg.Chat.MaxSteps, toolLimits(cfg)), TaskLister: s.ChatTaskLister, Tasks: s.ChatTasks, TaskLogs: s.ChatTaskLogs, TaskIdentity: s.DefaultChatIdentity, Bus: s.Bus, - BotUser: s.Cfg.BotUser, + BotUser: cfg.BotUser, Channel: channel, - Operator: s.Cfg.Chat.Operator, + Operator: cfg.Chat.Operator, Log: s.Log, }) if err := runner.Recover(context.Background()); err != nil && s.Log != nil { diff --git a/internal/config/holder.go b/internal/config/holder.go new file mode 100644 index 000000000..3c0535aed --- /dev/null +++ b/internal/config/holder.go @@ -0,0 +1,72 @@ +package config + +import "sync" + +// Holder publishes a Config snapshot to concurrent readers and lets a +// single writer swap the snapshot atomically. +// +// # Immutability invariant +// +// A published Config is immutable. The only way to update the published +// value is to call Set with a freshly constructed Config; in-place +// mutation of a published Config is a bug. The reason this matters: Get +// returns a value copy, but the copy shares its reference-type fields +// (Models, Providers, Repos, Identities, MCPServers, Extra, etc.) with +// the published snapshot. Mutating a map or slice through that copy +// mutates the published snapshot too, and any other reader sees the +// mutation outside the protection of the read lock. +// +// Reload paths (Loader.Reload, the file watcher, the UI PATCH handler) +// construct a fresh Config and call Set; they never mutate an existing +// one. Decode paths must finish constructing the new Config before Set +// is called; the existing decode.go:80 cfg.Extra[name] = value is fine +// because it runs pre-publish. +// +// # Convention +// +// Call Get once per logical operation and bind the result to a local: +// +// cfg := d.Cfg.Get() +// interval := cfg.PollInterval.Std() +// +// 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. +// +// # Why a pointer +// +// The zero value of Holder is not usable (the mutex is uninitialised); +// construct one with [NewHolder]. Holder is always passed by pointer +// because the embedded sync.RWMutex is itself a non-copyable type, and +// copying a Daemon that embeds a value Holder triggers go vet copylocks. +type Holder struct { + mu sync.RWMutex + cfg Config +} + +// NewHolder returns a Holder preloaded with c. +func NewHolder(c Config) *Holder { + return &Holder{cfg: c} +} + +// 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. +func (h *Holder) Get() Config { + if h == nil { + return Config{} + } + h.mu.RLock() + defer h.mu.RUnlock() + return h.cfg +} + +// 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. +func (h *Holder) Set(c Config) { + h.mu.Lock() + defer h.mu.Unlock() + h.cfg = c +} diff --git a/internal/config/holder_test.go b/internal/config/holder_test.go new file mode 100644 index 000000000..943769c16 --- /dev/null +++ b/internal/config/holder_test.go @@ -0,0 +1,75 @@ +package config + +import ( + "sync" + "testing" +) + +func TestHolderGetReturnsConstructorValue(t *testing.T) { + c := Config{BotUser: "archie", PollInterval: Duration(1)} + h := NewHolder(c) + if got := h.Get(); got.BotUser != "archie" || got.PollInterval != Duration(1) { + t.Fatalf("Get() = %+v, want BotUser=archie PollInterval=1", got) + } +} + +func TestHolderSetReplaces(t *testing.T) { + h := NewHolder(Config{BotUser: "old"}) + h.Set(Config{BotUser: "new"}) + if got := h.Get(); got.BotUser != "new" { + t.Fatalf("after Set, Get().BotUser = %q, want \"new\"", got.BotUser) + } +} + +func TestHolderConcurrentGetSetIsRaceFree(t *testing.T) { + // The actual contract is that Get never tears: under -race, no data + // race, and every observed Config is a value some Set wrote. We do + // not assert "Get after my Set returns my value" because with N + // concurrent writers that property is not what Get guarantees -- a + // later Set can land between this writer's Set and this writer's + // Get. The race detector is the real check. + h := NewHolder(Config{BotUser: "v0"}) + + const writers = 8 + const iters = 1000 + + var wg sync.WaitGroup + for i := 0; i < writers; i++ { + wg.Add(2) + go func() { + defer wg.Done() + for j := 0; j < iters; j++ { + h.Set(Config{BotUser: "w"}) + } + }() + go func() { + defer wg.Done() + for j := 0; j < iters; j++ { + _ = h.Get() + } + }() + } + wg.Wait() +} + +func TestHolderGetIsNilSafe(t *testing.T) { + var h *Holder + if got := h.Get(); got.BotUser != "" { + t.Fatalf("nil Holder returned non-zero Config: %+v", got) + } +} + +func TestHolderSharedReferenceField(t *testing.T) { + // Documents the immutability invariant: maps inside the snapshot + // are shared with all Get callers. Mutating one is visible to all + // others -- the contract forbids this, but the test pins the + // current behaviour so any future change (e.g. copying maps) is + // a deliberate decision. + original := Config{Models: map[string]string{"builder": "anthropic/claude"}} + h := NewHolder(original) + snapshot := h.Get() + snapshot.Models["builder"] = "mutated" + if got := h.Get().Models["builder"]; got != "mutated" { + t.Fatalf("expected Get to see mutation through shared map, got %q", got) + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index b20cd4a9c..010e41948 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -47,7 +47,9 @@ type TaskBus interface { } type Daemon struct { - Cfg config.Config + // 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 @@ -197,7 +199,7 @@ func (d *Daemon) Startup(ctx context.Context) error { if err := d.Forge.AcceptInvitations(ctx); err != nil { d.Log.Warn("invitation sweep failed", "err", err) } - for _, r := range d.Cfg.Repos { + for _, r := range d.Cfg.Get().Repos { if err := d.Forge.VerifyPush(ctx, r.Owner, r.Name); err != nil { d.Log.Warn("repo not pushable -- tasks from it will fail", "repo", r.FullName(), "err", err) } @@ -213,7 +215,7 @@ func (d *Daemon) Run(ctx context.Context) error { if len(d.Identities) > 0 { return d.runIdentities(ctx) } - ticker := time.NewTicker(d.Cfg.PollInterval.Std()) + ticker := time.NewTicker(d.Cfg.Get().PollInterval.Std()) defer ticker.Stop() for { d.Cycle(ctx) @@ -248,7 +250,7 @@ func (d *Daemon) runIdentities(ctx context.Context) error { wg.Add(1) go func(id *IdentityRunner) { defer wg.Done() - interval := d.Cfg.PollInterval.Std() + interval := d.Cfg.Get().PollInterval.Std() if id.Cfg.PollInterval > 0 { interval = id.Cfg.PollInterval.Std() } @@ -267,7 +269,7 @@ func (d *Daemon) runIdentities(ctx context.Context) error { // One shared maintenance-and-drain loop. wg.Go(func() { - ticker := time.NewTicker(d.Cfg.PollInterval.Std()) + ticker := time.NewTicker(d.Cfg.Get().PollInterval.Std()) defer ticker.Stop() for { d.maintainAndDrain(ctx) @@ -288,7 +290,7 @@ func (d *Daemon) runIdentities(ctx context.Context) error { // drains or reconciles -- those are store-wide and run in the shared // maintainAndDrain loop. func (d *Daemon) pollForIdentity(ctx context.Context, id *IdentityRunner) { - cfg := configForIdentity(d.Cfg, id.Cfg) + cfg := configForIdentity(d.Cfg.Get(), id.Cfg) for _, repo := range id.Repos { issues := d.pollIssuesWithConfig(ctx, id.Forge, cfg, repo) for _, is := range issues { @@ -382,7 +384,7 @@ func (d *Daemon) Cycle(ctx context.Context) { } func (d *Daemon) cleanupExpiredStorage(ctx context.Context) { - ttl := d.Cfg.Containers.VolumeTTL.Std() + ttl := d.Cfg.Get().Containers.VolumeTTL.Std() if ttl <= 0 { return } @@ -399,7 +401,7 @@ func (d *Daemon) cleanupExpiredStorage(ctx context.Context) { // drainSQLite claims queued tasks from SQLite and dispatches them concurrently. func (d *Daemon) drainSQLite(ctx context.Context) { - dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency, d.allowConcurrentForTask) + dispatcher := newTaskDispatcher(d.Cfg.Get().Containers.MaxConcurrency, d.allowConcurrentForTask) for ctx.Err() == nil { task, err := d.Store.ClaimNext(ctx) if err != nil { @@ -418,7 +420,7 @@ func (d *Daemon) drainSQLite(ctx context.Context) { // requeued tasks (waiting_human approval, retry-parked) that didn't come // through a NATS publish. func (d *Daemon) drainNATS(ctx context.Context) { - dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency, d.allowConcurrentForTask) + dispatcher := newTaskDispatcher(d.Cfg.Get().Containers.MaxConcurrency, d.allowConcurrentForTask) for ctx.Err() == nil { msg, err := d.Tasks.Fetch(ctx) if err != nil && !errors.Is(err, eventbus.ErrNoMessage) { @@ -535,14 +537,14 @@ func (d *taskDispatcher) Wait() { } func (d *Daemon) poll(ctx context.Context) { - for _, repo := range d.Cfg.Repos { + for _, repo := range d.Cfg.Get().Repos { issues := d.pollIssues(ctx, repo) for _, is := range issues { labels := strings.Join(is.Labels, ",") if d.Tasks != nil { - d.pollNATS(ctx, d.Forge, d.Cfg, repo, is, labels, "") + d.pollNATS(ctx, d.Forge, d.Cfg.Get(), repo, is, labels, "") } else { - d.pollSQLite(ctx, d.Forge, d.Cfg, repo, is, labels, "") + d.pollSQLite(ctx, d.Forge, d.Cfg.Get(), repo, is, labels, "") } } } @@ -686,7 +688,7 @@ func (d *Daemon) processNATSTask(ctx context.Context, msg eventbus.Message) { // config, using the root forge client. Identity poll loops use // pollIssuesWithConfig with their own forge and config instead. func (d *Daemon) pollIssues(ctx context.Context, repo config.Repo) []forge.Issue { - return d.pollIssuesWithConfig(ctx, d.Forge, d.Cfg, repo) + return d.pollIssuesWithConfig(ctx, d.Forge, d.Cfg.Get(), repo) } // closeResolvedIssue closes the forge issue behind a finished task. @@ -1071,9 +1073,10 @@ 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="+d.Cfg.NATS.URL) - if tokenEnv := d.Cfg.NATS.TokenEnv; tokenEnv != "" { + env = append(env, "NATS_URL="+cfg.NATS.URL) + if tokenEnv := cfg.NATS.TokenEnv; tokenEnv != "" { if token := os.Getenv(tokenEnv); token != "" { env = append(env, "NATS_TOKEN="+token) } @@ -1090,9 +1093,9 @@ func (d *Daemon) containerEnv(task *store.Task) []string { func (d *Daemon) executionFor(task *store.Task) (config.Config, agentexec.Runner) { if id := d.identityFor(task); id != nil { - return configForIdentity(d.Cfg, id.Cfg), id.Agent + return configForIdentity(d.Cfg.Get(), id.Cfg), id.Agent } - return d.Cfg, d.Agent + return d.Cfg.Get(), d.Agent } func (d *Daemon) configFor(task *store.Task) config.Config { @@ -1152,7 +1155,7 @@ func (d *Daemon) treesFor(task *store.Task) *worktree.Manager { // repoFor resolves task's repo config from the owning identity's repo // list when task.Identity is set, else the root Cfg.Repos. func (d *Daemon) repoFor(t *store.Task) (config.Repo, bool) { - repos := d.Cfg.Repos + repos := d.Cfg.Get().Repos if id := d.identityFor(t); id != nil { repos = id.Repos } diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index f220d6eb8..5948cb8bc 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -53,9 +53,9 @@ func (s *cleanupStorage) CleanupExpired(_ context.Context, ttl time.Duration) (i func TestCleanupExpiredStorageUsesConfiguredTTL(t *testing.T) { backend := &cleanupStorage{} d := &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ Containers: config.ContainerConfig{VolumeTTL: config.Duration(6 * time.Hour)}, - }, + }), Storage: backend, Log: slog.New(slog.DiscardHandler), } @@ -252,12 +252,12 @@ func TestTaskDispatcherWaitsForRunningTasks(t *testing.T) { func TestDaemonAllowConcurrentForReadsRepoConfig(t *testing.T) { d := &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ Repos: []config.Repo{ {Owner: "acme", Name: "widget", AllowConcurrent: true}, {Owner: "acme", Name: "todo"}, }, - }, + }), } if !d.allowConcurrentForTask(&store.Task{Owner: "acme", Repo: "widget"}) { @@ -279,10 +279,10 @@ func TestDaemonAllowConcurrentForReadsRepoConfig(t *testing.T) { func TestAllowConcurrentForTaskPrefersOwningIdentityRepo(t *testing.T) { shared := config.Repo{Owner: "acme", Name: "shared"} d := &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ // Root (legacy) list: shared is NOT opted in. Repos: []config.Repo{shared}, - }, + }), Identities: []*IdentityRunner{ { Name: "archie", @@ -305,12 +305,12 @@ func TestAllowConcurrentForTaskPrefersOwningIdentityRepo(t *testing.T) { func TestContainerEnvIncludesConfiguredNATSCredentials(t *testing.T) { t.Setenv("ARCHIE_NATS_SECRET", "test-nats-token") - d := &Daemon{Cfg: config.Config{ + d := &Daemon{Cfg: config.NewHolder(config.Config{ NATS: config.NATSConfig{ URL: "nats://nats.example:4222", TokenEnv: "ARCHIE_NATS_SECRET", }, - }} + })} got := d.containerEnv(nil) for _, want := range []string{ @@ -327,9 +327,9 @@ func TestContainerEnvUsesOnlyOwningIdentityProviderCredential(t *testing.T) { t.Setenv("ROOT_PROVIDER_KEY", "root-secret") t.Setenv("WORKER_PROVIDER_KEY", "worker-secret") d := &Daemon{ - Cfg: config.Config{Providers: map[string]config.Provider{ + Cfg: config.NewHolder(config.Config{Providers: map[string]config.Provider{ "openai": {Class: "openai", APIKeyEnv: "ROOT_PROVIDER_KEY"}, - }}, + }}), Identities: []*IdentityRunner{{ Name: "worker", Cfg: config.IdentityConfig{Name: "worker", Providers: map[string]config.Provider{ @@ -371,11 +371,11 @@ func daemonWithNATS(t *testing.T) (*Daemon, *store.Store, *arnats.Client) { s := store.OpenTest(t) d := &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ Dispatch: config.Dispatch{Labels: map[string]string{ "parked": "archie:parked", "queued": "archie:queued", "dead": "archie:dead", }}, - }, + }), Store: s, Tasks: client, Log: slog.New(slog.DiscardHandler), @@ -532,7 +532,9 @@ func TestRunViaAgentParksOnRunError(t *testing.T) { func TestRunViaAgentSendsExpectedRequest(t *testing.T) { d, s, busClient := daemonWithNATS(t) - d.Cfg.DiffCapLines = 999 + prev := d.Cfg.Get() + prev.DiffCapLines = 999 + d.Cfg.Set(prev) ctx := context.Background() if _, err := s.EnqueueIssue(ctx, "acme", "widget", 3, "t", "b", "", ""); err != nil { @@ -677,7 +679,7 @@ func testDaemon(t *testing.T, maxRetries, _ int) (*Daemon, *store.Store, *testFo log := slog.New(slog.NewTextHandler(os.Stderr, nil)) return &Daemon{ - Cfg: cfg, + Cfg: config.NewHolder(cfg), Store: s, Forge: fg, // Reconcile paths call Trees.Cleanup, which dereferences the @@ -751,12 +753,12 @@ func TestExecutionForUsesIdentityConfigAgentAndProvider(t *testing.T) { rootAgent := &identityRunnerStub{} identityAgent := &identityRunnerStub{} d := &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ Models: map[string]string{"builder": "root/model"}, Providers: map[string]config.Provider{ "root": {Class: "openai", APIKeyEnv: "ROOT_KEY"}, }, - }, + }), Agent: rootAgent, Identities: []*IdentityRunner{{ Name: "worker", Agent: identityAgent, @@ -814,7 +816,7 @@ func twoIdentityDaemon(t *testing.T) (d *Daemon, s *store.Store, rootFg, archieF repo := config.Repo{Owner: "acme", Name: "shared"} d = &Daemon{ - Cfg: config.Config{ + Cfg: config.NewHolder(config.Config{ Dispatch: config.Dispatch{ Labels: map[string]string{ "queued": "archie:queued", @@ -822,7 +824,7 @@ func twoIdentityDaemon(t *testing.T) (d *Daemon, s *store.Store, rootFg, archieF }, }, Repos: []config.Repo{repo}, // root/legacy repo list -- must NOT be consulted for identity tasks - }, + }), Store: s, Forge: rootFg, // must NOT be called for identity-owned tasks Log: log, @@ -858,7 +860,7 @@ func TestAcknowledgeUsesOwningIdentityForgeNotRoot(t *testing.T) { is := forge.Issue{Number: 1, Title: "shared issue"} // archie's poll cycle acknowledges via its own forge client. - d.acknowledge(ctx, archieFg, d.Cfg, repo, is) + d.acknowledge(ctx, archieFg, d.Cfg.Get(), repo, is) if len(archieFg.stateLabels) != 0 { t.Fatalf("archie forge got %d state label calls, want 0", len(archieFg.stateLabels)) } @@ -945,7 +947,7 @@ func TestMaintainAndDrainReconcilesPRsInMultiIdentityMode(t *testing.T) { // issues assigned to the root bot user. func TestPollIssuesWithConfigUsesIdentityScopedDispatch(t *testing.T) { fg := &recordingForge{} - d := &Daemon{Cfg: config.Config{}, Log: slog.New(slog.DiscardHandler)} + d := &Daemon{Cfg: config.NewHolder(config.Config{}), Log: slog.New(slog.DiscardHandler)} // Root uses bot_user "root"; the identity uses "winter". Both default // to the assignee trigger. diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index 2e795e1ed..88314cb4d 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -40,7 +40,7 @@ func (s *Server) handleChannels(w http.ResponseWriter, r *http.Request) { return } - chat := s.Cfg.Chat + chat := s.Cfg.Get().Chat views := []ChannelView{ telegramChannelView(chat.Telegram), webhookChannelView(chat.WebhookAddr), @@ -292,7 +292,11 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]any{}) return } - cfg := s.Cfg + // cfg := s.Cfg was a shared-pointer copy that aliased the live + // config. Under the Holder it becomes a value snapshot, which is + // what the read-only view always wanted -- every ConfigView field + // is read from this local. + cfg := s.Cfg.Get() view := ConfigView{ Identity: IdentityView{ diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index 7de93f8d5..3b54ca4dd 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -23,8 +23,8 @@ const ( fakeNATSToken = "nats-FAKESECRETTOKEN000" ) -func configWithFakeSecrets() *config.Config { - return &config.Config{ +func configWithFakeSecrets() *config.Holder { + return config.NewHolder(config.Config{ WorkDir: "/work/archie", SkillsDir: "/work/archie/.agents/skills", DBPath: "/work/archie/archie.db", @@ -58,7 +58,7 @@ func configWithFakeSecrets() *config.Config { Chat: config.ChatConfig{ Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"}, }, - } + }) } // leakCandidates returns the set of fake secret strings a test should @@ -72,11 +72,11 @@ func leakCandidates() []string { func TestHandleConfigNeverLeaksSecrets(t *testing.T) { cases := []struct { name string - cfg *config.Config + cfg *config.Holder }{ {name: "populated config with secrets", cfg: configWithFakeSecrets()}, {name: "nil config", cfg: nil}, - {name: "zero-value config", cfg: &config.Config{}}, + {name: "zero-value config", cfg: config.NewHolder(config.Config{})}, } for _, tc := range cases { diff --git a/internal/webui/api_logs.go b/internal/webui/api_logs.go index 5bc2b4178..31ead1302 100644 --- a/internal/webui/api_logs.go +++ b/internal/webui/api_logs.go @@ -116,7 +116,7 @@ func (s *Server) logFile() string { if s.Cfg == nil { return "" } - return strings.TrimSpace(s.Cfg.Log.File) + return strings.TrimSpace(s.Cfg.Get().Log.File) } func splitCSV(v string) []string { diff --git a/internal/webui/api_setup.go b/internal/webui/api_setup.go index 7fb81e953..dd29cf311 100644 --- a/internal/webui/api_setup.go +++ b/internal/webui/api_setup.go @@ -35,18 +35,19 @@ func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) { // The operator's name is deployment data, configured once in [chat]. The // dashboard greets with it rather than hardcoding a name, which would be // wrong on every deployment but one. - operator := strings.TrimSpace(s.Cfg.Chat.Operator) + cfg := s.Cfg.Get() + operator := strings.TrimSpace(cfg.Chat.Operator) steps = append(steps, SetupStep{ Title: "Give Archie an identity", Detail: "The account it commits and comments as.", - Done: strings.TrimSpace(s.Cfg.BotUser) != "", + Done: strings.TrimSpace(cfg.BotUser) != "", }) steps = append(steps, SetupStep{ Title: "Connect a repository", Detail: "Archie polls these for issues assigned to it.", - Done: len(s.Cfg.Repos) > 0, + Done: len(cfg.Repos) > 0, }) steps = append(steps, SetupStep{ @@ -75,6 +76,7 @@ func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) { // Chat is disabled entirely when no channel token is set, so the presence of // one is the honest signal here. func (s *Server) hasChannel() bool { - return strings.TrimSpace(s.Cfg.Chat.Telegram.TokenEnv) != "" || - strings.TrimSpace(s.Cfg.Chat.WebhookAddr) != "" + cfg := s.Cfg.Get() + return strings.TrimSpace(cfg.Chat.Telegram.TokenEnv) != "" || + strings.TrimSpace(cfg.Chat.WebhookAddr) != "" } diff --git a/internal/webui/api_skills.go b/internal/webui/api_skills.go index 55c7ffdc1..4d8f8c5cc 100644 --- a/internal/webui/api_skills.go +++ b/internal/webui/api_skills.go @@ -28,7 +28,8 @@ func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) { return } - roots := skill.DefaultRoots(s.Cfg.WorkDir, s.Cfg.SkillsDir) + cfg := s.Cfg.Get() + roots := skill.DefaultRoots(cfg.WorkDir, cfg.SkillsDir) catalog, err := skill.CatalogRoots(roots...) if err != nil { http.Error(w, "failed to read skill catalogue: "+err.Error(), http.StatusInternalServerError) @@ -41,7 +42,7 @@ func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) { Name: entry.Name, Description: entry.Description, Workflow: entry.Workflow, - Source: skillSource(entry.Root, s.Cfg.WorkDir, s.Cfg.SkillsDir), + Source: skillSource(entry.Root, cfg.WorkDir, cfg.SkillsDir), }) } diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index 549d2060f..ca5de4bc5 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -374,12 +374,13 @@ func (s *Server) maxRetriesFor(task *store.Task) int { if s.Cfg == nil { return 0 } - for _, repo := range s.Cfg.Repos { + cfg := s.Cfg.Get() + for _, repo := range cfg.Repos { if repo.Owner == task.Owner && repo.Name == task.Repo { - return repo.EffectiveMaxRetries(s.Cfg.MaxRetries) + return repo.EffectiveMaxRetries(cfg.MaxRetries) } } - return s.Cfg.MaxRetries + return cfg.MaxRetries } // closeRejectedIssue closes the forge issue behind a task the operator has diff --git a/internal/webui/api_tasks_actions_test.go b/internal/webui/api_tasks_actions_test.go index 36af47c1a..67aab008e 100644 --- a/internal/webui/api_tasks_actions_test.go +++ b/internal/webui/api_tasks_actions_test.go @@ -62,7 +62,7 @@ func actionServer(t *testing.T, status, parkReason string) (*Server, *store.Task srv.Issues = closer srv.Events = bus - srv.Cfg = &config.Config{MaxRetries: 3} + srv.Cfg = config.NewHolder(config.Config{MaxRetries: 3}) return srv, task, closer, bus, sub } @@ -128,7 +128,7 @@ func TestRetryEnforcesMaxRetries(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { srv, task, _, _, _ := actionServer(t, store.StatusParked, "it broke") - srv.Cfg = &config.Config{MaxRetries: tc.maxRetries} + srv.Cfg = config.NewHolder(config.Config{MaxRetries: tc.maxRetries}) ctx := t.Context() for range tc.priorCount { if err := srv.Store.IncrementRetryCount(ctx, task.ID); err != nil { @@ -203,7 +203,7 @@ func TestRejectDoesNotCloseAChatTaskIssue(t *testing.T) { ctx := t.Context() closer := &recordingCloser{} srv.Issues = closer - srv.Cfg = &config.Config{MaxRetries: 3} + srv.Cfg = config.NewHolder(config.Config{MaxRetries: 3}) task, err := srv.Store.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "") if err != nil { @@ -380,7 +380,7 @@ func TestTaskActionStoreFailureIs500(t *testing.T) { srv := &Server{ Store: &stubStore{TaskStore: base.Store, requeueErr: errors.New("db locked")}, Log: base.Log, - Cfg: &config.Config{MaxRetries: 3}, + Cfg: config.NewHolder(config.Config{MaxRetries: 3}), } w := postAction(t, srv, task.ID, "approve") if w.Code != http.StatusInternalServerError { diff --git a/internal/webui/server.go b/internal/webui/server.go index ef2b40f7b..be67998fa 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -32,8 +32,10 @@ type Server struct { Log *slog.Logger // Cfg backs the setup checklist and configuration views. Optional: the - // dashboard degrades to task data alone when it is nil. - Cfg *config.Config + // dashboard degrades to task data alone when it is nil. Held through a + // Holder so a reload swaps the snapshot atomically across handler + // goroutines that would otherwise race on the raw shared pointer. + Cfg *config.Holder // Workflows is the executable registry snapshot supplied by composition. Workflows []workflow.Definition